我使用的是 ASP.NET Core 3.1,将 Identity EF 与自定义 ApplicationUser 一起使用,该 ApplicationUser 具有 3 个额外的跟踪属性。
我遇到了 [Authorize]
属性的问题。
当您访问带有 HomeController
装饰的 [Authorize]
时,用户将毫无问题地到达并获得相应的视图。
但是当它尝试在第二个控制器 (HistoricosController
) 上执行此操作时,该控制器也应用了 [Authorize]
,用户将被带到登录页面,并要求再次登录。之后,他就可以不用重新登录了。
我已经调查过为什么我的 [Authorize]
属性会出现这种情况,但没有成功。以下是我已经考虑过但没有结果的一些事情:
app.UseRouting | app.UseAuthentication | app.UseAuthorization | app.UseEndpoints
的顺序services.AddAuthentication()
和 services.AddAuthorization()
中间件我的ConfigureServices
方法:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("ApConectionString2"));
});
services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
options.SignIn.RequireConfirmedEmail = false;
options.SignIn.RequireConfirmedPhoneNumber = false;
options.Password.RequireDigit = true;
options.Password.RequiredUniqueChars = 0;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@";
})
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders()
.AddDefaultUI();
services.AddTransient<IEmailSender, EmailSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);
services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromHours(24);
options.LoginPath = "/Identity/Account/Login";
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
options.SlidingExpiration = true;
});
services.AddControllersWithViews().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
services.AddRazorPages();
}
我的 Configure
启动方法:
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.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
此外,这种“奇怪的行为”仅在我从 Internet 进行测试时发生,而在我在本地(本地主机)调试时不会发生。
如果您能帮助我找到解决方案,我将不胜感激。