在Web API 中我谢了个基本认证的filter,主要代码如下:
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { context.Principal = null; AuthenticationHeaderValue authenticationHeader = context.Request.Headers.Authorization; if (authenticationHeader != null && authenticationHeader.Scheme == "Basic") { if (!string.IsNullOrEmpty(authenticationHeader.Parameter)) { Tuple<string, string> data = GetUserNameAndPassword(context, authenticationHeader.Parameter); context.Principal = await AuthenticateAsync(data.Item1, data.Item2,context, cancellationToken); } } if (context.Principal == null) { context.ErrorResult = new UnauthorizedResult(new[] {new AuthenticationHeaderValue("Basic")}, context.Request); } }
登录代码如下:
[HttpPost] public async Task<HttpResponseMessage> Login(LoginView model) { if (ModelState.IsValid) { AppUser user = await UserManager.FindAsync(model.Name, model.Password); if (user == null) ModelState.AddModelError("", "用户名或密码不存在"); else { ClaimsIdentity identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); AuthManager.SignOut(); AuthManager.SignIn(new AuthenticationProperties {IsPersistent = true}, identity); var authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes(model.Name + ":" + model.Password)); Request.Headers.Authorization=new AuthenticationHeaderValue("Basic",authorization); return Request.CreateResponse(HttpStatusCode.OK, "success"); } } return Request.CreateResponse(HttpStatusCode.BadRequest, "failed"); }
在登录成功后,然后用ajax去调用某个Action,该Action加了前面的基本认证的filter,每次调试进去 AuthenticationHeaderValue authenticationHeader = context.Request.Headers.Authorization;authenticationHeader总是为Null。
而我在登录代码中加了认证:
Request.Headers.Authorization=new AuthenticationHeaderValue("Basic",authorization);
为什么在过滤器中context.Request.Headers.Authorization为NULL呢?希望各位能够赐教,ajax调用代码如下:
function ajaxOp(url, type, data, contentType) { $.ajax({ url: url, type: type, data: data, contentType: contentType, success: function(result) { alert(result); } }); }
因为你在发请求的时候没加进去.
你要一个东西的时候至少想想他是怎么来的啊..
后台加Cookie
HttpResponseMessage responseMessage = Request.CreateResponse(HttpStatusCode.OK, "success"); CookieHeaderValue cookie = new CookieHeaderValue("userToken", authorization) { Path = "/", Domain = Request.RequestUri.Host, Expires = DateTimeOffset.Now.AddDays(7) }; responseMessage.Headers.AddCookies(new[] {cookie});
ajax取出cookie
function ajaxOp(url, type, data, contentType) { $.ajax({ url: url, type: type, data: data, //crossDomain: true, beforeSend: function(xhr) { xhr.setRequestHeader('Authorization', 'Basic ' + $.cookie("userToken")); }, contentType: contentType, success: function(result) { alert(result); } }); }