Search code examples
identityserver4single-page-applicationregistration

IdentityServer4 and SPA Applications and New User Registration


What is the correct approach to handle new user registration for a SPA (Angular) application? I am using IdentityServer 4 for authentication (Code Flow) and authorization to my APIs and that is working well. However, I am unsure where should new user registration takes place, especially I want the new user to be automatically logged in after registration, in other words, I would not want them to have to go to a log-screen after registration. Should the registration be handle in the SPA application or in a special view in IdentityServer? In either case, how do I get the JWT token afterward to allow access to my APIs?

Thanks in advance.


Solution

  • You'll want the registration to be handled in the Identity Server project. You can add two new methods to the AccountController.cs class that will be similar to the Login* methods in the class, one for loading the page and another for handling the registration input.

    Assuming that you are using Microsoft Identity for managing user accounts you can have your registration endpoint take the info from the registration page, create the Identity in the database, then call the same login method that the login endpoint calls. Something along the lines of this

    // Do model validation, verify the user doesn't already exist, etc...
    ...
    var createUser = await _userManager.CreateAsync(new ApplicationUser
        {
            Email = model.UserName,
            NormalizedEmail = model.UserName,
            UserName = model.UserName,
            FirstName = model.FirstName,
            LastName = model.LastName
        }, model.Password);
    var user = await _userManager.FindByEmailAsync(model.UserName);
    if (createUser.Succeeded)
    {
        // Add roles to the user
        await _userManager.AddToRoleAsync(user, "Customer");
        var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, false, lockoutOnFailure: false);
    ...
    // You'll want to redirect back to the client site to complete the login process