app.UseCookieAuthentication(new CookieAuthenticationOptions() { AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme, LoginPath = new PathString("/Account/Unauthorized/"), AccessDeniedPath = new PathString("/Account/Forbidden/"), AutomaticAuthenticate = true, AutomaticChallenge = false, CookieHttpOnly = true, CookieName = "MyCookie", ExpireTimeSpan = TimeSpan.FromHours(2) });
public async void Login() { if (!HttpContext.User.Identities.Any(identity => identity.IsAuthenticated)) { var user = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "bob") }, CookieAuthenticationDefaults.AuthenticationScheme)); await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user); HttpContext.Response.ContentType = "text/plain"; await HttpContext.Response.WriteAsync("Hello First timer"); } else { HttpContext.Response.ContentType = "text/plain"; await HttpContext.Response.WriteAsync("Hello old timer"); } }
高手帮忙解答
将 AutomaticChallenge 改为 true 试试。
将 AutomaticChallenge 改为 true 后一样报错,改为public async Task<bool> Login() 且不报错,但是Cookies还是写不进去,身份认证无效
问题已解决,参考 MusicStore-dev
怎么解决的,能不能说一下?
@夕阳茶: 就是把Cookies设置放到 MVC之前
app.UseCookieAuthentication(new CookieAuthenticationOptions() { AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme, LoginPath = new PathString("/Account/Unauthorized/"), AccessDeniedPath = new PathString("/Account/Forbidden/"), AutomaticAuthenticate = true, AutomaticChallenge = false, CookieHttpOnly = true, CookieName = "MyCookie", ExpireTimeSpan = TimeSpan.FromHours(2) }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });
@痛快: 嗯,我在官方的文档上也找到了答案,谢谢。https://docs.asp.net/en/latest/security/authentication/cookie.html