tof*_*325 5 c# cookies rest asp.net-core
我只是想保存包含安全令牌的 cookie,但它们不会保留在浏览器中。这是我AuthController保存 cookie 的方法(简化):
[AllowAnonymous]
[HttpPost("authorize")]
[ProducesResponseType((int)HttpStatusCode.OK)]
public async Task<IActionResult> AuthorizeAsync()
{
//generating access token ommited for brevity
SetTokenCookie(accessToken);
return Ok(userIdentity);
}
Run Code Online (Sandbox Code Playgroud)
及SetTokenCookie方法:
private void SetTokenCookie(string accessToken)
{
var options = _jwtOptions.AccessToken;
var cookieOptions = new CookieOptions()
{
HttpOnly = true,
IsEssential = true,
Secure = false,
SameSite = SameSiteMode.Strict,
Domain = options.Issuer, //http://localhost:3394 by default
Expires = DateTime.UtcNow.AddDays(14)
};
Response.Cookies.Append(options.Name, accessToken, cookieOptions);
}
Run Code Online (Sandbox Code Playgroud)
现在,当我分析 Api 的响应时,我发现Set-Cookieheader 和 token 本身都很好:
解码后的令牌:
{
"id": "70132f61-4d83-4772-9685-7a77a9204685",
"name": "admin",
"email": "xyz@xyz.pl",
"role": "Administrator",
"persist": "True",
"nbf": 1646336045,
"exp": 1646336945,
"iat": 1646336045,
"iss": "http://localhost:3394",
"aud": [
"blog.webgateway",
"blog.blogging",
"blog.comments",
"blog.users"
]
}
Run Code Online (Sandbox Code Playgroud)
但是当我检查cookies时,什么也没有保存。
我知道与此问题相关的主题有很多,但我已经用完了可以在网上找到的想法:
HttpOnly, Secure, SameSite)UseHttpsRedirection()从我的中删除Startup.cs并确保我通过以下方式连接HTTP似乎什么都不起作用。我使用的是 Firefox 97.0.1。你知道我还可以尝试什么吗?
您是否尝试将其更改Domain为localhost?
根据我的测试,使用``对我来说不起作用,然后我发现其他cookie显示它们属于domain localhost,所以我使用localhost代替,然后我可以看到新创建的cookie。我测试通过chrome中的工具调用api,所以我认为它应该与你的场景类似。
public string saveCookie() {
var cookieOptions = new CookieOptions()
{
HttpOnly = true,
IsEssential = true,
Secure = false,
SameSite = SameSiteMode.Strict,
Domain = "localhost", //using https://localhost:44340/ here doesn't work
Expires = DateTime.UtcNow.AddDays(14)
};
Response.Cookies.Append("testCookie", "Cookie content", cookieOptions);
return "hello world";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11352 次 |
| 最近记录: |