使用 .NET MVC 5 实现基于角色的授权
Implementing role-based authorization using .NET MVC 5
我想在我正在构建的 Web 应用程序中实施基于角色的授权。我想象的方法是在我的数据库中创建 3 tables,如下所示:
1. Roles
2. UserRoles (many to many table)
3. Users
之后,每个用户都会分配给他一个角色。现在...我的问题是,如何允许或禁止访问我的 .NET MVC 应用程序中的特定 views/controllers。我偶然发现了这个:
[Authorize(Roles = "HrAdmin, CanEnterPayroll")]
[HttpPost]
public ActionResult EnterPayroll(string id)
{
// . . . Enter some payroll . . .
}
Authorize 属性 似乎将特定 controllers/actions 限制为特定角色...但是如果我像我的情况一样从 table UserRoles 中读取用户角色怎么办? ?我的应用程序如何知道用户在系统中扮演什么角色??
有人可以帮我解决这个问题吗?
如果您授权角色访问控制器(在 class 级别)或操作(功能级别),他们的角色将具有访问权限。否则访问被拒绝。
如果您只使用 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
假设您已将用户名和角色存储在会话中:
[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);
. . . .
}
这里是一些代码片段,您可以如何使用 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");
}
这是我的博客 post:http://www.eidias.com/blog/2016/1/16/using-azure-active-directory-application-roles。您可以在那里找到如何在 AAD 中配置上述角色。
我想在我正在构建的 Web 应用程序中实施基于角色的授权。我想象的方法是在我的数据库中创建 3 tables,如下所示:
1. Roles
2. UserRoles (many to many table)
3. Users
之后,每个用户都会分配给他一个角色。现在...我的问题是,如何允许或禁止访问我的 .NET MVC 应用程序中的特定 views/controllers。我偶然发现了这个:
[Authorize(Roles = "HrAdmin, CanEnterPayroll")]
[HttpPost]
public ActionResult EnterPayroll(string id)
{
// . . . Enter some payroll . . .
}
Authorize 属性 似乎将特定 controllers/actions 限制为特定角色...但是如果我像我的情况一样从 table UserRoles 中读取用户角色怎么办? ?我的应用程序如何知道用户在系统中扮演什么角色??
有人可以帮我解决这个问题吗?
如果您授权角色访问控制器(在 class 级别)或操作(功能级别),他们的角色将具有访问权限。否则访问被拒绝。
如果您只使用 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
假设您已将用户名和角色存储在会话中:
[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);
. . . .
}
这里是一些代码片段,您可以如何使用 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");
}
这是我的博客 post:http://www.eidias.com/blog/2016/1/16/using-azure-active-directory-application-roles。您可以在那里找到如何在 AAD 中配置上述角色。