gpt4 book ai didi

c# - 通过身份验证后访问 Web API 上的方法

转载 作者:行者123 更新时间:2023-11-30 17:55:25 25 4
gpt4 key购买 nike

我无法理解如何使用我的 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 错误?我确保将以下 header 添加到我的 GET 中:

Cookie: .ASPXAUTH=4FDA2F2D23381CD0C9AD901BB8A9FE808254502F3BB9442CF80B67F318E7000A1C8B395A97616DBE893317072957F7E1790D81F8648C8472EA80AE2A5E60BE81F08F8C0BF07F2F1EB8E1C661EE56FB61FEA7FCD4D7AABF2718B58690D4D82B049B16126D44368429331D8E3138D533D4

最佳答案

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

关于c# - 通过身份验证后访问 Web API 上的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15100049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com