c# - EF Core 中的 ASP.NET Core 5 MVC 和 Identity - 基于资源的授权
问题描述
我有一个用于学习目的的项目。我想为用户实现基于资源的授权。我UserId()
在控制器中开发了一个受保护的方法,我调用 get 和 post 方法,类似于下面显示的代码。
我只是想问一下,这个解决方案好吗,或者甚至有更好的方法可以使用身份框架来做到这一点,非常欢迎任何想法:)
// protected UserId method
protected string UserId()
{
return User.FindFirstValue(ClaimTypes.NameIdentifier);
}
// GET view for categories, here I call the UserId method to check if items for that user exist.
public IActionResult Index()
{
List<Category> model = _categoryService.GetCategories().Where(x => UserId().Contains(x.UserId)).ToList();
return View(model);
}
// POST method for category
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Category category)
{
if (ModelState.IsValid)
{
category.UserId = UserId();
_categoryService.CreateCategory(category);
return RedirectToAction("Index");
}
return View(category);
}
// my Category model
public class Category
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public string UserId { get; set; }
}
解决方案
在我看来,这个解决方案是最好的。FindFirstValue 方法是直接根据 claimType 找到 Claims。
这只会搜索声明中的值(在服务器内存中),它不会联系 sql 服务器。
推荐阅读
- python - matplotlib.pyplot.savefig 需要很长时间
- bash - Bash:在单行(作为参数)上获得带空格的文件名的打乱列表?
- css - 静态django链接css文件
- javascript - 检查预定义角色并执行命令
- javascript - Javascript - 在 promise 和 await 之间不保存本地对象变量
- mysql - SQL 查询以零附加日期(月/日)值
- printers - GPRS打印机集成
- reactjs - withStyles 组件包装
- php - Laravel 5.7 - 在一定时间后杀死工匠
- mongodb - macOS Mojave 10.14.2 上缺少 libatomic