Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 254
cschiewek Avatar asked Nov 10 '22 01:11

cschiewek


1 Answers

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?

like image 116
cschiewek Avatar answered Nov 15 '22 06:11

cschiewek