Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Oauth2.0 to verify identity in ASP.NET MVC

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you about how to use Oauth2.0 authentication in ASP.NET MVC. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

1. Roles in OAuth3.0

● Resource Owner: the resource owner is the user who has access to the restricted resource.

● Resource Server: resource host that can accept and process requests to access protected resources using an access token (access token) (such as a server that provides API).

● Client: it generally refers to all third-party programs (whether Web applications, desktop applications, or server-side applications) that access protected resources through the resource owner and its authorization.

● Authorization Server: used to issue tokens to successfully authorized clients and to verify authorization for tokens. And manage the Client.

Protocol flow of 2.OAuth3.0

a. The third-party program sends authorization request to the resource owner (user). This process can either request the user directly through the client or use the authorization server as an intermediary to complete the request. (note: for the concept of authorization request, which is equivalent to user login, the application can directly display a login page or jump to the unified login page of the authentication server)

b. Users "submit" authorization-related information to third-party programs. There are four different authorization methods in OAuth, each of which requires different data. For example, user name and password are required for authorization based on user password.

c. The third-party program submits the user's authorization information to the authorization server and requests an Access Token.

d. After the authorization server verifies the authorization information of the user, it sends the Access Token to the third party program.

e. Third-party programs carry Access Token to access protected resources.

f. After verifying that the Access Token is valid, the resource server returns the resource to a third-party program.

3. Authorization mode in OAuth (that is, how to obtain Access Token)

● Authorization Code (Authorization Code Mode): the core of this mode is that the client applies for Access Token from the authorization server through an authorization code. It is a kind of authorization mode based on redirection. The authorization server acts as the intermediary between the user and the third-party application (Client). When the user visits the third-party application, the third-party application jumps to the authorization server to guide the user to complete the authentication, generates the Authorization Code and transfers it to the third-party application, so that the third-party application can complete the subsequent Access Token acquisition according to this authorization code.

● Implicit (simplified mode): the simplified mode is a simplified authorization code mode. When accessing a third-party application for the first time, the authorization code mode jumps to the authorization server for authentication and returns the authorization code, while the simplified mode returns Access Token directly after jumping to the authorization server. This mode reduces the number of requests to obtain Access Token.

● Resource Owner Password Credentials (user password mode): a method of obtaining Access Token directly through the user name and password of the resource owner (user), which requires that third-party applications (Client) are highly trusted and other authorization methods are not available.

● Client Credentials (client mode): this mode is to send one's own credential to the authorization server to obtain the Access Token through the third-party application (Client). The use of this mode requires that the Client has been managed by the authorized server and limited its access to protected resources. In addition, in this mode, Client should be a resource owner (user), such as a microservice program.

4. Access Token & Refresh Token

It is easy to understand that third-party applications obtain protected resources through Access Token, but Access Token is valid and cannot be used once it expires. In order to avoid that Access Token cannot be used after it expires, the concept of Refresh Token is added to complete the update of Access Token by refreshing.

5. Registration of Client

In OAuth3.0, all programs that need to access restricted resources are regarded as third-party applications (Client). In order to ensure that the Client is secure and trusted, OAuth needs to manage the Client. Reference: https://tools.ietf.org/html/rfc6749#section-2

6. The endpoint of OAuth

Here the endpoint represents the HTTP resource, and some endpoint support is needed in the OAuth authorization process, such as the acquisition of Authorization code (authorization code) and Access Token. The endpoint is provided by the authorization server. Reference: https://tools.ietf.org/html/rfc6749#section-3

7. Access Token Type

The type of Access Token is to let Client use Access Token to complete requests for protected resources based on the specific type.

There are two types of OAuth3.0, Bearer and Mac, which are represented as follows:

● Bearer:

● Mac:

Reference: https://tools.ietf.org/html/rfc6750

Using OAuth to implement authentication based on authorization code mode in .net

OAuth3.0 is an open standard, since it is a standard, it can be implemented. Microsoft has implemented the OAuth3.0 protocol based on Owin in .net. Here is how to implement OAuth authentication in ASP.NET MVC programs.

Note: this example is based on ASP.NET MVC default with authentication template.

1. Component installation

Install the Microsoft.Owin.Security.OAuth components through NuGet:

Note: as can be seen from the name of this component, .net 's implementation of OAuth is actually based on Owin, so much of the content uses the related authentication concepts in Owin, which can be found in this series and authentication articles.

two。 Add OAuth Licensing Server

According to the introduction of OAuth above, the authorization server is one of the roles of OAuth, and the main function of this role is the issuance and authorization of Access Token. In addition, it is also used to support the distribution of authorization codes in authorization code mode and the management of Client.

