码迷,mamicode.com
首页 > Web开发 > 详细

Asp.Net Core 使用 Jwt

时间:2020-04-23 23:03:22      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:sch   mic   parameter   home   col   获取   服务   and   route   

Jwt全称josn web token,生成token支持多种语言,token的方式做登录身份校验

VS创建WebApi nuget引用jwt的包

Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 3.1.3

新建一个类JwtAuthorization.cs用于编写Jwt的验证服务

    public static void JwtAuthorizationStartup(this IServiceCollection services)
     {
         if (services == null)
         {
             throw new ArgumentNullException(nameof(services));
         }

         //授权角色
         services.AddAuthorization(options =>
         {
             options.AddPolicy("Client", policy => policy.RequireRole("Client").Build());
             options.AddPolicy("AdminOrSystem", policy => policy.RequireRole("Admin", "System").Build());
         });
         //密钥加密
         SymmetricSecurityKey signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("1234567890123456"));
         SigningCredentials signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
         // 令牌验证参数
         TokenValidationParameters tokenValidationParameters = new TokenValidationParameters
         {
             ValidateIssuerSigningKey = true,
             IssuerSigningKey = signingKey,
             ValidateIssuer = true,
             ValidIssuer = "DUST",//发行人
             ValidateAudience = true,
             ValidAudience = "DUST",//订阅人
             ValidateLifetime = true,
             ClockSkew = TimeSpan.FromSeconds(30),
             RequireExpirationTime = true,
         };
         // 认证jwt
         services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
          {
              options.TokenValidationParameters = tokenValidationParameters;
              options.Events = new JwtBearerEvents
              {
                  OnAuthenticationFailed = context =>
                  {
                      context.NoResult();

                      context.Response.StatusCode = 401;
                      context.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = context.Exception.Message;
                      return Task.CompletedTask;
                  },
                  OnTokenValidated = context =>
                  {
                      return Task.CompletedTask;
                  }
              };
          });
     }

在Startup类ConfigureServices方法里注册JwtAuthorizationStartup

   services.JwtAuthorizationStartup();

在Startup类Configure方法里启用授权验证

   app.UseAuthentication();
   app.UseAuthorization();

创建Login控制器添加三个动作获取三个角色的token

 [ApiController]
 [Route("[controller]")]
 public class LoginController : ControllerBase
 {
     private readonly ILogger<LoginController> _logger;

     public LoginController(ILogger<LoginController> logger)
     {
         _logger = logger;
     }

     [HttpPost("System")]
     public IActionResult System()
     {
         Claim[] claims = new[]
          {
                 new Claim(ClaimTypes.Sid,"1"),
                 new Claim(ClaimTypes.Name, "张三"),
                 new Claim(ClaimTypes.Email,"net*****@163.com"),
                 new Claim(ClaimTypes.Role, "System"),
             };
         //密钥
         SymmetricSecurityKey signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("1234567890123456"));
         SigningCredentials signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
         JwtSecurityToken jwtSecurityToken = new JwtSecurityToken
         (
             issuer: "DUST",
             audience: "DUST",
             claims: claims,
             expires: DateTime.Now.AddDays(7),
             signingCredentials: signingCredentials
         );
         string token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
         return Ok(token);
     }

     [HttpPost("Admin")]
     public IActionResult Admin()
     {
         Claim[] claims = new[]
          {
                 new Claim(ClaimTypes.Sid,"1"),
                 new Claim(ClaimTypes.Name, "张三"),
                 new Claim(ClaimTypes.Email,"net*****@163.com"),
                 new Claim(ClaimTypes.Role, "System"),
             };
         //密钥
         SymmetricSecurityKey signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("1234567890123456"));
         SigningCredentials signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
         JwtSecurityToken jwtSecurityToken = new JwtSecurityToken
         (
             issuer: "DUST",
             audience: "DUST",
             claims: claims,
             expires: DateTime.Now.AddDays(7),
             signingCredentials: signingCredentials
         );
         string token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
         return Ok(token);
     }

     [HttpPost("Client")]
     public IActionResult Client()
     {
         Claim[] claims = new[]
          {
                 new Claim(ClaimTypes.Sid,"1"),
                 new Claim(ClaimTypes.Name, "张三"),
                 new Claim(ClaimTypes.Email,"net*****@163.com"),
                 new Claim(ClaimTypes.Role, "System"),
             };
         //密钥
         SymmetricSecurityKey signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("1234567890123456"));
         SigningCredentials signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
         JwtSecurityToken jwtSecurityToken = new JwtSecurityToken
         (
             issuer: "DUST",
             audience: "DUST",
             claims: claims,
             expires: DateTime.Now.AddDays(7),
             signingCredentials: signingCredentials
         );
         string token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
         return Ok(token);
     }
 }

添加一个Home控制器标注控制器的角色有两种写法一种是默认的基于角色授权,这里用的第二种基于策略的授权

 [Route("api/[controller]")]
 [ApiController]
 //[Authorize(Roles = "Admin,System")] 
 [Authorize(policy: "AdminOrSystem")]//使用策略的授权的好处就是不用在controller中,写多个 roles
 public class HomeController : ControllerBase
 {
     [HttpGet]
     public IActionResult Get()
     {
         return Ok("Client");
     }
 }

然后在postman测试 Demo下载

Asp.Net Core 使用 Jwt

标签:sch   mic   parameter   home   col   获取   服务   and   route   

原文地址:https://www.cnblogs.com/SuperDust/p/12764065.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!