公式のasp.netドキュメント(https://docs.asp.net/en/latest/security/authentication/cookie.html)に記載されているように、ASP.NETコアからCookieミドルウェアを使用してカスタム認証を作成しようとしました。クッキーミドルウェアが正しくクッキーを設定していない
残念ながら、私のASP.NET MVCプロジェクトでは機能しません。「HttpContext.Authentication.SignInAsync」を呼び出した後にクッキーが設定されていません。
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentity();
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "CookieInstance",
LoginPath = new PathString("/Account/Login/"),
AccessDeniedPath = new PathString("/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookieSecure = env.IsDevelopment()
? CookieSecurePolicy.None
: CookieSecurePolicy.Always
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
ログインコントローラ
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
if (ModelState.IsValid && model.Email == "[email protected]")
{
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, "Kev", ClaimValueTypes.String)
};
var userIdentity = new ClaimsIdentity(claims, "CookieInstance");
var userPrincipal = new ClaimsPrincipal(userIdentity);
await HttpContext.Authentication.SignInAsync("CookieInstance", userPrincipal,
new AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
IsPersistent = false,
AllowRefresh = false
});
return RedirectToLocal(returnUrl);
} else { ... }
...
}
それが正常にページを修正するために私をリダイレクトしませんが、apparentelyクッキーの意志:ここ
は私の現在のコードです設定する。たとえば、SignInManager.IsSignedIn(User)はまだfalseを返しています。
解決方法はありますか?
おかげ
あなたはクッキーが作成されていないことを確認するためにWebブラウザのdevツールを使用しましたか? ClaimTypes.NameIdentifierクレーム –
が必要な場合もあります。SignInManagerは、独自のCookieミドルウェアを設定しているので使用しているように見えないIdentityシステムの一部です。 –