代码之家  ›  专栏  ›  技术社区  ›  johnny 5

WebApi从HttpContext获取访问令牌

  •  1
  • johnny 5  · 技术社区  · 7 年前

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

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

    编辑

    SignInManager.GetExternalAuthenticationSchemesAsync()
    

    在外部登录回调中,我使用signin manager存储令牌,如下所示:

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

    即使我尝试获取访问令牌,我也会收到null。但是,我可以看到我是从HttpContext.User登录的。

    如何从HttpContext获取访问令牌?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Md. Abdul Alim    7 年前

    你能试试这个代码吗。

    HttpContext.Request.Headers["authorization"]
    
        2
  •  0
  •   johnny 5    7 年前

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