目录

1 Obtaining an Access Token

1.1 Applying for an Authorization Code

After a user clicks the button for 'signing in using a HUAWEI ID', your app processes the click event, combines the link for requesting the authorization code from the OAuth service, and redirects the user's browser to the link to access the OAuth service.

Sample code:

  1. <html>
  2. <head>
  3.    <title>Demo</title>
  4.    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  5.    <meta name="client_id" content="<APP ID>" />
  6.    <meta name="redirect_uri" content="<App redirection URI>" />
  7.    <meta name="scope" content="openid+profile" />
  8. </head>
  9. <body>
  10.    <p> <button id="hwlogin" onclick=redirect()>HUAWEIID login</button></p>
  11. </body>
  12. <script type="text/javascript">
  13.         var client_id ='',redirect_uri='',scope='';
  14.         for(var metas=document.getElementsByTagName("meta"),i=0;i<metas.length;++i){
  15.                   switch(metas[i].name) {
  16.              case 'client_id':
  17.                 client_id = metas[i].content;
  18.                 break;
  19.              case 'redirect_uri':
  20.                  redirect_uri = metas[i].content;
  21.                 break;
  22.              case 'scope':
  23.                 scope = metas[i].content;
  24.                 break;
  25.              default:break
  26.                   }
  27.         }
  28.         var redirectUrl='https://oauth-login.cloud.huawei.com/oauth2/v3/authorize?'+
  29.         'response_type=code&access_type=offline&state=state_parameter_passthrough_value&client_id='+client_id +'&redirect_uri='+ redirect_uri +'&scope='+ scope;
  30. function redirect() {
  31.         window.location.href=redirectUrl;
  32. }
  33. </script>
  34. </html>

Redirection URI:

  1. https://oauth-login.cloud.huawei.com/oauth2/v3/authorize?
  2. response_type=code&
  3. access_type=offline&
  4. state=state_parameter_passthrough_value&
  5. client_id=<APP ID>&
  6. redirect_uri=<App redirection URI>&
  7. scope=openid+profile
Parameter

Mandatory (M)

/Optional (O)

Description
response_typeMSet this parameter to code (indicating the authorization code mode).
client_idMAPP ID created in Preparing for Web App Development.
redirect_uriM

Redirection URI after authorization, that is, URI for the app to receive the authorization code. The value must be the same as the redirection URI set in Preparing for Web App Development. You can add a parameter to the end of the redirection URI.

The redirection URI is:

https://www.thirdwebdemo.com/redirect_url,

and other parameters may be added after the redirection URI like this:

https://www.thirdwebdemo.com/redirect_url?somearg=XXXXXX

scopeMCharacter string array separated by spaces (spaces are changed to plus signs (+) after URL encoding). The character 'openid' must be contained.
access_typeOIf this parameter is set to 'offline', a Refresh Token will be generated to refresh the Access Token.
stateORandom string, which is used to prevent CSRF. The value is returned without any change along with the authorization code.

1.2 Signing In and Authorizing the App by a User

When the request is redirected to the OAuth service, the OAuth service displays an authorization page to prompt a user to perform authorization. The page shows the name and icon of your app as well as the permission required by your app.

Note:
If a user has not signed in with the HUAWEI ID, the HUAWEI ID sign-in page is displayed. The user enters the HUAWEI ID and password or scans a QR code and confirms the sign-in. Then, the authorization page will be displayed.

As follow:

Sign-in page

Authorization page

1.3 Returning a Response by the OAuth Service

The OAuth service calls back the value in the response to the app through redirect_uri.

Sample code:

  1. https://www.thirdwebdemo.com/redirect_url?
  2. code=<Returned authorization code>&
  3. state=state_parameter_passthrough_value
  1. https://www.thirdwebdemo.com/redirect_url #error=1107&error_description=access+denied

1.4 Obtaining an Access Token by Authorization Code

