コード例 #1
0
        public async Task Updates_with_refresh_token()
        {
            // setup
            var auth0serverUrl = "https://localhost";
            var apiClient      = new Mock <IAuthenticationApiClient>(MockBehavior.Strict);
            RefreshTokenDelegationRequestDto delegationRequest = null;

            apiClient.Setup(ac => ac.GetDelegationTokenAsync(It.IsAny <RefreshTokenDelegationRequestDto>(), auth0serverUrl))
            .Callback((DelegationRequestBaseDto token, string server) => delegationRequest = token as RefreshTokenDelegationRequestDto)
            .Returns(Task.FromResult(new AccessToken {
                IdToken = Guid.NewGuid().ToString()
            }));
            var tokenProvider = new Auth0TokenProvider(loggerFactor.Object, new Auth0ClientSettings {
                Auth0ServerUrl = auth0serverUrl
            }, apiClient.Object, autoScheduler.Object);
            var auth0ClientSettings = new Auth0ClientSettings {
                Auth0ClientId = Guid.NewGuid().ToString(), Auth0RefreshToken = Guid.NewGuid().ToString()
            };

            // execute
            await tokenProvider.AddOrUpdateClientAsync(auth0ClientSettings);

            // validate
            apiClient.Verify(ac => ac.GetDelegationTokenAsync(It.IsAny <DelegationRequestBaseDto>(), auth0serverUrl), Times.Once);
            Assert.NotNull(delegationRequest);
            delegationRequest.RefreshToken.Should().Be(auth0ClientSettings.Auth0RefreshToken);
            delegationRequest.SourceClientId.Should().Be(auth0ClientSettings.Auth0ClientId);
            delegationRequest.TargetClientId.Should().Be(auth0ClientSettings.Auth0ClientId);
        }
コード例 #2
0
        public async Task Updates_with_username_and_password()
        {
            // setup
            var auth0serverUrl = "https://localhost";
            var auth0Connection = "unit-test-connection";
            var apiClient = new Mock<IAuthenticationApiClient>(MockBehavior.Strict);
            RoAuthenticationRequestDto authRequest = null;
            apiClient.Setup(ac => ac.AuthenticateAsync(It.IsAny<RoAuthenticationRequestDto>(), auth0serverUrl))
                .Callback((RoAuthenticationRequestDto token, string server) => authRequest = token)
                .Returns(Task.FromResult(new AuthenticationResponseDto { IdToken = Guid.NewGuid().ToString()}));
            var tokenProvider = new Auth0TokenProvider(loggerFactor.Object, new Auth0ClientSettings {Auth0ServerUrl = auth0serverUrl, Auth0Connection = auth0Connection}, apiClient.Object, autoScheduler.Object);
            var auth0ClientSettings = new Auth0ClientSettings {Auth0ClientId = Guid.NewGuid().ToString(), Auth0Username = Guid.NewGuid().ToString(), Auth0Password = Guid.NewGuid().ToString()};

            // execute
            await tokenProvider.AddOrUpdateClientAsync(auth0ClientSettings);

            // validate
            apiClient.Verify(ac => ac.AuthenticateAsync(It.IsAny<RoAuthenticationRequestDto>(), auth0serverUrl), Times.Once);
            Assert.NotNull(authRequest);
            authRequest.ClientId.Should().Be(auth0ClientSettings.Auth0ClientId);
            authRequest.Username.Should().Be(auth0ClientSettings.Auth0Username);
            authRequest.Password.Should().Be(auth0ClientSettings.Auth0Password);
            authRequest.Scope.Should().Be("openid");
            authRequest.Connection.Should().Be(auth0Connection);
            authRequest.GrantType.Should().Be("password");
            authRequest.Device.Should().Be("api");
        }
コード例 #3
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");
        }
コード例 #4
0
        public async Task Schedules_auto_refresh_for_refresh_token()
        {
            // setup
            var apiClient = new Mock <IAuthenticationApiClient>(MockBehavior.Strict);

            apiClient.Setup(ac => ac.GetDelegationTokenAsync(It.IsAny <RefreshTokenDelegationRequestDto>(), It.IsAny <string>()))
            .Returns(Task.FromResult(new AccessToken {
                IdToken = Guid.NewGuid().ToString()
            }));
            var scheduler = new Mock <IAutoScheduler>(MockBehavior.Strict);

            scheduler.Setup(s => s.ScheduleRefresh(It.IsAny <Auth0ClientSettings>()));
            var tokenProvider = new Auth0TokenProvider(loggerFactor.Object, new Auth0ClientSettings {
                Auth0ServerUrl = Guid.NewGuid().ToString()
            }, apiClient.Object, scheduler.Object);
            var auth0ClientSettings = new Auth0ClientSettings {
                Auth0ClientId = Guid.NewGuid().ToString(), Auth0RefreshToken = Guid.NewGuid().ToString()
            };

            // execute twice
            await tokenProvider.AddOrUpdateClientAsync(auth0ClientSettings);

            // validate that it was called only once
            scheduler.Verify(ac => ac.ScheduleRefresh(It.IsAny <Auth0ClientSettings>()), Times.Once);
        }
コード例 #5
0
        public async Task Updates_with_username_and_password()
        {
            // setup
            var auth0serverUrl  = "https://localhost";
            var auth0Connection = "unit-test-connection";
            var apiClient       = new Mock <IAuthenticationApiClient>(MockBehavior.Strict);
            RoAuthenticationRequestDto authRequest = null;

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

            // execute
            await tokenProvider.AddOrUpdateClientAsync(auth0ClientSettings);

            // validate
            apiClient.Verify(ac => ac.AuthenticateAsync(It.IsAny <RoAuthenticationRequestDto>(), auth0serverUrl), Times.Once);
            Assert.NotNull(authRequest);
            authRequest.ClientId.Should().Be(auth0ClientSettings.Auth0ClientId);
            authRequest.Username.Should().Be(auth0ClientSettings.Auth0Username);
            authRequest.Password.Should().Be(auth0ClientSettings.Auth0Password);
            authRequest.Scope.Should().Be("openid");
            authRequest.Connection.Should().Be(auth0Connection);
            authRequest.GrantType.Should().Be("password");
            authRequest.Device.Should().Be("api");
        }
コード例 #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Auth0TokenProvider" /> class.
 /// </summary>
 /// <param name="defaultSettings">The settings.</param>
 /// <param name="autoScheduler">The auto-scheduler that refreshes the Auth0 token after X minutes.</param>
 public Auth0TokenProvider(ILoggerFactory loggerFactory, Auth0ClientSettings defaultSettings,
     IAuthenticationApiClient authenticationApiClient = null, IAutoScheduler autoScheduler = null)
     : base(loggerFactory, defaultSettings, authenticationApiClient)
 {
     this.autoScheduler = autoScheduler ?? new AutoScheduler(loggerFactory, this);
     defaultPassword = defaultSettings.Auth0Password;
     defaultUsername = defaultSettings.Auth0Username;
     defaultConnection = defaultSettings.Auth0Connection;
 }
コード例 #7
0
 protected BaseAuth0TokenProvider(ILoggerFactory loggerFactory, Auth0ClientSettings defaultSettings, IAuthenticationApiClient authenticationApiClient)
 {
     this.authenticationApiClient = authenticationApiClient ?? new AuthenticationApiClient();
     clientTokenCache = new ConcurrentDictionary<string, Auth0ClientSettings>();
     domainClientIdCache = new ConcurrentDictionary<string, string>();
     logger = loggerFactory.CreateLogger<BaseAuth0TokenProvider>();
     defaultDomain = defaultSettings.Auth0ServerUrl;
     defaultRefreshToken = defaultSettings.Auth0RefreshToken;
     defaultAutoRefreshAfter = defaultSettings.AutoRefreshAfter;
 }
