Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get access token in middleware .net core 2.0

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();
like image 922
Mr.Deer Avatar asked Aug 13 '19 09:08

Mr.Deer


2 Answers

Add using Microsoft.AspNetCore.Authentication; to your middleware file. That's the namespace of the AuthenticationTokenExtensions with the GetTokenAsync method.

like image 139
pinki Avatar answered Sep 28 '22 21:09

pinki


If the access tokenis 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
like image 20
Kewin Remy Avatar answered Sep 28 '22 20:09

Kewin Remy