Four authorization methods of oauth2.0


This article is included in personal blog: Sharing technology resources and making progress together

Last week, my self-developed open source project began to break ground, and “open source project took the first step, 1 out of 10? Page templates become the first stumbling block

》It took a long time for the plot to be put into action. The original intention of doing this was not to make myself too stable,If technology doesn’t advance, it means retrogressionYou have to force yourself to learn.

The project is inclined to technical practice, so it will not do too much business piling up. It is better to learn business code in the company. Now we are doing the selection and reserve of technologies, such as the mainstream ones,Project front and rear separationMicroservicesSpringbootSpringcloudIn fact, I will not be able to apply many technologies to the project. I am also checking the data repeatedly. The process of exploration is really much faster than that in work. After all, there is an essential difference between active and passive learning.

In the past few days, I intend to build the front-end and back-end separation architecture of the project. Since the front-end and back-end separation project is involved, authentication is inevitableoauth2.0What we have to know is a little knowledge.

1、 What is oauth2.0

OAuthSimple understanding is an authorization mechanism. It is an authorization layer between client and resource owner, which is used to separate two different roles. After the resource owner agrees and issues a token to the client, the client carries the token to access the resource owner’s resource.

OAuth2.0yesOAuthA version of the protocol, with2.0There is a version1.0The interesting thing is thatOAuth2.0But not backward compatibleOAuth1.0It’s equivalent to being abandoned1.0edition.

What is OAuth authorization?

At home, the article ordered a takeout. The delivery brother arrived downstairs in 30 seconds. However, there was no access control. You can enter the password, but for security reasons, I don’t want to tell him the password.

At this time, the takeaway brother saw a high-level button on the entrance guard“One click authorization”As long as I agree, he will get a token valid for 2 hours(token)Normal access.

Four authorization methods of oauth2.0

Token(token)AndpasswordAlthough the functions of the system are similar, they can enter the system, but there are some differences.tokenWith the scope of authority and timeliness, it will automatically become invalid and invalid to modify when it expires.

2、 Oauth2.0 authorization mode

OAuth2.0The simple understanding of authorization is to obtain a token(token)The process,OAuthThe protocol defines four authorization methods to obtain token(authorization grant)As follows:

  • Authorization code(authorization-code
  • Hidden(implicit
  • Cryptanalysispassword):
  • Client credentials(client credentials

However, it is worth noting that no matter what kind of authorization method we use, we must apply for a unique identity in the system: client ID before applying for the token by three parties(client ID)And client key(client secret)。 This ensures thattokenNot to be used maliciously.

Next, we will analyze the principle of each authorization method. Before entering the topic, we will first understandOAuth2.0Several important parameters in the authorization process:

  • response_type: code indicates that the authorization code is required to be returned, and token means that the token is returned directly
  • client_id: client identity
  • client_secret: client key
  • redirect_uri: redirection address
  • scope: indicates the scope of authorization,readRead only permission,allread-write permission
  • grant_type: indicates the method of authorization,AUTHORIZATION_CODE(authorization code)password(password)client_credentials(voucher type)refresh_tokenUpdate token
  • state: a random number passed by the application to preventCSRFAttack.

1. Authorization code

OAuth2.0Among the four kinds of authorization, authorization code is the most complex, but also the most secure and commonly used one. This method is suitable for theWebProject, because some projects only have back-end or front-end, the authorization code mode is not applicable.

In the figure below, we useWXLog in to Nuggets as an example, take a detailed look at the overall process of authorization code.

Four authorization methods of oauth2.0

User selectionWXLog in to the Nuggets, and the Nuggets willWXInitiate authorization request, nextWXAsk the user if he or she agrees to authorize (common pop-up authorization).response_typebycodeRequest to return authorization code,scopeThe parameter indicates that the authorization scope is read-only,redirect_uriRedirection address.

After the user agrees to authorize,WXaccording toredirect_uriWith the authorization code.

When the Nuggets get the authorization code (code), with the authorization code and key and other parameters to theWXRequest token.grant_typeIndicates that this authorization is in the way of authorization codeauthorization_codeTo obtain the token, the client key is requiredclient_secret, and the authorization code obtained in the previous stepcode

lastWXAfter receiving the requestredirect_uriAddress sendingJSONData, of whichaccess_tokenIt’s a token.


2. Hidden

It was mentioned that there were someWebThe application does not have a back-end and belongs to a pure front-end application. The authorization code mode above cannot be used. Token application and storage need to be completed in the front end, skipping the authorization code step.

Front end application direct accesstokenresponse_typeSet totoken, which requires the token to be returned directly and the authorization code is skipped,WXRedirect to specified after authorization passesredirect_uri

3. Cryptanalysis

The password mode is easy to understand. Users can input their own password directly in nuggetsWXUser name and password, Nuggets go directly with informationWXRequest token, request responseJSONResultstokengrant_typebypasswordIndicates password based authorization.

The disadvantages of this authorization method are obvious and very dangerous. If this method is adopted, the application must be highly trusted.

4. Voucher type

The certificate type is similar to the password type, which is mainly applicable to those command-line applications without front-end. It can obtain the token in the simplest way, and can be used in the request responseJSONResultstoken

grant_typebyclient_credentialsIt means Certificate Authorization,client_idandclient_secretIt’s used to identify people.

3、 Usage and update of token

1. How to use the token?

Get the token and call itWXAPI request data, how to use token?

Every arrivalWXAll requests must be brought with youtoken, willtokenPut inhttpOne of the request headersAuthorizationField.

If usedpostmanTo simulate the request, theAuthorization -> Bearer TokenPut intokenbe careful: low versionpostmanThere is no such option.

Four authorization methods of oauth2.0

2. What if the token is expired?

tokenIt is time sensitive. Once expired, you need to obtain it again. However, going through the authorization process again is not only troublesome, but also the user experience is not good. How to make the update token more elegant?

Generally, two tokens are sent at a time when a token is issued, and one token is used to requestAPI, the other is responsible for updating the tokenrefresh_tokengrant_typebyrefresh_tokenRequest for update token, parameterrefresh_tokenIs the token used to update the token.


OAuth2.0In fact, authorization is not very difficult, but the authorization process is a little cumbersome, and the logic is a little twisted,OAuth2.0It is often asked about the interview knowledge, or should be more understanding. The next actual combatOAuth2.0Four kinds of authorization, please look forward to, welcome to pay attention to~

Original is not easy, burning hair output content, if there is a loss of harvest, like to encourage it!

Hundreds of technical e-books have been sorted out and sent to our friends. Pay attention to the official number and reply [666] to collect it by yourself. We have set up a technology exchange group with some partners to discuss technology and share technical information, aiming to learn and progress together. If you are interested, please join us!

Four authorization methods of oauth2.0