Add the following code to the Configuration method of type Startup to add an authorization server to the Owin middleware (note: the middleware is an Owin authentication middleware can refer to "ASP.NET has no magic-ASP.NET Identity's" multiple "authentication").

OAuthAuthorizationServerOptions is defined as follows:

The above definitions can be divided into the following categories:

● endpoint address: AuthorizeEndpointPath, TokenEndpointPath, etc., which defines the access to obtain the authorization code and the address information of the Token.

● Token provider: AuthorizationCodeProvider, AccessTokenProvider, and RefreshTokenProvider are responsible for the creation and processing of the corresponding tokens.

"encryption" and "decryption" of ● Token: this function is a combination of OAuth and Owin authentication. The corresponding Token can be converted into an AuthenticationTicket through the implementation of ISecureDataFormat interfaces such as AccessTokenFormat. Please refer to the usage of TicketDataFormat in the article "ASP.NET has no magic-encryption and decryption of ASP.NET Identity".

● OAuth authorization service: Provider is the core of the entire OAuth server, which includes the processing and response of endpoints, four Access Token authorization methods in OAuth, the way to obtain Access Token by refreshing tokens, and the related verification of requests and clients:

3. Add endpoints to the authorization server

When OAuth is introduced above, the endpoint is actually used to obtain the authorization code or Access Token. Using the Microsoft.Owin.Security.OAuth component in .net, you only need to specify the authorization code and the endpoint access address obtained by Token in the form of configuration (Note: set the AllowInsecureHttp configuration property to true to allow insecure http to access the endpoint, which is only used in the development environment):

When you are finished, you can access these two addresses through the browser:

You can see that it is accessible, but there is an error (note: the parameter reference documentation for the QueryString of the request address).

4. Management and verification of Client

Client refers to all the applications that third parties need to access restricted resources in OAuth. In order to identify and verify Client, the authorization server needs to complete the management and verification functions of Client. (note: Microsoft only provides the interface for Client authentication in the Microsoft.Owin.Security.OAuth component, so it is necessary to implement the Client data management and validation logic on its own):

1)。 Add the Client entity and the corresponding repository (in this case, the storage is implemented in memory, and the database should at least be saved in actual use):

The figure above is the most basic attribute of Client (note: if you also need to restrict the access scope of Client, you should also add a list of Scope, which is no longer restricted by Scope in this case).

2)。 Warehousing of Client:

3)。 Implement the authentication of Client by the authorization server:

Because the interface that the authorization server validates to the client is in the OAuthAuthorizationServerProvider type, you should first inherit that type and overload the corresponding authentication method:

The above code does the following:

● attempts to get Client information, including Id and password, from Http request header or request body.

If the ● does not have the Id information of the Client, it is directly judged to fail the verification, and if there is any password information of the Client, it is saved to the Owin context for subsequent processing.

● uses the obtained ClientId to query in the Client repository to determine whether it is a legitimate Client, and if not, it fails the verification.

4)。 Set the redirect Url for the Client after verification (Note: this method is still the method in the overloaded OAuthAuthorizationServerProvider type):

5. Add authenticator provider

The generation of the authorization code is a function of the authorization server endpoint. When using the authorization code mode, the user accessing the Client will be directed to the authorization server to complete authentication (login), and then jump back to Client,Client with the authorization code to obtain the Access Token. In the .net implementation of OAuth, you need to configure a token provider of type IAuthenticationTokenProvider in the configuration, which is used to create and parse tokens. The creation here is actually the generation of the authorization code after login and the association between the authorization code and the login identity information of the user. Resolution is actually the process of obtaining the corresponding user identity information and generating Access Token according to the authorization code.

Here is how to implement a custom authorization code provider by implementing IAuthenticationTokenProvider:

As can be seen from the above code, the core function of this provider is to generate a key value (authorization code) in the way of Guid to save the current user's information, and to obtain the user's identity information through the key value (that is, the authorization code) when parsing. (note: the AuthenticationTokenCreateContext object is used to serialize and deserialize AuthenticationTicket pairs of current user identity information)

When you are finished, configure the provider into the authorization server middleware:

6. Add a user authorization prompt page for the authorization server

When a user accesses the authenticator endpoint, he or she should know that Client needs his authorization. To do this, you need to add a Controller, Action, and View that match the address of the authenticator endpoint in the ASP.NET MVC program:

1)。 Controller and Action (Note: the Action needs to be authenticated. If you do not need to jump to the login page to complete authentication, you can only access it):

