lem*_*mon 7 cookies asp.net-web-api asp.net-core axios
我正在我的 ASP.NET CORE WEB API + React 应用程序中实现刷新令牌,但我不知道如何使用另一个请求将此令牌发送回我的 API。
我的API 将refreshToken 作为HttpOnly cookie 添加到请求中。
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> GenerateToken([FromForm]LoginModel model)
{
var result = await _userService.GetTokenAsync(model);
SetRefreshTokenInCookie(result.RefreshToken);
return Ok(result);
}
Run Code Online (Sandbox Code Playgroud)
private void SetRefreshTokenInCookie(string refreshToken)
{
var cookieOptions = new CookieOptions
{
HttpOnly = true,
Expires = DateTime.UtcNow.AddDays(10)
};
Response.Cookies.Append("refreshToken", refreshToken, cookieOptions);
}
Run Code Online (Sandbox Code Playgroud)
在我的 Chrome 开发工具中浏览“网络”时,我可以看到带有刷新令牌的 cookie。
但“应用程序”中没有cookie
并且下一个请求中也没有cookie。
我正在使用 axios 发送请求。如何在后端获取刷新令牌?
您需要添加withCredentials
. 使用此标志,它将向服务器发送所有 HttpOnly cookie。
axios("http://example.com/api/things/", {
method: "post",
data: someJsonData,
withCredentials: true
})
Run Code Online (Sandbox Code Playgroud)
事实证明这是 CORS 问题。在我的 Startup.cs 文件中设置它就像一个魅力。
services.AddCors(options =>
{
options.AddPolicy("CORSAllowLocalHost3000",
builder =>
builder.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials() // <<< this is required for cookies to be set on the client - sets the 'Access-Control-Allow-Credentials' to true
);
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15103 次 |
最近记录: |