I'm using AddOpenIdConnect
and need to modify the response in case the OnRedirectToIdentityProvider
event is raised. Within this event the response status is modified to 401 and I would like to set a custom message. To write this custom message, I've created the SetResponseBody
method.
The solution of this post is used to set the response status, but I need to modify the Body as well.
I'm calling the SetResponseBody
method (a custom method which I implemented) in order to modify the response body as soon as the OnRedirectToIdentityProvider
event is raised from AddOpenIdConnect
.'
As mentioned in one of the comments by @Panagiotis Kanavos in the post, the SetResponseBody
method doesn't seem to be a correct solution (despite the response actually contains valid json). Could you provide an alternative?
Summarized: I would like to return a custom response besides the status code 401.
OnRedirectToIdentityProvider = async e =>
{
// e is of type RedirectContext
if (e.Request.Path.StartsWithSegments("/api")))
{
if (e.Response.StatusCode == (int)HttpStatusCode.OK)
{
e.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
// TestMessage is a const
// e.Response is readonly (get) so it's not possible to set it directly.
await ResponseRewriter.SetResponseBody(e.Response, TestMessage);
}
e.HandleResponse();
}
await Task.CompletedTask;
}
with ResponseRewriter.SetResponseBody
defined as follows
public static async Task SetResponseBody(HttpResponse response, string message)
{
var originalResponseBody = response.Body;
var responseBody = new MemoryStream();
response.Body = responseBody;
response.ContentType = "application/json";
var body = new { Message = message };
string json = JsonSerializer.Serialize(body);
await response.WriteAsync(json);
response.Body.Seek(0, SeekOrigin.Begin);
await responseBody.CopyToAsync(originalResponseBody);
}
The last two lines are implemented as written in this post.