Asp. NET no magic--asp.net MVC uses Oauth2.0 for authentication

Source: Internet
Author: User
Tags oauth openid net domain

Original: ASP. NET no magic--asp.net MVC uses Oauth2.0 for authentication

With the development of software, there are more authentication usage scenarios, in addition to the typical authentication between server and client, such as service and service (such as microservices architecture), server and a variety of clients (such as PC, Mobile, web, etc.), even need to open to third parties in the form of services, Authentication has been translated into a service, and many large applications have their own authentication servers and even clusters, so common authentication methods are no longer sufficient.

There are also open source authentication server components in the. NET domain, such as identityserver (http://identityserver.io/), but these components may feel larger for some smaller projects, increasing learning and maintenance costs, So this chapter describes the OAuth and how to implement the authentication mode using OAuth.
The main contents of this chapter are:

OAuth2.0 Introduction
Using OAuth in. NET to implement authentication based on authorization code patterns
Implementing access token-based authentication
Add Refresh token support
Implementing access tokens through User password mode
Implement client mode get access Token
On. The encryption instructions for OAuth-related tokens in net

  Note: This chapter content source code download:https://files.cnblogs.com/files/selimsong/OAuth2Demo.zip

OAuth2.0 Introduction

At the beginning of the article, it was said that the increasingly rich authentication scenarios of modern software applications are a communication diagram of modern applications that describe how a common "client" communicates with the services provided by the server.

  

The figure is from identityserver:https://identityserver4.readthedocs.io/en/release/intro/big_picture.html
In order to meet these scenarios, a standard protocol is established, which is the OAuth (open Authorization) protocol, and OAuth enables third-party applications to access restricted HTTP services. OAuth has two versions of 1.0 and 2.0, but because the 1.0 version is too complex, the 1.0 version is replaced by the 2.0 version, and two versions are incompatible.
Next, we introduce the concepts related to OAuth2.0:

1. Roles in the OAuth2.0

Resource owner: The resource owner is the user who has access to the restricted resources (note: The user here is a generic, it can be either a real user or a service program).
Resource server: A resource host that can accept and process requests for access to a protected resource (such as a server that provides an API) using an access token.
Client: It refers to all third-party programs (whether Web applications, desktop apps, or server-side apps) that access protected resources through the resource owner and its authorization.
Authorization Server: Used to publish tokens for successful clients and authorization to authenticate tokens. And the client is managed.

2.OAUTH2.0 's protocol process

  

A. A third-party program sends an authorization request to the resource owner (user), which can be requested either directly from the client or through the authorization server as a mediator. ( Note: The concept of an authorization request is equivalent to a user login, the application can directly display a login page, you can also jump to the authentication server's Unified login page )
B. The user will authorize the relevant information "submit" to a third-party program, in OAuth there are 4 different ways to grant permissions, each method requires different data, such as the user password based on the authorization method requires a user name and password.
C. A third-party program submits the user's authorization information to the authorization server, requesting an Access Token.
D. After the authorization server verifies that the user's authorization information has been completed, the access token is released to a third-party program.
E. A third-party program carries access tokens to a protected resource.
F. Resource server verifies that access token is valid and returns the resource to a third-party program.

3. The authorization mode in OAuth (that is, how to get access tokens)

Authorization Code (Authorization Code mode): The core of this mode is that the client requests access Tokenfrom the authorization server through an authorization code . is a redirection-based licensing model that authorizes the server to act as a mediator for users and third-party applications (Client) when a user accesses a third-party application, a third-party app jumps to the authorization server to guide the user through authentication, generates authorization code, and forwards it to a third-party application, To facilitate third-party applications to complete subsequent access token acquisition based on this authorization code.
Implicit (simplified mode): Simplified mode is a simplified mode of Authorization code, in which the authorization code mode jumps to the authorization server for the first access to the third-party application to authenticate the return authorization code, while the simplified mode returns directly to access after jumping to the authorization server Token, this mode reduces the number of requests to access token.
Resource Owner Password Credentials (user password mode): A way to get access tokens directly through the user name and password of the resource owner (user) , which requires a third-party application (client) is highly trusted and is used in situations where other licensing methods are not available.
Client Credentials: The mode is to send an own credential to the authorization server through a third-party application to obtain access Token, The use of this mode requires that the client has been authorized to administer the server and restrict its access to the protected resources. In this mode, the client should be a resource owner (user), such as a microservices program.

4. Access Token & Refresh Token

It's good to understand that third-party apps use access tokens to get protected resources, but access tokens are valid and cannot be used once they expire, and to prevent access tokens from expiring after they expire, the concept of refresh token is added. The update of Access tokens is done in a refreshed manner.

5. Client Registration

In OAuth2.0, all programs that require access to restricted resources are considered third-party applications (clients), so that OAuth needs to be managed by the client in order to ensure that the client is secure and trustworthy. Reference: Https://tools.ietf.org/html/rfc6749#section-2

6. Endpoint for OAuth

The endpoint here represents an HTTP resource that needs support for some endpoints during the OAuth authorization process, such as the acquisition of Authorization Code (authorization Code), and access token acquisition, which 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 for the client to use Access tokens to complete a request for a protected resource based on the specific type.
Two types of OAuth2.0 are bearer and Macs, which are shown in the following ways:
Bearer:

  

MAC:

  

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

Using OAuth in. NET to implement authentication based on authorization code patterns

OAUTH2.0 is an open standard, since it is standard then can be implemented, in. NET Microsoft-based Owin implementation of the OAUTH2.0 protocol, the following describes how to implement OAuth authentication in ASP.
  Note: This example is done based on the ASP. NET MVC default authentication template.

1. Component Installation

Installing the Microsoft.Owin.Security.OAuth component from NuGet:

  

  Note: From the name of the component you can see that. NET implementations of OAuth are actually based on Owin, so much of the content uses the relevant authentication concepts in Owin, which can be referenced in this series and in the authentication article.

2. Add an OAuth authorization server

According to the above OAuth introduction, the authorization server is one of the OAuth role, the role of the main function is the issuance of Access token and authorization , and it is also used to support authorization Code mode of authorization code issuance and the management of the client .
Add the following code to the startup type's configuration method, which adds an authorization server for the Owin middleware ( Note: The middleware is a Owin authentication middleware that can be referenced byASP. NET does not have the "multiple" Authentication of Magic--asp.net identity ).

  

Where oauthauthorizationserveroptions is defined as follows:

  

The above definitions can be divided into the following categories:
Endpoint address: Authorizeendpointpath, Tokenendpointpath, etc., which defines access to the authorization code and the address information for obtaining tokens.
Token provider: Authorizationcodeprovider, Accesstokenprovider, Refreshtokenprovider are responsible for the creation and processing of corresponding tokens.
Token "Encryption" and "decryption": This function is the combination of OAuth and Owin authentication, through the implementation of Accesstokenformat and other Isecuredataformat interface can convert the corresponding token into a Authenticationticket. Refer to the ASP. NET does not have the use of Ticketdataformat in the encryption and decryption of magic--asp.net identity.
OAuth Licensing Service: Provider is the core of the entire OAuth server , which contains the processing and response of endpoints , 4 ways of access token authorization in OAuth, and Refresh the token to get access token and the request, the client related validation :

  

3. Add an endpoint for the licensing server

The above introduction to OAuth describes the endpoint is actually used to obtain the authorization Code or access Token , in the. NET uses the Microsoft.Owin.Security.OAuth component only in the form of configuration to specify the authorization code and token to obtain the endpoint access address ( Note: Set the Allowinsecurehttp configuration property to True, You can allow unsecured HTTP to access the endpoint, which is used only for the development environment :

  

Once you are done, you can access these two addresses via your browser:

  

  

You can see that it is accessible, but there is an error (note: The QueryString parameter Reference document for the requested address).

4. Client Management and validation

The client in OAuth refers to an application where all third parties need access to restricted resources, and the authorization server needs to complete the client management and validation functions in order to be able to identify and authenticate the client. (Note: Microsoft only provides the interface for client authentication in the Microsoft.Owin.Security.OAuth component, so it implements the management of client data and the validation logic itself):

1). Add the client entity and the corresponding warehousing (this example implements the storage in memory, at least the database should be saved in actual use):

  

Is the client's most basic attribute (note: If you also need to limit the scope of the client's access, you should also include a scope list, which is no longer restricted to scope).

2). Client's warehousing:

  

