# Authorize with OAuth

Node.JS Demo source code: https://github.com/Authing/oauth-demo

# Use authorization code (Authorization Code Flow) mode

The following sequence diagram shows an OAuth2.0 authorization code mode processing method.

# 01-Configure OAuth2.0 Provider in the console

If you haven't created an app, please go to Control Panel> App> App List, and click the button "Create App" in the upper right corner.

Go to Control Panel> Applications> Application List, find your application, and click "Settings".

In the "Configure OAuth2.0 Identity Provider" tab, open the "Enable OAuth2.0 Provider "Switch, then in the authorization mode below, turn on the authorization_code mode, and then click "Save".

# 02-Initiate a login request

GET
https://yourdomain.authing.cn/oauth/auth

Splice a link and let the end user access it in the browser to initiate an OAuth2.0 authorization login request.

To initiate authorization, you need to splice a URL for authorization and allow end users to access it in a browser. The specific parameters are as follows:

Query Parameters
client_id
REQUIRED
string

Application ID.

redirect_uri
REQUIRED
string

Callback link. After the user is successfully authenticated by the OP, the OP will send the authorization code to this address in the form of a URL query. This value must appear in the callback address of the console configuration, otherwise the OP is not allowed to call back to this address.

scope
OPTIONAL
string

The requested permission is not implemented yet, please fill in user.

response_type
REQUIRED
string

Return type, code must be filled here. It is used to specify what information the OP will return after a successful login. If it is specified as code, OP will return the authorization code code, or it can be specified as token, OP will return the user's access_token. For this method, please refer to the implicit below Mode chapter.

state
REQUIRED
string

A random string used to prevent CSRF attacks. If the state value in the response is different from the state value set before sending the request, it means that it is under attack.

Example request:

https://yourdomain.authing.cn/oauth/auth?client_id=5c9b079883e333d55a101082&redirect_uri=https://www.example.cn/example&scope=user&response_type=code&state=52378542395

# 03-User Login

After initiating OAuth2.0 login, if the user has not logged in at OP before, OP will redirect the user to the login page and guide the user to complete the authentication at OP. At this time, the user needs to choose a method to log in:

You can go to this website to experience: https://first-oauth-app.authing.cn/login (opens new window)

User login

Authing will verify whether the user is legitimate. After the verification is passed, the browser will be redirected to the redirect_uri specified when the authorization login request was initiated, and the authorization code code parameter will be passed through the URL query.

# 04-Exchange code for token

In exchange for token, the credential information of OAuth2.0 Provider needs to be sent to Authing. OAuth2.0 Provider supports two authentication methods in exchange for token.

POST
https://yourdomain.authing.cn/oauth/token

Exchange token by client_secret_post

Send the application ID and application key to the OAuth2.0 token endpoint through the POST Body.

Headers
Content-Type
REQUIRED
string

application/x-www-form-urlencoded

Form Data Parameters
client_id
REQUIRED
string

App ID

client_secret
REQUIRED
string

Application Secret

grant_type
REQUIRED
string

authorization_code

redirect_uri
REQUIRED
string

Redirect_uri value when initiating OAuth2.0 authorized login must be consistent with the parameters when initiating login request

code
REQUIRED
string

The obtained authorization code, one code is only for one-time use, and becomes invalid after use. The validity period is 10 minutes.

200: OK
{
  "access_token": "de60825d1bffd91474e9ac6a08a84bdc71f7f404",
  "token_type": "Bearer",
  "expires_in": 3599,
  "refresh_token": "c0b0b4acd686d30bb8b26dae73c2e64c1cec6698",
  "scope": "user"
}

NodeJS code exchange token request sample code:

let code2tokenResponse;
try {
  code2tokenResponse = await axios.post(
    "https://yourdomain.authing.cn/oauth/token",
    qs.stringify({
      code,
      client_id: appId,
      client_secret: appSecret,
      grant_type: "authorization_code",
      redirect_uri,
    }),
    {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    }
  );
} catch (error) {
  ctx.body = error.response.data;
  return;
}

Example of sending a request using curl:

curl --location --request POST'https://yourdomain.authing.cn/oauth/token' \
--header'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode'code=61yhuOVrgyhKlFTU~bnEKA_fnnz' \
--data-urlencode'client_id=5e37979f7b757ead14c534af' \
--data-urlencode'client_secret=64b517f8de3648091654eb4ee9b479d3' \
--data-urlencode'grant_type=authorization_code' \
--data-urlencode'redirect_uri=https://baidu.com'

Return example:

{
  "access_token": "de60825d1bffd91474e9ac6a08a84bdc71f7f404",
  "token_type": "Bearer",
  "expires_in": 3599,
  "refresh_token": "c0b0b4acd686d30bb8b26dae73c2e64c1cec6698",
  "scope": "user"
}
POST
https://yourdomain.authing.cn/oauth/token

