文章出處
文章列表
業務場景:
IdentityServer4 默認使用TestUser
和UserStore
,需要模擬和加載所有的用戶數據,正式環境肯定不能這樣實現,我們想從自己的數據庫中讀取用戶信息,另外,因為 IdentityServer4 實現了 OpenId 協議,我們想在用戶登錄的時候,在請求中添加用戶的一些額外信息,這樣就不需要再去請求用戶服務了。
具體實現:
using IdentityServer4.Models;
using IdentityServer4.Services;
using System.Linq;
using System.Threading.Tasks;
public class ProfileService : IProfileService
{
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
if (context.IssuedClaims.Count == 0)
{
if (context.Subject.Claims.Count() > 0)
{
context.IssuedClaims = context.Subject.Claims.ToList();
}
}
}
public async Task IsActiveAsync(IsActiveContext context)
{ }
}
Startup
添加對應配置(注入服務接口):
public void ConfigureServices(IServiceCollection services)
{
var builder = services.AddIdentityServer();
builder.AddTemporarySigningCredential()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients());
builder.Services.AddTransient<IProfileService, ProfileService>();
}
上面代碼,會在await _interaction.GrantConsentAsync(request, grantedConsent);
執行的時候執行,用戶登錄直接訪問數據庫寫在Login
中,就可以了。
如果授權模式為密碼模式,需要去實現IResourceOwnerPasswordValidator
接口。
參考資料:
文章列表
全站熱搜