Overview of ASP.NET Core authentication
By Mike Rousos
Authentication is the process of determining a user's identity. Authorization is the process of determining whether a user has access to a resource. In ASP.NET Core, authentication is handled by the authentication service, IAuthenticationService, which is used by authentication middleware. The authentication service uses registered authentication handlers to complete authentication-related actions. Examples of authentication-related actions include:
- Authenticating a user.
- Responding when an unauthenticated user tries to access a restricted resource.
The registered authentication handlers and their configuration options are called "schemes".
Authentication schemes are specified by registering authentication services in Program.cs
:
- By calling a scheme-specific extension method after a call to AddAuthentication, such as AddJwtBearer or AddCookie. These extension methods use AuthenticationBuilder.AddScheme to register schemes with appropriate settings.
- Less commonly, by calling
AuthenticationBuilder.AddScheme
directly.
For example, the following code registers authentication services and handlers for cookie and JWT bearer authentication schemes:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme,
options => builder.Configuration.Bind("JwtSettings", options))
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
options => builder.Configuration.Bind("CookieSettings", options));
The AddAuthentication
parameter JwtBearerDefaults.AuthenticationScheme is the name of the scheme to use by default when a specific scheme isn't requested.
If multiple schemes are used, authorization policies (or authorization attributes) can specify the authentication scheme (or schemes) they depend on to authenticate the user. In the example above, the cookie authentication scheme could be used by specifying its name (CookieAuthenticationDefaults.AuthenticationScheme by default, though a different name could be provided when calling AddCookie
).
In some cases, the call to AddAuthentication
is automatically made by other extension methods. For example, when using ASP.NET Core Identity, AddAuthentication
is called internally.
The Authentication middleware is added in Program.cs
by calling UseAuthentication. Calling UseAuthentication
registers the middleware that uses the previously registered authentication schemes. Call UseAuthentication
before any middleware that depends on users being authenticated.