9 Authentication and authorization

 

This chapter covers

  • Authentication and Authorization general concepts
  • ASP.NET Core Identity overview
  • Implementing authentication via user accounts and JSON Web Tokens (JWT)
  • Implementing authorization using AuthorizeAttribute and IAuthorizationFilter
  • Third-party Auth providers

The ASP.NET Core Web API that we have built throughout the previous chapters has taken a rather solid shape. Before being able to publish it, however, we must address some major security permissions issues that we have intentionally left open: if we take a closer look at our BoardGamesController, DomainsController, and MechanicsController, we can easily see how they all have some Post and Delete methods that could be used by anyone to permanently alter our valuable data. We definitely don’t want that, do we?

For that very reason, before ever thinking of deploying our Web API over the internet and making it publicly accessible, we need to find a way to restrict the usage of those methods to a limited set of authorized users.

In this chapter we’ll learn how to do that using ASP.NET Core Identity, a built-in API that can be used to manage users, roles, claims, tokens, policies, auth-related behaviors, and more.

9.1 Basic concepts

Before delving into the code, it is appropriate to provide a general overview of the concepts of authentication and authorization. Although often used in the same context, the two terms have a distinct and precise meaning.

9.1.1 Authentication

9.1.2 Authorization

9.2 ASP.NET Core Identity

9.2.1 Installing the NuGet packages

9.2.2 Creating the User entity

9.2.3 Updating the ApplicationDbContext

9.2.4 Adding and applying a new migration

9.2.5 Setting up the services and middlewares

9.2.6 Implementing the AccountController

9.3 Authorization settings

9.3.1 Adding the Authorization HTTP Header

9.3.2 Setting up the [Authorize] attribute

9.3.3 Testing the authorization flow

9.4 Role-Based Access Control (RBAC)

9.4.1 Registering the new users

9.4.2 Creating the new Roles

9.4.3 Assigning Users to Roles

9.4.4 Adding role-based claims to JWT