Asp.NetCore3.1 WebApi 使用Jwt 授权认证使用
2020-12-26 15:27
标签:read 官网 etc 空间 local new 成功 bsp isp 1:导入NuGet包 Microsoft.AspNetCore.Authentication.JwtBearer 2:配置 jwt相关信息 3:在 startUp中 4:使用时在Controller /action 上打上特性 [Authorize] 可以单独在Action上打上特性[Authorize] 不需要检查授权认证的话打上特性: [AllowAnonymous] 5:难道后端返回的Tocken,可以在PostMan上面测试,和JWT.io官网上面来测试 6: 发送请求到后端,带上Tocken 如Get ://localhost:5000/user/login 7:action上面的code 8:完整的Jwt代码封装 9:模型实体 10:配置内容:
11:测试效果
Asp.NetCore3.1 WebApi 使用Jwt 授权认证使用 标签:read 官网 etc 空间 local new 成功 bsp isp 原文地址:https://www.cnblogs.com/Fengge518/p/13368635.html 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 }
两个特性类都在如下命名空间下:
using Microsoft.AspNetCore.Authorization;
Key value
Authorization Bearer qweTdfdsfsJhdsfd0.fdsfdsgfdsewDDQDD.fdsfdsg*** 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 }
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 ///
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 }
上一篇:C# 委托与回调
下一篇:C#中的异常处理语句
文章标题:Asp.NetCore3.1 WebApi 使用Jwt 授权认证使用
文章链接:http://soscw.com/index.php/essay/38379.html