簡體   English   中英

ASP.NET CORE MVC 身份用戶和角色不起作用

[英]ASP.NET CORE MVC identity users and roles doesn't work

我有一個啟用了標識的 ASP.NET CORE MVC 3.1 應用程序:

services.AddIdentity<IdentityUser,IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();

DB Context 繼承自身份:

ApplicationDbContext : IdentityDbContext

啟動配置:

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();
}); 

但是,它不會在瀏覽應用程序時強制執行身份驗證。 但是,如果我使用 services.AddDefaultIdentity,它可以工作,但我失去了訪問 RolManager 以獲取經過身份驗證的用戶角色的功能。

您能否就我需要做什么來強制執行身份驗證提出建議?

你有兩種可能:

  1. [Authorize]裝飾您想要保護的每個端點。 這在較大的代碼庫中會變得非常重復。
  2. 在您的端點上全局需要授權:
    app.UseEndpoints(endpoints =>
     {
         //or | and  MapControllersWithViews()
         endpoints.MapControllers().RequireAuthorization();
         endpoints.MapRazorPages().RequireAuthorization();
     });

請注意,這也將保護您的登錄端點,因此您必須通過使用[AllowAnonymous]裝飾它們來排除它們。

細節:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM