1 request briefly

OAuth 2.0 is a licensing protocol that allows software applications to access resources on behalf of (rather than acting as) the resource owner. The application requests authorization from the resource owner, obtains a token, and uses it to access the resource without the resource owner providing the application with sensitive data such as user names and passwords.

2 request role

OAuth defines four roles throughout the authorization process:

  • Cilent: software that accesses protected resources on behalf of the resource owner. It uses OAuth to obtain access.
  • Resource Owner: a subject that grants access rights to clients. In most cases, the Resource Owner is a person who uses client software to access resources under his control.
  • Resource Server: A Resource Server can be accessed through an HTTP Server and requires an OAuth access token to access. The protected resource needs to validate the token received and decide whether and how to respond to the request;
  • Authorization Server: An HTTP Server that acts as a central component in the OAuth system. The authorization server authenticates the resource owner and client, allowing the resource owner to authorize and issue tokens to the client. Some authorization servers provide additional functionality, such as token introspection and memorizing authorization decisions;

Suppose you use a photo cloud storage service and a cloud print service, and you want to use the cloud print service to print photos stored on the cloud storage service. Fortunately, the two services can communicate using apis. That’s great, but the two services are provided by different companies, which means your account on the cloud storage service and your account on the cloud printing service are not linked. Using OAuth solves this problem by authorizing the cloud printing service to access the photos without giving it the password for the account on the storage service. In the above paragraph: Client: cloud printing service Resource Owner: Your resource server, Authorization server: photo cloud storage service

3 OAuth License type

3.1 Grant Type: Authorization Code

The resource owner completes the login in the authorization server to obtain the authorization code, and the client finally exchanges the token through Ajax request. This form makes the token invisible to the outside world and ensures the security of the token to a certain extent. It is usually used in the development of OAuth2.0 on the Web side. The specific process steps are as follows: (1) The resource owner completes the login and authorization on the authorization server, and the resource server redirects to the client with a temporary authorization code, which is of short duration; (2) After obtaining the temporary authorization code, the client makes a request to the resource server interface through the temporary authorization code and other application information, in order to exchange for the token (backend interface request).

3.2 Grant Type: Implicit

Some Web applications are pure front-end applications without a back end. At this point, there is no need to use the authorization code form, but instead return the token directly, omitting the authorization code to redeem the token (which is done in the back end to hide the token content from the front end). The implicit licensing process cannot be used to obtain refresh tokens. Because of the transient nature of the in-browser application, the session only lasts as long as it is loaded into the browser.

// Request, the response_type value is token, which is the authorization page, and the user is redirected to the redirect_uri HTTP/1.1 302 Moved Temporarily Location: http://localhost:9001/authorize? response_type=token&scope=foo&client_ id=oauth-client-1&redirect_uri=http%3A%2F%2Flocalhost%3A9000%2Fcallback&state =Lwt50DDQKUB8U7jtfLQCVGDL9cnmwHH1 Vary: Accept Content-Type: text/html; charset=utf-8 Content-Length: 444 Date: Fri, 31 Jul 2015 20:50:19 GMT // Return accss_token, Note: #access_token GET /callback#access_token=987tghjkiu6trfghjuytrghj&token_type=Bearer of HTTP/1.1 Host: Localhost: 9000 the user-agent: Mozilla / 5.0 (Macintosh; Intel Mac OS X 10.10; The rv: 39.0) Gecko / 20100101 Firefox 39.0 / Accept: text/HTML, application/XHTML + XML, application/XML. Q = 0.9 * / *; Q = 0.8 Referer: http://localhost:9001/authorize? response_type=code&scope=foo&client_id= oauth-client-1&redirect_uri=http%3A%2F%2Flocalhost%3A9000%2Fcallback&state= Lwt50DDQKUB8U7jtfLQCVGDL9cnmwHH1Copy the code

3.3 Grant Type: Client Credential

Back-end systems need to communicate directly with each other and do not represent a specific user. No user authorizes the client. The client authenticates directly to the authorization server, which issues access tokens to the client. The client ID and key must be provided (manually applied before interconnection). The requirements are as follows:

POST /token
Host: localhost:9001
Accept: application/json
Content-type: application/x-www-form-encoded
grant_type=client_credentials&scope=foo%20bar&client_id=abcdsafdf&client_secret=qdfjadfj
Copy the code

3.4 Asserting the license type

Under the assertion license type, the client gets a structured, encryption-protected piece of information called an assertion, which is used to exchange tokens with the authorization server. This license type uses only the back-end channel and is similar to the client credential license type, with no explicit resource owner involved. Unlike the client-side credential process, the permissions associated with this issued token depend on the assertion presented, not just on the client itself. Because assertions generally come from a third party other than the client, the client can be unaware of the meaning of the assertion itself. Currently standard assertion format:

  • Security Assertion Markup Language: SAML
  • JSON WEB TOKEN: JWT
