【问题标题】:ASP.NET Core 5 MVC and Identity in EF Core - resource based authorizationEF Core 中的 ASP.NET Core 5 MVC 和 Identity - 基于资源的授权
【发布时间】:2021-08-24 02:47:41
【问题描述】:

我有一个学习项目。我想为用户实现基于资源的授权。我在控制器中开发了一个受保护的方法UserId(),我在 get 和 post 方法上调用它,类似于下面显示的代码。

我只是想问一下,这个解决方案是否可行,或者使用 Identity 框架有更好的方法来做到这一点,非常欢迎任何想法 :)

// 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-core asp.net-core-mvc asp.net-identity


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      • 2020-07-30
      相关资源
      最近更新 更多