Ejemplo n.º 1
0
        public async Task <AccessTokenResult> ValidateToken(HttpRequest request)
        {
            try
            {
                if (request == null || !request.Headers.ContainsKey(AUTH_HEADER_NAME) ||
                    !request.Headers[AUTH_HEADER_NAME].ToString().StartsWith(BEARER_PREFIX))
                {
                    return(AccessTokenResult.NoToken());
                }

                var config = await _configurationManager.GetConfigurationAsync(CancellationToken.None);

                var token = request.Headers[AUTH_HEADER_NAME].ToString().Substring(BEARER_PREFIX.Length);

                var tokenParams = new TokenValidationParameters
                {
                    RequireSignedTokens      = true,
                    ValidAudience            = _audience,
                    ValidateAudience         = true,
                    ValidIssuer              = _issuer,
                    ValidateIssuer           = true,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime         = true,
                    IssuerSigningKeys        = config.SigningKeys
                };

                var result = new JwtSecurityTokenHandler()
                             .ValidateToken(token, tokenParams, out _);

                using (var client = new HttpClient())
                {
                    var userInfo = await client.GetUserInfoAsync(new UserInfoRequest
                    {
                        Address = config.UserInfoEndpoint,
                        Token   = token
                    });

                    if (userInfo.IsError)
                    {
                        throw userInfo.Exception;
                    }

                    var identity = new ClaimsIdentity(result.Identities.First());
                    identity.AddClaims(userInfo.Claims);

                    return(AccessTokenResult.Success(new ClaimsPrincipal(identity)));
                }
            }
            catch (SecurityTokenExpiredException)
            {
                return(AccessTokenResult.Expired());
            }
            catch (Exception ex)
            {
                return(AccessTokenResult.Error(ex));
            }
        }
Ejemplo n.º 2
0
        public static string EmailAddress(this AccessTokenResult accessTokenResult)
        {
            if (accessTokenResult.Status != AccessTokenStatus.Valid)
            {
                throw new AuthenticationException("Token invalid", accessTokenResult.Exception);
            }

            return(accessTokenResult.Principal.Claims
                   .First(x => x.Type.Equals("email", StringComparison.InvariantCultureIgnoreCase))
                   .Value);
        }