3

我无法理解如何使用我的 api 以用户身份登录然后访问特定方法:

 public class UsersController : ApiController
    {
        [HttpPost]
        public HttpResponseMessage Login(LoginModel model)
        {
            HttpResponseMessage Response = new HttpResponseMessage();
            // check if all required fields are set
            if (ModelState.IsValid)
            {
                // authenticate user
                var success = Membership.ValidateUser(model.UserName, model.Password);

                if (success)
                {
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                            model.UserName,
                            DateTime.UtcNow,
                            DateTime.UtcNow.AddDays(1),
                            true,
                            "Api ticket",
                            FormsAuthentication.FormsCookiePath);

                    //Encrypt the ticket.
                    string encTicket = FormsAuthentication.Encrypt(ticket);

                    //Create the cookie.
                    CookieHeaderValue mycookie = new CookieHeaderValue(FormsAuthentication.FormsCookieName, encTicket);

                    // Set the cookie's expiration time to the tickets expiration time
                    if (ticket.IsPersistent)
                        mycookie.Expires = ticket.Expiration;


                    Response.Headers.AddCookies(new CookieHeaderValue[] { mycookie });


                    return Response;
                }
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            //return View(model);
            return Response;
        }
        [Authorize]
        [HttpGet]
        public string Get()
        {
            return User.Identity.Name;
        }
    }

我正在使用 Fiddler,并使用我的 json 对象(包括我的用户名和密码)发布到此方法。如果我调试,一切顺利,我得到以下响应:

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/8.0
Set-Cookie: .ASPXAUTH=4FDA2F2D23381CD0C9AD901BB8A9FE808254502F3BB9442CF80B67F318E7000A1C8B395A97616DBE893317072957F7E1790D81F8648C8472EA80AE2A5E60BE81F08F8C0BF07F2F1EB8E1C661EE56FB61FEA7FCD4D7AABF2718B58690D4D82B049B16126D44368429331D8E3138D533D4; expires=Wed, 27 Feb 2013 21:45:48 GMT
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcUHJvamVjdHNcRGVjaXNpb25NYWtlclxEZWNpc2lvbk1ha2VyXGFwaVx1c2Vyc1w=?=
X-Powered-By: ASP.NET
Date: Tue, 26 Feb 2013 21:45:48 GMT
Content-Length: 0

从这里,我如何访问我的Get()方法而不返回 401 Unauthorized 错误?我确保将以下标头添加到我的 GET 中:

Cookie: .ASPXAUTH=4FDA2F2D23381CD0C9AD901BB8A9FE808254502F3BB9442CF80B67F318E7000A1C8B395A97616DBE893317072957F7E1790D81F8648C8472EA80AE2A5E60BE81F08F8C0BF07F2F1EB8E1C661EE56FB61FEA7FCD4D7AABF2718B58690D4D82B049B16126D44368429331D8E3138D533D4

4

1 回答 1

1

使用 cookie 进行安静的 API 访问并不是最好的方法。最好使用带有授权属性的令牌来实现安全性。这是一个很好的blog post说明如何编写自定义操作过滤器来实现这一点。

于 2013-02-26T21:55:01.220 回答