コード例 #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));
            }
        }
コード例 #2
0
        public void TestBadRequestNoAuthToken()
        {
            var principal = AccessTokenResult.NoToken();

            tokenProvider.Setup(t => t.ValidateToken(It.IsAny <HttpRequest>())).Returns(principal);

            var request  = TestFactory.CreateHttpRequest("");
            var response = (UnauthorizedResult)_fixture.Run(request, testLogger);

            Assert.AreEqual(response.StatusCode, StatusCodes.Status401Unauthorized);
        }
コード例 #3
0
        public async void NoToken_ShouldReturnException()
        {
            var request  = TestFactory.CreateHttpRequest();
            var settings = new InMemoryConfigurationService();

            settings.SetValue(ConfigurationServiceWellKnownKeys.JwtTokenSignatureKey, base.TokenSignatureKey);
            var userFunctionsHost = new UserFunctions(new UserService(new InMemoryUserStore(), settings), settings);

            var response = await userFunctionsHost.RunRefreshToken(request, AccessTokenResult.NoToken(), Logger);

            Assert.NotNull(response as StatusCodeResult);
            Assert.Equal(401, (response as StatusCodeResult).StatusCode);
        }
        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));
            }
        }
コード例 #5
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));
            }
        }