I have simple "gate" method which determines whether user's jwt token is valid and then redirects him to some action
I have two end points that require being authorized,
One of them is used just to determine whether token is ok (returns 401 if not, or OK if it is)
Second one is protected area that requires valid token
My problem is that first end point returns that token is OK, but second returns 401
Because of "Workaround" which is: returning View instead of action
I realized that I forgot about Authorization header, but
how to add headers to redirect to action?
It's kind of important to return redirect to action instead of View, because with View browser shows old url which's in this case localhost/Gate instead of localhost/Authorized
public async Task<IActionResult> Gate()
{
var token = ExtractToken();
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
var get = client.GetAsync($"https://localhost:12345/TokenValidator").Result;
switch (get.StatusCode)
{
case HttpStatusCode.Unauthorized:
return RedirectToAction("Unauthorized");
case HttpStatusCode.OK:
return RedirectToAction("Authorized"); // it enters this case
default:
return RedirectToAction("Index");
}
}
[Route("TokenValidator")]
[Authorize]
public IActionResult TokenValidator()
{
return new OkObjectResult("OK");
}
[Route("Authorized")]
[Authorize]
public IActionResult Authorized()
{
return View();
}
Thanks to Jean-François Fabre for removing my comment.
Sometimes an old comment in an unresolved post helps to revive the debate.
For those interested, follow the answer.
In Startup.cs (Configure) Add the code:
app.UseSession();
app.Use(async (context, next) =>
{
var JWToken = context.Session.GetString("JWToken");
if (!string.IsNullOrEmpty(JWToken))
{
context.Request.Headers.Add("Authorization", "Bearer " + JWToken);
}
await next();
});
And in View, after token validation:
HttpContext.Session.SetString("JWToken", post.AccessToken);
Then you can proceed with the process normally.
I use RedirectToAction:
return RedirectToAction(actionName: "Default", controllerName: "Usuario");
Hugs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With