2016-10-27 47 views
6

我想在我正在构建的Web应用程序中实现基于角色的授权。我想这样做的方式是在我的数据库中创建3个表格,如下所示:使用.NET MVC实现基于角色的授权5

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 . . . 
} 

的授权属性似乎限制了特定的控制器/行动,以特定的角色......但是,如果我读从表中的UserRole用户角色就像我的情况?我的应用程序如何知道用户对系统有什么作用?

有人可以帮我解决这个问题吗?

+0

你检出了[ASP.NET身份](https://www.asp.net/identity)吗? – SeM

+0

您需要在您的“Login()”方法中添加您的角色声明。 – SeM

+0

以上内容已经在MVC5内置的Identity框架中实现。您无需担心自己创建这些表,只需修改默认连接字符串并将其指向服务器即可。 – uk2k05

回答

7

让假装你已经保存您的用户名和角色的会议:

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

    . . . . 
} 
+0

优秀的例子,非常感谢! :) – User987

+0

不客气:) – SeM

+0

我已经尝试过这种方法,但它说,AuthenticationManager类不包含SignIn方法出于某种原因:/ – User987

1

如果您授权角色访问控制器(在课程级别)或角色有权访问的操作(功能级别)。否则访问被拒绝。

如果您只使用Authorize关键字而不指定角色或用户,则所有经过身份验证的用户都有权访问。

希望我完全清楚了吗?

使用基于声明的身份请参阅下面的

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

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

这是核心

What is the claims in ASP .NET Identity

+0

是的,我理解你。这里的问题是,如何从我的数据库中添加角色,以便应用程序知道用户从数据库中拥有哪个角色。 @SeM说我可以用一个叫做“索赔”的东西来做...这是正确的方式吗? – User987

+0

是基于索赔是一种方式去,我已经修改我的休息与一些可以帮助你的链接 – Emil

0

以下是一些代码,您可以使用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中配置上述角色。