示例#1
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;
 }
示例#2
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);
        }
示例#3
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;
 }
        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);
        }
示例#5
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);
        }
示例#6
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);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="Auth0TokenProvider" /> class.
 /// </summary>
 /// <param name="loggerFactory">The logger factory.</param>
 /// <param name="defaultSettings">The settings.</param>
 /// <param name="authenticationApiClient">The optional AuthenticationApiClient to use. Usually not required to use the built-in client.</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)
 {
     this.autoScheduler           = autoScheduler ?? new AutoScheduler(loggerFactory, this);
     this.authenticationApiClient = authenticationApiClient ?? new AuthenticationApiClient();
     clientTokenCache             = new ConcurrentDictionary <string, Auth0ClientSettings>();
     domainClientIdCache          = new ConcurrentDictionary <string, string>();
     logger                  = loggerFactory.CreateLogger <Auth0TokenProvider>();
     defaultDomain           = defaultSettings.Auth0ServerUrl;
     defaultPassword         = defaultSettings.Auth0Password;
     defaultUsername         = defaultSettings.Auth0Username;
     defaultConnection       = defaultSettings.Auth0Connection;
     defaultRefreshToken     = defaultSettings.Auth0RefreshToken;
     defaultAutoRefreshAfter = defaultSettings.AutoRefreshAfter;
 }
        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);
            }
        }
示例#9
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);
 }
示例#10
0
 public abstract void CacheAuthSettings(Auth0ClientSettings settings);
示例#11
0
 public abstract void ScheduleAutoRefresh(Auth0ClientSettings auth0ClientSettings);
示例#12
0
 internal void ScheduleAutoRefresh(Auth0ClientSettings auth0ClientSettings, IAutoScheduler autoScheduler)
 {
     autoScheduler.ScheduleRefresh(auth0ClientSettings);
 }
示例#13
0
 public override void ScheduleAutoRefresh(Auth0ClientSettings auth0ClientSettings)
 {
     autoScheduler.ScheduleRefresh(auth0ClientSettings);
 }
示例#14
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;
 }
 private void ScheduleAutoRefresh(Auth0ClientSettings auth0ClientSettings)
 {
     autoScheduler.ScheduleRefresh(auth0ClientSettings);
 }