client_secret_basic exchange for token

client_secret_basic uses HTTP Basic authentication mode for authentication.

Headers
Authorization
REQUIRED
string

Basic NWNhNzY1ZTM5MzE5NGQ1ODxxxx

Content-Type
REQUIRED
string

application/x-www-form-urlencoded

Form Data Parameters
grant_type
REQUIRED
string

authorization_code

redirect_uri
REQUIRED
string

Redirect_uri value when initiating OAuth2.0 authorized login. This parameter cannot be filled in at will, and must be the same as the parameter when initiating the login request.

code
REQUIRED
string

The obtained authorization code, one code is only for one-time use, and becomes invalid after use. The validity period is 10 minutes.

200: OK
{
  "access_token": "de60825d1bffd91474e9ac6a08a84bdc71f7f404",
  "token_type": "Bearer",
  "expires_in": 3599,
  "refresh_token": "c0b0b4acd686d30bb8b26dae73c2e64c1cec6698",
  "scope": "user"
}

The value after the Basic<space> of the Authorization request header is the base64 value of <client_id>:<client_secret>.

# 05-Refresh token

POST
https://yourdomain.authing.cn/oauth/token

Use refresh_token to refresh the user's access_token.

To use the refresh token function, you need to enter Control Panel > Application > Application List, find your application, click "Configuration", and click "Configure OAuth2.0 Identity Provider" "Tab, check refresh_ token in the authorization mode.

refresh_token

Headers
Content-Type
REQUIRED
string

application/x-www-form-urlencoded

Form Data Parameters
client_id
REQUIRED
string

Application ID.

client_secret
REQUIRED
string

Apply Secret.

grant_type
REQUIRED
string

refresh_token

refresh_token
REQUIRED
string

The refresh_token returned when using code to exchange token. Example: 372c1205032a7f87d579f4db8655b17bc2422c5f

200: OK
{
  "access_token": "44c1628697b64f676ffb3f464ce47b7562b3c4df",
  "token_type": "Bearer",
  "expires_in": 3599,
  "refresh_token": "372c1205032a7f87d579f4db8655b17bc2422c5f",
  "scope": "user"
}

# 06-Withdraw token

POST
https://yourdomain.authing.cn/oauth/token/revocation

Withdraw token

Access_token and refresh_token can be withdrawn.

Headers
Content-Type
REQUIRED
string

application/x-www-form-urlencoded

Form Data Parameters
token
REQUIRED
string

The token value to be withdrawn

token_type_hint
OPTIONAL
string

The type of token to be withdrawn, optional values ​​are access_token, refresh_token

client_id
REQUIRED
string

Application ID, required

client_secret
OPTIONAL
string

Application Secret, in the console application configuration details, in the "Configure OAuth2.0 Identity Provider" tab, it is required when the authentication method of configuring the withdrawal token is client_secret_post

200: OK

Without any content, the HTTP response code is 200, which means the withdrawal was successful.

# 07-Check token status

POST
https://yourdomain.authing.cn/oauth/token/introspection

Check token status

You can check the status of access_token.

Headers
Content-Type
REQUIRED
string

application/x-www-form-urlencoded

Authorization
OPTIONAL
string

In the console application configuration details, in the "Configure OAuth2.0 Identity Provider" tab, the configuration verification token authentication method is required when client_secret_basic is configured, in the form: Basic base64 (application ID +':' + application Secret)

Form Data Parameters
token
REQUIRED
string

Token value to be tested

token_type_hint
OPTIONAL
string

The token type to be checked, the optional value is access_token.

client_id
OPTIONAL
string

Application ID. In the console application configuration details, in the "Configure OAuth2.0 Identity Provider" tab, it is required to configure the verification token authentication method as client_secret_post and none

client_secret
OPTIONAL
string

Application Secret, in the console application configuration details, in the "Configure OAuth2.0 Identity Provider" tab, it is required to configure the verification token authentication method as client_secret_post

200: OK

When the token is valid, the following format content is returned

{
  "active": true,
  "sub": "5dc10851ebafee30ce3fd5e9",
  "client_id": "5cded22b4efab31716fa665f",
  "exp": 1602423020,
  "iat": 1602419420,
  "iss": "https://core.authing.cn/oauth",
  "jti": "SaPg48dbO66T77xkT8wy0",
  "scope": "user",
  "token_type": "Bearer"
}

When the token is invalid (expired, error, withdrawn), the following format content is returned

{
  "active": false
}

# Use implicit mode (Implicit Flow)