3). Implement authentication of the client by the authorization server:

Because the authorization server interfaces to client authentication are in the Oauthauthorizationserverprovider type, you first inherit the type and overload the appropriate validation methods:

  

The above code does a few things:
Attempt to get client information from HTTP request header or request body, including ID and password.
If there is no client ID information, then directly judged not to pass validation, if the client's password information is saved to the Owin context for subsequent processing use.
Use the obtained ClientID in the client repository to determine whether a legitimate client, if not, is judged not to pass the validation.

4). Set the redirect URL for the client after verification is complete (note: This method is still overloaded with methods in the Oauthauthorizationserverprovider type):

  

5. Add the Authorization code provider

Authorization code generation is a function of the authorization server endpoint, when using the Authorization Code mode , the user access client will be booted to the authorization server to complete the authentication (login), and then To jumpback to the client with the authorization code, the client uses the authorization code to obtain access tokens. In the. NET implementation of OAuth, the provider is used to create and parse tokens by configuring a token provider of type Iauthenticationtokenprovider in the configuration. The creation of this is actually the user to complete the authorization code generation and authorization code and user Login Identity Information Association, and the actual resolution is based on the authorization code to obtain the corresponding user identity information and generate access token process.

The following is a custom authorization code provider implemented by implementing the Iauthenticationtokenprovider method:

  

