首页 > 解决方案 > 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; }
}

标签: c#entity-framework-coreasp.net-core-mvcasp.net-identity

解决方案


在我看来,这个解决方案是最好的。FindFirstValue 方法是直接根据 claimType 找到 Claims。

这只会搜索声明中的值(在服务器内存中),它不会联系 sql 服务器。


推荐阅读