How to extend IdentityServer4 workflow to run custom code

隐身守侯 提交于 2019-12-06 02:35:30

Unfortunately, there is no way to do that. When you request any IdentityServer endpoint, IdentityServer middleware short-circuits the rest of the pipeline. You can check source code: IdentityServerMiddleware class.

I believe it was done for a reason. But if you really need to modify the response, you have at least three options:

  1. Create a fork and remove return operator from IdentityServerMiddleware Invoke method (be careful to short-circuit the rest of the pipeline adding return into your last middleware).
  2. Create your own IdentityServerMiddleware, IdentityServerApplicationBuilderExtensions implementations and use them instead of default.
  3. Place your middleware before the UseIdentityServer. Your middleware should look like this:

    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;
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!