Asp.NetCore3.1 WebApi 使用Jwt 授权认证使用

一笑奈何 提交于 2020-10-09 04:27:26

1:导入NuGet包 Microsoft.AspNetCore.Authentication.JwtBearer

2:配置 jwt相关信息

3:在 startUp中

 1 public void ConfigureServices(IServiceCollection services){
 2 #region JWT 认证
 3 services
 4 .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
 5 .AddJwtBearer(options => {
 6 var jsonmodel = AppJsonHelper.InitJsonModel();
 7 options.TokenValidationParameters = new TokenValidationParameters
 8 {
 9 ValidIssuer = jsonmodel.Issuer,// Configuration["JwtSetting:Issuer"],
10 ValidAudience = jsonmodel.Audience,// Configuration["JwtSetting:Audience"],
11 // IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSetting:SecurityKey"])),
12 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jsonmodel.TockenSecrete)),
13 // 默认允许 300s 的时间偏移量,设置为0即可
14 ClockSkew = TimeSpan.Zero
15 };
16 });
17 #endregion
18 }
19 
20 //注意需要放在addmvc上面 services.AddMvc();
21 
22 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
23 {
24 app.UseAuthentication();//身份验证
25 app.UseAuthorization();// 授权
26 }
View Code

4:使用时在Controller /action 上打上特性 [Authorize]

可以单独在Action上打上特性[Authorize]  不需要检查授权认证的话打上特性: [AllowAnonymous]
两个特性类都在如下命名空间下:
using Microsoft.AspNetCore.Authorization;

5:登陆成功后端并返回生成的Tocken,可以在PostMan上面测试,和JWT.io官网上面来测试

6: 发送请求到后端,带上Tocken 如Get ://localhost:5000/user/login
Key value
Authorization Bearer qweTdfdsfsJhdsfd0.fdsfdsgfdsewDDQDD.fdsfdsg***

7:action上面的code

 1 [HttpPost, Route("Login")]
 2         public ApiResult Login(personnel p)
 3         {
 4             ApiResult result = new ApiResult();
 5             try
 6             {
 7                 string tockenStr = ZrfJwtHelper.GetTocken(p);
 8                 result.data = tockenStr;
 9                 result.code = statuCode.success;
10                 result.message = "获取成功!";
11             }
12             catch (Exception ex)
13             {
14                 result.message = "查询异常:" + ex.Message;
15             }
16             return result;
17         }
18 
19 
20         [HttpPost, Route("authTest")]
21         [Authorize]
22         [AllowAnonymous]// 跳过授权认证
23         public ApiResult authTest(string accesTocken)
24         {
25             ApiResult result = new ApiResult();
26             try
27             {
28                 var info = ZrfJwtHelper.GetTockenInfo(accesTocken);
29                 result.data = info;
30                 result.code = statuCode.success;
31                 result.message = "获取成功!";
32             }
33             catch (Exception ex)
34             {
35                 result.message = "查询异常:" + ex.Message;
36             }
37             return result;
38         }
View Code

