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

2022-05-15 234 views 4

扫一扫用手机浏览

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:测试效果

 

 

 

 

,

欧博客户端下载

欢迎进入欧博客户端下载(Allbet Game):www.aLLbetgame.us,欧博官网是欧博集团的官方网站。欧博官网开放Allbet注册、Allbe代理、Allbet电脑客户端、Allbet手机版下载等业务。

Allbet网站内容转载自互联网,如有侵权,联系www.ALLbetgame.us删除。

本文链接地址:http://www.lijiweihejin.com/post/1352.html

相关文章

OPPO Enco Free2 评测:42dB降噪专武!

随着真无线耳机成为消费者主流使用的聆听设备,不仅音响大厂顺应这股趋势,持续推陈出新,就连行动装置品牌也争相进入TWS耳机市场,在众...

科技 2022-05-18 阅读17 评论1

发表评论