简体   繁体   English

使用自定义表在MVC和Web API中实现基于角色的授权

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

I have inherited an application with database. 我已经用数据库继承了一个应用程序。 The database has following tables related to authentication and authorization. 该数据库具有与身份验证和授权相关的下表。

User Table 用户表

UserName 用户名

Password 密码

UserTypeId UserTypeId

UserType Table 用户类型表

UserTypeId UserTypeId

UserTypeDesc UserTypeDesc

The User Type table stores the roles for the user eg Admin, Editor, etc. 用户类型表存储了用户的角​​色,例如管理员,编辑者等。

If I want to implement authorization like below 如果我想实现如下授权

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

Where and what should I code so that the roles are available to the authorize attribute ? 我应该在哪里和什么地方编写代码,以便角色可以用于authorize属性?

Edit 编辑

I already have a database. 我已经有一个数据库。 So I cannot use the AspNetUserRoles or AspNetRoles tables. 因此,我不能使用AspNetUserRoles或AspNetRoles表。 I need to set the roles using my custom tables. 我需要使用自定义表设置角色。

Edit2 编辑2

As asked by @Nkosi, here is code snippet of how authentication is implemented. 如@Nkosi所问,这是如何实现身份验证的代码段。 The actual implementation calls the business layer service and performs encryption and other stuff but I have simplified the snippet 实际的实现调用业务层服务并执行加密等操作,但是我简化了代码段

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

This method is called from the login page where user enters the UserName and Password 从用户输入用户名和密码的登录页面调用此方法。

Your question was very easy. 您的问题很简单。 You just need to sync these 2 tables with AspNetUserRoles and AspNetRoles tables respectively. 您只需要分别将这两个表与AspNetUserRoles和AspNetRoles表同步即可。 Actually, Authorize attribute by default checks these two tables. 实际上,默认情况下,Authorize属性会检查这两个表。 So your roles need to reflect in them. 因此,您的角色需要在其中体现出来。 These tables are made by default by EF if you select MVC template project. 如果您选择MVC模板项目,这些表是EF默认创建的。

Using these Answers for reference 使用这些答案作为参考

Having Trouble with Forms Authentication Roles 表单身份验证角色遇到问题

FormsAuthentication Roles without Membership 没有成员身份的FormsAuthentication角色

After having set the auth cookie on login like you did originally, 像最初一样在登录时设置了身份验证Cookie之后,

you do the following in your Global.asax.cs 您在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 ;
        }
    }
}

The nice thing about how they implemented it is that it handles Claims based roles using the ClaimsIdentity and ClaimsPrincipal objects, without putting the roles in the user's cookie. 关于它们如何实现的ClaimsIdentity是,它使用ClaimsIdentityClaimsPrincipal对象处理基于Claims的角色,而无需将角色放入用户的cookie中。 It also handles authentication in the Global.asax.cs file without having to resort to putting in custom authorize attributes. 它还可以处理Global.asax.cs文件中的身份验证,而不必Global.asax.cs自定义授权属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在ASP.NET MVC Web API服务和MVC客户端体系结构中实现身份验证和基于角色的授权 - Implementing Authentication and role based authorization in ASP.NET MVC web API service and MVC client architecture 使用 .NET MVC 5 实现基于角色的授权 - Implementing role-based authorization using .NET MVC 5 具有基于角色的授权的ASP.NET Web Api - ASP.NET Web Api with Role based authorization ASP.net MVC 4中基于角色的授权 - Role based Authorization in ASP.net MVC 4 Web API的ASP.Net MVC自定义授权 - ASP.Net MVC Custom Authorization for Web API ASP.NET Core 3.1 MVC 访问被拒绝基于角色的授权 - 与自定义 UserClaimsPrincipalFactory 冲突 - ASP.NET Core 3.1 MVC Access Denied role based authorization - Conflict with custom UserClaimsPrincipalFactory 实现我自己的基于角色的授权而不是使用成员资格的优势? - Advantage of implementing my own role based authorization instead of using Membership? IdentityServer4 基于角色的 Web API 授权与 ASP.NET Core 标识 - IdentityServer4 Role Based Authorization for Web API with ASP.NET Core Identity 创建我的自定义安全角色和自定义用户组表,以实现对asp.net mvc Web应用程序的自定义授权 - Creating my custom security role and custom user group tables, to implement custom authorization for my asp.net mvc web application 基于ASP.NET Web API角色的身份验证自定义属性,检查用户是否在角色中 - asp.net web api role based authentication custom attribute check if user in role
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM