示例#1
0
        public async Task <JwtSecurityToken> ParseTokenFromContextAsync(HttpContext context)
        {
            return(await Task.Run(() => {
                var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
                if (token != null)
                {
                    try
                    {
                        JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

                        RSAManager rSAManager = RSAManager.GetInstance;

                        tokenHandler.ValidateToken(token, new TokenValidationParameters
                        {
                            ValidateIssuerSigningKey = true,
                            IssuerSigningKey = new RsaSecurityKey(rSAManager.Key.Rsa.ExportParameters(false)),
                            ValidateIssuer = true,
                            ValidateAudience = false,
                            ValidateLifetime = true,
                            ValidIssuer = _configuration["Jwt:Issuer"],
                            ClockSkew = TimeSpan.Zero
                        }, out SecurityToken validatedToken);

                        return (JwtSecurityToken)validatedToken;
                    }
                    catch (Exception) {
                        return null;
                    }
                }
                return null;
            }));
        }
        public async Task <Token> GenerateJwtTokenAsync(User trustedUser)
        {
            return(await Task.Run(() => {
                try {
                    Token expToken = new Token {
                        ExpiryDate = (long)(DateTime.UtcNow.AddMinutes(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds,
                        UserId = trustedUser.UserId,
                        IssuedAt = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds,
                        User = trustedUser,
                        Value = Guid.NewGuid().ToString()
                    };

                    if (expToken == null)
                    {
                        return null;
                    }

                    JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

                    Claim[] claims = new Claim[] {
                        new Claim(JwtRegisteredClaimNames.Sub, Convert.ToString(trustedUser.UserId)),
                        new Claim(JwtRegisteredClaimNames.Iss, _configuration["Jwt:Issuer"]),
                        new Claim(JwtRegisteredClaimNames.Exp, expToken.ExpiryDate.ToString()),
                        new Claim(JwtRegisteredClaimNames.Jti, expToken.Value),
                        new Claim(JwtRegisteredClaimNames.Iat, expToken.IssuedAt.ToString()),
                        new Claim(ClaimTypes.Role, trustedUser.Role.ToString())
                    };

                    ClaimsIdentity identity = new ClaimsIdentity(claims);

                    RSAManager rSAManager = RSAManager.GetInstance;

                    SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor {
                        Subject = identity,
                        Expires = DateTime.UtcNow.AddMinutes(10),
                        SigningCredentials = new SigningCredentials(rSAManager.Key, SecurityAlgorithms.RsaSsaPssSha256)
                    };

                    SecurityToken token = tokenHandler.CreateToken(descriptor);
                    string jwtToken = tokenHandler.WriteToken(token);
                    if (jwtToken != null)
                    {
                        expToken.JwtToken = jwtToken;
                        return expToken;
                    }
                }
                catch (Exception) {
                    return null;
                }
                return null;
            }));
        }