After obtaining the authorization code, the app calls the API (https://oauth-login.cloud.huawei.com/oauth2/v3/token) of the OAuth service to obtain an Access Token, a Refresh Token, and an ID Token based on the authorization code.

Sample code:

  1. POST /oauth2/v3/token HTTP/1.1
  2. Host: oauth-login.cloud.huawei.com
  3. Content-Type: application/x-www-form-urlencoded
  4. grant_type=authorization_code&
  5. code=<Returned authorization code>&
  6. client_id=<App ID>&
  7. client_secret=<App secret>&
  8. redirect_uri=<App redirection URI>
Parameter

Mandatory (M)

/Optional (O)

Description
grant_typeMThis parameter is defined in the OAuth 2.0 specifications and must be set to authorization_code.
codeMThe value is the same as the  authorization code returned in section 1.3 Returning a Response by the OAuth service.
client_idMAPP ID created in Preparing for Web App Development.
client_secretMAPP SECRET allocated to the APP ID created in Preparing for Web App Development.
redirect_uriMThe value must be the same as the  redirection URI transferred in section 1.1 Applying for an  Authorization Code.
  1. HTTP/1.1 200 OK
  2. Content-Type: text/json ; charset=UTF-8
  3. Cache-Control: no-store
  4. {
  5.  "access_token": "<Returned access token>",
  6.  "refresh_token": "<Returned refresh token>",
  7.  "expires_in": 3600,
  8.  "scope": "profile openid",
  9.  "token_type": "Bearer",
  10.  "id_token": "<Returned ID token in JWT format>"
  11. }
Parameter

Mandatory (M)

/Optional (O)

Description
access_tokenMAccess token of a user.
expires_inMRemaining validity period of an Access Token, in seconds.
scopeMScope contained in the Access Token generated.
token_typeMThis value is always Bearer,  indicating the type of the returned Access Token.
id_tokenMID Token in JWT format. If the input  parameter scope in section 1.1 Applying for an Authorization Code contains profile and email, the app can directly parse the ID token to obtain user's basic account and email address information after the verification on id_token is complete locally  (for details about the verification, please refer to section 5.1 Performing Local Verification) without the need to request the information from Huawei user information server. For details about the parsed fields, please refer to section 5.2 Parsing the Id_token Field.
refresh_tokenOThe value of this parameter is returned, if access_type=offline is contained in the input parameter in section 1.1 Applying for an Authorization Code. This parameter is used to update an Access Token.

By now, the user has signed in to your app with the HUAWEI ID, and your app obtains user's basic account information. If you need to call other Huawei public APIs, please refer to the following section.

2 Calling Huawei APIs by Your App

When your app calls a Huawei API, the Access Token used to check whether the API can be called is placed in the Authorization header.

Example: Call the API (/openapi/inner/v1/sports/dailySteps). In section 1.1 Applying for an Authorization Code, Scope contains the permission item https://www.huawei.com/health/sport.readonly for calling this API. In this case, the obtained Access Token can be placed in the header of the request to call this API.

  1. GET /openapi/inner/v1/sports/dailySteps?startDate=<Service parameter 1>&endDate=<Service parameter 2> HTTP/1.1
  2. Host: <XXX>
  3. Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
  4. Accept: application/json
  5. x-huid: <Service parameter 3>
  6. x-appid: <Service parameter 4>
  7. x-client-version: <Service parameter 5>
  8. x-prdPkgName: <Service parameter 6>
  9. cache-control: no-cache
  10. Authorization:  Bearer <Obtained access token>

3 Updating the Access Token (for Offline Access) by Your App

The Access Token has a validity period. After the access token expires, the access token is unavailable. If the Access Token is called again, the authentication fails. In this case, you are advised to add the input parameter access_type that is set to offline when combining the link in section 1.1 Applying for an Authorization Code. In this way, a Refresh Token and an Access Token are generated at the same time. (Note: The Refresh Token and Access Token cannot be replaced with each other.)

The validity period of the Refresh Token is long (180 days by default). Within the validity period, the app can directly call the API (https://oauth-login.cloud.huawei.com/oauth2/v3/token) of the OAuth service through the Refresh Token to obtain a new Access Token. In this way, your app does not need to bring up the authorization page again to ask for sign-in authorization from the user.

Sample code:

  1. POST /oauth2/v3/token HTTP/1.1
  2. Host: oauth-login.cloud.huawei.com
  3. Content-Type: application/x-www-form-urlencoded
  4. grant_type=refresh_token&
  5. client_id=<App ID>&
  6. client_secret=<App secret>&
  7. refresh_token=<Refresh token obtained after authorization>
  1. HTTP/1.1 200 OK
  2. Content-Type: text/html;charset=UTF-8
  3. Cache-Control: no-store
  4. {
  5.  "access_token": "<New access token>",
  6.  "expires_in": 3600,
  7.  "id_token": "<Returned ID token in JWT format>",
  8.  "scope": "profile openid",
  9.  "token_type": "Bearer"
  10. }

4 Revoking HUAWEI ID Authorization

Your app can call the API (https://oauth-login.cloud.huawei.com/oauth2/v3/revoke) to revoke the authorization from an authorized Access Token or Refresh Token. The Access Token and Refresh Token are in a pair. If the authorization of one token is revoked, the authorization of the other token also becomes invalid.

Sample code:

  1. POST /oauth2/v3/revoke HTTP/1.1
  2. Host: oauth-login.cloud.huawei.com
  3. Content-Type: application/x-www-form-urlencoded
  4. token=<Access token for which authorization is to be revoked>
  1. HTTP/1.1 200 OK
  2. Cache-Control: no-store
  3. Pragma: no-cache
  4. {}

5 Appendix

5.1 Performing Local Verification

1. Obtain the public key URI field jwks_uri from the return value of https://oauth-login.cloud.huawei.com/.well-known/openid-configuration, request the URI, and access the URI to obtain the public key. (The public key is updated once a day, and cached on the app server.)

  1. //JAVA_Demo sample code:
  2. getRSAPublicKeyByKid(decoder.getKeyId());

2. Verify the signature. The ID Token is in JWT format, whose signature can be verified by using a common JWT library, such as jwt.io.

  1. //JAVA_Demo sample code:
  2. DecodedJWT decoder = JWT.decode(idToken);
  3. Algorithm algorithm = Algorithm.RSA256(getRSAPublicKeyByKid(decoder.getKeyId()) , null);
  4. JWTVerifier verifier = JWT.require(algorithm).build();
  5. // Verify the signature.
  6. verifier.verify(decoder);

3. Check whether the value of iss in the ID Token is https://accounts.huawei.com.

  1. //JAVA_Demo sample code:
  2. decoder.getIssuer().equals(ID_TOKEN_ISSUE);

4. Check whether the value of aud in the ID Token is the same as the value of client_id of the app.

  1. //JAVA_Demo sample code:
  2. decoder.getAudience().get(0).equals(CLIENT_ID);

5. Check whether the ID Token expires at the time specified by exp.

  1. //JAVA_Demo sample code:
  2. verifier.verify(decoder);// If the token expires, TokenExpiredException is thrown.

6. If the preceding items pass the check, the ID Token is successfully verified. The app can parse the user information in the ID Token.

  1. //JAVA_Demo sample code:
  2. JSONObject jsonObject = JSONObject.parseObject(new String(Base64.decodeBase64(decoder.getPayload())));

Verify JAVA_Demo code locally. To obtain the code, click Download.

Note:
IIf the current time of the phone is behind the standard time, the local verification may fail. As a result, the exception "com.auth0.jwt.exception.InvalidClaimException" is thrown, and the message "The Token cann't be used before ..." is displayed. In this case, handle this exception based on the situation (for example, calibrate the phone time).


5.2 Parsing the Id_token Field

Your app verifies the signature of the id_token field. After the parsing, the tables of openid, email, and profile contained in scope are obtained.

openid in scope:

Parameter

Mandatory (M)

/Optional (O)

TypeDescription
issMStringThis value is always https://accounts.huawei.com.
subMStringUnionID obtained after a value containing a user ID and developer ID is encoded. The value is unique.
audMStringApp ID, which is contained in the ID Token.
expMLongExpiration time.
iatMLongTime when an ID Token is generated.
nonceOStringRandom character string.
at_hashOStringAccess Token HASH value.
azpOStringApp ID, which is used to generate an ID Token.

email in scope:

Parameter

Mandatory (M)

/Optional (O)

TypeDescription
email_verifiedOBoolean

Indicates whether a user's email box has  been verified. The options are as follows:

true: yes

false: no

emailOStringUser email address.

 profile in scope:

Parameter

Mandatory  (M)

/Optional (O)

TypeDescription
pictureOStringLink to profile picture of a user.
nameOStringFull name of a user.
localeOStringPreferred language of a user, for  example, zh-cn or en-us.
family_nameOStringLast name.
given_nameOStringFirst name.
display_nameOStringNickname of a HUAWEI ID.