コード例 #8
0
        private void ExecuteRefresh(Auth0ClientSettings auth0ClientSettings)
        {
            // log that we're refreshing
            logger.LogInformation($"Scheduling an automatic refresh of the Bearer token for client_id {auth0ClientSettings.Auth0ClientId} in {auth0ClientSettings.AutoRefreshAfter}.");

            // trigger the actual refresh
            var task = tokenProvider.AddOrUpdateClientAsync(auth0ClientSettings.Auth0ClientId);

            // log error cases
            task.ContinueWith(t => logger.LogError(0, t.Exception, $"Error while refreshing the Bearer token for client_id {auth0ClientSettings.Auth0ClientId}."), TaskContinuationOptions.OnlyOnFaulted);
        }
コード例 #9
0
        /// <summary>
        /// Locally caches Auth0 settings for a given client based on the <paramref name="settings"/> provided.
        /// If the <paramref name="settings"/> instance doesn't provide certain parameters, the provider falls
        /// back to the submitted default settings.
        /// </summary>
        public override void CacheAuthSettings(Auth0ClientSettings settings)
        {
            // apply defaults
            settings.Auth0ClientSecret = string.IsNullOrWhiteSpace(settings.Auth0ClientSecret) ? defaultClientSecret : settings.Auth0ClientSecret;
            settings.Auth0Audience = string.IsNullOrWhiteSpace(settings.Auth0Audience) ? defaultAudience : settings.Auth0Audience;
            settings.Auth0ServerUrl = string.IsNullOrWhiteSpace(settings.Auth0ServerUrl) ? defaultDomain : settings.Auth0ServerUrl;
            settings.Auth0RefreshToken = string.IsNullOrWhiteSpace(settings.Auth0RefreshToken) ? defaultRefreshToken : settings.Auth0RefreshToken;
            settings.AutoRefreshAfter = settings.AutoRefreshAfter == TimeSpan.MinValue ? defaultAutoRefreshAfter : settings.AutoRefreshAfter;

            // cache settings
            clientTokenCache.TryAdd(settings.Auth0ClientId, settings);
        }
コード例 #10
0
        /// <summary>
        /// Locally caches Auth0 settings for a given client based on the <paramref name="settings"/> provided.
        /// If the <paramref name="settings"/> instance doesn't provide certain parameters, the provider falls
        /// back to the submitted default settings.
        /// </summary>
        public override void CacheAuthSettings(Auth0ClientSettings settings)
        {
            // apply defaults
            settings.Auth0Username = string.IsNullOrWhiteSpace(settings.Auth0Username) ? defaultUsername : settings.Auth0Username;
            settings.Auth0Password = string.IsNullOrWhiteSpace(settings.Auth0Password) ? defaultPassword : settings.Auth0Password;
            settings.Auth0ServerUrl = string.IsNullOrWhiteSpace(settings.Auth0ServerUrl) ? defaultDomain : settings.Auth0ServerUrl;
            settings.Auth0Connection = string.IsNullOrWhiteSpace(settings.Auth0Connection) ? defaultConnection : settings.Auth0Connection;
            settings.Auth0RefreshToken = string.IsNullOrWhiteSpace(settings.Auth0RefreshToken) ? defaultRefreshToken : settings.Auth0RefreshToken;
            settings.AutoRefreshAfter = settings.AutoRefreshAfter == TimeSpan.MinValue ? defaultAutoRefreshAfter : settings.AutoRefreshAfter;

            // cache settings
            clientTokenCache.TryAdd(settings.Auth0ClientId, settings);
        }
