How to change marker endpoint response body with Owin OAuth2 in Asp.Net Web API 2

I want to change the response body from the marker endpoint response.

I tried to intercept the request / token with MessageHandler, but it does not work.

I can add additional information to the response by overriding the OAuthAuthorizationServerProvider.TokenEndpoint method, but I cannot create my own response authority.

Is there a way to intercept the request / token ?


Edit

I learned how to remove the contents of the response body from the response of the marker endpoint, for example: HttpContext.Current.Response.SuppressContent = true;

It seems like the right way to achieve my goal, but now that I use the context.AdditionalResponseParameters.Add() method to add my user information, SuppressContent blocks any changes.

Now I have something like this:

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

To simply add new elements in response to a JSON token, you can use TokenEndpointResponse instead of notifying TokenEndpoint .


If you are looking for a way to completely replace the response to the token prepared by the OAuth2 authorization server with your own, then, unfortunately, there is no easy way to do this, because OAuthAuthorizationServerHandler.InvokeTokenEndpointAsync does not check the OAuthTokenEndpointContext.IsRequestCompleted property after calling the TokenEndpointResponse notification.

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

This is a known issue, but it was too late to include it in Katana 3 when I suggested fixing it.

You should give Owin.Security.OpenIdConnect.Server try: this is the (experimental) fork OAuthAuthorizationServerMiddleware that I am developing with @manfredsteyer.

https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/tree/dev

Of course, it includes a valid check, allowing you to bypass the processing of default marker requests (this was even one of the first things that I fixed when it forked).

+4
source

You were almost there + Samoji @Samoji and really helped / inspired me to get an answer.

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

I found that he just replaced my old token with my new one.

0
source

This question is similar to How to Extend IdentityServer4 Workflow to Run Custom Code

So you can create your own middleware and register it before the OAuth2 service in Startup:

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

where is custom middleware:

  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; } 
0
source

The best way to intercept the request and response is through MessageHandler, if you want to avoid this after the request has reached the IControllerFactory handler in the pipeline - obviously, in this case use a custom attribute

I used MessageHandlers in the past to intercept a request for api / token, create a new request and get a response, create a new response.

  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 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; } 

This works great for me. However, this handler requires the configuration file WebApiConfig.cs (RouteConfig.cs if you are using ASP.NET MVC).

Can you tell me that this does not work for you on the handler?

-1
source

Source: https://habr.com/ru/post/982844/


All Articles