Пример #1
0
        public async Task Updates_with_client_secret()
        {
            // setup
            var auth0serverUrl  = "https://localhost";
            var auth0Connection = "unit-test-connection";
            var apiClient       = new Mock <IAuthenticationApiClient>(MockBehavior.Strict);
            TokenAuthenticationRequestDto authRequest = null;

            apiClient.Setup(ac => ac.TokenAuthenticateAsync(It.IsAny <TokenAuthenticationRequestDto>(), auth0serverUrl))
            .Callback((TokenAuthenticationRequestDto token, string server) => authRequest = token)
            .Returns(Task.FromResult(new AuthenticationResponseDto {
                IdToken = Guid.NewGuid().ToString()
            }));
            var tokenProvider = new Auth0v2TokenProvider(loggerFactor.Object, new Auth0ClientSettings {
                Auth0ServerUrl = auth0serverUrl, Auth0Connection = auth0Connection
            }, apiClient.Object, autoScheduler.Object);
            var auth0ClientSettings = new Auth0ClientSettings {
                Auth0ClientId = Guid.NewGuid().ToString(), Auth0ClientSecret = Guid.NewGuid().ToString(), Auth0Audience = Guid.NewGuid().ToString()
            };

            // execute
            await tokenProvider.AddOrUpdateClientAsync(auth0ClientSettings);

            // validate
            apiClient.Verify(ac => ac.TokenAuthenticateAsync(It.IsAny <TokenAuthenticationRequestDto>(), auth0serverUrl), Times.Once);
            Assert.NotNull(authRequest);
            authRequest.ClientId.Should().Be(auth0ClientSettings.Auth0ClientId);
            authRequest.ClientSecret.Should().Be(auth0ClientSettings.Auth0ClientSecret);
            authRequest.Audience.Should().Be(auth0ClientSettings.Auth0Audience);
            authRequest.GrantType.Should().Be("client_credentials");
        }
Пример #2
0
        /// <summary>
        /// Updates the auth0 authentication header for the client id using username and password asynchronous.
        /// </summary>
        /// <param name="clientId">The client identifier.</param>
        /// <param name="forceRefresh">if set to <c>true</c> [force refresh].</param>
        /// <returns>
        /// A task, when completed, ensures that the authentication header got updated.
        /// </returns>
        /// <exception cref="System.Collections.Generic.KeyNotFoundException"></exception>
        public override async Task UpdateAuthHeaderWithCredentialsAsync(string clientId, bool forceRefresh = false)
        {
            if (await syncObject.WaitAsync(5000))
            {
                try
                {
                    if (!clientTokenCache.ContainsKey(clientId))
                    {
                        throw new KeyNotFoundException($"Cannot update the auth token for client {clientId}, because of missing information.");
                    }

                    // Only update if really needed.
                    // Especially when multiple tasks are invoked at the same time we only need to update once.
                    // Testing for a valid token happens within GetAuthHeaderForClient but outside of the locked section.
                    // Therefore it might happen that the token was already updated once entering the locked section.
                    if (clientTokenCache[clientId].LastRefresh > DateTimeOffset.Now.AddSeconds(-5) && !forceRefresh)
                    {
                        return;
                    }

                    var request = new TokenAuthenticationRequestDto
                    {
                        ClientId     = clientId,                                     // client ID of auth0 app configured to authenticate against target Auth0 API
                        ClientSecret = clientTokenCache[clientId].Auth0ClientSecret, // auth0 client secret
                        Audience     = clientTokenCache[clientId].Auth0Audience,     //audience url
                        GrantType    = "client_credentials",                         // it should be granted based on client id/secret
                    };

                    // authenticate with auth0
                    var authToken = await authenticationApiClient.TokenAuthenticateAsync(request, clientTokenCache[clientId].Auth0ServerUrl);

                    // set the authorization header
                    clientTokenCache[clientId].Auth0HeaderValue = new AuthenticationHeaderValue("Bearer", authToken.AccessToken);
                    clientTokenCache[clientId].LastRefresh      = DateTimeOffset.Now;
                    logger.LogInformation($"Successfully authenticated with the service client id {clientId} with client secret.");

                    ScheduleAutoRefresh(clientTokenCache[clientId], autoScheduler);
                }
                catch (Exception ex)
                {
                    // any exceptions during authentication are logged here
                    logger.LogError($"Error authenticating with service: {clientId} using user {clientTokenCache[clientId].Auth0Username}.", ex);
                }
                finally
                {
                    syncObject.Release();
                }
            }
            else
            {
                logger.LogWarning("Auth0TokenProvider could not get lock for retrieving an authentication token.");
            }
        }