8

上下文: 我正在使用带有 OWIN 自主机的 ASP.NET MVC。以下是其余的配置/设置。

在身份服务器中的我的Client中(注意AllowedScopes集):

public static class InMemoryClientSource
{
    public static List<Client> GetClientList()
    {
        return new List<Client>()
        {
            new Client()
            {
                ClientName = "Admin website",
                ClientId = "admin",
                Enabled = true,
                Flow = Flows.Hybrid,
                ClientSecrets = new List<Secret>()
                {
                    new Secret("admin".Sha256())
                },
                RedirectUris = new List<string>()
                {
                    "https://admin.localhost.com/"
                },
                PostLogoutRedirectUris = new List<string>()
                {
                    "https://admin.localhost.com/"
                },
                AllowedScopes = new List<string> {
                    Constants.StandardScopes.OpenId,
                    Constants.StandardScopes.Profile,
                    Constants.StandardScopes.Email,
                    Constants.StandardScopes.Roles
                }
            }
        };
    }
}

这是范围

public static class InMemoryScopeSource
{
    public static List<Scope> GetScopeList()
    {
        var scopes = new List<Scope>();

        scopes.Add(StandardScopes.OpenId);
        scopes.Add(StandardScopes.Profile);
        scopes.Add(StandardScopes.Email);
        scopes.Add(StandardScopes.Roles);

        return scopes.ToList();
    }
}

Identity Server中,这是服务器的配置方式。(注意客户端范围是上面提供的):

var userService = new UsersService( .... repository passed here .... );

        var factory = new IdentityServerServiceFactory()
            .UseInMemoryClients(InMemoryClientSource.GetClientList())
            .UseInMemoryScopes(InMemoryScopeSource.GetScopeList());

        factory.UserService = new Registration<IUserService>(resolver => userService);

        var options = new IdentityServerOptions()
        {
            Factory = factory,
            SigningCertificate = Certificates.Load(), // certificates blah blah
            SiteName = "Identity"
        };

        app.UseIdentityServer(options);

最后,在客户端 Web 应用程序端,这是设置身份验证的方式:

app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            AuthenticationType = "Cookies"
        });

        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
        {
            Authority = "https://id.localhost.com",
            ClientId = "admin",
            RedirectUri = "https://admin.localhost.com/",
            PostLogoutRedirectUri = "https://admin.localhost.com/",
            ResponseType = "code id_token token",
            Scope = "openid profile email roles",
            ClientSecret = "admin",
            SignInAsAuthenticationType = "Cookies"
        });

我为 IUserService 实现了一个自定义类:

public class UsersService : UserServiceBase
{
    public UsersService( .... repository passed here .... )
    {
        //.... ctor stuff
    }

    public override Task AuthenticateLocalAsync(LocalAuthenticationContext context)
    {
        // var user = .... retrieved from database ..... 
        // ... auth logic ...

        if (isAuthenticated)
        {
            var claims = new List<Claim>();
            claims.Add(new Claim(Constants.ClaimTypes.GivenName, user.FirstName));
            claims.Add(new Claim(Constants.ClaimTypes.FamilyName, user.LastName));
            claims.Add(new Claim(Constants.ClaimTypes.Email, user.EmailAddress));
            context.AuthenticateResult = new AuthenticateResult(user.Id.ToString(), user.EmailAddress, claims);
        }

        return Task.FromResult(0);
    }
}

如您所见,声明在这一行中传递:

context.AuthenticateResult = new AuthenticateResult(user.Id.ToString(), user.EmailAddress, claims);

当我尝试登录 IdentityServer3 时,我可以成功登录到客户端 Web 应用程序。但是,当我收到用户声明时,我看不到任何身份声明。没有given_namefamily_nameemail声明。截图如下:

如您所见,不包括 given_name、family_name 和 email 声明。

有什么我可能错过的吗?提前致谢!

4

3 回答 3

6

我的解决方案是将声明列表添加到我的范围配置中,以便返回这些声明。此处的 wiki 文档对其进行了描述。

对于内存中的客户端,我所做的一切都是这样的:

public class Scopes
{
    public static IEnumerable<Scope> Get()
    {
        return new Scope[]
        {
            StandardScopes.OpenId,
            StandardScopes.Profile,
            StandardScopes.Email,
            StandardScopes.Roles,
            StandardScopes.OfflineAccess,
            new Scope
            {
                Name = "yourScopeNameHere",
                DisplayName = "A Nice Display Name",
                Type = ScopeType.Identity,
                Emphasize = false,
                Claims = new List<ScopeClaim>
                {
                    new ScopeClaim("yourClaimNameHere", true),
                    new ScopeClaim("anotherClaimNameHere", true)
                }
            }
         };
    }
}
于 2015-12-01T06:27:42.553 回答
5

终于找到了解决这个问题的办法。

首先,我将声明的创建移至被覆盖的 GetProfileDataAsync(在我的 UserService 类中)。这是我的实现:

public override Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var identity = new ClaimsIdentity();

            UserInfo user = null;
            if (!string.IsNullOrEmpty(context.Subject.Identity.Name))
                user = _facade.Get(context.Subject.Identity.Name);
            else
            {
                // get the sub claim
                var claim = context.Subject.FindFirst(item => item.Type == "sub");
                if (claim != null)
                {
                    Guid userId = new Guid(claim.Value);
                    user = _facade.Get(userId);
                }
            }

            if (user != null)
            {
                identity.AddClaims(new[]
                {
                    new Claim(Constants.ClaimTypes.PreferredUserName, user.Username),
                    new Claim(Constants.ClaimTypes.Email, user.EmailAddress)
                    // .. other claims
                });
            }

context.IssuedClaims = identity.Claims; //<- MAKE SURE you add the claims here
            return Task.FromResult(identity.Claims);
        }

在返回任务之前,请确保我们将声明传递给 GetProfileDataAsync() 中的“context.IssueClaims”。

对于那些对我的 AuthenticateLocalAsync() 外观感兴趣的人:

var user = _facade.Get(context.UserName);
            if (user == null)
                return Task.FromResult(0);

            var isPasswordCorrect = BCrypt.Net.BCrypt.Verify(context.Password, user.Password);
            if (isPasswordCorrect)
            {
                context.AuthenticateResult = new AuthenticateResult(user.Id.ToString(), user.Username);
            }

            return Task.FromResult(0);

我在 IdentityServer3 GitHub 项目页面中提出了一个类似的问题,其中包含对我遇到问题的原因的解释。这是链接: https ://github.com/IdentityServer/IdentityServer3/issues/1938

于 2015-09-25T18:29:15.050 回答
-1

我没有使用身份服务器,但是我使用的是 Windows Identity Foundation,我相信这是 IdentityServer 使用的。为了访问我使用的声明:

((ClaimsIdentity)User.Identity).Claims

于 2015-09-18T14:28:30.707 回答