Loading

IdentityServer Topics(2)- 定义资源

您通常在系统设计中的第一件事就是您要保护的资源。 这可能是您的用户的身份信息,如个人资料数据或电子邮件地址,或访问API。

您可以使用C#对象模型定义资源(硬编码),或从数据存储中加载它们。 IResourceStore的实现处理这些低级细节。 本文使用的是in-memory的实现。

定义身份资源

身份资源也是数据,如用户ID,姓名或用户的电子邮件地址。 身份资源具有唯一的名称,您可以为其分配任意身份信息单元(比如姓名、性别、身份证号和有效期等都是身份证的身份信息单元)类型。 这些身份信息单元将被包含在用户的身份标识(Id Token)中。 客户端将使用scope参数来请求访问身份资源。

OpenID Connect规范指定了一对标准的身份资源。 最低要求是,您提供支持为您的用户颁发一个唯一的ID - 也称为subject id(sid)。 这是通过暴露称为openid的标准身份资源完成的:

public static IEnumerable<IdentityResource> GetIdentityResources()
{
    return new List<IdentityResource>
    {
        new IdentityResources.OpenId()
    };
}

IdentityResources类支持定义规范中的所有作用域(scope)(openid,email,profile,电话和地址)。 如果您想全部支持,可以将它们添加到支持的身份资源列表中:

public static IEnumerable<IdentityResource> GetIdentityResources()
{
    return new List<IdentityResource>
    {
        new IdentityResources.OpenId(),
        new IdentityResources.Email(),
        new IdentityResources.Profile(),
        new IdentityResources.Phone(),
        new IdentityResources.Address()
    };
}

定义自定义身份资源

您还可以定义自定义身份资源。 创建一个新的IdentityResource类,为其指定一个名称和一个可选的显示名称和描述,并在请求此资源时定义哪个用户身份单元应该包含在身份令牌(Id Token)中:

public static IEnumerable<IdentityResource> GetIdentityResources()
{
    var customProfile = new IdentityResource(
        name: "custom.profile",
        displayName: "Custom profile",
        claimTypes: new[] { "name", "email", "status" });

    return new List<IdentityResource>
    {
        new IdentityResources.OpenId(),
        new IdentityResources.Profile(),
        customProfile
    };
}

定义API资源

为了允许客户请求API的访问令牌,您需要定义API资源,例如:

要访问API的令牌,还需要为其注册作用域(Scope)。 这次作用域类型是Resource类型的:

public static IEnumerable<ApiResource> GetApis()
{
    return new[]
    {
        // simple API with a single scope (in this case the scope name is the same as the api name)
        new ApiResource("api1", "Some API 1"),

        // expanded version if more control is needed
        new ApiResource
        {
            Name = "api2",

            // secret for using introspection endpoint
            ApiSecrets =
            {
                new Secret("secret".Sha256())
            },

            // include the following using claims in access token (in addition to subject id)
            UserClaims = { JwtClaimTypes.Name, JwtClaimTypes.Email },

            // this API defines two scopes
            Scopes =
            {
                new Scope()
                {
                    Name = "api2.full_access",
                    DisplayName = "Full access to API 2",
                },
                new Scope
                {
                    Name = "api2.read_only",
                    DisplayName = "Read only access to API 2"
                }
            }
        }
    };
}

装载用户身份单元资源由IProfileService实现来完成。

posted @ 2017-12-29 13:57  晓晨Master  阅读(6845)  评论(6编辑  收藏  举报