当使用ASP.NET Core Web API与Identity和React SPA前端进行身份验证时,遇到身份验证cookie未保存到浏览器的问题。以下是可能的解决方法和代码示例:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
// 配置JWT验证选项
});
services.AddIdentity()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options =>
{
// 配置身份验证cookie选项
});
import Axios from 'axios';
const api = Axios.create({
// 配置API基本URL等
});
// 发送API请求时将身份验证cookie传递到后端
api.interceptors.request.use(config => {
const token = localStorage.getItem('token'); // 从本地存储中获取JWT令牌
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// 示例API请求
api.get('/api/some-endpoint')
.then(response => {
// 处理响应
})
.catch(error => {
// 处理错误
});
var claims = new List
{
// 添加身份验证相关的声明
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
var authenticationProperties = new AuthenticationProperties
{
// 配置身份验证cookie属性
};
await HttpContext.SignInAsync(principal, authenticationProperties);
通过在身份验证cookie的AuthenticationProperties中设置Domain和Path属性,可以确保cookie在浏览器中正确保存。
希望这些解决方法和代码示例能够帮助你解决身份验证cookie未保存到浏览器的问题。