Overview of ASP.NET Core authentication
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.
Authentication concepts
Authentication is responsible for providing the ClaimsPrincipal for authorization to make permission decisions against. There are multiple authentication scheme approaches to select which authentication handler is responsible for generating the correct set of claims:
- Authentication scheme
- The default authentication scheme, discussed in the next two sections.
- Directly set HttpContext.User.
When there is only a single authentication scheme registered, it becomes the default scheme. If multiple schemes are registered and the default scheme isn't specified, a scheme must be specified in the authorize attribute, otherwise, the following error is thrown:
InvalidOperationException: No authenticationScheme was specified, and there was no DefaultAuthenticateScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions).
DefaultScheme
When there is only a single authentication scheme registered, the single authentication scheme:
- Is automatically used as the DefaultScheme.
- Eliminates the need to specify the
DefaultScheme
in AddAuthentication(IServiceCollection) or AddAuthenticationCore(IServiceCollection).
To disable automatically using the single authentication scheme as the DefaultScheme
, call AppContext.SetSwitch("Microsoft.AspNetCore.Authentication.SuppressAutoDefaultScheme")
.
Authentication scheme
The authentication scheme can select which authentication handler is responsible for generating the correct set of claims. For more information, see Authorize with a specific scheme.
An authentication scheme is a name that corresponds to:
- An authentication handler.
- Options for configuring that specific instance of the handler.
Schemes are useful as a mechanism for referring to the authentication, challenge, and forbid behaviors of the associated handler. For example, an authorization policy can use scheme names to specify which authentication scheme (or schemes) should be used to authenticate the user. When configuring authentication, it's common to specify the default authentication scheme. The default scheme is used unless a resource requests a specific scheme. It's also possible to:
- Specify different default schemes to use for authenticate, challenge, and forbid actions.
- Combine multiple schemes into one using policy schemes.
Authentication handler
An authentication handler:
- Is a type that implements the behavior of a scheme.
- Is derived from IAuthenticationHandler or AuthenticationHandler<TOptions>.
- Has the primary responsibility to authenticate users.
Based on the authentication scheme's configuration and the incoming request context, authentication handlers:
- Construct AuthenticationTicket objects representing the user's identity if authentication is successful.
- Return 'no result' or 'failure' if authentication is unsuccessful.
- Have methods for challenge and forbid actions for when users attempt to access resources:
- They're unauthorized to access (forbid).
- When they're unauthenticated (challenge).
RemoteAuthenticationHandler<TOptions>
vs AuthenticationHandler<TOptions>
RemoteAuthenticationHandler<TOptions> is the class for authentication that requires a remote authentication step. When the remote authentication step is finished, the handler calls back to the CallbackPath
set by the handler. The handler finishes the authentication step using the information passed to the HandleRemoteAuthenticateAsync callback path. OAuth 2.0 and OIDC both use this pattern. JWT and cookies don't since they can directly use the bearer header and cookie to authenticate. The remotely hosted provider in this case:
- Is the authentication provider.
- Examples include Facebook, Twitter, Google, Microsoft, and any other OIDC provider that handles authenticating users using the handlers mechanism.
远程身份验证步骤完成后,处理程序将回调处理程序设置的 CallbackPath
。 处理程序使用传递给 HandleRemoteAuthenticateAsync 回调路径的信息完成身份验证步骤。 OAuth 2.0 和 OIDC 都使用此模式。 JWT 和 cookies 不使用此模式,因为它们可以直接使用持有者标头和 cookie 进行身份验证。
Authenticate
An authentication scheme's authenticate action is responsible for constructing the user's identity based on request context. It returns an AuthenticateResult indicating whether authentication was successful and, if so, the user's identity in an authentication ticket. See AuthenticateAsync. Authenticate examples include:
- A cookie authentication scheme constructing the user's identity from cookies.
- A JWT bearer scheme deserializing and validating a JWT bearer token to construct the user's identity.
Challenge 如果用户尝试访问受限资源,把用户导向一个登录页面
An authentication challenge is invoked by Authorization when an unauthenticated user requests an endpoint that requires authentication. An authentication challenge is issued, for example, when an anonymous user requests a restricted resource or follows a login link. Authorization invokes a challenge using the specified authentication scheme(s), or the default if none is specified. See ChallengeAsync. Authentication challenge examples include:
- A cookie authentication scheme redirecting the user to a login page.
- A JWT bearer scheme returning a 401 result with a
www-authenticate: bearer
header.
A challenge action should let the user know what authentication mechanism to use to access the requested resource.
Forbid
An authentication scheme's forbid action is called by Authorization when an authenticated user attempts to access a resource they're not permitted to access. See ForbidAsync. Authentication forbid examples include:
- A cookie authentication scheme redirecting the user to a page indicating access was forbidden.
- A JWT bearer scheme returning a 403 result.
- A custom authentication scheme redirecting to a page where the user can request access to the resource.
A forbid action can let the user know:
- They're authenticated.
- They're not permitted to access the requested resource.
See the following links for differences between challenge and forbid:
- Challenge and forbid with an operational resource handler.
- Differences between challenge and forbid.
Authentication providers per tenant
ASP.NET Core doesn't have a built-in solution for multi-tenant authentication. While it's possible for customers to write one using the built-in features, we recommend customers to consider Orchard Core or ABP Framework for multi-tenant authentication.
Orchard Core is:
- An open-source, modular, and multi-tenant app framework built with ASP.NET Core.
- A content management system (CMS) built on top of that app framework.
See the Orchard Core source for an example of authentication providers per tenant.
ABP Framework supports various architectural patterns including modularity, microservices, domain driven design, and multi-tenancy. See ABP Framework source on GitHub.
Additional resources
- Authorize with a specific scheme in ASP.NET Core
- Policy schemes in ASP.NET Core
- Create an ASP.NET Core app with user data protected by authorization
- Globally require authenticated users
- GitHub issue on using multiple authentication schemes
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2022-07-19 How to set the Google Analytics cookie only after another consent cookie is set and "true"?
2022-07-19 Using Google Consent Mode to Adjust Tag Behavior Based on Consent
2020-07-19 IIS自带的http modules分别注册了HttpApplication pipeline里面的哪些事件
2019-07-19 .NET Assembly File Format
2019-07-19 dnSpy PE format ( Portable Executable File Format)
2019-07-19 .net 查壳工具
2019-07-19 How to change the button text of <input type=“file” />?