2)。 View: displays authorization prompts

7. Run the program

1)。 Access the authorization code endpoint to get the authorization code: http://localhost:59273/oauth3/authorize?response_type=code&client_id=test1

Since there is no login, jump to the login page first.

After logging in, jump back to the authorization page:

After clicking the authorization button, jump to the redirect Url of the client with the authorization code (Note: the Url set by the test1 Client here is the authorization server itself, so it does not appear to be redirected)

After obtaining the authorization code, visit the Access Token endpoint with the authorization code to obtain Access Token (Note: here the Postman extension of the Chrome browser is used to simulate the request):

Note: the access_token in the above response information contains the user's identity information after encryption. The encryption process can be referred to the user information encryption process based on Cookie. ASP.NET has no magic-- encryption and decryption of ASP.NET Identity

Implement authentication based on Access Token

The above describes how to obtain Access Token based on the authorization code mode, and then describes how to use Access Token to access restricted resources. (note: the resource server in this example is in the same instance as the authorization server, so when the resource server decrypts the access token, it can be guaranteed to be consistent with the key used by the authorization server to generate access token, and can be decrypted normally. The Cookie nature of authentication in Access Token and Cookie-based authentication is the same, both are encrypted strings after serializing the user's identity information)

1. Add Bearer-based OAuth authentication middleware to the Startup class:

two。 Add resources with restricted access:

3. Access to restricted resources:

Jump directly to the login page without adding authorization information.

Resources can be accessed normally after adding Access Token:

Join Refresh Token support

The Access Token generated using the authorization code mode above has an expiration time (in fact, no matter how the Access Token is generated), and it is impossible for the user to authorize again after the Token expires, so it is necessary to use Refresh Token to regularly refresh the Refresh Token in the Access Token,.Net in a way similar to the authorization code, which is associated with the user's identity information when the Refresh Token is generated. You can use this Refresh Token later to generate a new Access Token.

1. Create a Refresh Token provider (implemented in the same way as the authorization code provider):

two。 Configure the Refresh Token provider for the authorization server:

3. After obtaining the authorization code again, obtain the Access Token according to the authorization code, and the returned information will contain the Refresh Token:

4. Refresh Access Token according to Refresh Token:

Implement to obtain Access Token through user password mode

The implementation of the authorization code pattern is described above, but the core of this method is actually to establish a mapping between the authorization code and the user information (including the refresh token method is also to establish the mapping between the refresh token and the user information). The subsequent Access Token actually uses this to generate the user information. In other words, user information is the core. The embodiment of user information in .net from bottom to high is: IIdentity- > ClaimsIdentity- > AuthenticationTicket. For more information about user identity, please see: "ASP.NET has no magic-ASP.NET Identity and authorization". In the authorization code-based mode, the user information is obtained through the login function in the authorization server, but there is no such jump login link based on the username password mode. Therefore, you need to obtain the user information directly through the user name and password. The implementation overrides the GrantResourceOwnerCredentials method of type OAuthAuthorizationServerProvider as follows:

This method obtains the UserManager object in Identity from the Owin environment, verifies the existence of the user through UserManager, and creates a ClaimsIdentity object using the user information if it exists (Note: here is the implementation of omission. The normal implementation can refer to the Cookie verification method to add information such as Scope or Role to the Identity object as needed). Another UserManager is added to the Owin context through the following code, whose Key value is "AspNet.Identity.Owin:" + typeof (ApplicationUserManager). AssemblyQualifiedName.

Use the username and password to get the Access Token:

Implement client mode to get Access Token

The client mode is similar to the user name and password mode. It is authorized through the Id and password of Client, and uses Client-related information. It is implemented as follows: overload the GrantClientCredentials method, verify whether the changed Client is legal through the id and password information verified by the client, and create an Identity object for the legitimate Client (Note: here you can add the corresponding attributes in the Identity according to the actual needs):

Use Client information to get Access Token:

The above is the implementation of OAuth in .net, and there is no interface to simplify the mode in .net, but it does provide a GrantCustomExtension, that is to say, the authorization pattern is extensible.

Encryption instructions for OAuth-related tokens in .net

In this example, except for the authorization code and the refresh token, which are two Guid connections, the access token (including all tokens generated by authorization mode), the user information corresponding to the authorization code and the user information corresponding to the refresh token are encrypted. The encryption and decryption object creation process is as follows. For more information, please see "ASP.NET has no magic-encryption and decryption of ASP.NET Identity".

This is how to use Oauth2.0 to verify your identity in the ASP.NET MVC shared by the editor. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report