コード例 #11
0
        public async Task Does_not_reauthenticate_within_a_short_period_of_time_for_refresh_token()
        {
            // setup
            var apiClient = new Mock<IAuthenticationApiClient>(MockBehavior.Strict);
            apiClient.Setup(ac => ac.GetDelegationTokenAsync(It.IsAny<RefreshTokenDelegationRequestDto>(), It.IsAny<string>()))
                .Returns(Task.FromResult(new AccessToken { IdToken = Guid.NewGuid().ToString() }));
            var tokenProvider = new Auth0TokenProvider(loggerFactor.Object, new Auth0ClientSettings { Auth0ServerUrl = Guid.NewGuid().ToString() }, apiClient.Object, autoScheduler.Object);
            var auth0ClientSettings = new Auth0ClientSettings { Auth0ClientId = Guid.NewGuid().ToString(), Auth0RefreshToken = Guid.NewGuid().ToString() };

            // execute twice
            await tokenProvider.AddOrUpdateClientAsync(auth0ClientSettings);
            await tokenProvider.AddOrUpdateClientAsync(auth0ClientSettings);

            // validate that it was called only once
            apiClient.Verify(ac => ac.GetDelegationTokenAsync(It.IsAny<RefreshTokenDelegationRequestDto>(), It.IsAny<string>()), Times.Once);
        }
コード例 #12
0
        public void Triggers_refresh_when_auto_scheduling()
        {
            // setup
            var resetEvent = new ManualResetEvent(false);
            var clientSettings = new Auth0ClientSettings {Auth0ClientId = Guid.NewGuid().ToString(), AutoRefreshAfter = TimeSpan.FromTicks(1)};
            var tokenProvider = new Mock<IAuth0TokenProvider>(MockBehavior.Strict);
            tokenProvider.Setup(tp => tp.AddOrUpdateClientAsync(clientSettings.Auth0ClientId, false)).Callback(() => resetEvent.Set()).Returns(Task.FromResult(true));
            var scheduler = new AutoScheduler(loggerFactory.Object, tokenProvider.Object);

            // execute
            scheduler.ScheduleRefresh(clientSettings);

            // validate
            resetEvent.WaitOne(TimeSpan.FromSeconds(10));
            tokenProvider.Verify(tp => tp.AddOrUpdateClientAsync(clientSettings.Auth0ClientId, false), Times.Once);
        }
