【发布时间】:2022-02-16 22:30:19
【问题描述】:
我一直被与 cookie 相关的此类问题所困扰。
我的情况是这样的:
- 我的后端在服务器上 (localhst:12456)
- 我的 Angular 2 应用程序在另一台服务器 (localhost:5555) 上运行
我的后端只是一个 ASP.NET 应用程序,我正在尝试从 apiController 对用户进行身份验证。 api Controller 是这样的:
[System.Web.Mvc.HttpPost]
public HttpResponseMessage HandleLogin([FromBody] LoginModel loginModel)
{
if (!String.IsNullOrEmpty(loginModel.Username) && !String.IsNullOrEmpty(loginModel.Password))
{
if (Members.Login(loginModel.Username, loginModel.Password))
{
var resp = Request.CreateResponse<UserAuthenticationModel>(
HttpStatusCode.OK,
new UserAuthenticationModel() { IsAuthenticated = true}
);
//create and set cookie in response
var cookie = new CookieHeaderValue("customCookie", "cookieVal");
cookie.Expires = DateTimeOffset.Now.AddDays(1);
cookie.Domain = Request.RequestUri.Host;
cookie.Path = "/";
resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return resp;
}
}
return Request.CreateResponse<UserAuthenticationModel>(
new UserAuthenticationModel() { IsAuthenticated = false }
);
}
现在,在我的 Angular 应用中,我正在调用一个 http 帖子:
headers.append('Access-Control-Allow-Credentials', true);
return this._http.post(this._globalVariables.BACKEND_API_HANDLE_LOGIN, loginModel, {headers: headers})
.map((response : Response) => response);
this._loginService.getLoginModel() 。订阅( loginModel => this._signInPageModel = loginModel, 错误 => 控制台日志(错误) ); 现在,在我的 api 控制器方法(HandleLogin)中,我有一个测试 cookie 和另一个用于 FormsAuthentication 的 cookie,当用户成功登录并返回到我的 Angular 应用程序时,不会创建任何 cookie。
现在,可以看到 cookie 以及我的响应标头的帖子:
我对此感到很困惑,并感谢任何帮助以成功获得登录过程。
提前谢谢你。
【问题讨论】:
-
你还有什么问题?
-
你找到问题了吗?
标签: asp.net-mvc angular cookies asp.net-web-api cors