ASP.NET Core 3.1 JWT token测试

0. Bearer Token(Token 令牌)

为了验证使用者的身份,需要客户端向服务器端提供一个可靠的验证信息,称为Token,这个token通常由Json数据格式组成,通过hash散列算法生成一个字符串,所以称为Json Web Token(Json表示令牌的原始值是一个Json格式的数据,web表示是在互联网传播的,token表示令牌,简称JWT)。

1. 引入包

新建 .Core WebApi项目,并引入包

install-package Microsoft.AspNetCore.Authentication.JwtBearer -Version 3.0.3

install-package System.IdentityModel.Tokens.Jwt –Version 6.16.0

 2. 建立生成jwt token的方法

2.1 新建工具类JwtTokenUtil.cs

    public class JwtTokenUtil
    {
        private readonly IConfiguration _configuration;

        public JwtTokenUtil(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public string GetToken(User user)
        {
            // push the user’s name into a claim, so we can identify the user later on.
            var claims = new[]
            {
                   new Claim(ClaimTypes.Name, user.name),
                   //new Claim(ClaimTypes.Role, admin)//在这可以分配用户角色,比如管理员 、 vip会员 、 普通用户等
            };
            //sign the token using a secret key.This secret will be shared between your API and anything that needs to check that the token is legit.
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecurityKey"])); // 获取密钥
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); //凭证 ,根据密钥生成
            //.NET Core’s JwtSecurityToken class takes on the heavy lifting and actually creates the token.
            /**
             * Claims (Payload)
                Claims 部分包含了一些跟这个 token 有关的重要信息。 JWT 标准规定了一些字段,下面节选一些字段:

                iss: The issuer of the token,token 是给谁的  发送者
                aud: 接收的
                sub: The subject of the token,token 主题
                exp: Expiration Time。 token 过期时间,Unix 时间戳格式
                iat: Issued At。 token 创建时间, Unix 时间戳格式
                jti: JWT ID。针对当前 token 的唯一标识
                除了规定的字段外,可以包含其他任何 JSON 兼容的字段。
             * */
            var token = new JwtSecurityToken(
                issuer: "jwttest",
                audience: "jwttest",
                claims: claims,
                expires: DateTime.Now.AddMinutes(60*9),
                signingCredentials: creds
            );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }

2.2 在控制器中新建登录方法,生成token

namespace JwtToken.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class HomeController : Controller
    {
        List<User> users = new List<User>() { 
            new User{ name = "admin",password = "admin"},
            new User{ name = "xiaoxiao",password = "xiaoxiao"}
        };

        private readonly IConfiguration _configuration;
        public HomeController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        //登录操作
        [HttpPost]
        public JsonResult login([FromForm] User model)
        {
            UserMsg msg = new UserMsg()
            {
                mark = 0,
                msg = "",
                token = "",
            };

            //User user = _context.User.Where(x => x.name == model.name).FirstOrDefault();
            User user = users.Where(x => x.name == model.name).FirstOrDefault();
            //string password_form = _common.Get_MD5_Method1(model.password);
            string password_form = model.password;

            if (user != null && user.password == password_form.ToLower())
            {
                JwtTokenUtil jwtTokenUtil = new JwtTokenUtil(_configuration);
                string token = jwtTokenUtil.GetToken(user);   //生成token
                //var headers = new HttpResponseMessage().Headers;
                //headers.Add("Authorization",token);

                msg.mark = 1;
                msg.msg = "登录成功";
                msg.token = token;
            }
            else
            {
                msg.msg = "用户名或者密码错误";
            }
            return Json(msg);
        }
    }
}

3. 配置jwt验证服务

3.1 Startup.cs中配置 服务 ,添加jwt 验证 服务添加服务 ( ConfigureServices方法中 )

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {           
            //添加jwt验证:
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options => {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,//是否验证Issuer
                        ValidateAudience = true,//是否验证Audience
                        ValidateLifetime = true,//是否验证失效时间
                        ValidateIssuerSigningKey = true,//是否验证SecurityKey
                        ValidAudience = "jwttest",//Audience
                        ValidIssuer = "jwttest",//Issuer,这两项和前面签发jwt的设置一致
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecurityKey"]))//拿到SecurityKey
                    };
                });

            services.AddControllers();
        }

3.2 启用 Configure方法中

app.UseAuthentication();//启用验证

4. Token应用到需要的方法中