コード例 #13
0
        public void Triggers_refresh_when_auto_scheduling()
        {
            // setup
            var resetEvent     = new ManualResetEvent(false);
            var clientSettings = new Auth0ClientSettings {
                Auth0ClientId = Guid.NewGuid().ToString(), AutoRefreshAfter = TimeSpan.FromTicks(1)
            };
            var tokenProvider = new Mock <IAuth0TokenProvider>(MockBehavior.Strict);

            tokenProvider.Setup(tp => tp.AddOrUpdateClientAsync(clientSettings.Auth0ClientId, false)).Callback(() => resetEvent.Set()).Returns(Task.FromResult(true));
            var scheduler = new AutoScheduler(loggerFactory.Object, tokenProvider.Object);

            // execute
            scheduler.ScheduleRefresh(clientSettings);

            // validate
            resetEvent.WaitOne(TimeSpan.FromSeconds(10));
            tokenProvider.Verify(tp => tp.AddOrUpdateClientAsync(clientSettings.Auth0ClientId, false), Times.Once);
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: Cimpress/FomaSdk.Net
        private HttpClient CreateHttpClient(ILoggerFactory loggerFactory, string username, string password)
        {
            // settings take from the Cimpress documentation: https://cimpress-support.atlassian.net/wiki/spaces/CI/pages/168001556/Password-Realm+Grants
            Auth0ClientSettings clientSettings = new Auth0ClientSettings
            {
                Auth0ServerUrl = "https://cimpress.auth0.com/",
                Auth0Audience  = "https://api.cimpress.io/",
                Auth0ClientId  = "ST0wwOc0RavK6P6hhAPZ9Oc2XFD2dGUF",
                Auth0GrantType = "http://auth0.com/oauth/grant-type/password-realm",
                Auth0Realm     = "default",
                Auth0Username  = username,
                Auth0Password  = password
            };
            IAuth0TokenProvider tokenProvider = new PasswordRealmTokenProvider(loggerFactory, clientSettings);
            var measurementHandler            = new MeasurementHandler(loggerFactory.CreateLogger <Program>());
            var handler = new AuthHandler(measurementHandler, loggerFactory.CreateLogger <Program>(), tokenProvider);

            return(new HttpClient(handler));
        }
コード例 #15
0
        public async Task Updates_with_refresh_token()
        {
            // setup
            var auth0serverUrl = "https://localhost";
            var apiClient = new Mock<IAuthenticationApiClient>(MockBehavior.Strict);
            RefreshTokenDelegationRequestDto delegationRequest = null;
            apiClient.Setup(ac => ac.GetDelegationTokenAsync(It.IsAny<RefreshTokenDelegationRequestDto>(), auth0serverUrl))
                .Callback((DelegationRequestBaseDto token, string server) => delegationRequest = token as RefreshTokenDelegationRequestDto)
                .Returns(Task.FromResult(new AccessToken { IdToken = Guid.NewGuid().ToString() }));
            var tokenProvider = new Auth0TokenProvider(loggerFactor.Object, new Auth0ClientSettings {Auth0ServerUrl = auth0serverUrl}, apiClient.Object, autoScheduler.Object);
            var auth0ClientSettings = new Auth0ClientSettings { Auth0ClientId = Guid.NewGuid().ToString(), Auth0RefreshToken = Guid.NewGuid().ToString() };

            // execute
            await tokenProvider.AddOrUpdateClientAsync(auth0ClientSettings);

            // validate
            apiClient.Verify(ac => ac.GetDelegationTokenAsync(It.IsAny<DelegationRequestBaseDto>(), auth0serverUrl), Times.Once);
            Assert.NotNull(delegationRequest);
            delegationRequest.RefreshToken.Should().Be(auth0ClientSettings.Auth0RefreshToken);
            delegationRequest.SourceClientId.Should().Be(auth0ClientSettings.Auth0ClientId);
            delegationRequest.TargetClientId.Should().Be(auth0ClientSettings.Auth0ClientId);
        }
コード例 #16
0
        public void ScheduleRefresh(Auth0ClientSettings auth0ClientSettings)
        {
            // do not auto-refresh
            if (auth0ClientSettings.AutoRefreshAfter <= TimeSpan.Zero)
            {
                logger.LogDebug($"Not scheduling an automatic refresh of the Bearer token for client_id {auth0ClientSettings.Auth0ClientId} " +
                                $"and auto-refresh settings {auth0ClientSettings.AutoRefreshAfter}.");
                return;
            }

            lock (syncObj)
            {
                // add timer is it doesn't exist for the given client id
                if (!triggers.ContainsKey(auth0ClientSettings.Auth0ClientId))
                {
                    triggers.Add(auth0ClientSettings.Auth0ClientId,
                        new Timer(state => ExecuteRefresh((Auth0ClientSettings) state), auth0ClientSettings, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan));
                }

                // trigger refresh after given time
                triggers[auth0ClientSettings.Auth0ClientId].Change(auth0ClientSettings.AutoRefreshAfter, Timeout.InfiniteTimeSpan);
            }
        }
コード例 #17
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");
        }
コード例 #18
0
        public async Task Reauthenticate_within_a_short_period_of_time_when_forced_for_username_password()
        {
            // setup
            var apiClient = new Mock <IAuthenticationApiClient>(MockBehavior.Strict);

            apiClient.Setup(ac => ac.AuthenticateAsync(It.IsAny <RoAuthenticationRequestDto>(), It.IsAny <string>()))
            .Returns(Task.FromResult(new AuthenticationResponseDto {
                IdToken = Guid.NewGuid().ToString()
            }));
            var tokenProvider = new Auth0TokenProvider(loggerFactor.Object, new Auth0ClientSettings {
                Auth0ServerUrl = Guid.NewGuid().ToString()
            }, apiClient.Object, autoScheduler.Object);
            var auth0ClientSettings = new Auth0ClientSettings {
                Auth0ClientId = Guid.NewGuid().ToString(), Auth0Username = Guid.NewGuid().ToString(), Auth0Password = Guid.NewGuid().ToString()
            };

            // execute twice
            await tokenProvider.AddOrUpdateClientAsync(auth0ClientSettings);

            await tokenProvider.AddOrUpdateClientAsync(auth0ClientSettings, true);

            // validate that it was called only once
            apiClient.Verify(ac => ac.AuthenticateAsync(It.IsAny <RoAuthenticationRequestDto>(), It.IsAny <string>()), Times.Exactly(2));
        }
