如何在IdentityServer4中使用现有的数据库 [英] How to use existing DB with IdentityServer4

查看:948
本文介绍了如何在IdentityServer4中使用现有的数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将IdentityServer4与我的自定义数据库一起使用.我为管理员和学生提供了单独的表格,并且两个实体都有各自的权限.

I want to use IdentityServer4 with my custom database. I've separate tables for admin and students and both entities have separate rights.

我想知道如何配置IdentityServer EF数据库以与我现有的数据库一起使用吗?

I want to know how to configure IdentityServer EF database to work with my existing DB?

任何帮助将不胜感激.

谢谢.

推荐答案

我从IdentityServer4开始快速入门示例7_JavaScriptClient .

I started with the IdentityServer4 Quick Start sample 7_JavaScriptClient.

首先,我创建了一个UserManager类,该类可以连接到我的数据源,并通过用户名和密码验证用户并返回该用户对象.

First I created a UserManager class that could connect to my data source and validate a user by user name and password and return that user object.

public class UserManager
{
    private SecurityContext _context;

    public UserManager(SecurityContext context)
    {
        _context = context;
    }

    public  Task<User> Find(string username, string password)
    {
         ...Logic to query your custom user table(s)...
    }

    public Task<List<Claim>> GetClaimsAsync(User user)
    {
        var claims = new List<Claim>();

        //custom database call here to where you store your claims.
        var myClaims = ...Your Database call here...
        var claimGroupName = "SomeCustomName";

        if (security != null && security.Count() > 0)
        {
            foreach (var claim in security)
            {
                //Add the value from the field Security_Id from the database to the claim group "SomeCustomName".
                claims.Add(new Claim(claimGroupName , claim.SECURITY_ID));
            }
        }

        return Task.FromResult(claims);


    }
 }

用户对象

public class User
{
    public string FIRST_NAME { get; set; }
    public string LAST_NAME { get; set; }
    public string EMAIL { get; set; }

    ...Other attributes/properties...
}

第二,我在示例中使用了AccountController中的UserManager对象.

Second I used the UserManager Object from the AccountController in the sample.

private readonly UserManager _userManager;

public AccountController(
        IIdentityServerInteractionService interaction,
        IClientStore clientStore,
        IHttpContextAccessor httpContextAccessor,
        UserManager userManager
        )
{
    _userManager = userManager;
 }

AccountController.Login()HTTP Post方法中的第三点我调用了UserManager.Find(用户名,密码)以返回用户.

Third in the AccountController.Login() HTTP Post method I called the UserManager.Find(username, password) to return a user.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginInputModel model)
{
     // validate username/password
     var user = await _userManager.Find(model.Username, model.Password);

     //sign the user in with a subject[user_id] and name[web_id]
     await HttpContext.Authentication.SignInAsync(user.USER_ID, user.WEB_ID, props);
}

第四,我实现了IProfileService. [[我将此文章资源.]

Fourth I implemented the IProfileService. [I used this article as a resource.]

public class ProfileService : IProfileService
{
     UserManager _myUserManager;
     private readonly ILogger<ProfileService> _logger;

     public ProfileService(ILogger<ProfileService> logger)
    {
        _logger = logger;
        _myUserManager = new UserManager(new SecurityContext());
    }

    //Called by IdentityServer Middleware.
     public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        var sub = context.Subject.FindFirst("sub")?.Value;
        if (sub != null)
        {
            var user = await _myUserManager.FindByNameAsync(sub);

            //Call custom function to get the claims from the custom database.
            var cp = await   getClaims(user);

            var claims = cp.Claims;

            ...Optionaly remove any claims that don't need to be sent...

            context.IssuedClaims = claims.ToList();
        }
     }

     //Called by IdentityServer Middleware.
     public async Task IsActiveAsync(IsActiveContext context)
    {
        var sub = context.Subject.GetSubjectId();
        var user = await _myUserManager.FindByNameAsync(sub);
        context.IsActive = user != null;
        return;
    }

    //Custom function to get claims from database via the UserManager.GetClaimsAsync() method.
    private async Task<ClaimsPrincipal> getClaims(User user)
    {
       var id = new ClaimsIdentity();
       //set any standard claims
       id.AddClaim(new Claim(JwtClaimTypes.PreferredUserName, user.USER_ID));
       //get custom claims from database or other source.
       id.AddClaims(await _myUserManager.GetClaimsAsync(user));

       return new ClaimsPrincipal(id);
    }
}

最后在Startup.cs中设置所有用于依赖项注入的对象.

Lastly in the Startup.cs setup any Objects for Dependency Injection.

public void ConfigureServices(IServiceCollection services)
{
   builder.Services.AddTransient<IProfileService, ProfileService>();

   //This is the DbContext to our Database where the users and their claims are stored.
   services.AddTransient<SecurityContext>();
   services.AddTransient<UserManager>();

 }

这是一个类似的问题以及anser .

请注意,它们还引用了IResourceOwnerPasswordValidator接口和实现,该接口和实现用于验证OAuth 2.0资源所有者密码凭证授予(也称为密码).与GrantTypes.ResourceOwnerPasswordAndClientCredentials或GrantTypes.ResourceOwnerPassword一起使用.

Note that they also reference the IResourceOwnerPasswordValidator interface and implementation which is for authenticating OAuth 2.0 resource owner password credential grant (aka password). Used with GrantTypes.ResourceOwnerPasswordAndClientCredentials or GrantTypes.ResourceOwnerPassword.

这篇关于如何在IdentityServer4中使用现有的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