WebApi使用JWT认证(一)

WebApi使用JWT认证(一)

2023年6月20日发(作者:)

WebApi使⽤JWT认证(⼀)这是第⼀部:先实现NetFramework上的WebApi使⽤JWT认证1、VS新建⼀个WebApi项⽬2、项⽬右键----管理Nuget程序包----找到JWT,然后安装3、Model⽂件夹下新建三个类LoginResult,LoginRequest,AuthInfo 1 namespace 2 { 3 public class LoginResult 4 { 5 public bool Success { get; set; } 6

7 public string Token { get; set; } 8

9 public string Message { get; set; }10 }11 }1 namespace 2 {3 public class LoginRequest4 {5 public string UserName { get; set; }6

7 public string Password { get; set; }8 }9 } 1 using c; 2

3 namespace 4 { 5 public class AuthInfo 6 { 7 //模拟JWT的payload 8 public string UserName { get; set; } 9

10 public List Roles { get; set; }11

12 public bool IsAdmin { get; set; }13 }14 }4、在Controllers⽂件夹中的HomeController(没有就新建⼀个)中添加⼀个Post⽅法,这是⽣成JWT Token⽅法的地⽅,⼀般应放在登录的Action下 1 using JWT; 2 using thms; 3 using izers; 4 using ; 5 using System; 6 using c; 7 using ; 8

9 namespace llers10 {11 public class HomeController : ApiController12 {13 public LoginResult Post([FromBody]LoginRequest request)14 {15 LoginResult rs = new LoginResult();16 //这是是获取⽤户名和密码的,这⾥只是为了模拟17 if (me == "wangshibang" && rd == "123456")18 {19 AuthInfo info = new AuthInfo { UserName = "wangshibang", Roles = new List { "Admin", "Manage" }, IsAdmin = true };20 try21 {22 const string secret = "To Live is to change the world";23 //secret需要加密24 IJwtAlgorithm algorithm = new HMACSHA256Algorithm();25 IJsonSerializer serializer = new JsonNetSerializer();26 IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();27 IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);28 var token = (info, secret);29 e = "XXXXX";30 = token;31 s = true;32 }33 catch (Exception ex)34 {35 e = e;36 s = false;37 }38 }39 else40 {41 e = "fail";42 s = false;43 }44 return rs;45 }46 }47 }5、项⽬下添加⼀个Attributes⽂件夹,需要写个权限拦截器,新建⼀个ApiAuthorizeAttribute类继承⾃AuthorizeAttribute类 1 using JWT; 2 using izers; 3 using ; 4 using System; 5 using ; 6 using ; 7 using llers; 8

9 namespace utes10 {11 public class ApiAuthorizeAttribute : AuthorizeAttribute12 {13 protected override bool IsAuthorized(HttpActionContext actionContext)14 {15 var authHeader = from t in s where == "auth" select rDefault();16 if (authHeader != null)17 {18 string token = rDefault();19 if (!OrEmpty(token))20 {21 try22 {23 const string secret = "To Live is to change the world";24 //secret需要加密25 IJsonSerializer serializer = new JsonNetSerializer();26 IDateTimeProvider provider = new UtcDateTimeProvider();27 IJwtValidator validator = new JwtValidator(serializer, provider);28 IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();29 IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);30

31 var json = ToObject(token, secret, verify: true);32 if (json != null)33 {34 ("auth", json);35 return true;36 }37 return false;38 }39 catch (Exception ex)40 {41 return false;42 }43 }44 }45 return false;46 }47 }48 }6、Controllers⽂件夹中新建⼀个UserController,新建⼀个Get的Action,需要加上ApiAuthorize特性 1 using utes; 2 using ; 3 using ; 4

5 namespace llers 6 { 7 public class UserController : ApiController 8 { 9 // GET: User10 [ApiAuthorize]11 public string Get()12 {13 AuthInfo info = ["auth"] as AuthInfo;14 if (info == null)15 {16 return "获取不到,失败";17 }18 else19 {20 return $"获取到了,Auth的Name是 {me}";21 }22 }23 }24 }7、然后⽤PostMan测试下⾯是解决接⼝调⽤的跨域问题,有两种,⼀种是⽤CORS,另外⼀种就是修改WebConfig添加⾃定义options谓词处理模块我只⽤了⾃定义Options谓词处理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 好了,现在把你的WebApi部署到服务器上,然后⽤另⼀个跨域页⾯调取接⼝访问吧 1 2 3 4 5 6 7 8 9 10

11 ⾝份验证12
13 14
15
16 17
18
19
20 21
22
23

24

25 调⽤接⼝26 27
28 63 64

发布者:admin,转转请注明出处:http://www.yc00.com/news/1687249937a30.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信