WebApi从HttpContext获取访问令牌

时间:2018-11-25 02:46:22

标签: c# .net authentication oauth-2.0 .net-core

我正在尝试使用.Net-Core 2.1从我的Api中的HttpContext获取登录的用户访问令牌:

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

修改

我正在使用签名管理器来显示身份验证提供者:

SignInManager.GetExternalAuthenticationSchemesAsync()

在外部登录回调中,我将令牌存储在登录管理器中,如下所示:

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

身份验证配置的设置如下:

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");
    });

当Even尝试获取访问令牌时,我将收到null。但是我可以看到我是从HttpContext.User登录的。

如何从HttpContext获取访问令牌?

2 个答案:

答案 0 :(得分:1)

您可以尝试使用此代码吗?

HttpContext.Request.Headers["authorization"]

答案 1 :(得分:0)

由于某种原因,当我使用登录管理器登录时,它没有在HttpContext上设置令牌。因此,相反,我像这样获取访问令牌:

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

    return true;
}