Exemplo n.º 1
0
        public static string GenerateTokenJwt(string username)
        {
            // appsetting for Token JWT
            var secretKey     = Utilerias.JWT_Secret_Key();
            var audienceToken = Utilerias.JWT_Audience_Token();
            var issuerToken   = Utilerias.JWT_Issuer_Token();
            var expireTime    = Utilerias.JWT_Expire_Minutes();

            var securityKey        = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(secretKey));
            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

            // create a claimsIdentity
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) });

            // create token to the user
            var tokenHandler     = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var jwtSecurityToken = tokenHandler.CreateJwtSecurityToken(
                audience: audienceToken,
                issuer: issuerToken,
                subject: claimsIdentity,
                notBefore: DateTime.UtcNow,
                expires: DateTime.UtcNow.AddMinutes(Convert.ToInt32(expireTime)),
                signingCredentials: signingCredentials);

            var jwtTokenString = tokenHandler.WriteToken(jwtSecurityToken);

            return(jwtTokenString);
        }
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpStatusCode statusCode;
            string         token;

            // determine whether a jwt exists or not
            if (!TryRetrieveToken(request, out token))
            {
                statusCode = HttpStatusCode.Unauthorized;
                return(base.SendAsync(request, cancellationToken));
            }

            try
            {
                var secretKey     = Utilerias.JWT_Secret_Key();
                var audienceToken = Utilerias.JWT_Audience_Token();
                var issuerToken   = Utilerias.JWT_Issuer_Token();
                var securityKey   = new SymmetricSecurityKey(Encoding.Default.GetBytes(secretKey));

                SecurityToken             securityToken;
                var                       tokenHandler         = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
                TokenValidationParameters validationParameters = new TokenValidationParameters()
                {
                    ValidAudience            = audienceToken,
                    ValidIssuer              = issuerToken,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    LifetimeValidator        = LifetimeValidator,
                    IssuerSigningKey         = securityKey
                };

                // Extract and assign Current Principal and user
                Thread.CurrentPrincipal  = tokenHandler.ValidateToken(token, validationParameters, out securityToken);
                HttpContext.Current.User = tokenHandler.ValidateToken(token, validationParameters, out securityToken);

                return(base.SendAsync(request, cancellationToken));
            }
            catch (SecurityTokenValidationException)
            {
                statusCode = HttpStatusCode.Unauthorized;
            }
            catch (Exception)
            {
                statusCode = HttpStatusCode.InternalServerError;
            }

            return(Task <HttpResponseMessage> .Factory.StartNew(() => new HttpResponseMessage(statusCode) { }));
        }