public async Task <AuthResult> GetAccessToken(AuthenticationOptions authOptions, IDialogContext context) { if (context.UserData.TryGetValue($"{Name}{ContextConstants.AuthResultKey}", out AuthResult authResult) && (!authOptions.UseMagicNumber || (context.UserData.TryGetValue($"{Name}{ContextConstants.MagicNumberValidated}", out string validated) && validated == "true"))) { try { var tokenCache = new InMemoryTokenCacheMSAL(authResult.TokenCache).GetMsalCacheInstance(); var client = new ConfidentialClientApplication(authOptions.ClientId, authOptions.RedirectUrl, new ClientCredential(authOptions.ClientSecret), tokenCache, null); authResult = (await client.AcquireTokenSilentAsync(authOptions.Scopes, client.GetUser(authResult.UserUniqueId))) .FromMSALAuthenticationResult(tokenCache); context.StoreAuthResult(authResult, this); } catch (Exception ex) { Trace.TraceError("Failed to renew token: " + ex.Message); await context.PostAsync("Your credentials expired and could not be renewed automatically!"); await Logout(authOptions, context); return(null); } return(authResult); } return(null); }
public async Task <AuthResult> GetAccessTokenSilent(AuthenticationOptions options, IDialogContext context) { if (context.UserData.TryGetValue($"{Name}{ContextConstants.AuthResultKey}", out AuthResult result) && context.UserData.TryGetValue($"{Name}{ContextConstants.MagicNumberValidated}", out string validated) && validated == "true") { try { var tokenCache = new InMemoryTokenCacheMSAL(result.TokenCache).GetMsalCacheInstance(); var client = new ConfidentialClientApplication(options.ClientId, options.RedirectUrl, new ClientCredential(options.ClientSecret), tokenCache, null); var r = await client.AcquireTokenSilentAsync(options.Scopes, client.GetUser(result.UserUniqueId)); result = r.FromMSALAuthenticationResult(tokenCache); context.StoreAuthResult(result, this); return(result); } catch (Exception) { return(null); } } return(null); }
public static async Task <string> GetAuthUrlAsync(ResumptionCookie resumptionCookie, string[] scopes) { var extraParameters = BuildExtraParameters(resumptionCookie); Uri redirectUri = new Uri(AuthSettings.RedirectUrl); if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase)) { InMemoryTokenCacheMSAL tokenCache = new InMemoryTokenCacheMSAL(); Microsoft.Identity.Client.ConfidentialClientApplication client = new Microsoft.Identity.Client.ConfidentialClientApplication("https://login.microsoftonline.com/" + AuthSettings.Tenant + "/oauth2/v2.0", AuthSettings.ClientId, redirectUri.ToString(), new Microsoft.Identity.Client.ClientCredential(AuthSettings.ClientSecret), tokenCache); //var uri = "https://login.microsoftonline.com/" + AuthSettings.Tenant + "/oauth2/v2.0/authorize?response_type=code" + // "&client_id=" + AuthSettings.ClientId + // "&client_secret=" + AuthSettings.ClientSecret + // "&redirect_uri=" + HttpUtility.UrlEncode(AuthSettings.RedirectUrl) + // "&scope=" + HttpUtility.UrlEncode("openid profile " + string.Join(" ", scopes)) + // "&state=" + encodedCookie; var uri = await client.GetAuthorizationRequestUrlAsync( scopes, null, $"state={extraParameters}"); return(uri.ToString()); } else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase)) { return(null); } return(null); }
public static async Task <string> GetAccessToken(this IBotContext context, string resourceId) { AuthResult authResult; if (context.Activity.ChannelId.Equals("cortana", StringComparison.InvariantCultureIgnoreCase)) { string token = null; if (context.UserData.TryGetValue(ContextConstants.AuthResultKey, out authResult)) { //we have credential } else { token = GetCortanaAccessToken(context); var jwt = new JwtSecurityToken(token); if (authResult == null) { authResult = new AuthResult(); } authResult.AccessToken = token; long tick = long.MinValue; long.TryParse(jwt.Payload.Claims.Where(c => c.Type.Equals("exp", StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault()?.Value, out tick); authResult.ExpiresOnUtcTicks = tick; InMemoryTokenCacheMSAL tokenCache = new InMemoryTokenCacheMSAL(Encoding.ASCII.GetBytes(token)); authResult.TokenCache = tokenCache.Serialize(); context.StoreAuthResult(authResult); } return(authResult.AccessToken); } else { if (context.UserData.TryGetValue(ContextConstants.AuthResultKey, out authResult)) { try { InMemoryTokenCacheADAL tokenCache = new InMemoryTokenCacheADAL(authResult.TokenCache); var result = await AzureActiveDirectoryHelper.GetToken(authResult.UserUniqueId, tokenCache, resourceId); authResult.AccessToken = result.AccessToken; authResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks; authResult.TokenCache = tokenCache.Serialize(); context.StoreAuthResult(authResult); } catch (Exception ex) { Trace.TraceError("Failed to renew token: " + ex.Message); await context.PostAsync("Your credentials expired and could not be renewed automatically!"); await context.Logout(); return(null); } return(authResult.AccessToken); } return(null); } }
public async Task <AuthResult> GetTokenByAuthCodeAsync(AuthenticationOptions authOptions, string authorizationCode) { var tokenCache = new InMemoryTokenCacheMSAL().GetMsalCacheInstance(); var authResult = (await new ConfidentialClientApplication(authOptions.ClientId, authOptions.RedirectUrl, new ClientCredential(authOptions.ClientSecret), tokenCache, null) .AcquireTokenByAuthorizationCodeAsync(authorizationCode, authOptions.Scopes)) .FromMSALAuthenticationResult(tokenCache); return(authResult); }
public async Task <string> GetAuthUrlAsync(AuthenticationOptions authOptions, string state) { var redirectUri = new Uri(authOptions.RedirectUrl); var tokenCache = new InMemoryTokenCacheMSAL().GetMsalCacheInstance(); var client = new ConfidentialClientApplication(authOptions.ClientId, redirectUri.ToString(), new ClientCredential(authOptions.ClientSecret), tokenCache, null); var uri = await client.GetAuthorizationRequestUrlAsync(authOptions.Scopes, null, $"state={state}"); return(uri.ToString()); }
public static async Task <string> GetAlias(this IBotContext context) { AuthResult authResult; string validated = null; if (context.UserData.TryGetValue(ContextConstants.AuthResultKey, out authResult) && context.UserData.TryGetValue(ContextConstants.MagicNumberValidated, out validated) && validated == "true") { try { if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase)) { InMemoryTokenCacheMSAL tokenCache = new InMemoryTokenCacheMSAL(authResult.TokenCache); var result = await AzureActiveDirectoryHelper.GetToken(authResult.UserUniqueId, tokenCache, AuthSettings.Scopes); authResult.AccessToken = result.AccessToken; authResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks; authResult.TokenCache = tokenCache.Serialize(); authResult.Alias = result.Alias; context.StoreAuthResult(authResult); } else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase)) { throw new NotImplementedException(); } else if (string.Equals(AuthSettings.Mode, "v1", StringComparison.OrdinalIgnoreCase)) { InMemoryTokenCacheADAL tokenCache = new InMemoryTokenCacheADAL(authResult.TokenCache); var result = await AzureActiveDirectoryHelper.GetToken(authResult.UserUniqueId, tokenCache, ConfigurationManager.AppSettings["ActiveDirectory.ResourceId"]); authResult.AccessToken = result.AccessToken; authResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks; authResult.TokenCache = tokenCache.Serialize(); authResult.Alias = result.Alias; context.StoreAuthResult(authResult); } } catch (Exception ex) { Trace.TraceError("Failed to renew token: " + ex.Message); await context.PostAsync("Your credentials expired and could not be renewed automatically!"); await context.Logout(); return(null); } return(authResult.Alias.Split('@')[0]); } return(null); }
public static async Task <string> GetAuthUrlAsync(ResumptionCookie resumptionCookie) { var encodedCookie = UrlToken.Encode(resumptionCookie); Uri redirectUri = new Uri(AuthSettings.RedirectUrl); if (string.Equals(AuthSettings.Mode, "v1", StringComparison.OrdinalIgnoreCase)) { Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext context = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(AuthSettings.EndpointUrl + "/" + AuthSettings.Tenant); var uri = await context.GetAuthorizationRequestUrlAsync( AuthSettings.ResourceId, AuthSettings.ClientId, redirectUri, Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier.AnyUser, "state=" + encodedCookie); return(uri.ToString()); } else if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase)) { InMemoryTokenCacheMSAL tokenCache = new InMemoryTokenCacheMSAL(); Microsoft.Identity.Client.ConfidentialClientApplication client = new Microsoft.Identity.Client.ConfidentialClientApplication(AuthSettings.ClientId, redirectUri.ToString(), new Microsoft.Identity.Client.ClientCredential(AuthSettings.ClientSecret), tokenCache); var uri = await client.GetAuthorizationRequestUrlAsync( AuthSettings.Scopes, null, "state=" + encodedCookie); //, // null // clientId.Value, // redirectUri, // Microsoft.Experimental.IdentityModel.Clients.ActiveDirectory.UserIdentifier.AnyUser, // "state=" + encodedCookie); return(uri.ToString()); } else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase)) { return(null); } return(null); }
public static async Task <string> GetAccessToken(this IBotContext context, string[] scopes) { AuthResult authResult; if (context.UserData.TryGetValue(ContextConstants.AuthResultKey, out authResult)) { try { if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase)) { InMemoryTokenCacheMSAL tokenCache = new InMemoryTokenCacheMSAL(authResult.TokenCache); var result = await AzureActiveDirectoryHelper.GetToken(authResult.UserUniqueId, tokenCache, scopes); authResult.AccessToken = result.AccessToken; authResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks; authResult.TokenCache = tokenCache.Serialize(); context.StoreAuthResult(authResult); } else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase)) { throw new NotImplementedException(); } } catch (Exception ex) { Trace.TraceError("Failed to renew token: " + ex.Message); await context.PostAsync("Your credentials expired and could not be renewed automatically!"); await context.Logout(); return(null); } return(authResult.AccessToken); } return(null); }