From the above code, it can be seen that the core function of this provider is to generate a key value (authorization code) as a GUID to save the current user's information, when resolved by the key value (that is, the authorization code) to obtain user identity information. ( Note: The Authenticationtokencreatecontext object is used to serialize and deserialize the current user identity information authenticationticket pairs. )

When you are finished, configure the provider to the licensing server middleware:

  

6. Add a User authorization prompt page for the licensing server

When a user accesses the authorization code endpoint, it is supposed to let the user know that the client needs his authorization, and for this purpose in the ASP. NET MVC program, you need to add a controller, action, and view that matches the address of the authorization Code endpoint:

1). Controller and Action (note: The action needs to be authenticated and not accessible if you do not need to jump to the login page to complete the authentication):

  

2). View: Show authorization prompt

  

7. Running the program

1). Access Authorization Code endpoint get authorization code: HTTP://LOCALHOST:59273/OAUTH2/AUTHORIZE?RESPONSE_TYPE=CODE&CLIENT_ID=TEST1

Because you are not logged in, jump to the login page first.

  

After completing the login, jump back to the authorization page:

  

After clicking the authorization button, bring the authorization code to the redirect URL of the client test1 ( Note: Here test1 this client setting URL is the authorization server itself, so it does not appear to be redirected )

  

After obtaining the authorization code, carry the authorization code to access the token endpoint to get access token (note: The postman extension of Chrome browser is used to achieve the requested impersonation):

  

  Note: The Access_token in the above response information contains the encrypted user's identity information, the encryption process can refer to the cookie-based user information encryption process. ASP. NET no magic--asp.net identity encryption and decryption

Implementing access token-based authentication

