Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 22 additions & 20 deletions libraries/Microsoft.Bot.Builder/BotFrameworkAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,7 @@ public async Task<TokenResponse> GetUserTokenAsync(ITurnContext turnContext, str
}

var client = await CreateOAuthApiClientAsync(turnContext).ConfigureAwait(false);
return await client.GetUserTokenAsync(turnContext.Activity.From.Id, connectionName, magicCode, null, cancellationToken).ConfigureAwait(false);
return await client.UserToken.GetTokenAsync(turnContext.Activity.From.Id, connectionName, turnContext.Activity.ChannelId, magicCode, cancellationToken).ConfigureAwait(false);
}

/// <summary>
Expand Down Expand Up @@ -579,7 +579,7 @@ public async Task<string> GetOauthSignInLinkAsync(ITurnContext turnContext, stri
var state = Convert.ToBase64String(encodedState);

var client = await CreateOAuthApiClientAsync(turnContext).ConfigureAwait(false);
return await client.GetSignInLinkAsync(state, null, cancellationToken).ConfigureAwait(false);
return await client.BotSignIn.GetSignInUrlAsync(state, null, null, null, cancellationToken).ConfigureAwait(false);
}

/// <summary>
Expand Down Expand Up @@ -627,7 +627,7 @@ public async Task<string> GetOauthSignInLinkAsync(ITurnContext turnContext, stri
var state = Convert.ToBase64String(encodedState);

var client = await CreateOAuthApiClientAsync(turnContext).ConfigureAwait(false);
return await client.GetSignInLinkAsync(state, finalRedirect, cancellationToken).ConfigureAwait(false);
return await client.BotSignIn.GetSignInUrlAsync(state, null, null, finalRedirect, cancellationToken).ConfigureAwait(false);
}

/// <summary>
Expand All @@ -649,7 +649,7 @@ public async Task<string> GetOauthSignInLinkAsync(ITurnContext turnContext, stri
}

var client = await CreateOAuthApiClientAsync(turnContext).ConfigureAwait(false);
await client.SignOutUserAsync(userId, connectionName, cancellationToken).ConfigureAwait(false);
await client.UserToken.SignOutAsync(userId, connectionName, turnContext.Activity?.ChannelId, cancellationToken).ConfigureAwait(false);
}

