网址:https://bbs.huaweicloud.com/blogs/189278
 
 
Asp.NetCore3.1 WebApi 使用Jwt 授权认证使用
【摘要】 1:导入NuGet包Microsoft.AspNetCore.Authentication.JwtBearer2:配置jwt相关信息3:在startUp中1publicvoidConfigureServices(IServiceCollectionservices){2#regionJWT认证3services4.AddAuthentication(JwtBearerDefau...

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

2:配置 jwt相关信息

3:在 startUp中

Asp.NetCore3.1 WebApi 使用Jwt 授权认证使用_web
 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

Asp.NetCore3.1 WebApi 使用Jwt 授权认证使用_web
 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代码封装

Asp.NetCore3.1 WebApi 使用Jwt 授权认证使用_web
  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     /// 
 15     /// @auth fengge
 16     /// 
 17     public class ZrfJwtHelper
 18     {
 19         /// 
 20         /// 生成Tocken
 21         /// 
 22         /// 
 23         /// 
 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();
 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