Пример #1
0
 public static async Task<string> GetAccessToken(this IBotContext context, string resourceId)
 {
     AuthResult authResult;
     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;
 }
Пример #2
0
        /// <summary>
        /// Get access token for accessing resource.
        /// </summary>
        /// <param name="botData">Bot data</param>
        /// <param name="resourceId">Resource ID</param>
        /// <param name="token">Cancellation token</param>
        /// <returns>Access token as an awaitable task.</returns>
        public async static Task <string> GetTokenAsync(this IBotData botData, AuthenticationOptions authOptions, IAuthProvider authProvider, CancellationToken token)
        {
            AuthResult authResult = default;

            if (botData.UserData.TryGetValue($"{authProvider.Name}{ContextConstants.AuthResultKey}", out authResult))
            {
                try
                {
                    InMemoryTokenCacheADAL tokenCache = new InMemoryTokenCacheADAL(authResult.TokenCache);

                    AuthenticationContext authContext = new AuthenticationContext(authOptions.Authority, tokenCache);
                    var result = await authContext.AcquireTokenSilentAsync(authOptions.ResourceId,
                                                                           new ClientCredential(authOptions.ClientId, authOptions.ClientSecret),
                                                                           new UserIdentifier(authResult.UserUniqueId, UserIdentifierType.UniqueId));

                    authResult = result.FromADALAuthenticationResult(tokenCache);
                    await botData.StoreAuthResultAsync(authResult, authProvider, token);
                }
                catch (Exception)
                {
                    return(null);
                }
                return(authResult.AccessToken);
            }
            return(null);
        }
Пример #3
0
        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);
            }
        }
Пример #4
0
        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);
        }
Пример #5
0
        public static async Task <string> GetAccessToken(this IBotContext context)
        {
            AuthResult authResult;

            if (context.UserData.TryGetValue(ContextConstants.AuthResultKey, out authResult))
            {
                DateTime expires = new DateTime(authResult.ExpiresOnUtcTicks);

                if (DateTime.UtcNow >= expires)
                {
                    Trace.TraceInformation("Token Expired");

                    try
                    {
                        if (string.Equals(AuthSettings.Mode, "v1", StringComparison.OrdinalIgnoreCase))
                        {
                            InMemoryTokenCacheADAL tokenCache = new InMemoryTokenCacheADAL(authResult.TokenCache);

                            Trace.TraceInformation("Trying to renew token...");
                            var result = await AzureActiveDirectoryHelper.GetToken(authResult.UserUniqueId, tokenCache);

                            authResult.AccessToken       = result.AccessToken;
                            authResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks;
                            authResult.TokenCache        = tokenCache.Serialize();

                            context.StoreAuthResult(authResult);
                        }
                        else if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase))
                        {
                            InMemoryTokenCacheMSAL tokenCache = new InMemoryTokenCacheMSAL(authResult.TokenCache);

                            Trace.TraceInformation("Trying to renew token...");
                            var result = await AzureActiveDirectoryHelper.GetToken(authResult.UserUniqueId, tokenCache);

                            authResult.AccessToken       = result.AccessToken;
                            authResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks;
                            authResult.TokenCache        = tokenCache.Serialize();

                            context.StoreAuthResult(authResult);
                        }
                        else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase))
                        {
                        }
                        Trace.TraceInformation("Token renewed!");
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("Failed to renew token: " + ex.Message);

                        await context.PostAsync("Your credentials expired and could not be renewed automatically!");

                        context.Logout();

                        return(null);
                    }
                }

                return(authResult.AccessToken);
            }

            return(null);
        }