POST /token HTTP/1.1
Host: as.example.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic b2F1dGgtY2xpZW50LTE6b2F1dGgtY2xpZW50LXNlY3JldC0x
grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer
&assertion=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6InJzYS0xIn0.eyJpc3MiOi
JodHRwOi8vdHJ1c3QuZXhhbXBsZS5uZXQvIiwic3ViIjoib2F1dGgtY2xpZW50LTEiLCJzY29wZSI....
Copy the code

3.5 Resource Owner License (Not recommended)

If the resource owner has a plain text user name and password on the authorization server, the client can ask the user for the user’s credentials, which can then be exchanged for a token, also known as the password flow. The resource owner interacts directly with the client, not the authorization server. This type of license uses only token endpoints and communicates only through back-end channels.

3.6 How to Select a License Type

4 OAuth Related to security

4.1 CSRF attacks

The state parameter, which is a random number used as an interface request parameter, can be used in both the license code license and implicit license types. The client uses the state parameter to maintain an opaque value of the state between the request and the callback. The authorization server includes this value when it redirects the user agent back to the client. This parameter should be used to prevent CROSS-site request forgery. Practical examples follow.

4.2 Authorization Server Security

  • Destroy the authorization code after it is used once.
  • The authorization server should use an exact matching redirection URI validation algorithm, which is the only safe method.
  • Implementing the authorization server entirely according to the OAuth core specification may result in it becoming an open redirector. This is fine if the redirection is properly monitored, but it can be risky if it is not.
  • Note that information may be leaked through URI fragments or Referrer headers during error prompts.

4.3 Authorization Code Security

An authorization code prevents the token from being exposed directly to others, but it can still be hijacked in vain. An authorization code by itself is useless, especially if the client has a key for its own authentication. However, native apps have special issues with client-side keys (apps may need to write the keys dead in source code to leak them); Solution: PKCE (Proof Key for Code Exchange) (1) Client creates and records secret information named code_verifier (2) Client computes code_challenge based on code_verifier (e.g. Password hash MAC) (3) Client requests authorization server with code_challenge and code_challenge_method (calculation method, optional); (4) The authorization server responds normally and records code_challenge and code_challenge_method (associated with the authorization code); (5) After receiving the authorization code, the client carries the code_Verifier previously generated to execute the token application request; (6) The authorization server calculates code_challenge and checks whether it is consistent.

5 the request token

Clients in the OAuth system do not need to know anything about the token itself. All the client needs to know is how to get the token from the authorization server and how to use the token on the resource server. However, the authorization server and resource server need to know the contents of the token. The authorization server knows how to generate tokens to issue to clients, and the resource server knows how to recognize and validate tokens sent by clients.

  • OAuth tokens can have an expiration date, can support withdrawal, can be permanent, or a combination of these features as the case may be;
  • A token may represent a specific user or all users in the system, or may not represent any user;
  • Tokens can have internal structures, they can be random, meaningless strings, they can be cryptographically protected, or they can even be combined.
  • After the authorization server generates the token, the token value is stored (not required) in a shared database on disk. When a protected resource receives a token from a client, it looks up the token value in the same database to determine that the token is valid. This token does not carry any information and simply acts as a retrieval value for a database query.

5.1 Structured Token: JWT

JSON Web Tokens – jwt.io

  • Advantages: Without querying to a shared database and keeping all necessary information inside the token, the authorized server can communicate with the protected resource indirectly through the token itself without invoking any network API.
  • Disadvantages: Issued tokens cannot be revoked.

5.1.1 JWT structure

At its core, JWT encapsulates a JSON object into a format for network transport. The overall mechanism is segmented by periods, and each part is a BASE64URL-encoded JSON object composed of three parts:

  • Head: Declares the signature algorithm and the payload type
  • Payload: user data
  • Signature: The signature of the first two parts
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJ SMeKKF2QT4fwpMeJf36POk6yJV_adQssw5cCopy the code

5.1.2 Payload Common statement

5.1.3 JWT signature: JOSE

Two algorithms are shared here: (1) HAMC algorithm: With symmetric keys, both the authorization server and the resource server are able to generate tokens because they both have the keys needed to create tokens. (2) RSA algorithm: with public key encryption, the authorized server has public key and private key, which can be used to generate the token, while the protected resource can only access the public key of the authorized server, which can be used to verify the token. In contrast to HMAC, the resource server cannot generate valid tokens on its own. When the token requests the resource server, it checks the token. After the check succeeds, it parses the payload. Only if the signature is valid can the JWT continue to be parsed and its contents checked for consistency. If all the checks pass, you can hand it over to the application for use.

5.2 Obtaining token information online: Token introspection

Packaging token information into the token itself has its drawbacks. To contain all the necessary declarations and the password structure needed to protect them, the token size becomes very large. Moreover, if the protected resource is entirely dependent on the information contained in the token itself, it can be very difficult to withdraw a valid token once it has been generated and published. Token introspection: The authorization server issues the token to the client, the client presents the token to the protected resource, and the protected resource queries the authorization server for the token status (introspection request: The protected resource needs to authenticate to the authorization server during the request (providing client_ID and client_secret) so that the authorization server knows who is asking. And may return different responses based on the identity of the inquirer. The introspection agreement only requires that the protected resource be authenticated, not how.

POST/Introspect HTTP/1.1 Host: localhost:9001 Accept: Application /json Content-Type: application/x-www-form-encoded Authorization: Basic cHJvdGVjdGVkLXJlc291cmNlLTE6cHJvdGVjdGVkLXJlc291cmNlLXNlY3JldC0x token = 987 tghjkiu6trfghjuytrghj / / introspection is a JSON request response Object that describes token information. HTTP 200 OK Content-Type: application/json {"active": true, "scope": "foo bar baz", "client_id": "oauth-client-1", "username": "alice", "iss": "http://localhost:9001/", "sub": "alice", "aud": "http://localhost:/9002/", "iat": 1440538696, "exp": 1440538996, }Copy the code

The introspection protocol specification also adds several declaration definitions to JWT, the most important of which is the Active declaration. This declaration tells the protected resource whether the current token is valid on the authorized server and is the only declaration that must be returned. Using the token capital causes increased network traffic within the OAuth system. To solve this problem, the protected resource is allowed to cache the results of the introspection request for a given token. It is recommended to set a cache validity period shorter than the lifetime of the token to reduce the likelihood that the token will be withdrawn but the cache will remain valid.

5.3 Token lifecycle management

OAuth tokens generally follow a predictable life cycle. The token is created by the authorization server, consumed by the client, and validated by the protected resource. They may fail on their own or be withdrawn by the resource owner (or administrator) from the authorization server. Tokens are invalid for formats such as JWT and can only be expired but not invalidated.

5.3.1 Token Withdrawal agreement

OAuth token Retraction is a simple protocol that allows a client to simply tell the authorized server to withdraw a valid token. The client needs to send an HTTP POST request with authentication to a specialized retraction endpoint, putting the token to be withdrawn into the request body as a form parameter.

POST/REVOKE HTTP/1.1 Host: localhost:9001 Accept: application application/x-www-form-encoded Authorization: Basic b2F1dGgtY2xpZW50LTE6b2F1dGgtY2xpZW50LXNlY3JldC0x token=987tghjkiu6trfghjuytrghjCopy the code

The credentials used for client authentication are the same as those used on the endpoint of the token (to determine whether the token was requested by the client). The authorization server queries the token value, removes the token from where it was stored, and returns a response informing the client that the deletion was successful. If the authorization server does not find the token, or if the client that does not allow the token to be presented withholds the token, the authorization server returns success, so as not to reveal to the client the token information that does not belong to it.

5.3.2 Refreshing the token

The refresh token is issued to the client by the authorization server. In OAuth, access tokens can become invalid at any time. Tokens may be revoked by the user, may expire, or may be invalidated by other systems. When the access token is invalid, the client receives an error response while using it. Of course, the client can request permission again from the resource owner or request a new access token from the authorization server using the refresh token. Refreshing the token also allows the client to narrow down its permissions. If A client is granted scope A, B, and C, but it knows that only scope A is required for A particular request, it can use the refresh token to retrieve an access token that contains only scope A

6 Refer to the online OAuth interface documentation

Access Access_Token with Authorization_Code — WIKI WeChat OAuth: Preparation work | WeChat open document pay treasure to request: user authorization Google request: Using the 2.0 for the Web Server Applications | Google Identity Platform a lot OAuth:Authorizing OAuth Apps – GitHub Docs

7 OAuth Online personal OAuth application

As we know, Alipay and Github both support personal identity application. This example uses Github as an example. Alipay Application Address:Apply for a Web applicationGithub Application address:Apply for the OAuth application After filling in the above content, the reference will get app_id and app_secret, so that we can start docking. The specific content can be referred to the document in Part 6

8 Postman OAuth configuration

Since we have applied for Github OAuth2 application in Part 7, we can directly conduct quick interface test through Postman, taking Github interface for obtaining basic user information as an example. The interface request is GETapi.github.com/user It opens atGet New Access TokenFor configuration, refer to the documentation provided in Part 6

  • AuthUrl:github.com/login/oauth…
  • AccessTokenUrl:github.com/login/oauth…

So we can get an access token invocation interface.