IdentityServer4 登錄使用數據庫


業務場景:

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接口。

參考資料:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM