This class extends the implementation of JWTSecurityTokenHandler to read configuration settings from the token handler configuration if its initialized by WIF. It falls back on App settings if the configuration object is null.
상속: JWTSecurityTokenHandler
예제 #1
0
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            Check.IsNotNull(request, "request");
            HttpStatusCode statusCode;
            string         token;

            if (request.RequestUri.AbsolutePath.Contains("/authenticate"))
            {
                return(base.SendAsync(request, cancellationToken));
            }

            if (request.RequestUri.AbsolutePath.Contains("/signout"))
            {
                return(base.SendAsync(request, cancellationToken));
            }

            if (request.RequestUri.AbsolutePath.Contains("/SignOutCallback"))
            {
                return(base.SendAsync(request, cancellationToken));
            }

            if (request.RequestUri.AbsolutePath.Contains("/windowsLiveAuthorization"))
            {
                return(base.SendAsync(request, cancellationToken));
            }

            if (request.RequestUri.AbsolutePath.Contains("api/GetSupportedIdentityProviders"))
            {
                return(base.SendAsync(request, cancellationToken));
            }

            if (request.RequestUri.AbsolutePath.Contains("api/SignInCallBack"))
            {
                return(base.SendAsync(request, cancellationToken));
            }

            if (!TryRetrieveToken(request, out token))
            {
                statusCode = HttpStatusCode.Unauthorized;
                return(Task <HttpResponseMessage> .Factory.StartNew(() => new HttpResponseMessage(statusCode)));
            }

            try
            {
                diagnostics.WriteInformationTrace(TraceEventId.Flow, "Validating bearer token: {0}", token);

                string issuersValue        = ConfigurationManager.AppSettings["Issuers"];
                string signingSymmetricKey = ConfigurationManager.AppSettings["SigningSymmetricKey"];
                string allowedAudience     = ConfigurationManager.AppSettings["AllowedAudience"];

                // Use JWTSecurityTokenHandler to validate the JWT token
                ApiJWTSecurityTokenHandler tokenHandler = new ApiJWTSecurityTokenHandler();

                List <string> issuers = new List <string>();
                issuers.AddRange(issuersValue.Split(new[] { ',' }));

                InMemorySymmetricSecurityKey securityKey = new InMemorySymmetricSecurityKey(Convert.FromBase64String(signingSymmetricKey));

                NamedKeySecurityToken namedToken = new NamedKeySecurityToken(allowedAudience, new List <SecurityKey>()
                {
                    securityKey
                });

                // Set the expected properties of the JWT token in the TokenValidationParameters
                TokenValidationParameters validationParameters = new TokenValidationParameters()
                {
                    AllowedAudience = allowedAudience,
                    ValidIssuers    = issuers,
                    SigningToken    = namedToken
                };

                ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(token, validationParameters);
                ClaimsIdentity  claimsIdentity  = (ClaimsIdentity)claimsPrincipal.Identity;
                try
                {
                    IUserService userService = (IUserService)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IUserService));
                    User         user        = IdentityHelper.GetCurrentUser(userService, claimsPrincipal);
                    foreach (var role in user.UserRoles)
                    {
                        if (!claimsIdentity.HasClaim(ClaimTypes.Role, role.Role.Name))
                        {
                            claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, role.Role.Name));
                        }
                    }
                }
                catch (UserNotFoundException)
                {
                    // No need to do anything here because GetUsersByNameIdentifier action in UsersController will take care of sending appropriate http response.
                }

                Thread.CurrentPrincipal = claimsPrincipal;
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.User = claimsPrincipal;
                }

                diagnostics.WriteInformationTrace(TraceEventId.Flow,
                                                  "Authorization token validated successfully");

                return(base.SendAsync(request, cancellationToken));
            }
            catch (SecurityTokenValidationException secutiryTokenValidationException)
            {
                FederatedAuthentication.WSFederationAuthenticationModule.SignOut(true);
                HttpResponseMessage response = request.CreateErrorResponse(HttpStatusCode.Unauthorized, secutiryTokenValidationException);
                return(Task <HttpResponseMessage> .Factory.StartNew(() => response));
            }
        }
예제 #2
0
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            Check.IsNotNull(request, "request");
            HttpStatusCode statusCode;
            string token;
          
            if (request.RequestUri.AbsolutePath.Contains("/authenticate"))
            {
                return base.SendAsync(request, cancellationToken);
            }

            if (request.RequestUri.AbsolutePath.Contains("/signout"))
            {
                return base.SendAsync(request, cancellationToken);
            }

            if (request.RequestUri.AbsolutePath.Contains("/SignOutCallback"))
            {
                return base.SendAsync(request, cancellationToken);
            }

            if (request.RequestUri.AbsolutePath.Contains("/windowsLiveAuthorization"))
            {
                return base.SendAsync(request, cancellationToken);
            }

            if (request.RequestUri.AbsolutePath.Contains("api/GetSupportedIdentityProviders"))
            {
                return base.SendAsync(request, cancellationToken);
            }

            if (request.RequestUri.AbsolutePath.Contains("api/SignInCallBack"))
            {
                return base.SendAsync(request, cancellationToken);
            }

            if (!TryRetrieveToken(request, out token))
            {
                statusCode = HttpStatusCode.Unauthorized;
                return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(statusCode));
            }

            try
            {
                diagnostics.WriteInformationTrace(TraceEventId.Flow, "Validating bearer token: {0}", token);

                string issuersValue = ConfigurationManager.AppSettings["Issuers"];
                string signingSymmetricKey = ConfigurationManager.AppSettings["SigningSymmetricKey"];
                string allowedAudience = ConfigurationManager.AppSettings["AllowedAudience"];

                // Use JWTSecurityTokenHandler to validate the JWT token
                ApiJWTSecurityTokenHandler tokenHandler = new ApiJWTSecurityTokenHandler();

                List<string> issuers = new List<string>();
                issuers.AddRange(issuersValue.Split(new[] { ',' }));

                InMemorySymmetricSecurityKey securityKey = new InMemorySymmetricSecurityKey(Convert.FromBase64String(signingSymmetricKey));

                NamedKeySecurityToken namedToken = new NamedKeySecurityToken(allowedAudience, new List<SecurityKey>() { securityKey });

                // Set the expected properties of the JWT token in the TokenValidationParameters
                TokenValidationParameters validationParameters = new TokenValidationParameters()
                {
                    AllowedAudience = allowedAudience,
                    ValidIssuers = issuers,
                    SigningToken = namedToken
                };

                ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(token, validationParameters);
                ClaimsIdentity claimsIdentity = (ClaimsIdentity)claimsPrincipal.Identity;
                try
                {
                    IUserService userService = (IUserService)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IUserService));
                    User user = IdentityHelper.GetCurrentUser(userService, claimsPrincipal);
                    foreach (var role in user.UserRoles)
                    {
                        if (!claimsIdentity.HasClaim(ClaimTypes.Role, role.Role.Name))
                        {
                            claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, role.Role.Name));
                        }
                    }
                }
                catch (UserNotFoundException)
                {
                    // No need to do anything here because GetUsersByNameIdentifier action in UsersController will take care of sending appropriate http response.
                }

                Thread.CurrentPrincipal = claimsPrincipal;
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.User = claimsPrincipal;
                }

                diagnostics.WriteInformationTrace(TraceEventId.Flow,
                                        "Authorization token validated successfully");

                return base.SendAsync(request, cancellationToken);
            }
            catch (SecurityTokenValidationException secutiryTokenValidationException)
            {
                FederatedAuthentication.WSFederationAuthenticationModule.SignOut(true);
                HttpResponseMessage response = request.CreateErrorResponse(HttpStatusCode.Unauthorized, secutiryTokenValidationException);
                return Task<HttpResponseMessage>.Factory.StartNew(() => response);
            }
        }