我有一个带有 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 });
});
}