johnny 5
johnny 5

Reputation: 20997

WebApi Get access Token from HttpContext

I'm trying to get the logged in users access token from the HttpContext in my Api I'm using .Net-Core 2.1 :

[HttpGet]
public async Task<bool> Test()
{
    var token = await HttpContext.GetTokenAsync("access_token");
    return true;
}

Edit

I'm using the signing manager to show Auth Providers:

SignInManager.GetExternalAuthenticationSchemesAsync()

And in the External Login Callback I store My tokens with the signin manager like so:

var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
if (result.Succeeded)
{
    await _signInManager.UpdateExternalAuthenticationTokensAsync(info);
    _logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider);
    return RedirectToLocal(returnUrl);
}

Authentication Configuration is setup like so:

services.AddAuthentication(COOKIE_AUTH)
    .AddCookie(options => options.ExpireTimeSpan = TimeSpan.FromMinutes(60))
    .AddCoinbase(options => {
        options.SendLimitAmount = 1;
        options.SendLimitCurrency = "USD";
        options.SendLimitPeriod = SendLimitPeriod.day;
        options.ClientId = Configuration["Coinbase:ClientId"];
        options.ClientSecret = Configuration["Coinbase:ClientSecret"];
        COINBASE_SCOPES.ForEach(scope => options.Scope.Add(scope));
        options.SaveTokens = true;
        options.ClaimActions.MapJsonKey("urn:coinbase:avatar", "avatar_url");
    });

When Even I try to obtain the access token I receive null. However I can see that i'm logged in from the HttpContext.User.

How do I obtain my access token from the HttpContext?

Upvotes: 1

Views: 4605

Answers (2)

johnny 5
johnny 5

Reputation: 20997

For some reason when I use the signin manger to login, It doesn't set the tokens on the HttpContext. So Instead I get the access token like so:

[HttpGet]
public async Task<bool> Test()
{
    var userFromManager = await _userManager.GetUserAsync(User);
    var externalAccessToken = await _userManager.GetAuthenticationTokenAsync(
                                   userFromManager, "Coinbase", "access_token");

    return true;
}

Upvotes: 0

Md. Abdul Alim
Md. Abdul Alim

Reputation: 689

Can you try with this code.

HttpContext.Request.Headers["authorization"]

Upvotes: 3

Related Questions