How to get users from existing database for identityServer4

I am trying to figure out how I can bind users (email, password, first name, last name and os on) that are stored in an existing database (located: localhost: 3306) in my identityserver4 project so that I can use this information to login to the system or register a new user in this database?

I've read several tutorials (especially http://docs.identityserver.io/en/release/quickstarts/8_entity_framework.html ) but I think this is always for db in the same project. my db is not in the same project.

In this context, I read about asp.net-core Identity. but I don't quite understand how this is related.

Can someone tell me how can I bind the db in my project and what is the role of the person with the User application, etc.?

early

+3


source to share


2 answers


This article is more relevant to your situation. The one you are linking is configuration data, not user data: http://docs.identityserver.io/en/release/quickstarts/6_aspnet_identity.html

In short, you want to access your user data through Asp.Net Identity Identity. You need:

  • Make a user class containing the relevant fields as a database
  • Create the EntityFramework DbContext class to map the database to your class
  • Register your custom class and dbcontext with aspnet core id.
  • Tell IdentityServer to use AspNetIdentity


This is what your Startup ConfigureServices method might look like ever implemented. The DbContext and User classes are not displayed here, which you should do.

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddEntityFramework()
        .AddSqlServer()
        .AddDbContext<YourUserStoreDbContextHere>(options =>
            options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

    services.AddIdentity<YourUserClassHere, YourRoleClassHereIfAny>()
        .AddEntityFrameworkStores<YourUserStoreDbContextHere>()
        .AddDefaultTokenProviders();

    services.AddIdentityServer()
        // Other config here
        .AddAspNetIdentity<YourUserClassHere>();
}

      

For details on setting up your custom class and dbcontext, see the docs at AspNet Identity: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity

+1


source


You need to implement your own UserStore

( example )

public async Task<TapkeyUser> ValidateCredentialsAsync(string username, string password)
{
      //This is pseudo-code implement your DB logic here
      if (database.query("select id from users where username = username and password = password") 
      {
           return new User(); //return User from Database here 
      } else {
           return null;
      }        
}

      



And use this in your AccountController

:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginInputModel model)
    {
        if (ModelState.IsValid)
        {
            // use our custom UserStore here
 -------->  if (_users.ValidateCredentials(model.Username, model.Password))
            {
                AuthenticationProperties props = null;
                // only set explicit expiration here if persistent. 
                // otherwise we reply upon expiration configured in cookie middleware.
                if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                {
                    props = new AuthenticationProperties
                    {
                        IsPersistent = true,
                        ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                    };
                };

                // issue authentication cookie with subject ID and username
                var user = _users.FindByUsername(model.Username);
                await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username));
                await HttpContext.Authentication.SignInAsync(user.SubjectId, user.Username, props);

                // make sure the returnUrl is still valid, and if yes - redirect back to authorize endpoint or a local page
                if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
                {
                    return Redirect(model.ReturnUrl);
                }

                return Redirect("~/");
            }

            await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

            ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage);
        }

        // something went wrong, show form with error
        var vm = await _account.BuildLoginViewModelAsync(model);
        return View(vm);
    }

      

+1


source







All Articles