11

我想从令牌端点响应修改响应正文。

我试图用 MessageHandler 拦截/Token请求,但它不起作用。

我可以通过覆盖该OAuthAuthorizationServerProvider.TokenEndpoint方法向响应添加一些附加信息,但我无法创建自己的响应正文。

有没有办法拦截/Token请求?


编辑

我发现了如何从令牌端点响应中删除响应正文内容,如下所示:HttpContext.Current.Response.SuppressContent = true;

这似乎是实现我的目标的正确方法,但现在当我使用该context.AdditionalResponseParameters.Add()方法添加我的自定义信息时,SuppressContent阻止任何更改。

现在我有这样的事情:

// Removing the body from the token endpoint response
HttpContext.Current.Response.SuppressContent = true;
// Add custom informations
context.AdditionalResponseParameters.Add("a", "test");
4

4 回答 4

6

要简单地将新项目添加到 JSON 令牌响应,您可以使用TokenEndpointResponse而不是TokenEndpoint通知。


如果您正在寻找一种方法将 OAuth2 授权服务器准备的令牌响应完全替换为您自己的,那么遗憾的是没有简单的方法可以做到这一点,因为在调用通知后OAuthAuthorizationServerHandler.InvokeTokenEndpointAsync不检查属性。OAuthTokenEndpointContext.IsRequestCompletedTokenEndpointResponse

https://github.com/aspnet/AspNetKatana/blob/dev/src/Microsoft.Owin.Security.OAuth/OAuthAuthorizationServerHandler.cs

这是一个已知问题,但当我建议修复它时,将其包含在 Katana 3 中为时已晚。

你应该试一试:它是为 Katana 3.0 和 4.0 设计Owin.Security.OpenIdConnect.Server的一个分支。OAuthAuthorizationServerMiddleware

https://www.nuget.org/packages/Owin.Security.OpenIdConnect.Server/1.0.2

当然,它包括允许绕过默认令牌请求处理的正确检查(这甚至是我在 fork 时修复的第一件事)。

于 2015-02-23T21:38:22.727 回答
0

你几乎在那里 +Samoji @Samoji 并且真的帮助/启发了我得到答案。

// Add custom informations
context.AdditionalResponseParameters.Add("a", "test");
// Overwrite the old content
var newToken = context.AccessToken;
context.AdditionalResponseParameters.Add("access_token", newToken);

我发现它只是用我的新令牌替换了我的旧令牌。

于 2016-06-21T14:52:10.787 回答
-1

这个问题类似于How to extend IdentityServer4 workflow to run custom code

所以你可以在 Startup 中创建自定义中间件并在 OAuth2 服务之前注册它:

    public void Configuration(IAppBuilder app)
    {
        ....
        app.Use(ResponseBodyEditorMiddleware.EditResponse);

        app.UseOAuthAuthorizationServer(...);
        ...
    }

自定义中间件在哪里:

    public static async Task EditResponse(IOwinContext context, Func<Task> next)
    {
        // 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();

        // get a body as string
        var bodyString = Encoding.UTF8.GetString(buffer.GetBuffer());

        // make some changes to the body
        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;
    }
于 2018-05-11T11:28:42.413 回答
-2

拦截请求和响应的最佳方法是通过 MessageHandler 如果您想在请求到达管道中的 IControllerFactory 处理程序后避免这样做 - 显然在这种情况下使用自定义“属性”

我过去曾使用 MessageHandlers 来拦截对 api/token 的请求,创建新请求并获取响应,创建新响应。

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        //create a new auth request
        var authrequest = new HttpRequestMessage();
        authrequest.RequestUri = new Uri(string.Format("{0}{1}", customBaseUriFromConfig, yourApiTokenPathFromConfig));

        //copy headers from the request into the new authrequest
        foreach(var header in request.Headers)
        {
            authrequest.Headers.Add(header.Key, header.Value);
        }

        //add authorization header for your SPA application's client and secret verification
        //this to avoid adding client id and secret in your SPA
        var authorizationHeader =
            Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", _clientIdFromConfig, _secretKeyFromConfig)));

        //copy content from original request
        authrequest.Content = request.Content;

        //add the authorization header to the client for api token
        var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(request.Headers.Authorization.Scheme, authorizationHeader);
        var response = await client.PostAsync(authrequest.RequestUri, authrequest.Content, cancellationToken);

        if(response.StatusCode == HttpStatusCode.OK)
        {
            response.Headers.Add("MyCustomHeader", "Value");
            //modify other attributes on the response
        }

        return response;
    }

这对我来说非常有效。但是,WebApiConfig.cs 文件中需要此处理程序的配置(如果您使用的是 ASP.NET MVC,则为 RouteConfig.cs)。

您能否详细说明在处理程序上对您不起作用的是什么?

于 2015-07-11T10:01:04.153 回答