在需要token验证的类或方法上添加特性[Authorize]

    [Route("api/[controller]")]
    public class TestController : Controller
    {
        // GET api/values
        [HttpGet]
        [Authorize]//添加Authorize标签,可以加在方法上,也可以加在类上
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }
        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }
    }

5. 应用

5.1 网站部署IIS

 5.2 获取token

 5.3 获取数值

 6. 其他

对应资源:

(4条消息) ASP.NETCore3.1JWTtoken实现与应用-C#文档类资源-CSDN文库

参考博客:

ASP.NET Core 2.1 JWT token (一) - 简书 (jianshu.com)

JWT-生成、校验、解析Token(C#) - .Neterr - 博客园 (cnblogs.com)

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用 JWT 进行身份验证时,通常会设置一个过期时间,以确保用户在一段时间内保持登录状态。当 JWT 过期时,用户需要重新登录并获取新的 JWT 令牌。为了避免用户频繁重新登录,我们可以使用刷新令牌的方式来延长用户的登录状态。 在 .NET Core 3.1 中,我们可以使用 JwtSecurityTokenHandler 类来生成和验证 JWT 令牌。下面是一个简单的 JwtHelper 类的实现,它支持生成、刷新和验证 JWT 令牌: ```csharp using Microsoft.IdentityModel.Tokens; using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; public class JwtHelper { private static readonly string secret = "your_secret_key_here"; private static readonly string issuer = "your_issuer_here"; private static readonly int expireMinutes = 30; private static readonly int refreshExpireMinutes = 60; public static string GenerateToken(string userId) { var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId) }; var tokenDescriptor = new SecurityTokenDescriptor { Issuer = issuer, Audience = issuer, Subject = new ClaimsIdentity(claims), Expires = DateTime.UtcNow.AddMinutes(expireMinutes), SigningCredentials = credentials }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } public static string RefreshToken(string token) { var tokenHandler = new JwtSecurityTokenHandler(); var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)); try { var claimsPrincipal = tokenHandler.ValidateToken(token, new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidIssuer = issuer, ValidAudience = issuer, IssuerSigningKey = securityKey, ValidateLifetime = false }, out SecurityToken validatedToken); var jwtToken = validatedToken as JwtSecurityToken; if (jwtToken == null || !jwtToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) { throw new SecurityTokenException("Invalid token"); } var userId = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier).Value; return GenerateToken(userId); } catch(Exception ex) { throw new SecurityTokenException("Invalid token", ex); } } public static bool ValidateToken(string token) { var tokenHandler = new JwtSecurityTokenHandler(); var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)); try { var claimsPrincipal = tokenHandler.ValidateToken(token, new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidIssuer = issuer, ValidAudience = issuer, IssuerSigningKey = securityKey, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }, out SecurityToken validatedToken); var jwtToken = validatedToken as JwtSecurityToken; if (jwtToken == null || !jwtToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) { throw new SecurityTokenException("Invalid token"); } return true; } catch(Exception) { return false; } } } ``` 在上面的代码中,我们定义了一个静态的 secret 字符串来存储 JWT 的密钥,一个 issuer 字符串来存储 JWT 的发行者,以及一个 expireMinutes 和 refreshExpireMinutes 来分别设置 JWT 令牌和刷新令牌的过期时间。在 GenerateToken 方法中,我们使用 JwtSecurityTokenHandler 类来创建一个 JWT 令牌,并设置其过期时间和签名凭证。在 RefreshToken 方法中,我们首先验证传入的 JWT 令牌是否有效,并提取其中的用户 ID。然后,我们使用 GenerateToken 方法来生成一个新的 JWT 令牌。在 ValidateToken 方法中,我们验证传入的 JWT 令牌是否有效,并返回一个布尔值表示验证结果。 使用 JwtHelper 类非常简单,只需要调用其中的 GenerateToken、RefreshToken 和 ValidateToken 方法即可。下面是一个示例: ```csharp var token = JwtHelper.GenerateToken("user_id"); var isValid = JwtHelper.ValidateToken(token); var refreshedToken = JwtHelper.RefreshToken(token); ``` 需要注意的是,由于 JWT 令牌是无状态的,因此在刷新令牌时,我们需要使用一些外部存储机制(如数据库或缓存)来存储每个用户的刷新令牌。当用户请求刷新令牌时,我们可以从外部存储中检索出用户的刷新令牌,并验证其有效性后生成新的 JWT 令牌。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值