IdentityServer4學習(一)定義身份資源
Posted on
2021-04-09 08:32
RefineYJ
閱讀(0)
評論(0)
編輯
收藏
定義資源(IdentityResource)
兩種基本資源
1.身份資源:代表有關使用者的聲明,例如使用者ID,顯示名稱,電子郵件位址等
2.Api資源 代表用戶端想要通路的功能
IResourceStore 可以實作這個接口 做到從資料存儲中定義資源 (官網示例文檔是從記憶體中加載資源)
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResource(
name: "openid",
userClaims: new[] { "sub" },
displayName: "Your user identifier")
};
}
簡寫:
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId()
};
}
(從記憶體中擷取)
public class ResourceStore : IResourceStore
{
/// <summary>
/// The DbContext.
/// </summary>
protected readonly IConfigurationDbContext Context;
/// <summary>
/// The logger.
/// </summary>
protected readonly ILogger<ResourceStore> Logger;
/// <summary>
/// Initializes a new instance of the <see cref="ResourceStore"/> class.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="logger">The logger.</param>
/// <exception cref="ArgumentNullException">context</exception>
public ResourceStore(IConfigurationDbContext context, ILogger<ResourceStore> logger)
{
Context = context ?? throw new ArgumentNullException(nameof(context));
Logger = logger;
}
...
}
(從資料庫擷取資源)
自定義身份資源
定義一個名稱為profile自定義身份資源
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResource(
name: "profile",
userClaims: new[] { "name", "email", "website" },
displayName: "Your profile data")
};
}
定義資源後,可以通過AllowedScopes 将通路權限授予用戶端
var client = new Client
{
ClientId = "client",
AllowedScopes = { "openid", "profile" }
};
用戶端可以使用scope參數請求資源
例如 使用vue + oidc-client
constructor () {
super({
authority: 'http://localhost:5000/',
client_id: 'vuejs',
redirect_uri: 'http://192.168.1.26:8081/callback',
response_type: 'id_token token',
scope: 'openid profile roles ',
post_logout_redirect_uri: 'http://192.168.1.26:8081'
})
}
https://http://localhost:5000/connect/authorize?client_id=client&scope=openid profile
Next(Api資源定義)