ASP.NET Core 生成签名安全的 JWT Token

2023年1月13日 1518点热度 2人点赞 0条评论
内容纲要

大多数情况下,大家使用的生成 JWT Token 代码是这样的:

            // 定义用户信息
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, userName)
            };

            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenOption.SecurityKey));
            JwtSecurityToken token = new JwtSecurityToken(
                issuer: userName,
                audience: "http://192.168.6.6:666",
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddDays(1),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
            );

但是这样生成的 Token 属于不安全的 Token,没有被签名。

file

为了让 Token 更加安全,可以这样:

            // 定义用户信息
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, userName)
            };

            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenOption.SecurityKey));

            SecurityToken securityToken = new JwtSecurityTokenHandler().CreateToken(new SecurityTokenDescriptor
            {
                Claims = claims.ToDictionary(x => x.Type, x => (object)x.Value),
                Issuer = "http://192.168.6.6:666",
                Audience = userName,
                NotBefore = DateTime.Now,
                Expires = DateTime.Now.AddDays(100),
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
            });
            var indf = securityToken.ToString();
            var jwtToken = new JwtSecurityTokenHandler().WriteToken(securityToken);

            return jwtToken;

file

另外检查 Token 的代码可以这样写:

            if (string.IsNullOrWhiteSpace(token)) return false;
            if (!token.StartsWith("Bearer ")) return false;
            var newToken = token[7..];

            var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();

            if (!jwtSecurityTokenHandler.CanReadToken(newToken)) return false;

            var checkResult = await jwtSecurityTokenHandler.ValidateTokenAsync(newToken, new TokenValidationParameters()
            {
                RequireExpirationTime = true,
                ValidateIssuer = false,
                ValidateAudience = false,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenOption.SecurityKey)),
            });

            if (!checkResult.IsValid) return false;

            var jwt = jwtSecurityTokenHandler.ReadJwtToken(newToken);
            IEnumerable<Claim> claims = jwt.Claims;

痴者工良

高级程序员劝退师

文章评论