簡體   English   中英

使用 .NET MVC 5 實現基於角色的授權

[英]Implementing role-based authorization using .NET MVC 5

我想在我正在構建的 Web 應用程序中實現基於角色的授權。 我想象的方法是在我的數據庫中創建 3 個表,如下所示:

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

之后,每個用戶都會有一個分配給他的角色。 現在...我的問題是,如何允許或禁止訪問我的 .NET MVC 應用程序中的特定視圖/控制器。 我偶然發現了這個:

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

Authorize 屬性似乎將特定控制器/操作限制為特定角色......但是如果我從表 UserRoles 中讀取用戶角色怎么辦? 我的應用程序如何知道用戶在系統中扮演什么角色??

有人可以幫我解決這個問題嗎?

讓我們假設您已經在 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);

    . . . .
}

如果您授權角色訪問控制器(在類級別)或操作(功能級別),則他們的角色將有權訪問。 否則訪問被拒絕。

如果您只使用 Authorize 關鍵字而不指定角色或用戶,則所有經過身份驗證的用戶都將具有訪問權限。

希望我說清楚了?

要使用基於聲明的身份,請參閱以下內容

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

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

這是在核心

ASP .NET Identity 中的聲明是什么

以下是一些如何使用 Azure Active Directory 實現這一目標的代碼。 在 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();
}

這是用法:

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

和:

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

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

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

這是我的博客文章: http : //www.eidias.com/blog/2016/1/16/using-azure-active-directory-application-roles 您可以在那里找到如何在 AAD 中配置上述角色。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM