[英]ASP.NET Core 3.1 [Authorize] attribute redirects to login even for logged in user
我有一個 ASP.NET Core 沙箱項目。 我添加了IdentityDbContext
。 注冊頁面工作正常。 登錄/注銷頁面工作正常。 (可以通過為SignInManager.IsSignedIn(User)
用戶顯示的 html 看到)
我有一個標有[Authorize]
的控制器:
[Authorize]
public class MyTestController : Controller
{
...
}
當我第一次嘗試導航到它時 - 它工作正常(重定向到登錄頁面)
但是在成功登錄后,它再次重定向到使用相同鏈接登錄: https://localhost:44359/Identity/Account/Login?ReturnUrl=%2FMyTest
這是我來自Startup.cs
代碼:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews().AddRazorRuntimeCompilation();
services.AddRazorPages().AddRazorRuntimeCompilation();
services.AddControllers().AddNewtonsoftJson(options =>
{
// Use the default property (Pascal) casing
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
services.AddDbContext<MyAppContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
services.AddDefaultIdentity<IdentityUser>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
})
.AddEntityFrameworkStores<MyAppContext>();
services.AddAuthorization();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
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?}");
endpoints.MapRazorPages();
});
}
以前,我為登錄、注銷、注冊添加了腳手架身份項。 沒有[Authorize]
控制器運行良好。
在我看來,您的中間件的順序不正確。 ASP.NET 需要知道用戶是否首先通過了身份驗證,以便確定它是否有權進行請求。 嘗試交換這兩個:
app.UseAuthentication();
app.UseAuthorization();
微軟關於這個主題的文檔: 配置身份
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.