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

做~自己de王妃 提交于 2019-12-21 05:07:09

问题


I'm trying to create an MVC5 application that uses Windows Authentication but uses roles pulled from a User model.

I've searched high and low for an example, but the only ones I can find are based on the old ASP.NET identity framework.

Anyone care to point me in the right direction?!

Thanks!


回答1:


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?



来源:https://stackoverflow.com/questions/26004026/asp-net-mvc-5-identity-2-0-windows-auth-user-model-with-role-attribute

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