简体   繁体   中英

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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM