IdentityServer4中的Azure AD声明

6
我尝试使用IdentityServer4和Azure AD进行身份验证,已从github获取了示例。
虽然我已经成功发出一个令牌,但是似乎我期望从Azure AD收到的声明并没有包含在通过IdentityServer发放的令牌中。
这可能是有意为之,也可能是我的理解有误,但我希望用户通过Azure AD分配的角色(以及来自Azure令牌的其他有用“位”)能够被包含在发给客户端的令牌中。
请问有人能为我解惑吗?我可以在此处粘贴代码,但是与我正在使用的代码基本相同。
1个回答

6
我尝试做同样的事情,并最终从查看IS4文档、Github和StackOverflow中拼凑出一些信息。您需要配置一个新的IProfileService实例(文档),以告诉IdentityServer4您希望将哪些附加声明(在您的情况下从Azure AD获取)传递回客户端。以下是一个示例:
public class CustomProfileService : IProfileService
{
  public Task GetProfileDataAsync(ProfileDataRequestContext context)
  {
    // Get the 'upn' claim out from the identity token returned from Azure AD.
    var upnClaim = context.Subject.FindFirst(c => c.Type == ClaimTypes.Upn);

    // Get 'firstname' and 'givenname' claims from the identity token returned from Azure AD.
    var givenNameClaim = context.Subject.FindFirst(c => c.Type == ClaimTypes.GivenName);
    var surNameClaim = context.Subject.FindFirst(c => c.Type == ClaimTypes.Surname);

    // Add the retrieved claims into the token sent from IdentityServer to the client.
    context.IssuedClaims.Add(upnClaim);
    context.IssuedClaims.Add(givenNameClaim);
    context.IssuedClaims.Add(surNameClaim);
  }

  public Task IsActiveAsync(IsActiveContext context)
  {
      context.IsActive = true;
      return Task.CompletedTask;
  }
}

接下来,您需要在Startup.cs中注册此服务:

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentityServer()
            .AddDeveloperSigningCredential()

            // Register the new profile service. 
            .AddProfileService<CustomProfileService>();
}

最后,在您的AccountController.cs中(在IdentityServer4项目中 - 我假设您已经有了这个,如果没有,请参见此处的入门设置),您需要将以下内容添加到ExternalLoginCallback()中:
[HttpGet]
public async Task<IActionResult> ExternalLoginCallback()
{

    //...

    // this allows us to collect any additonal claims or properties
    // for the specific protocols used and store them in the local auth cookie.
    // this is typically used to store data needed for signout from those protocols.
    var additionalLocalClaims = new List<Claim>();

    // ADD THIS LINE TO TELL IS4 TO ADD IN THE CLAIMS FROM AZURE AD OR ANOTHER EXTERNAL IDP.
    additionalLocalClaims.AddRange(claims);

    //...

}

希望这些可以帮到你。

谢谢Connor - 我以为我会在回复时收到电子邮件,所以很抱歉回复晚了。我相信你上面所说的是正确的 - 但似乎AD将模式用作声明名称的一部分,例如: {http://schemas.microsoft.com/ws/2008/06/identity/claims/role: FleetManager} 至少使用上述解决方案,这些可以被解析并添加到声明列表中。除非有一种方法让这些AD声明自动出现在IdSvr4的最终声明列表中? - Sean
我意识到这个问题一直没有回答。我认为它回答了原问题的某些部分,并且对@Arshath有效,因此我会标记它。 - Sean

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接