示例#1
0
        private async Task InitializeAsync(string scheme)
        {
            if (string.IsNullOrEmpty(scheme))
            {
                var defaultScheme = await _authenticationSchemeProvider.GetDefaultAuthenticateSchemeAsync();

                if (defaultScheme != null && defaultScheme.HandlerType == typeof(ApiTokenHandler))
                {
                    _innerScheme = defaultScheme.Name;
                }
                else
                {
                    throw new InvalidOperationException($"Default authenticate scheme type is not {typeof(ApiTokenHandler).FullName}, you must be to set scheme.");
                }
            }

            _options = _optionsMonitor.Get(_innerScheme);
        }
示例#2
0
        public virtual async Task <ClaimsPrincipal> ValidateTokenAsync(ApiTokenOptions options, [NotNull] string token, string schemeName)
        {
            TokenModel tokenModel = null;

            //Get from cache
            if (options.UseCache)
            {
                var tokenModelCache = await _cacheService.GetAsync(token, schemeName);

                if (tokenModelCache != null)
                {
                    if (tokenModelCache.Available)
                    {
                        tokenModel = tokenModelCache.Token;
                    }
                    else
                    {
                        throw new TokenInvalidException("matching token could not be found from cache");
                    }
                }
            }

            //If cache return null, then get from db
            if (tokenModel == null)
            {
                var queryTokenModel = await _store.GetAsync(token, schemeName);

                if (queryTokenModel != null && queryTokenModel.IsValid)
                {
                    tokenModel = queryTokenModel;
                }

                //set cache
                if (tokenModel != null && options.UseCache)
                {
                    await _cacheService.SetAsync(tokenModel);
                }
            }

            if (tokenModel == null)
            {
                if (options.UseCache)
                {
                    await _cacheService.SetNullAsync(token, schemeName);
                }

                throw new TokenInvalidException("matching token could not be found");
            }

            //Check expiration
            if (!tokenModel.IsValid)
            {
                throw new TokenExpiredException("Token expired at " + tokenModel.Expiration, tokenModel.Expiration.DateTime);
            }

            //Generate ClaimsPrincipal
            var claims = tokenModel.Claims;

            var result = new ClaimsPrincipal();

            result.AddIdentity(new ClaimsIdentity(claims, schemeName, options.NameClaimType, options.RoleClaimType));

            return(result);
        }