登录页面的Asp.Net Core 3.1 Cookie身份验证循环



当我成功登录到HTTP上下文并被重定向到主控制器时,主控制器的Authorize属性会将我重定向到登录路径,因为我不知道。(无限循环(

validate-async方法不会让我注销或拒绝cookie(我检查过了(

但问题出在哪里?我在ASP.NET Core 2.1项目中有相同的身份验证过程,它在那里工作得很好。

我使用自定义authorize属性对其进行测试,以检查上下文。在这种情况下,我有一个委托人,我通过了身份验证。

但是为什么要重定向标准的authorize属性?

我的配置是:

HomeController.cs

public class HomeController : Controller
{
[Authorize]
public IActionResult Index()
{
return this.View("Index");
}
}

启动.cs

public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/auth/login/";
options.ExpireTimeSpan = TimeSpan.FromDays(7);
options.Events.OnValidatePrincipal = ValidateAsync;
});
services.AddControllersWithViews();
services.AddAntiforgery();
services.AddDbContext<ApplicationDbContext>((serviceProvider, options) =>
{
options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection"));
options.EnableSensitiveDataLogging();
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
public static async Task ValidateAsync(CookieValidatePrincipalContext context)
{
context = context ?? throw new ArgumentNullException(nameof(context));
String userId = context.Principal.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.NameIdentifier)?.Value;
if(userId == null)
{
context.RejectPrincipal();
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return;
}
ApplicationDbContext dbContext = context.HttpContext.RequestServices.GetRequiredService<ApplicationDbContext>();
User user = await dbContext.Users.FindAsync(Guid.Parse(userId));
if(user == null)
{
context.RejectPrincipal();
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return;
}
if(!user.StaySignedIn && 
user.LastLogin != null && 
(user.LastLogin.Subtract(TimeSpan.FromDays(1)) > DateTimeOffset.Now))
{
context.RejectPrincipal();
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return;
}
}

AuthController.cs

[Route("/login")]
[Route("/auth/login")]
public async Task<IActionResult> Login([FromForm]LoginModel loginModel)
{
Claim nameIdentifier = new Claim(ClaimTypes.NameIdentifier, user.Id.ToString());
ClaimsIdentity userIdentity = new ClaimsIdentity(new List<Claim> { nameIdentifier }, CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(userIdentity);
await this.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
return this.RedirectToAction("Index", "Home");
}

我找到了问题的解决方案。

的顺序

app.UseAuthorization();
app.UseAuthentication();

必须更改,然后才能工作。

问题已解决当使用身份时不允许使用cookie。它会覆盖某些信息。Git讨论

Cookie选项告诉身份验证中间件Cookie在浏览器中的工作方式。在Startup类中,将此代码添加到ConfigureServices方法中

services.AddAuthentication(options =>
{
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(options => { options.LoginPath = "/Login"; });

最新更新