IdentityServer4-Resource定义-翻译

时间:2022-04-04 08:18:02

资源定义(Defining Resource)

通常,第一件事是定义那些你想保护的资源。这些资源可能是你的用户信息,比如个人数据,电子邮件或者对Api的访问。

Note:

你可以用C#实体类来定义资源或者加载从数据库中加载他们,都是通过对IResourceStore的实现来处理这些二级细节。此文档将在内存中进行实现。

定义身份资源(Defining identity resource)

身份资源通常都是指那些用户ID,名称,邮箱等信息。一个identity 资源有一个独一无二的名称,你能分配任意(arbitrary )的claim类型。这些claim将被包含在用户的token中。客户端将使用scope参数请求对identity resource的访问。

这个OpenID Connect规范指定了一组标准的身份资源。最低要求是,你为用户发行唯一ID的提供支持,也叫做subject id。这是通过暴露一个叫做OpenId的标准的身份资源来完成的。


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

这个IdentityResources类支持规范中所有的scopes 定义(比如,openid,email.profile,telephone,address)。如果你想支持这些,你可以在你的身份资源List中添加它们。

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类,给它一个名称和一个可选的显示名称和描述,并在请求此资源时定义哪些用户声明应该包含在身份令牌中。


public static IEnumerable<IdentityResource> GetIdentityResources()
{
var customProfile =new IdentityResource(
name:"custom.Profile",
displayName:"cstProfile",
claimType:new[]{"name","email","status"}); return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
customProfile
};
}

有关身份资源设置的更多信息,请参阅reference 部分。

定义API resource

允许请求的access token访问哪些api,你需要定义这些api resource。

想得到关于APIs的accsee token,你需要以scope的身份注册它们。下面展示Resource类型的scope.

public static IEnumerable<ApiResource> GetApis()
{
return new[]
{ new ApiResource("api1","Some API 1"), new ApiResource
{
Name = "api2", ApiSecrets=
{
new Secret("secret".Sha256())
},
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"
}
}
}
};
}

有关API资源设置的更多信息,请参阅reference部分。

Note:

由资源定义的用户声明由IProfileService可扩展性点加载。