如何在Asp.Net Web API 2中使用Owin OAuth2修改令牌端点响应体

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个回答

6
为了简单地向JSON令牌响应中添加新项,您可以使用TokenEndpointResponse而不是TokenEndpoint通知。
如果您想完全替换OAuth2授权服务器准备的令牌响应为自己的响应,很遗憾,没有简单的方法可以实现,因为OAuthAuthorizationServerHandler.InvokeTokenEndpointAsync在调用TokenEndpointResponse通知后不会检查OAuthTokenEndpointContext.IsRequestCompleted属性。

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

这是一个已知的问题,但当我建议修复它时,已经太晚包含在Katana 3中了。
你应该尝试使用Owin.Security.OpenIdConnect.Server:它是OAuthAuthorizationServerMiddleware的一个分支,专为Katana 3.0和4.0设计。

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

当然,它包括正确的检查以允许绕过默认的令牌请求处理(这甚至是我分叉时首先修复的问题之一)。

@Alisson 在这里:https://github.com/aspnet/AspNetKatana/blob/dev/src/Microsoft.Owin.Security.OAuth/Provider/OAuthAuthorizationServerProvider.cs#L343-L377 - Kévin Chalet

2

你差点就做到了 +Samoji @Samoji,你真的帮助/启发了我得到答案。

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

我发现只需用新令牌替换旧令牌即可。

-1

这个问题类似于如何扩展IdentityServer4工作流以运行自定义代码

因此,您可以创建自定义中间件并在启动时在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;
    }

-2

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

我过去曾经使用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)。

您能详细说明一下处理程序上有什么问题吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接