C#中使用JWT实现WabApi的权限控制

首先需要在你的项目中引入JWT,你只需要在nuget中安装JWT,JWT依赖于.NET  Framwork 4.6以上版本,所以你的webapi项目也需要.NET Framwork4.6以上版本,我这里做法如下:

 1     /// <summary>
 2     /// 验证是否含有token
 3     /// </summary>
 4     public class ApiAuthorizeAttribute : AuthorizeAttribute
 5     {
 6         private UserIBLL userBll = new UserBLL();
 7         /// <summary>
 8         /// 验证是否授权
 9         /// </summary>
10         /// <param name="actionContext"></param>
11         /// <returns></returns>
12         protected override bool IsAuthorized(HttpActionContext actionContext)
13         {
14             //获取header头信息
15             IEnumerable<string> tokenInfo;
16             actionContext.Request.Headers.TryGetValues("Token", out tokenInfo);
17             IEnumerable<string> id;
18             actionContext.Request.Headers.TryGetValues("id", out id);
19             if (tokenInfo != null)
20             {
21                 string token = tokenInfo.ToList<string>()[0];
22                 var userid = id.ToList<string>()[0];
23                 if (!string.IsNullOrEmpty(token))
24                 {
25                     try
26                     {
27                         UserEntity userEntity = userBll.GetEntityByUserId(id.ToList<string>()[0]);
28                         if (userEntity == null)
29                         {
30                             return false;
31                         }
32                         IJsonSerializer serializer = new JsonNetSerializer();
33                         IDateTimeProvider provider = new UtcDateTimeProvider();
34                         IJwtValidator validator = new JwtValidator(serializer, provider);
35                         IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
36                         IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
37                         var json = decoder.Decode(token, userEntity.Secret, verify: true);
38                         if (string.IsNullOrEmpty(json))
39                         {
40                             return false;
41                         }
42                         var newModel = json.ToObject<UserEntity>();
43                         if (newModel.F_UserId != userEntity.F_UserId || newModel.Secret != userEntity.Secret)
44                         {
45                             return false;
46                         }
47                         return true;
48                     }
49                     catch (Exception)
50                     {
51                         return false;
52                     }
53                 }
54             }
55             return false;
56         }
57     }

 

上一篇:Java操作数据库


下一篇:Spring boot + MongoDB 整合 增删改查及聚合写法