Creating a user registration API

It goes without saying that, in order to authenticate and authorize users, we need to provide some mechanism to register them to our application. ASP.NET Core makes this task easy by providing utility classes that we can use to make sure that user registration is secure. 

Open (or create, if needed) the AccountController and add to the constructor the following dependencies:

  • UserManager<User>: Provides the APIs for managing users in a persistence store
  • SignInManager<User>: Provides the APIs for user logins
  • IConfiguration: Provides the access point for the application configuration

Store each dependency in a class member. Your class should look similar to this:

[Produces("application/json")]
[Route("api/Account")]
public class AccountController : Controller
{
private readonly UserManager<User> _userManager;
private readonly SignInManager<User> _signInManager;
private readonly IConfiguration _configuration;

public AccountController(UserManager<User> userManager,
SignInManager<User> signInManager,
IConfiguration configuration)
{
_userManager = userManager;
_signInManager = signInManager;
_configuration = configuration;
}
}

To register a user, the backend application exposes an action in the URL /api/account/register, which should be called with a POST HTTP request, and receives the user's email address, password, and a password confirmation. 

Add a new class to your DTO folder and name it RegisterUserDTO. This class will be the input of our registration action:

public class RegisterUserDTO
{
[Required]
[EmailAddress]
public string Email { get; set; }

[Required]
[StringLength(100, MinimumLength = 6)]
[DataType(DataType.Password)]
public string Password { get; set; }

[DataType(DataType.Password)]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}

I've set validation attributes on the class properties so that we can easily validate the user request.

Now, add the following method to your AccountController:

[AllowAnonymous]
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] RegisterUserDTO registration)
{
if (!ModelState.IsValid) { return BadRequest(ModelState); }

User newUser = new User
{
Email = registration.Email,
UserName = registration.Email,
Id = registration.Email,
};
IdentityResult result = await _userManager.CreateAsync(newUser, registration.Password);
if (!result.Succeeded)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(error.Code, error.Description);
}
return BadRequest(ModelState);
}

return Ok();
}

The method starts by validating the user input by checking if the ModelState is valid. Then, a new User object is created and added through the UserManager. One of the things that the UserManager does for you is save the user's password in a secure way by hashing it. Cryptographic code is complex and it is easy to do it wrong, so I always recommend using a library that was created by people who are experts in the subject, just as the identity package was.

The CreateAsync method returns an IdentityResult output that contains information on whether or not the operation succeeded, and the collection of errors if it failed. In the case of failure, I add the errors to the ModelState and return a BadRequest result to the user.

Run the application and register a new user by sending an HTTP POST request with Postman, as shown here:

The text in this image is not important; you may get different values. The purpose of this image is to show you what the structure of the request and response should look like in Postman.

You have now successfully registered a new user to your system, and now, we can add login functionality to the application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.18.198