8:完整的Jwt代码封装

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Threading.Tasks;
  5 namespace ZRFCoreTestMongoDB.Commoms
  6 {
  7     using Microsoft.AspNetCore.Http;
  8     using Microsoft.IdentityModel.Tokens;
  9     using System.IdentityModel.Tokens.Jwt;
 10     using System.Security.Claims;
 11     using System.Text;
 12     using ZRFCoreTestMongoDB.Model;
 13 
 14     /// <summary>
 15     /// @auth fengge
 16     /// </summary>
 17     public class ZrfJwtHelper
 18     {
 19         /// <summary>
 20         /// 生成Tocken
 21         /// </summary>
 22         /// <param name="p"></param>
 23         /// <returns></returns>
 24         public static string GetTocken(personnel p)
 25         {
 26             //读取配置文件获得Jwt的json文件信息
 27             var model = AppJsonHelper.InitJsonModel();
 28             string _issuer = model.Issuer;//分发者
 29             string audience = model.Audience;//接受者
 30             string TockenSecrete = model.TockenSecrete;//秘钥
 31 
 32             //秘钥
 33             var securityKey = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(TockenSecrete)), SecurityAlgorithms.HmacSha256);
 34             // 設定要加入到 JWT Token 中的聲明資訊(Claims)
 35             //var claims = new List<Claim>();
 36             //// 在 RFC 7519 規格中(Section#4),總共定義了 7 個預設的 Claims,我們應該只用的到兩種!
 37             ////claims.Add(new Claim(JwtRegisteredClaimNames.Iss, issuer));
 38             //claims.Add(new Claim(JwtRegisteredClaimNames.Sub, userInfo.UserId));
 39 
 40             //Claim
 41             var claims = new Claim[] {
 42                     new Claim(JwtRegisteredClaimNames.Sid,p.Uid),
 43                     new Claim(JwtRegisteredClaimNames.Iss,_issuer),
 44                     new Claim(JwtRegisteredClaimNames.Sub,p.Name),
 45                     new Claim("Guid",Guid.NewGuid().ToString("D")),
 46                     new Claim("Roleid",p.Roleid.ToString()),
 47                     new Claim("Age",p.Age.ToString()),
 48                     new Claim("BirthDay",p.BirthDay.ToString())
 49             };
 50 
 51             SecurityToken securityToken = new JwtSecurityToken(
 52                 issuer: _issuer,
 53                 audience: audience,
 54                 signingCredentials: securityKey,
 55                 expires: DateTime.Now.AddMinutes(2),//过期时间
 56                 claims: claims
 57                 );
 58 
 59             return new JwtSecurityTokenHandler().WriteToken(securityToken);
 60         }
 61 
 62         /// <summary>
 63         /// 获取accessTocken
 64         /// </summary>
 65         /// <param name="context"></param>
 66         /// <returns></returns>
 67         public static string GetTockenString(HttpContext context)
 68         {
 69             return context != null ? context.Request.Headers["Authorization"].ToString() : "";
 70         }
 71 
 72         /// <summary>
 73         /// 解析Jwt生成的 Tocken
 74         /// </summary>
 75         /// <param name="accesTocken"></param>
 76         /// <returns></returns>
 77         public static TockenInfo GetTockenInfo(string accesTocken)
 78         {
 79             try
 80             {
 81                 if (accesTocken.Contains("Bearer")) //防止前端传过来的tocken 为待了 Bearer 的字符串
 82                 {
 83                     accesTocken = accesTocken.Replace("Bearer ", "");
 84                 }
 85                 var tockHandler = new JwtSecurityToken(accesTocken);
 86                 TockenInfo info = new TockenInfo
 87                 {
 88                     // Age=tockHandler.Claims.FirstOrDefault(c=>c.Type==JwtRegisteredClaimNames.Email)
 89                     Uid = tockHandler.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Sid).Value,
 90                     Name = tockHandler.Claims.FirstOrDefault(c => c.Type ==JwtRegisteredClaimNames.Sub).Value,//在于自己来定义了,上面生成是和下面获取时Key要一致
 91 
 92                     Age = tockHandler.Claims.FirstOrDefault(c => c.Type == "Age").Value,
 93                     BirthDay = tockHandler.Claims.FirstOrDefault(c => c.Type == "BirthDay").Value,
 94                     Roleid = tockHandler.Claims.FirstOrDefault(c => c.Type == "Roleid").Value,
 95                 };
 96                 return info;
 97             }
 98             catch (Exception ex)
 99             {
100                 throw new Exception("解析Tocken时错误!");
101             }
102         }
103     }
104     public class TockenInfo
105     {
106         public string Uid { get; set; }
107         public string Name { get; set; }
108         public string Age { get; set; }
109         public string BirthDay { get; set; }
110         public string Roleid { get; set; }
111     }
112 }
View Code

9:模型实体

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 
 6 namespace ZRFCoreTestMongoDB.Model
 7 {
 8     using System.ComponentModel.DataAnnotations;
 9     [Serializable]
10     public class personnel
11     {
12 
13         [Required(ErrorMessage = "姓名必填")]
14         [StringLength(maximumLength: 10, ErrorMessage = "姓名最多是10个字符")]
15         [MinLength(2, ErrorMessage = "姓名长度最少为两个字符")]
16         public string Name { get; set; }
17 
18         [Range(1, 150, ErrorMessage = "年龄范围为:1-150")]
19         public int Age { get; set; }
20         [DataType(DataType.Date, ErrorMessage = "生日不学为日期格式,例如:1998-10-10")]
21         public DateTime BirthDay { get; set; }
22 
23         [Required(ErrorMessage = "密码必填")]
24         [StringLength(maximumLength: 10, MinimumLength = 6, ErrorMessage = "密码长度最多10位")]
25         public string Password { get; set; }
26         public int Roleid { get; set; }
27         public string Uid { get; set; }
28     }
29 }
View Code

10:配置内容:

 

 

 

11:测试效果

 

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!