c# - mvc 中的功能权限
问题描述
我是初学者,在我的项目中有各种功能,如通知、画廊、滑块图像我想授予各种用户访问这些功能的权利(如果用户没有画廊的权限,那么他看不到该功能)通过属性。
解决方案
在 ASP.NET MVC 中,我在动作上使用了很多属性来执行常见的工作
[ReturnableActionFilter]
[BreadcrumbActionFilter(Text = "Invoices")]
[ClaimsAuthorize("InvoicesController", "Read")]
[HttpGet]
public async Task<ActionResult> Index()
{
return View(await IndexModel_Get());
}
你会注意到其中一个暗示了索赔。这与 Microsoft 标识一起使用。这使用存储所有用户的数据库。当用户登录网站时,他们会针对数据库进行身份验证。
有一个名为 AspNetUserClaims 的表格,您可以在其中为每个用户添加声明。默认情况下,我假设控制器具有 READ、CREATE、EDIT 和 DELETE 声明 - 根据需要添加其他类型(例如 ViewTradePrices - 这将是一个简单的“是”作为声明)
然后,您可以添加一个类来保存授权代码。我还在控制器中添加了 HTML 助手和助手,以检查用户是否有特定的声明。希望这能让你开始
/// <summary>
/// Allows use of an authorisation attribute on controllers and controller methods
/// </summary>
public class ClaimsAuthorizeAttribute : AuthorizeAttribute
{
private string claimType;
private string claimValue;
/// <summary>
/// Authorise using a claim by type (and optional value)
/// </summary>
/// <param name="type">The Claim Type - Usually [Controller]_[Action]</param>
/// <param name="value">The Claim Value, usually one of Read | Edit | Create | Delete, or some other relevant value</param>
public ClaimsAuthorizeAttribute(string type, string value = "")
{
this.ClaimType = type;
this.ClaimValue = value;
}
/// <summary>
/// Gets the Claim Type - Usually [Controller]_[Action]
/// </summary>
public string ClaimType { get => claimType; protected set => claimType = value; }
/// <summary>
/// Gets the Claim Value, usually one of Read | Edit | Create | Delete, or some other relevant value
/// </summary>
public string ClaimValue { get => claimValue; protected set => claimValue = value; }
public override void OnAuthorization(AuthorizationContext filterContext)
{
// assume not authorised
bool isAuthorised = false;
// check user exists
if (filterContext.HttpContext.User != null)
{
// get user by claim principle
var user = filterContext.HttpContext.User as System.Security.Claims.ClaimsPrincipal;
if (user != null && user.HasClaim(ClaimType, ClaimValue))
{
// user has a claim of the correct type
isAuthorised = true;
}
}
if (isAuthorised)
{
filterContext.Result = null;
base.OnAuthorization(filterContext);
}
else
{
// we don't use 401 as this will cause a login loop : base.HandleUnauthorizedRequest(filterContext);
// Forbidden message will be shown
filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden, "You are forbidden to access this resource");
}
}
}
}
推荐阅读
- cntk - CNTK 2.5.1 Function::Load 溢出未处理的异常“未找到模块”
- wordpress - 如何重新链接“登录以回复”。关联
- javascript - 触发输入键时更改按钮样式
- react-native - `react-native init app` 在 React-Native 0.56 中不起作用
- python - 将图像分割成辐条并计算每个辐条中黑色像素的数量
- vba - CSV文本到VBA中的列
- node.js - Mongodb节点在重新连接时创建大量连接
- python - 将变量从一个函数传递到第二个函数python
- sparql - 通过 SPARQL 从 DBpedia 获取英国地方的坐标信息
- javascript - 如何为通用 js 库设置 Karma 和 Jasmine 单元测试?