通过外部登录获取访问令牌

时间:2019-02-27 01:32:59

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

我正在使用身份服务器修改身份验证,以使用内置的.net-core身份验证。我正在尝试从外部登录获取访问令牌。但是,当我从用户管理器中获取用户时,它将返回null。我正在使用OAuth授权代码流进行登录。我有一个回调方法可以登录并返回JWT(为简单起见,我省略了一些不相关的代码)

[HttpGet("ExternalLoginCallback")]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
    var info = await _signInManager.GetExternalLoginInfoAsync();
    // Sign in the user with this external login provider if the user already has a login.
    var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);

    var user = await (result.Succeeded ?
            _userManager.FindByLoginAsync(info.LoginProvider, info.ProviderKey)
        : this.CreateIdentityUser(info));

    var serviceProvider = HttpContext.RequestServices;
    var context = serviceProvider.GetRequiredService<PublicAstootContext>();
    await _signInManager.UpdateExternalAuthenticationTokensAsync(info);
    _logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider);

    return await GenerateJwtResponse(_jwtFactory.GenerateClaimsIdentity(user.UserName, user.Id, userId),
        _jwtFactory, _jwtOptions);
}

我这样创建我的用户身份:

private async Task<IdentityUser> CreateIdentityUser(ExternalLoginInfo info)
{
    string email = await this.GetEmailFromLoginInfo(info);

    //var email = info.Principal.FindFirstValue(ClaimTypes.Email);
    var user = new IdentityUser { UserName = email, Email = email };
    var signinResult = await _userManager.CreateAsync(user);

    if (false == signinResult.Succeeded)
    {
        throw new Exception("Failed to Create User");
    }

    var addLoginResult = await _userManager.AddLoginAsync(user, info);
    if (addLoginResult.Succeeded)
    {
        await _signInManager.SignInAsync(user, isPersistent: false);
        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
    }

    return user;
}

当我去获取第三方访问令牌时

var user = httpContext.User;
var userManager = sp.GetRequiredService<UserManager<IdentityUser>>();
var userFromManager = userManager.GetUserAsync(user).Result;

var accessToken = userManager.GetAuthenticationTokenAsync(
                                userFromManager, "Coinbase", "access_token").Result;

编辑

我在UserManager中找不到我的用户。如何获取我的第三方访问令牌?

看起来像我的HttpContext.User和UserManager不同步。

var user = httpContext.User;
var userManager = sp.GetRequiredService<UserManager<IdentityUser>>();

if(false == user.TryGetClaimByType<string>(AuthenticationRule.EMAIL_CLAIM_TYPE, out var email))
{
    throw new UnauthorizedAccessException();
}

如何同步HttpContext.User和Usermanger,所以我可以简单地调用:

var userFromManager = userManager.GetUserAsync(user).Result;

0 个答案:

没有答案