Implementing role-based authorization using .NET MVC 5

情到浓时终转凉″ 提交于 2019-12-09 12:44:46

问题


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 ?


回答1:


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);

    . . . .
}



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/40281330/implementing-role-based-authorization-using-net-mvc-5

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