Here's how to get access tokens based on the authorization code pattern, and then we'll show you how to access restricted resources using Access tokens ( Note: The resource server in this example is in the same instance as the authorization server, so when the resource server is on the access Token decryption is guaranteed to be consistent with the key used by the authorization server to generate access tokens and can be decrypted normally, where the authentication cookie in access token and cookie-based authentication is of the same nature, is the encrypted string after serializing the user's identity information )

1. Add the bearer-based OAuth authentication middleware to the startup class:

  

2. Add access to restricted resources:

  

3. Access restricted resources:

No authorization information is added directly to the login page.

  

After you add access tokens, you can access the resources normally:

  

Add Refresh token support

Access tokens generated using the authorization code pattern above have an expiration time (in fact, no matter how the generated access token has an expiration time), the token expires and it is not possible for the user to re-authorize again, so you need to use the refresh Token to refresh access tokens regularly. NET implements the refresh token in the same way as the authorization code, when the refresh token is generated and the user's identity information is associated, subsequent use of the refresh token can be used to generate a new access token.

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

  

2. Configure the Refresh token provider for the licensing server:

  

3. Once the authorization code is acquired again, access token is obtained according to the authorization code, and the return message will carry the Refresh token:

  

4. Refresh Access tokens According to refresh token:

  

Implementing access tokens through User password mode

The implementation of the authorization code pattern is described above, but the core of this approach is actually establishing a mapping of the authorization Code and user information (including the refresh token and the mapping of the refresh token to the user information), and subsequent access Token is actually generated using this user information. In other words, the user information is the core,. NET user information reflected from the bottom to the high is:iidentity->claimsidentity-> authenticationticket, about the user's identity information can refer to: "ASP." NET no magic--asp.net identity and authorization, in the authorization code-based mode when the authorization server through the login function to obtain user information, and based on the user name password mode does not have this jump login link, so need to directly through the user name password to obtain user information, Its implementation overloads the Grantresourceownercredentials method of the Oauthauthorizationserverprovider type as follows:

  

This method obtains the Usermanager object in the identity from the Owin environment, verifies that the user exists by Usermanager, and, if present, uses the user information to create a Claimsidentity object (note: Here is the omitted implementation, The normal implementation can also add information such as scope or role to the identity object according to the requirements of the cookie authentication method. Another usermanager is added to the Owin context by the following code, and its key value is "AspNet.Identity.Owin:" + typeof (Applicationusermanager). AssemblyQualifiedName.

  

Get access tokens using your username password:

  

Implement client mode get access Token

Client mode and user name password mode is similar, it is through the client's ID and password to authorize, using the client-related information, it is implemented as follows, overloaded Grantclientcredentials method, Verify that the client is legitimate by using the ID and password information that is verified by the clients, and create an identity object for the legitimate client (note: Here you can add the appropriate attributes to the identity based on the actual requirements):

  

Use client information to get access tokens:

  

The above is. NET in the implementation of OAuth, in addition. NET does not provide an interface to simplify the schema, but provides a grantcustomextension, which means that the authorization mode is extensible.

About. The encryption instructions for OAuth-related tokens in net

In this case, in addition to the authorization code and the refresh token is a 2 GUID connection, the access token (including all authorization mode generated tokens) and authorization code corresponding user information, refresh token corresponding user information is encrypted, and its decryption object creation process is as follows, the specific content can refer to the ASP. NET no magic--asp.net identity encryption and decryption

  

Summary

This chapter describes the content of the OAUTH2.0 protocol and implements most of the functionality of the Protocol through an ASP. NET MVC program based on the Microsoft Microsoft.Owin.Security.OAuth component. Using OAuth for authentication allows our applications to run from the web to any platform, but there are still some problems with this implementation, and further discussion and introduction to these issues will be discussed in the next article.

PS. This chapter content is more, if has the question can in the comment area message, in addition recent things more, so update slowly, thanks everybody's support.

Reference:

Https://stackoverflow.com/questions/39909419/jwt-vs-oauth-authentication
Http://www.cnblogs.com/linianhui/p/oauth2-authorization.html
http://www.c-sharpcorner.com/UploadFile/4b0136/openid-connect-availability-in-owin-security-components/
Https://docs.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server
Https://security.stackexchange.com/questions/94995/oauth-2-vs-openid-connect-to-secure-api
http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/

This article link: http://www.cnblogs.com/selimsong/p/8037717.html

Asp. NET no magic--Directory

Asp. NET no magic--asp.net MVC uses Oauth2.0 for authentication

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.