【问题标题】:How to extend IdentityServer4 workflow to run custom code如何扩展 IdentityServer4 工作流程以运行自定义代码
【发布时间】:2018-02-27 07:23:45
【问题描述】:

我有一个基于 quick start sample 的基本 Identityserver4 实现。

在我的创业中,我有以下几点:

    public void ConfigureServices(IServiceCollection services)
    {
        // configure identity server with in-memory stores, keys, clients and scopes
        services.AddIdentityServer()
            .AddTemporarySigningCredential()
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients());
    }

    public void Configure(IApplicationBuilder app)
    {
        ...
        app.UseIdentityServer();
    }

我想扩展 IdentityServer4 工作流程,以便在生成访问令牌后,我可以运行业务逻辑(基于访问令牌中的声明)并修改发送给调用客户端的响应。我尝试创建一个 .NET 核心中间件,但似乎 IdentityServer 中间件使管道的其余部分短路(将执行 UseIdentityServer 之后没有中间件位置)。

我可以使用 Identityserver4 中的任何扩展方法来始终修改 IdentityServer4 发出的响应吗?我正在使用凭据授予。本质上,一旦 IdentityServer4 完成其工作流程,我想运行一些业务逻辑来修改发送给客户端的响应

【问题讨论】:

    标签: asp.net-core asp.net-web-api2 identityserver4


    【解决方案1】:

    不幸的是,没有办法做到这一点。 当您请求任何 IdentityServer 端点时,IdentityServer 中间件会短路管道的其余部分。 您可以查看源代码: IdentityServerMiddleware class.

    我相信这样做是有原因的。但是如果你真的需要修改响应,你至少有三个选择:

    1. 创建一个分支并从中删除 return 运算符 IdentityServerMiddleware Invoke 方法(注意将管道的其余部分短路,将 return 添加到最后一个中间件中)。
    2. 创建自己的IdentityServerMiddlewareIdentityServerApplicationBuilderExtensions实现并使用 它们而不是默认值。
    3. 将中间件放在 UseIdentityServer 之前。您的中间件应如下所示:

      public ResponseBodyEditorMiddleware(RequestDelegate next)
      {
          _next = next;
      }
      
      public async Task Invoke(HttpContext context)
      {
          // get the original body
          var body = context.Response.Body;
      
          // replace the original body with a memory stream
          var buffer = new MemoryStream();
          context.Response.Body = buffer;
      
          // invoke the next middleware from the pipeline
          await _next.Invoke(context);
      
          // get the body as a string
          var bodyString = Encoding.UTF8.GetString(buffer.GetBuffer());
      
          // make some changes
          bodyString = $"The body has been replaced!{Environment.NewLine}Original body:{Environment.NewLine}{bodyString}";
      
          // update the memory stream
          var bytes = Encoding.UTF8.GetBytes(bodyString);
          buffer.SetLength(0);
          buffer.Write(bytes, 0, bytes.Length);
      
          // replace the memory stream with updated body
          buffer.Position = 0;
          await buffer.CopyToAsync(body);
          context.Response.Body = body;
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 2021-12-02
      • 2016-11-30
      • 2022-08-23
      • 1970-01-01
      • 2011-03-13
      相关资源
      最近更新 更多