/// <summary>
Expand All @@ -658,8 +658,9 @@ public async Task<string> GetOauthSignInLinkAsync(ITurnContext turnContext, stri
/// <param name="context">Context for the current turn of conversation with the user.</param>
/// <param name="userId">The user Id for which token status is retrieved.</param>
/// <param name="includeFilter">Optional comma seperated list of connection's to include. Blank will return token status for all configured connections.</param>
/// <param name="cancellationToken">The async operation cancellation token.</param>
/// <returns>Array of TokenStatus.</returns>
public async Task<TokenStatus[]> GetTokenStatusAsync(ITurnContext context, string userId, string includeFilter = null)
public async Task<TokenStatus[]> GetTokenStatusAsync(ITurnContext context, string userId, string includeFilter = null, CancellationToken cancellationToken = default(CancellationToken))
{
BotAssert.ContextNotNull(context);

Expand All @@ -669,7 +670,8 @@ public async Task<TokenStatus[]> GetTokenStatusAsync(ITurnContext context, strin
}

var client = await this.CreateOAuthApiClientAsync(context).ConfigureAwait(false);
return await client.GetTokenStatusAsync(userId, includeFilter).ConfigureAwait(false);
var result = await client.UserToken.GetTokenStatusAsync(userId, context.Activity?.ChannelId, includeFilter, cancellationToken).ConfigureAwait(false);
return result?.ToArray();
}

/// <summary>
Expand All @@ -679,8 +681,9 @@ public async Task<TokenStatus[]> GetTokenStatusAsync(ITurnContext context, strin
/// <param name="connectionName">The name of the Azure Active Direcotry connection configured with this bot.</param>
/// <param name="resourceUrls">The list of resource URLs to retrieve tokens for.</param>
/// <param name="userId">The user Id for which tokens are retrieved. If passing in null the userId is taken from the Activity in the ITurnContext.</param>
/// <param name="cancellationToken">The async operation cancellation token.</param>
/// <returns>Dictionary of resourceUrl to the corresponding TokenResponse.</returns>
public async Task<Dictionary<string, TokenResponse>> GetAadTokensAsync(ITurnContext context, string connectionName, string[] resourceUrls, string userId = null)
public async Task<IDictionary<string, TokenResponse>> GetAadTokensAsync(ITurnContext context, string connectionName, string[] resourceUrls, string userId = null, CancellationToken cancellationToken = default(CancellationToken))
{
BotAssert.ContextNotNull(context);

Expand All @@ -700,7 +703,7 @@ public async Task<Dictionary<string, TokenResponse>> GetAadTokensAsync(ITurnCont
}

var client = await this.CreateOAuthApiClientAsync(context).ConfigureAwait(false);
return await client.GetAadTokensAsync(userId, connectionName, resourceUrls).ConfigureAwait(false);
return await client.UserToken.GetAadTokensAsync(userId, connectionName, new AadResourceUrls() { ResourceUrls = resourceUrls?.ToList() }, context.Activity?.ChannelId, cancellationToken).ConfigureAwait(false);
}

/// <summary>
Expand Down Expand Up @@ -760,29 +763,28 @@ public virtual async Task CreateConversationAsync(string channelId, string servi
/// <returns>An OAuth client for the bot.</returns>
protected async Task<OAuthClient> CreateOAuthApiClientAsync(ITurnContext turnContext)
{
var client = turnContext.TurnState.Get<IConnectorClient>() as ConnectorClient;
if (client == null)
{
throw new ArgumentNullException("CreateOAuthApiClient: OAuth requires a valid ConnectorClient instance");
}

if (!OAuthClient.EmulateOAuthCards &&
if (!OAuthClientConfig.EmulateOAuthCards &&
string.Equals(turnContext.Activity.ChannelId, "emulator", StringComparison.InvariantCultureIgnoreCase) &&
(await _credentialProvider.IsAuthenticationDisabledAsync().ConfigureAwait(false)))
{
OAuthClient.EmulateOAuthCards = true;
OAuthClientConfig.EmulateOAuthCards = true;
}

if (OAuthClient.EmulateOAuthCards)
var connectorClient = turnContext.TurnState.Get<IConnectorClient>();
if(connectorClient == null)
{
var oauthClient = new OAuthClient(client, turnContext.Activity.ServiceUrl);
throw new InvalidOperationException("An IConnectorClient is required in TurnState for this operation.");
}

if (OAuthClientConfig.EmulateOAuthCards)
{
// do not await task - we want this to run in the background
var task = Task.Run(() => oauthClient.SendEmulateOAuthCardsAsync(OAuthClient.EmulateOAuthCards));
var oauthClient = new OAuthClient(new Uri(turnContext.Activity.ServiceUrl), connectorClient.Credentials);
var task = Task.Run(() => OAuthClientConfig.SendEmulateOAuthCardsAsync(oauthClient, OAuthClientConfig.EmulateOAuthCards));
return oauthClient;
}

return new OAuthClient(client, OAuthClient.OAuthEndpoint);
return new OAuthClient(new Uri(OAuthClientConfig.OAuthEndpoint), connectorClient.Credentials);
}

/// <summary>
Expand Down
221 changes: 221 additions & 0 deletions libraries/Microsoft.Bot.Connector/BotSignIn.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>

namespace Microsoft.Bot.Connector
{
using Microsoft.Rest;
using Microsoft.Bot.Schema;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

/// <summary>
/// BotSignIn operations.
/// </summary>
public partial class BotSignIn : IServiceOperations<OAuthClient>, IBotSignIn
{
/// <summary>
/// Initializes a new instance of the BotSignIn class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public BotSignIn(OAuthClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}

/// <summary>
/// Gets a reference to the OAuthClient
/// </summary>
public OAuthClient Client { get; private set; }

/// <param name='state'>
/// </param>
/// <param name='codeChallenge'>
/// </param>
/// <param name='emulatorUrl'>
/// </param>
/// <param name='finalRedirect'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<string>> GetSignInUrlWithHttpMessagesAsync(string state, string codeChallenge = default(string), string emulatorUrl = default(string), string finalRedirect = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (state == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "state");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("state", state);
tracingParameters.Add("codeChallenge", codeChallenge);
tracingParameters.Add("emulatorUrl", emulatorUrl);
tracingParameters.Add("finalRedirect", finalRedirect);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetSignInUrl", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/botsignin/GetSignInUrl").ToString();
List<string> _queryParameters = new List<string>();
if (state != null)
{
_queryParameters.Add(string.Format("state={0}", System.Uri.EscapeDataString(state)));
}
if (codeChallenge != null)
{
_queryParameters.Add(string.Format("code_challenge={0}", System.Uri.EscapeDataString(codeChallenge)));
}
if (emulatorUrl != null)
{
_queryParameters.Add(string.Format("emulatorUrl={0}", System.Uri.EscapeDataString(emulatorUrl)));
}
if (finalRedirect != null)
{
_queryParameters.Add(string.Format("finalRedirect={0}", System.Uri.EscapeDataString(finalRedirect)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers


if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}

// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<string>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
// MANUAL SWAGGER UPDATE
_result.Body = _responseContent;
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}

}
}
45 changes: 45 additions & 0 deletions libraries/Microsoft.Bot.Connector/BotSignInExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>

namespace Microsoft.Bot.Connector
{
using Microsoft.Bot.Schema;
using System.Threading;
using System.Threading.Tasks;

/// <summary>
/// Extension methods for BotSignIn.
/// </summary>
public static partial class BotSignInExtensions
{
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='state'>
/// </param>
/// <param name='codeChallenge'>
/// </param>
/// <param name='emulatorUrl'>
/// </param>
/// <param name='finalRedirect'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> GetSignInUrlAsync(this IBotSignIn operations, string state, string codeChallenge = default(string), string emulatorUrl = default(string), string finalRedirect = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSignInUrlWithHttpMessagesAsync(state, codeChallenge, emulatorUrl, finalRedirect, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}

}
}
Loading