检查用户是否使用社交媒体进行身份验证-IdentityServer4

时间:2018-12-14 04:20:04

标签: c# identityserver4

我的Identity Server 4能够使用ASP.NET身份和社交媒体(Facebook,Google)进行身份验证

在网址下方生成令牌

  

http://localhost:5105/connect/token

因此它将响应

{
    "access_token": "{Bearer Token}",
    "expires_in": 3600,
    "token_type": "Bearer"
}

是否可以添加新的属性调用authenticate_type?因此,我可以通过使用或不使用社交媒体来了解该用户的访问权限。

示例:

如果用户使用Facebook进行身份验证

{
    "access_token": "{Bearer Token}",
    "expires_in": 3600,
    "token_type": "Bearer",
    "authenticate_type": "Facebook"
}

如果用户通过Google进行身份验证

{
    "access_token": "{Bearer Token}",
    "expires_in": 3600,
    "token_type": "Bearer",
    "authenticate_type": "Google"
}

,反之亦然。知道怎么做吗?

2 个答案:

答案 0 :(得分:0)

在id_token中应该有一个名为IDP的声明,代表使用的提供者。

答案 1 :(得分:0)

我认为您已经知道如何获取登录提供者信息。如果没有,您可以从

获取
IdentityProvider = string.Join(", ",
                    (await _userManager.GetLoginsAsync(user)).Select(l => l.LoginProvider)),

保存此附加信息的最佳方法是在Claims中。您可以通过添加上述代码来修改您的身份资料服务

public class IdentityProfileService : IProfileService
{

    private readonly IUserClaimsPrincipalFactory<ApplicationUser> _claimsFactory;
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly ApplicationDbContext _db;

    public IdentityProfileService(IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory, UserManager<ApplicationUser> userManager,
        ApplicationDbContext dbContext)
    {
        _claimsFactory = claimsFactory;
        _userManager = userManager;
        _db = dbContext;
    }

    public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        var sub = context.Subject.GetSubjectId();
        var user = await _userManager.FindByIdAsync(sub);
        if (user == null)
        {
            throw new ArgumentException("");
        }

        var principal = await _claimsFactory.CreateAsync(user);
        var claims = principal.Claims.ToList();

        var login = await _userManager.GetLoginsAsync(user);
         login.Select(l => l.LoginProvider).ToList().ForEach(x => claims.Add(new Claim("authenticate_type", x)));

        context.IssuedClaims = claims;
    }

    public async Task IsActiveAsync(IsActiveContext context)
    {
        var sub = context.Subject.GetSubjectId();
        var user = await _userManager.FindByIdAsync(sub);
        context.IsActive = user != null;
    }
}

不要忘记将其附加到您的身份服务器上

services.AddIdentityServer().AddProfileService<IdentityProfileService>();
相关问题