您通常在系統設計中的第一件事就是您要保護的資源。 這可能是您的用戶的身份信息,如個人資料數據或電子郵件地址,或訪問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實現來完成。