7

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!

Jeremy
  • 1,023
  • 3
  • 18
  • 33

1 Answers1

10

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());
    }
}
ataravati
  • 8,891
  • 9
  • 57
  • 89
  • Can a custom authorization attribute automatically run on every request? I thought those were just to add an attribute above specific controllers like [MyCustomAttribute] to restrict users on a specific controller(s). – Jeremy May 11 '15 at 16:23