Resources 的定義
通常在系統中是頂一個需要保護的資源。這些資源可是用戶的信息,比如身份信息或者郵箱地址,也可以是某些API的訪問權限。
Note: 可以通過C#的對象模型或者通過數據庫定義資源。通過實現
IResourceStore
來處理這些低層次的細節。本文章使用in-memory
的實現方式。
identity resources 的定義
Identity resources 是用戶的Id,Name,Email數據。每一個Identity resource都有一個獨立的name,並且可以賦任何的claim type值給它。這些claims將會被包含在用戶的identity token里面。client 會使用 'scope' 參數去請求訪問identity resouce。
OpenID Connect 規范制定了一些標准的Identity resources. 最基本的Identity resource要求提供用戶的唯一識別Id-也可以叫做 subject Id. 這可以通過公開名稱為 openid
的標准 identity resource 來實現.
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId()
};
}
類 IdentityResources 支持所有定義在規范中的所有的 scope(openid, email, profile, telephone, address)。 實現方式如下:
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Email(),
new IdentityResources.Profile(),
new IdentityResources.Phone(),
new IdentityResources.Address()
};
}
custom identity resources 的定義
public static IEnumerable<IdentityResource> GetIdentityResources()
{
var customProfile = new IdentityResource(
name: "custom.profile",
displayName: "Custom profile", // optional
claimTypes: new[] { "name", "email", "status" });//包含的用戶claims
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
customProfile
};
}
API resources 的定義
要讓clients請求某些API的access token,需要定義API resource,同時將這些APIs注冊為一個scope。這一次 scope type是 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)
//這種情況下scope name和 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"
}
}
}
};
}
Note: resource定義的user claims 通過 IProfileService 擴展加載。