I am trying to get the access_token in my middleware class after one authentication process in .net core.
I am getting my token in my controllers using this code
var accessToken = await HttpContext.GetTokenAsync("access_token");
But when I want to get it on the middleware which is called after the authentication part the method GetTokenAsync
is not existing for the HttpContext.
My middleware class is this
public class Session
{
private readonly RequestDelegate _next;
public Session(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
var accessToken = // here I want to get my token
await _next(httpContext);
}
}
I tried different ways and I have been looking for a long time for answers but I still have no solution.
I think that the HttpContext class is different in Middleware and Controllers but I don't know how to solve this in the Middleware.
Someone knows how can I get access to the token in the middleware call or if it is even possible?
My startup callins are theese, maybe it is usefull too.
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseMiddleware<Session>();
app.UseMvc();
Add using Microsoft.AspNetCore.Authentication;
to your middleware file.
That's the namespace of the AuthenticationTokenExtensions
with the GetTokenAsync
method.
If the access token
is not in the HttpContext
and GetTokenAsync
returns empty, you can also use the HTTP header directly:
public async Task Invoke(HttpContext context)
{
// code dealing with the request
var result = await context.GetTokenAsync("access_token") ?? context.Request.Headers["Authorization"];
await _next(context);
// code dealing with the response
}
Please also be aware that GetTokenAsync
will give you the token while context.Request.Headers["Authorization"]
will give you "bearer sdfosidfds99wn20j293n...". You need to parse the header like this
result.Substring(7); // size of bearer + whitespace
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