Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET 5 Custom roles for Windows Authentication

I'm building an intranet type site with ASP.NET 5 that uses Windows Authentication. I have the authentication working, but I don't want everyone on the domain to have access to the intranet site. I can't use domain roles so I've set up my own custom roles in my SQL Server. I have a table that maps the domain username to roles. I want to restrict access to the intranet site to only users that have a role defined in my SQL Server role table. How would I set up custom roles for Windows Authentication in ASP.NET 5? Thanks!

like image 727
Jeremy Avatar asked May 10 '15 04:05

Jeremy


1 Answers

You don't set up custom roles. You need to create a custom authorization attribute, as described here.

UPDATE:

Yes, you can use your custom authorize attribute globally. Let's say here's your custom authorize attribute:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var username = httpContext.User.Identity.Name;

        // Check to see if user has a role in the database
        var isAuthorized = db.User.Find(username).Any();

        return isAuthorized;
    }
}

Then, you can either use it at the Action level or Controller level like this:

[MyAuthorize]
public ActionResult Index()
{
}

Or, you can register it as a global filter in your FilterConfig class under the App_Start folder, like this:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new MyAuthorizeAttribute());
    }
}
like image 102
ataravati Avatar answered Nov 05 '22 06:11

ataravati