reactjs - Asp.net core 2.0 react.js cookie认证同构-获取无限循环
问题描述
我有一个带有 react.js 的小型 asp.net 核心应用程序,它使用 cookie 身份验证对用户进行身份验证。当我直接调用控制器的操作时,似乎 cookie 身份验证工作正常。
例如,如果我输入http://localhost/Test/Index它会按预期工作。进行身份验证并创建 cookie,并在后面的请求中使用 cookie。
但是,当我的 react 组件使用 isomorphic-fetch 调用控制器方法时,它会变成无休止的身份验证循环。
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
public class TestController : Controller
{
public IActionResult Index()
{
return View();
}
}
这是我的startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddOptions();
services.AddAuthentication(o =>
{
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.DefaultAuthenticateScheme =
CookieAuthenticationDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(19);
options.AccessDeniedPath = "/Account/Forbidden/";
options.LoginPath = "/Account/Login/";
});
这是我验证用户的地方。(AccountController/Login)
var claims = new[]
{
new Claim(ClaimTypes.Name,userName),
new Claim("AccessToken", string.Format("Bearer {0}", token.AccessToken))
};
ClaimsIdentity userIdentity = new ClaimsIdentity(claims,CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
principal,new AuthenticationProperties{ IsPersistent=true});
return RedirectToAction("Index", "Home");
这是我创建无限登录循环的 fetch 方法。
export class ProposalGrid extends React.Component<RouteComponentProps<{}>, FetchDataExampleState> {
constructor(props: RouteComponentProps<{}>) {
super(props);
this.pageChange = this.pageChange.bind(this);
this.state = { proposalDatas: [], loading: true, dataState: { take: 10, skip: 0 } };
let url = "ProposalData/GetProposals?" + $.param({ take: 10, skip: 0 })
fetch(url)
.then(response => response.json() as Promise<ProposalData[]>)
.then(data => {
this.setState({ proposalDatas: data, loading: false });
});
}
解决方案
我在获取数据时包含凭据并将方法更改为 post.Problem 消失了。
fetch(url, {
method: 'POST',
credentials: 'include',
推荐阅读
- laravel - 注销路由是否应该受到保护?
- android - Kotlin Flow:带有回调对象延迟初始化器的 callbackFlow
- php - 如何在 symfony 5.2 中将实体依赖注入到控制器中?
- r - 如何绘制具有不连续 y 轴的构面
- oracle - 在 Oracle 中在另一个视图上创建物化视图而不会过时/需要编译状态
- netsuite - Suitescript 2.0 获取子列表上的按钮
- r - R:改变稀疏矩阵的对角线非常慢
- bots - 如何使用 ID 添加对特定消息的反应?(discord.py)
- javascript - 将 API 中的 JSON 数据保存到数据库中并缓存请求,因此我不需要再次从 API 请求 - Node.js / Express.js
- c# - 我有 ac# 一个控制台应用程序,我需要将其转换为 Azure 函数