簡體   English   中英

使用自定義表在MVC和Web API中實現基於角色的授權

[英]Implementing role based authorization in MVC and Web API with custom table

我已經用數據庫繼承了一個應用程序。 該數據庫具有與身份驗證和授權相關的下表。

用戶表

用戶名

密碼

UserTypeId

用戶類型表

UserTypeId

UserTypeDesc

用戶類型表存儲了用戶的角​​色,例如管理員,編輯者等。

如果我想實現如下授權

[Authorize(Roles="Admin, Editor")]
    public IHttpActionResult GetOrders()
        {
          //Code here
        }

我應該在哪里和什么地方編寫代碼,以便角色可以用於authorize屬性?

編輯

我已經有一個數據庫。 因此,我不能使用AspNetUserRoles或AspNetRoles表。 我需要使用自定義表設置角色。

編輯2

如@Nkosi所問,這是如何實現身份驗證的代碼段。 實際的實現調用業務層服務並執行加密等操作,但是我簡化了代碼段

public HttpResponseMessage Authenticate(User user)
{ 
    var isValid = myRepository.Exists(a => a.UserName == user.UserName &&       a.Password == user.Password);
   if(isValid)
  {
    FormsAuthentication.SetAuthCookie(user.UserName,false);
   }
}

從用戶輸入用戶名和密碼的登錄頁面調用此方法。

您的問題很簡單。 您只需要分別將這兩個表與AspNetUserRoles和AspNetRoles表同步即可。 實際上,默認情況下,Authorize屬性會檢查這兩個表。 因此,您的角色需要在其中體現出來。 如果您選擇MVC模板項目,這些表是EF默認創建的。

使用這些答案作為參考

表單身份驗證角色遇到問題

沒有成員身份的FormsAuthentication角色

像最初一樣在登錄時設置了身份驗證Cookie之后,

您在Global.asax.cs執行以下操作

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

    if (authCookie != null)
    {
        var ticket = FormsAuthentication.Decrypt(authCookie.Value);

        FormsIdentity formsIdentity = new FormsIdentity(ticket);

        ClaimsIdentity claimsIdentity = new ClaimsIdentity(formsIdentity);

        //get the user from your custom tables/repository
        var user = myUserRepository.GetUserByEmail(ticket.Name);
        if(user!=null){
            var userTypeId = user.UserTypeId;
            var role = myUserTypeRepository.GetUserTypeById(userTypeId);
            if(role != null) {
                //Assuming the roles for the user e.g. Admin, Editor, etc. 
                // is in the UserTypeDesc property
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, role.UserTypeDesc));
            }
        }    
        ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

        System.Threading.Thread.CurrentPrincipal = claimsPrincipal ;
        if (System.Web.HttpContext.Current != null) {
            System.Web.HttpContext.Current.User = claimsPrincipal ;
        }
    }
}

關於它們如何實現的ClaimsIdentity是,它使用ClaimsIdentityClaimsPrincipal對象處理基於Claims的角色,而無需將角色放入用戶的cookie中。 它還可以處理Global.asax.cs文件中的身份驗證,而不必Global.asax.cs自定義授權屬性。

暫無
暫無

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

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