且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC 5 Identity 2.0,Windows Auth,具有角色属性的用户模型

更新时间:2023-02-16 09:43:53

所以我想出了一种解决此问题的方法.我创建了一个自定义授权属性,用于检查User模型中的角色.

So I've figured out one approach to solving this problem. I created a custom Authorization Attribute that checks the User model for a role.

using System.Linq;
using System.Web;
using System.Web.Mvc;
using App.Models;
using System.Security.Claims;

namespace App.Extensions.Attributes
{
    public class AuthorizeUser : AuthorizeAttribute
    {
        Context context = new Context();

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {

            if (httpContext == null) 
                return false;

            string login = ClaimsPrincipal.Current.Claims.ElementAt(1).Value.Split('@')[0];
            string[] roles = base.Roles.Split(',');
            User user = context.Users.FirstOrDefault(u => u.Login == login);

            if (user == null)
                return false;
            else if (base.Roles == "")
                return true;
            else
                return roles.Contains(user.Role.ToString());
        }
    }
}

有想法吗?