文章出處

業務場景:

IdentityServer4 默認使用TestUserUserStore,需要模擬和加載所有的用戶數據,正式環境肯定不能這樣實現,我們想從自己的數據庫中讀取用戶信息,另外,因為 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接口。

參考資料:


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()