webapi简单实现JWT登陆

刚完成,怕忘记.特来记录一下

登陆返回token的代码没有,此处记录

 1 public class ApiAuthAttribute:AuthorizeAttribute
 2     {
 3         protected override bool IsAuthorized(HttpActionContext actionContext)
 4         {  //获取请求头中auth的字段
 5             var authHeader = from t in actionContext.Request.Headers where t.Key == "auth" select t.Value.FirstOrDefault();
 6             if (authHeader!=null)
 7             {
 8                 string token = authHeader.FirstOrDefault();
 9                 if (!string.IsNullOrEmpty(token))
10                 {
11                     try
12                     {
13                         string data = DesHelper.Decrypt(System.Web.HttpUtility.UrlDecode(token), "0123456");//这里是自己的加密方法,这里可以随意设定,重点就是后边把信息解出来
14                         var d = JsonConvert.DeserializeObject<Dictionary<string,object>>(data);
15                         if (d==null||string.IsNullOrEmpty(d["USERID"].ToString()))
16                         {
17                             HttpResponseMessage result = new HttpResponseMessage();
18                             result.StatusCode = (HttpStatusCode)401;
19                             actionContext.Response = result;
20                             return false;
21                         }
22                         else
23                         {
24                             return true;
25                         }
26                     }
27                     catch (Exception ex)
28                     {
29                         return false;
30                     }
31                 }
32             }
33             return false;
34         }
35     }

在需要验证请求头的方法前添加标签,例:

 1         [ActionName("GetRefreshMin")]
 2         [HttpGet]
 3         [ApiAuthAttribute]
 4         public IHttpActionResult GetRefreshMin()
 5         {
 6             try
 7             {
 8                 return Success(devBll.GetRefreshMin());
 9             }
10             catch (Exception ex)
11             {
12                 throw ex;
13             }
14         }    

猜你喜欢

转载自www.cnblogs.com/tabai/p/11906970.html