首页 新闻 会员 周边 捐助

Web API 基本认证Headers.Authorization为什么一直为NULL

0
悬赏园豆:50 [已关闭问题] 关闭于 2016-03-05 19:04

在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);
            }
        });
    }

 

 

 

云在青天水在哪的主页 云在青天水在哪 | 初学一级 | 园豆:184
提问于:2016-03-03 22:37
< >
分享
所有回答(2)
0

因为你在发请求的时候没加进去.

你要一个东西的时候至少想想他是怎么来的啊..

吴瑞祥 | 园豆:29449 (高人七级) | 2016-03-03 22:46
0

后台加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);             }         });     }

云在青天水在哪 | 园豆:184 (初学一级) | 2016-03-04 22:45
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册