コード例 #19
0
        public async Task Does_not_reauthenticate_within_a_short_period_of_time_for_client_secret()
        {
            // setup
            var apiClient = new Mock <IAuthenticationApiClient>(MockBehavior.Strict);

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

            // execute twice
            await tokenProvider.AddOrUpdateClientAsync(auth0ClientSettings);

            await tokenProvider.AddOrUpdateClientAsync(auth0ClientSettings);

            // validate that it was called only once
            apiClient.Verify(ac => ac.TokenAuthenticateAsync(It.IsAny <TokenAuthenticationRequestDto>(), It.IsAny <string>()), Times.Once);
        }
コード例 #20
0
 internal void ScheduleAutoRefresh(Auth0ClientSettings auth0ClientSettings, IAutoScheduler autoScheduler)
 {
     autoScheduler.ScheduleRefresh(auth0ClientSettings);
 }
コード例 #21
0
        private Auth0ClientSettings GetSettingsFromResponseHeader(HttpHeaderValueCollection<AuthenticationHeaderValue> wwwAuthenticationHeaderValues)
        {
            var result = new Auth0ClientSettings();

            foreach (var authenticationHeaderValue in wwwAuthenticationHeaderValues)
            {
                if (authenticationHeaderValue.Scheme.ToLowerInvariant() == "bearer")
                {
                    // The header looks like this: WWW-Authenticate: Bearer realm="example.auth0.com", scope="client_id=xxxxxxxxxx service=https://myservice.example.com"
                    // First we have to split on white spaces that are not within '" "'.
                    var parameters = Regex.Matches(authenticationHeaderValue.Parameter, "\\w+\\=\\\".*?\\\"|\\w+[^\\s\\\"]+?");

                    foreach (var param in parameters)
                    {
                        var parameterstring = param.ToString();
                        var info = parameterstring.Trim().Split('=');
                        if (info.Length < 2)
                        {
                            continue;
                        }

                        // Realm has only 1 value.
                        if ((info[0].ToLowerInvariant()) == "realm")
                        {
                            var domain = info[1].Replace("\"", "");
                            domain = domain.ToLowerInvariant().StartsWith("http") ? domain : $"https://{domain}";
                            result.Auth0ServerUrl = domain;
                            continue;
                        }

                        // Within the scope we can have multiple key/value pairs separated by white space.
                        if (info[0].ToLowerInvariant() == "scope")
                        {
                            var scopes = parameterstring.Substring(info[0].Length + 1).Replace("\"", "").Split(' ');
                            foreach (var scope in scopes)
                            {
                                var splittedScope = scope.Split('=');
                                if (splittedScope.Length < 2)
                                {
                                    continue;
                                }

                                // We are interested in the client id.
                                if ((splittedScope[0]?.ToLowerInvariant() ?? "") == "client_id")
                                {
                                    result.Auth0ClientId = splittedScope[1];
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            return result;
        }
コード例 #22
0
 public abstract void ScheduleAutoRefresh(Auth0ClientSettings auth0ClientSettings);
コード例 #23
0
 public abstract void CacheAuthSettings(Auth0ClientSettings settings);
コード例 #24
0
 public override void ScheduleAutoRefresh(Auth0ClientSettings auth0ClientSettings)
 {
     autoScheduler.ScheduleRefresh(auth0ClientSettings);
 }
コード例 #25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Auth0v2TokenProvider" /> class.
 /// </summary>
 /// <param name="defaultSettings">The settings.</param>
 /// <param name="autoScheduler">The auto-scheduler that refreshes the Auth0 token after X minutes.</param>
 public Auth0v2TokenProvider(ILoggerFactory loggerFactory, Auth0ClientSettings defaultSettings, IAuthenticationApiClient authenticationApiClient = null, IAutoScheduler autoScheduler = null) : base(loggerFactory, defaultSettings, authenticationApiClient)
 {
     this.autoScheduler = autoScheduler ?? new AutoScheduler(loggerFactory, this);
     defaultClientSecret = defaultSettings.Auth0ClientSecret;
     defaultAudience = defaultSettings.Auth0Audience;
 }
コード例 #26
0
 /// <summary>
 /// Adds or updates the client asynchronously.
 /// </summary>
 /// <param name="settings">The settings.</param>
 /// <param name="forceRefresh">if set to <c>true</c> [force refresh].</param>
 /// <remarks>Set to false during injection of pre-known clients to speed up initialization.</remarks>
 public async Task AddOrUpdateClientAsync(Auth0ClientSettings settings, bool forceRefresh = false)
 {
     CacheAuthSettings(settings);
     await UpdateAuthHeaderAsync(settings.Auth0ClientId, forceRefresh);
 }
コード例 #27
0
        public async Task Reauthenticate_within_a_short_period_of_time_when_forced_for_username_password()
        {
            // setup
            var apiClient = new Mock<IAuthenticationApiClient>(MockBehavior.Strict);
            apiClient.Setup(ac => ac.AuthenticateAsync(It.IsAny<RoAuthenticationRequestDto>(), It.IsAny<string>()))
                 .Returns(Task.FromResult(new AuthenticationResponseDto { IdToken = Guid.NewGuid().ToString() }));
            var tokenProvider = new Auth0TokenProvider(loggerFactor.Object, new Auth0ClientSettings { Auth0ServerUrl = Guid.NewGuid().ToString() }, apiClient.Object, autoScheduler.Object);
            var auth0ClientSettings = new Auth0ClientSettings { Auth0ClientId = Guid.NewGuid().ToString(), Auth0Username = Guid.NewGuid().ToString(), Auth0Password = Guid.NewGuid().ToString() };

            // execute twice
            await tokenProvider.AddOrUpdateClientAsync(auth0ClientSettings);
            await tokenProvider.AddOrUpdateClientAsync(auth0ClientSettings, true);

            // validate that it was called only once
            apiClient.Verify(ac => ac.AuthenticateAsync(It.IsAny<RoAuthenticationRequestDto>(), It.IsAny<string>()), Times.Exactly(2));
        }
コード例 #28
0
        public async Task Schedules_auto_refresh_for_username_password()
        {
            // setup
            var apiClient = new Mock<IAuthenticationApiClient>(MockBehavior.Strict);
            apiClient.Setup(ac => ac.AuthenticateAsync(It.IsAny<RoAuthenticationRequestDto>(), It.IsAny<string>()))
                 .Returns(Task.FromResult(new AuthenticationResponseDto { IdToken = Guid.NewGuid().ToString() }));
            var scheduler = new Mock<IAutoScheduler>(MockBehavior.Strict);
            scheduler.Setup(s => s.ScheduleRefresh(It.IsAny<Auth0ClientSettings>()));
            var tokenProvider = new Auth0TokenProvider(loggerFactor.Object, new Auth0ClientSettings { Auth0ServerUrl = Guid.NewGuid().ToString() }, apiClient.Object, scheduler.Object);
            var auth0ClientSettings = new Auth0ClientSettings { Auth0ClientId = Guid.NewGuid().ToString(), Auth0Username = Guid.NewGuid().ToString(), Auth0Password = Guid.NewGuid().ToString() };

            // execute twice
            await tokenProvider.AddOrUpdateClientAsync(auth0ClientSettings);

            // validate that it was called only once
            scheduler.Verify(ac => ac.ScheduleRefresh(It.IsAny<Auth0ClientSettings>()), Times.Once);
        }