ASP.NET MVC 5 Identity 2.0, Windows Auth, User model with role attribute

折月煮酒 提交于 2019-12-03 15:43:16

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

Thoughts?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!