User987
User987

Reputation: 3825

Implementing role-based authorization using .NET MVC 5

I would like to implement a role-based authorization in my web application that I'm building. The way I imagined to make this is to create 3 tables in my DB like following:

1. Roles
2. UserRoles (many to many table)
3. Users 

After that each user would have a role assigned to him. Now... My question is, How do I permit or forbid access to specific views/controllers inside my .NET MVC application. I've stumbled upon this:

[Authorize(Roles = "HrAdmin, CanEnterPayroll")]
[HttpPost]
public ActionResult EnterPayroll(string id)
{
    //  . . . Enter some payroll . . . 
}

The Authorize property seems to be limiting the specific controllers/actions to specific roles... But what if I read the user roles from the table UserRoles like in my case?? How is my application gonna know what role does the User have on the system ??

Can someone help me out with this ?

Upvotes: 7

Views: 33173

Answers (3)

Dawid Rutkowski
Dawid Rutkowski

Reputation: 2756

Here is some pieces of code how you can achieve that using Azure Active Directory. Configuring the application in Startup.cs:

public void ConfigureApplication(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    ...

    app.UseIISPlatformHandler();
    app.UseStaticFiles();

    app.UseCookieAuthentication(options =>
    {
        options.AutomaticAuthenticate = true;
    });            

    app.UseOpenIdConnectAuthentication(options =>
    {
        options.AutomaticChallenge = true;
        options.ClientId = Configuration.Get<string>("Authentication:AzureAd:ClientId");
        options.Authority = Configuration.Get<string>("Authentication:AzureAd:AADInstance") + "Common";
        options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = false,
            RoleClaimType = "roles"
        };
        options.Events = new OpenIdConnectEvents
        {
            OnAuthenticationValidated = (context) => Task.FromResult(0),
            OnAuthenticationFailed = (context) =>
            {
               context.Response.Redirect("/Home/Error");
               context.HandleResponse(); // Suppress the exception
               return Task.FromResult(0);
            },
            OnRemoteError = (context) => Task.FromResult(0)
        };
    });

    app.UseMvc(routes =>
    {
       routes.MapRoute(name: "default", template: "{controller=Dashboard}/{action=Index}/{id?}");                
    });

    DatabaseInitializer.InitializaDatabaseAsync(app.ApplicationServices).Wait();
}

And here is the usage:

[Authorize(Roles = "SuperAdmin, Worker")]
public ActionResult Index()
{
    ViewBag.Message = "Hello";
    return View();
}

and:

public ActionResult Submit(FormCollection formCollection)
{
    if (User.IsInRole("SuperAdmin") || User.IsInRole("Worker"))
    {
        ...
    }

    if (User.IsInRole("Admin"))
    { 
        //do some admin tasks
    }

    return RedirectToAction("Index", "Tasks");
}

Here is my blog post on that: http://www.eidias.com/blog/2016/1/16/using-azure-active-directory-application-roles. You can find there how to configure above roles in AAD.

Upvotes: 0

SᴇM
SᴇM

Reputation: 7213

Lets pretend you have stored your UserName and Roles in Session:

[AllowAnonymous]
[HttpGet]
public ActionResult Login()
{
    . . . .

    string userName = (string)Session["UserName"];
    string[] userRoles = (string[])Session["UserRoles"];

    ClaimsIdentity identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);

    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userName));

    userRoles.ToList().ForEach((role) => identity.AddClaim(new Claim(ClaimTypes.Role, role)));

    identity.AddClaim(new Claim(ClaimTypes.Name, userName));

    AuthenticationManager.SignIn(identity);

    . . . .
}

Upvotes: 7

Emil
Emil

Reputation: 281

if you Authorize a role to access a controller ( at class level ) or a action ( function level ) they roles will have access. otherwise the access is denied.

if you use just the Authorize keyword without specifying the roles or users, all authenticated users will have access.

hope fully i am making it clear ?

to use claims based identity refer to the following

https://msdn.microsoft.com/en-gb/library/ee517291.aspx

https://msdn.microsoft.com/en-gb/library/ff359101.aspx

this is on Core

What is the claims in ASP .NET Identity

Upvotes: 1

Related Questions