Beispiel #1
0
        public static AccessTokenResult ValidateToken(string token)
        {
            try
            {
                if (string.IsNullOrEmpty(token))
                {
                    return(AccessTokenResult.NoToken());
                }

                var tokenParams = new TokenValidationParameters()
                {
                    RequireSignedTokens      = true,
                    ValidAudience            = _jwtAudience,
                    ValidateAudience         = true,
                    ValidIssuer              = _jwtIssuer,
                    ValidateIssuer           = true,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime         = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtIssuerSigningKey))
                };

                // Validate the token
                var handler = new JwtSecurityTokenHandler();
                var result  = handler.ValidateToken(token, tokenParams, out var securityToken);
                return(AccessTokenResult.Success(result));
            }
            catch (SecurityTokenExpiredException)
            {
                return(AccessTokenResult.Expired());
            }
            catch (Exception ex)
            {
                return(AccessTokenResult.Error(ex));
            }
        }
        public async Task <object> GetValueAsync()
        {
            try
            {
                // Get the token from the header
                if (request.Headers.ContainsKey(AUTH_HEADER_NAME) &&
                    request.Headers[AUTH_HEADER_NAME].ToString().StartsWith(BEARER_PREFIX))
                {
                    var accessToken = request.Headers["Authorization"].ToString().Substring(BEARER_PREFIX.Length);

                    // Debugging purposes only, set this to false for production
                    Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;

                    ConfigurationManager <OpenIdConnectConfiguration> configManager =
                        new ConfigurationManager <OpenIdConnectConfiguration>(
                            $"{authConfig.Value.Authority}/.well-known/openid-configuration",
                            new OpenIdConnectConfigurationRetriever());

                    OpenIdConnectConfiguration config = null;
                    config = await configManager.GetConfigurationAsync();

                    ISecurityTokenValidator tokenValidator = new JwtSecurityTokenHandler();

                    // Initialize the token validation parameters
                    TokenValidationParameters validationParameters = new TokenValidationParameters
                    {
                        // App Id URI and AppId of this service application are both valid audiences.
                        ValidAudiences = new[] { authConfig.Value.Audience, authConfig.Value.ClientID },

                        // Support Azure AD V1 and V2 endpoints.
                        ValidIssuers      = authConfig.Value.ValidIssuers,
                        IssuerSigningKeys = config.SigningKeys
                    };

                    var claimsPrincipal = tokenValidator.ValidateToken(accessToken, validationParameters, out SecurityToken securityToken);
                    return(AccessTokenResult.Success(claimsPrincipal, securityToken));
                }
                else
                {
                    return(AccessTokenResult.NoToken());
                }
            }
            catch (SecurityTokenExpiredException)
            {
                return(AccessTokenResult.Expired());
            }
            catch (Exception ex)
            {
                return(AccessTokenResult.Error(ex));
            }
        }
Beispiel #3
0
        private AccessTokenResult ValidateToken(HttpRequest request)
        {
            try
            {
                var audience      = FunctionConfigs.Audience;
                var issuer        = FunctionConfigs.Issuer;
                var mySecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(FunctionConfigs.IssuerToken));
                // Get the token from the header
                if (request != null &&
                    request.Headers.ContainsKey(AUTH_HEADER_NAME) &&
                    request.Headers[AUTH_HEADER_NAME].ToString().StartsWith(BEARER_PREFIX))
                {
                    var token = request.Headers[AUTH_HEADER_NAME].ToString().Substring(BEARER_PREFIX.Length);

                    // Create the parameters
                    var tokenParams = new TokenValidationParameters()
                    {
                        RequireSignedTokens      = true,
                        ValidAudience            = audience,
                        ValidateAudience         = true,
                        ValidIssuer              = issuer,
                        ValidateIssuer           = true,
                        ValidateIssuerSigningKey = true,
                        ValidateLifetime         = true,
                        IssuerSigningKey         = mySecurityKey
                    };

                    // Validate the token
                    var handler = new JwtSecurityTokenHandler();
                    var result  = handler.ValidateToken(token, tokenParams, out var securityToken);
                    return(AccessTokenResult.Success(result));
                }
                else
                {
                    return(AccessTokenResult.NoToken());
                }
            }
            catch (SecurityTokenExpiredException)
            {
                return(AccessTokenResult.Expired());
            }
            catch (Exception ex)
            {
                return(AccessTokenResult.Error(ex));
            }
        }
Beispiel #4
0
        public async Task <object> GetValueAsync()
        {
            try
            {
                var accessTokenProvider = _request.HttpContext.RequestServices.GetRequiredService <IAccessTokenProvider>();

                var result = await accessTokenProvider.ValidateToken(_request);

                return(AccessTokenResult.Success(result.Principal));
            }
            catch (SecurityTokenExpiredException)
            {
                return(AccessTokenResult.Expired());
            }
            catch (Exception ex)
            {
                return(AccessTokenResult.Error(ex));
            }
        }