c# - 如何在资源 api 中使用 IdentityServer4 范围

标签 c# identityserver4

我正在我的身份服务器应用程序中创建一个 api 资源:

new ApiResource
{
    Name = "socialnetwork",

    Scopes =
    {
        new Scope()
        {
            Name = "socialnetwork.read_contents",
            DisplayName = "Read"
        },
        new Scope
        {
            Name = "socialnetwork.share_content",
            DisplayName = "Write"
        }
    }
}

但是我如何在我的社交网络 api Controller 中使用这个范围。

public class SocialController : Controller
{
   [HttpGet]
   public async Task<IActionResult> GetCotntents(){

   }

   [HttpPost]       
   public async Task<IActionResult> ShareCotntents(string content){

   }
}
  • 如果客户端有 socialnetwork.read_contents 范围,它可以访问 GetCotntents() 方法。
  • 如果客户端有 socialnetwork.share_content 范围,它可以访问 ShareCotntents() 方法。

作用域的目的究竟是什么?我该如何使用它?

最佳答案

我相信您需要做的是为您要使用的每个范围设置一个策略(在您的 ConfigureServices 中)

 services.AddAuthorization(x =>
            {
                x.AddPolicy("readcontents", policy => 
                  policy.RequireClaim("scope", "socialnetwork.read_contents"));
                x.AddPolicy("shared", policy => 
                 policy.RequireClaim("scope", "socialnetwork.share_content"));
            });

添加然后您可以使用策略在您的 api 方法上标记 Authorize 属性

   [HttpGet]
   [Authorize("readcontents")]
   public async Task<IActionResult> GetCotntents(){

   }

  [HttpPost]      
  [Authorize("shared")] 
  public async Task<IActionResult> ShareCotntents(string content){

  }

关于c# - 如何在资源 api 中使用 IdentityServer4 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49549594/

相关文章:

authentication - 身份服务器问题 AuthenticationScheme : Bearer was challenged for a token obtained by client credentials. 如何找出底层错误?

c# - 如何使用 Griffin-Framework Data-Mapper 从数据库映射数据

asp.net-core - 在 ASP.NET Core SPA 模板的 Identity Core token 响应中添加角色

c# - Identity Server 4 for Nativescript 应用程序应使用哪种流程以及它的安全性如何?

c# 从 xsi :schemaLocation attribute value 获取 .xsd 的本地路径

asp.net-mvc - 如何将 MVC4 客户端与 IdentityServer4 一起使用?

c# - 从身份服务器注销后如何将用户重定向到客户端应用程序?

c# - 反编译 C# .Net 1.1 应用程序的最佳工具

c# - 动态母版页,可以访问两个母版中的变量

c# - 释放没有 "finally"的 SqlConnection