【发布时间】:2023-03-28 08:56:02
【问题描述】:
我正在尝试在我的应用中实施身份验证方案。控制器,更具体地说是方法,负责检查用户的凭据并生成 jwt,然后将其放入 httponly cookie 中,如下所示
[HttpPost]
[Route("authenticate")]
public async Task<IActionResult> Authenticate([FromBody] User user)
{
var response = await _repository.User.Authenticate(user.Login, user.Password);
if (!response) return Forbid();
var claims = new List<Claim>
{
new Claim("value1", user.Login)
};
string token = _jwtService.GenerateJwt(claims);
HttpContext.Response.Cookies.Append(
"SESSION_TOKEN",
"Bearer " + token,
new CookieOptions
{
Expires = DateTime.Now.AddDays(7),
HttpOnly = true,
Secure = false
});
return Ok();
}
我在 Postman 中测试了这种方法 - 在那里一切正常且正常。 cookie 也正在创建中。此外,最近我使用 Angular 创建了一个应用程序,我使用了相同的身份验证方法,但是使用 Angular 的 HTTP 模块,cookie 一直在创建。这是使用 Axios 在我的 React 应用程序中该方法的样子
export const authenticate = async (login, password) => {
return await axiosLocal.post('/api/auth/authenticate',
{login, password}).then(response => {
return response.status === 200;
}, () => {
return false;
});
我在尝试登录时收到的所有响应都是响应代码 200。我很确定这与 Axios 的设置有关。 此外,如果有人的古玩,变量“axiosLocal”包含 API 的 baseURL。
- 更新 1 好的。如果我没有弄错,为了从响应中设置 cookie,我必须使用 { withCredentials: true } 选项发送所有请求。但是当我尝试这样做时,请求被 CORS 阻止,尽管我已经设置了一个 cors 策略,它必须允许处理来自任何来源的请求
app.UseCors(builder => builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials());
【问题讨论】:
标签: javascript asp.net asp.net-core