刚完成, 怕忘记. 特来记录一下
登陆返回 token 的代码没有, 此处记录
- public class ApiAuthAttribute:AuthorizeAttribute
- {
- protected override bool IsAuthorized(HttpActionContext actionContext)
- { // 获取请求头中 auth 的字段
- var authHeader = from t in actionContext.Request.Headers where t.Key == "auth" select t.Value.FirstOrDefault();
- if (authHeader!=null)
- {
- string token = authHeader.FirstOrDefault();
- if (!string.IsNullOrEmpty(token))
- {
- try
- {
- string data = DesHelper.Decrypt(System.web.HttpUtility.UrlDecode(token), "0123456");// 这里是自己的加密方法, 这里可以随意设定, 重点就是后边把信息解出来
- var d = JsonConvert.DeserializeObject<Dictionary<string,object>>(data);
- if (d==null||string.IsNullOrEmpty(d["USERID"].ToString()))
- {
- HttpResponseMessage result = new HttpResponseMessage();
- result.StatusCode = (HttpStatusCode)401;
- actionContext.Response = result;
- return false;
- }
- else
- {
- return true;
- }
- }
- catch (Exception ex)
- {
- return false;
- }
- }
- }
- return false;
- }
- }
在需要验证请求头的方法前添加标签, 例:
- [ActionName("GetRefreshMin")]
- [HttpGet]
- [ApiAuthAttribute]
- public IHttpActionResult GetRefreshMin()
- {
- try
- {
- return Success(devBll.GetRefreshMin());
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
来源: http://www.bubuko.com/infodetail-3297784.html