Fork me on GitHub

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

参考资料:

posted @ 2017-04-04 22:52  田园里的蟋蟀  阅读(11114)  评论(4编辑  收藏  举报