OAuth2.0 implicit mode does not return the authorization code code, but directly sends the access_token to the front end of the callback address through URL hash, and the value returned here cannot be obtained by the backend , Because the URL hash will not be sent directly to the backend.

# Configure OAuth application in the console

Go to Control Panel> Applications> Application List, find your application, click "Configuration", in the "Configure OAuth2.0 Identity Provider" tab, find the authorization mode, and select implicit mode, and finally click "Save".

# Initiate authorization

Initiating the implicit mode authorization login need to splice a URL and allow the end user to access it in the browser, **cannot directly enter **authentication address domain name. The specific parameters are as follows:

Parameter name Meaning
client_id Application ID.
redirect_uri Callback link. After the user is successfully authenticated by the OP, the OP will send the access_token to this address in the form of URL hash. This value must appear in the callback address of the console configuration, otherwise the OP is not allowed to call back to this address.
scope The requested permission is not implemented yet, please fill in user.
response_type token
state A random string used to prevent CSRF attacks. If the state value in the response is different from the state value set before sending the request, it means that it is under attack.

Suppose you create an OAuth2.0 application with the domain name example, then the URL for initiating the implicit mode OAuth2.0 authorization login is:

GET https://example.authing.cn/oauth/auth?client_id=5ca765e393194d5891db1927&redirect_uri=https://example.com&scope=user&response_type=token&state=6223573295

# Get access_token

The access_token will be passed in the form of URL hash, example of link after redirect:

https://authing.cn/#access_token=56d7c5649b486abfa67798d11c7e98ea741cab58&state=1234124

The process of exchanging user information is the same as the authorization code mode.

Why is the information in the URL hash instead of the query? Because the hash content will not be sent directly to the server, the access_token is prevented from being stolen.

# Use Password mode

This mode is not recommended, try to use other modes.

# Configure OAuth2.0 application in the console

Go to Control Panel > Application > Application List, find your application, and select password in the authorization mode on the "Configure OAuth2.0 Provider" tab. Click "Save".

password

POST
https://yourdomain.authing.cn/oauth/token

Use login credentials in exchange for token

In Password mode, you can directly use the user's login credentials (user name + password) in exchange for access_token

Body Paramter
scope
OPTIONAL
string

The requested permission is not implemented yet, please fill in user.

password
REQUIRED
string

password

username
REQUIRED
string

User name, cannot fill in the mailbox

grant_type
REQUIRED
string

Must fill in password.

client_secret
REQUIRED
string

Apply Secret.

client_id
REQUIRED
string

Application ID.

200: OK

The user login credentials are correct, and AccessToken is returned.

{
  "access_token": "f73a7c75ad7d093d096e1590038848e174e29ccf",
  "token_type": "Bearer",
  "expires_in": 3599,
  "refresh_token": "e221c8a1bb6415e2db284a14567cfb70a635fb93",
  "scope": "user"
}
400: Bad Request

The user login credentials are incorrect, and an error message is returned.

{
  "error": "invalid_grant",
  "error_description": "Invalid grant: user credentials are invalid"
}

Reference Materials

  1. When to use Password mode? 「Video」 (opens new window)
  2. Password mode is only used for forward compatibility with "video" (opens new window)

# Use Client Credentials mode

This mode is used to obtain the access_token of the OAuth application itself, and holding the access_token can be used to obtain the information of the OAuth application itself. You cannot get any user-related information through this access_token. About Client Credentials mode, please refer to https://oauth.net/2/grant-types/client-credentials (opens new window).

POST
https://yourdomain.authing.cn/oauth/token

Exchange the application ID and application key for the access_token of the application itself

The context of the access_token obtained in the Client Credentials mode is the OAuth application itself. Holding this token can prove that you are the owner of the OAuth Client.

Body Paramter
scope
OPTIONAL
string

The requested permission is not implemented yet, please fill in user.

grant_type
REQUIRED
string

Must fill in client_credentials.

client_secret
REQUIRED
string

Apply Secret.

client_id
REQUIRED
string

Application ID.

200: OK

The OAuth Client credentials are correct and AccessToken is returned.

{
  "access_token": "279188167773887e4da8921bcdb648bf8b1ad9fa",
  "token_type": "Bearer",
  "expires_in": 3599,
  "scope": "user"
}
400: Bad Request

OAuth Client credential error, return errorMisinformation.

{
  "error": "invalid_client",
  "error_description": "Invalid client: client is invalid"
}

# Common Problem

# Token valid time

The valid time of access_token in all modes is 1 hour, and the valid time of refresh_token is 2 weeks.

# The difference between the four modes

Regarding the application scenarios and differences of these four modes, it is recommended to browse Understanding OAuth2.0 (opens new window). In general, you only need to open authorization_codeMode.