使用asp.net登录IdentityServer后如何获得access_token

时间:2017-07-13 03:44:53

标签: asp.net-core facebook-login access-token identityserver4

使用Facebook access_token和userId获取Facebook信息并使用电子邮件登录/注册Identity Server帐户后,我想获取Identity Server帐户的access_token以登录主服务器帐户。

它可能包含sub(用户ID)但是我不能使用userManager的方法来查找令牌。

以下是获取access_token但不起作用的示例代码:

[HttpPost]
[AllowAnonymous]
public async Task<string> GetTokenForIOS(FacebookUserModel model)
{
    model.email = await GetEmail(model);

    var user = await _userManager.FindByNameAsync(model.email);
    var userInfo = _userManager.Users.SingleOrDefault(x => x.Email == model.email);
    if (user != null)
    {
        // sign in identityServer
        await _signInManager.SignInAsync(user, isPersistent: false);

        // the first way to get access_token
        var externalAccessToken = await _userManager.GetAuthenticationTokenAsync(user, "Facebook", "access_token");

        // the second way to get access_token
        string token = await GetAccessToken();
        //return access_token
        return token;
    }

    return "";
}

public async Task<string> GetAccessToken()
{
    // discover endpoints from metadata
    var disco = await DiscoveryClient.GetAsync("https://localhost:44355");

    // request token
    var tokenClient = new TokenClient(disco.TokenEndpoint, "client.ios");
    var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api");

    if (tokenResponse.IsError)
    {
        return "";
    }
    else
    {
        Console.WriteLine(tokenResponse.Json);
        JToken jObject = tokenResponse.Json;
        return tokenResponse.Json.ToString();
    }
}

这是我的客户端配置:

new Client
{
    ClientId = "client.ios",
    RequireClientSecret = false,
    ClientName = "iOS app client",
    AllowedGrantTypes = GrantTypes.Code,
    RequirePkce = true,
    RequireConsent = false,
    RedirectUris = { "net.openid.appauthdemo:/oauth2redirect" },
    PostLogoutRedirectUris = { "net.openid.appauthdemo:/oauth2redirect" },
    AllowedScopes =
    {
        IdentityServerConstants.StandardScopes.OpenId,
        IdentityServerConstants.StandardScopes.Profile,
        IdentityServerConstants.StandardScopes.Email,
        IdentityServerConstants.StandardScopes.Phone,
        "api"
    },
    AllowOfflineAccess = true
}

在这种情况下,有什么方法可以帮助我找到用户access_token来进行令牌响应吗?

0 个答案:

没有答案