1.登陆的时候根据用户信息生成Token
var token = FormsAuthentication.Encrypt( new FormsAuthenticationTicket( 0, "UserName", DateTime.Now, DateTime.Now.AddHours(1), true, string.Format("{0}&{1}", "userData1", "userData2" ), FormsAuthentication.FormsCookiePath)); / /放入Cookie var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, token); cookie.HttpOnly = true; HttpContext.Current.Response.Cookies.Add(cookie);
2.新增 一个Filter(取名规范 XXX+Attribute) :ActionFilterAttribute,重写OnActionExecutingAsync
public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) { var auth = actionContext.Request.Headers.Authorization; //记录进入请求的时间 actionContext.Request.Properties[key] = DateTime.Now.ToBinary(); //TODO 权限,各种操作在这都可以去拦截.. return base.OnActionExecutingAsync(actionContext, cancellationToken); }
3. 获取Token 中的信息
var user = HttpContext.Current.User.Identity.Name;