【问题标题】:How to implement role based authentication in ASP.net MVC .core 3.1 without Entity Framework如何在没有实体框架的 ASP.net MVC .core 3.1 中实现基于角色的身份验证
【发布时间】:2021-08-15 13:01:06
【问题描述】:

我目前正在从事一个由 3 个角色组成的视频流项目。 “管理员”、“员工”和“客户”。管理员有权赋予帐户特定角色。我不能为此使用实体框架。有人对我有很好的教程/文档吗?谢谢!

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-core asp.net-identity


    【解决方案1】:

    你需要像这样创建一个自定义属性

    // Custom [Authorized] attribute for JWT and Enum based roles
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class AuthorizedAttribute : Attribute, IAuthorizationFilter
    {
        private readonly Roles[] _roles;
        public AuthorizedAttribute(params Roles[] roles)
        {
            _roles = roles;
        }
    
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            // We're checking here to see if the route has been decorated with an [AllowAnonymous] attribute. If it has, we skip authorization
            // for the route. Doing this allows us to apply the [Authorize] attribute by default in the startup using:
            //
            // services.AddControllers().AddMvcOptions(x => x.Filters.Add(new AuthorizeAttribute()))
            //
    
            if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
            {
                var hasAllowAnonymousAttribute = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
                    .Any(a => a.GetType() == typeof(AllowAnonymousAttribute));
                if (hasAllowAnonymousAttribute)
                {
                    return;
                }
            }
    
            // Check if valid user
            var user = (AuthUser)context.HttpContext.Items["User"];
            if (user == null)
            {
                // Not logged in 
                context.Result = new ObjectResult(Logger.Error("Unauthorized request", HttpStatusCode.Unauthorized))
                { 
                    StatusCode = (int)HttpStatusCode.Unauthorized 
                };
                return;
            }
    
            // Check if valid role            
            Enum.TryParse(user.role, out Roles role);
            if (_roles.Length > 0 && !_roles.Contains(role))
            {
                // User is logged in, but the role is not allowed to access this method
                context.Result = new ObjectResult(Logger.Error($"Your current role `{user.role}` does not have access to this API", HttpStatusCode.Unauthorized))
                {
                    StatusCode = (int)HttpStatusCode.Unauthorized
                };
                return;
            }
        }
    
        
    }
    

    并像这样在控制器的操作方法中使用:-

     [HttpPost]
     [Authorized(Roles.Employee, Roles.Admin, Roles.Customers)]
     public async Task<IActionResult> Create()
     {
      //.............your code
     }
    

    这里是完整的例子,你可以参考它并相应地修改你的实现。无需实体框架

    【讨论】:

      【解决方案2】:

      您可以将您的应用程序配置为使用 JWT(json Web 令牌)登录并设置自定义身份验证。用户登录成功后,您可以生成一个带有 Role 声明的 JWT 令牌,然后将 JWToken 用于 HTTP 请求,然后实现基于角色的身份验证。更多详细信息,请参考以下链接:

      Login And Role Based Custom Authentication In ASP.NET Core 3.1

      ASP.NET Core 3.1 - Role Based Authorization Tutorial with Example API

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-06
        • 2016-03-07
        • 2019-06-19
        • 1970-01-01
        • 2016-07-11
        • 2020-01-23
        • 2011-11-09
        相关资源
        最近更新 更多