Platform Technology-User Authorization Introduction


Login Authorization

If your application needs to obtain user privacy data (such as products, orders, etc.) when connecting to the Taobao open platform, in order to ensure the security and privacy of user data, your application needs Obtain the user's authorization, that is, obtain the Access Token (the original SessionKey) for accessing user data. In this case, your application needs to guide the user through the "login authorization" process using a Taobao account. This process uses the internationally accepted OAuth2.0 standard protocol as the user authentication and authorization protocol, and supports websites, mobile clients, and desktop clients.
Currently, Taobao OAuth2.0 service supports two ways to obtain Access Token (authorization token), namely Server-side flow and Client-side flow. Please refer to the following instructions for details.

Note: Taobao ID (Taobao account) products cannot be used for Alibaba Group’s unofficial channels to provide Taobao membership services (such as order inquiries, logistics tracking, etc.) to Taobao buyers. Once illegal use is discovered, the open platform will immediately revoke the Taobao ID usage permission of the appkey.

Special Note

The authorization page described in this document is only applicable to the PC side. If your page is used in the mobile Taobao/Tmall client To access, please refer here. If your page is accessed in H5 mobile browser, please refer to here.

1. Server-side flow

This process requires the ISV application to have a Web Server application, which can save the key and status of the application itself, and can directly access Taobao through https the authorization server.

1. Request entrance address

1) Obtain authorization code (code)
Formal environment: https://oauth.taobao.com/ authorize
Sandbox environment: https://oauth.tbsandbox.com/authorize
2) Obtain access token (access_token)
Formal environment: https ://oauth.taobao.com/token
Sandbox environment: https://oauth.tbsandbox.com/token

2. Authorization operation steps

Here is an example of obtaining access_token in the formal environment. If it is a sandbox environment test, the request entry address and other related data need to be replaced with the corresponding entry address of the sandbox. Operation The process is consistent with the formal environment.
When actually performing authorization operations, the tested data client_id, client_secret, and redirect_uri need to be replaced according to the actual application data created by you. You cannot directly test the values ​​given in the example to avoid affecting the actual test effect. The figure below shows the server-side flow authorization method flow chart. The following is a step-by-step explanation based on the flow chart.
TB1CBIbHpXXXXaIXpXXSutbFXXX.jpg

1) Splicing authorization url
Splicing user authorization requires access to the url. Examples and parameter descriptions are as follows:
https://oauth.taobao.com/authorize?response_type= code&client_id=23075594&redirect_uri=http://www.oauth.net/2/&state=1212&view=web

##3) Get codeQQ截图20170213145452.png2) Guide the user Login authorization Guide users to access the above authorization url through the browser, and the following login page will pop up. The user enters the account number and password and clicks the "Login" button to enter the authorization page.

TB1pwkRHpXXXXXLXpXXSutbFXXX.jpg

On the above page, if the user clicks the "Authorize" button, TOP will return the authorization code to the callback address, and the application can obtain and use the code to exchange for access_token;

If the user clicks the "Cancel" button instead of authorizing, the following results will be returned, where error is the error code and error_description is the error description. As shown in the figure below:
TB1l1AfHpXXXXXDXXXXSutbFXXX.jpg

Instructions: can publish applications in the service market (
fuwu.taobao.com), after the application is online For example, if a user purchases an application and accesses it through "My Service - Use Now" (picture below), the system will automatically jump to the authorization page (therefore, if you access the application in this way, you do not need to splice the URL), you only need to pay attention to obtaining the code. That’s it. When returning the code at the same time, it will also return information related to the ordering service delivered through state, similar to: state=versionNo:1;itemCode:xxxxx (versionNo is the application version number, itemCode is the application charging code)

4) Exchange for access_tokenUse the curl command of Linux to obtain the access_token (authorization token), as follows;
For applications, please refer to the documentation **Example**Sample code here.

curl -i -d "code=OxlukWofLrB1Db1M6aJGF8x2332458&grant_type=authorization_code&client_id=23075594&
client_secret=69a1469a1469a1469a14a9bf269a14&redirect_uri=http://www .oauth.net/2/ "https: //oauth.taobao.com/token


QQ截图20170213145549.png

{
  "w2_expires_in": 0,
  "taobao_user_id": "263685215",
  "taobao_user_nick": "商家测试帐号52",
  "w1_expires_in": 1800,
  "re_expires_in": 0,
  "r2_expires_in": 0,
  "expires_in": 86400,
  "token_type": "Bearer",
  "refresh_token": "6200e1909ca29b04685c49d67f5ZZ3675347c0c6d5abccd263685215",
  "access_token": "6200819d9366af1383023a19907ZZf9048e4c14fd56333b263685215",
  "r1_expires_in": 1800
}


Example of return value in exchange for access_token

QQ截图20170213145648.png

2. Client-side flow

The client application authorization method is suitable for ISV applications that do not have an independent web server but can access the authorization server with the help of a browser or JS script.

1. Request entry address

Formal environment: https://oauth.taobao.com/authorize
Sandbox environment: https://oauth. tbsandbox.com/authorize

2. Authorization operation steps

Take the formal environment to obtain access_token as an example. If it is a sandbox environment, please use sandbox data.
At the same time, during the authorization process, parameters such as client_id need to be replaced according to the actual data of the application you created, otherwise the authorization cannot be completed.
The picture below is the client-side flow authorization method flow chart. The following is a step-by-step description according to the flow chartTB1gIY_HpXXXXagXVXXSutbFXXX.jpg

1) Splicing authorization url

https://oauth.taobao.com/authorize?response_type=token&client_id=23075594&state=1212&view=web

QQ截图20170213145724.png


##2) Import users Login authorizationThis step is the same as the Server-side flow authorization method, guiding the user to access the authorization url for authorization, as follows.

LB1c5YZKXXXXXamXFXXXXXXXXXX.jpg

#3) Obtain access_tokenAfter clicking Authorization on the page in the picture above, TOP will directly return the access_token to the Taobao default page (and Server -side flow returns code first and then changes access_token in different ways) At this time, you can use JS script (
if(window.location.hash!=""){alert(window.location.hash)}) to obtain Call back the field after page # to obtain the access token.

LB18bZlKXXXXXXdXXXXXXXXXXXX (1).jpg

Return parameter example:

https://oauth.taobao.com/oauth2?view=web# access_token=6101227f5e8c230696ac93a77b3de7daacb154c6ad98106263664221&token_type=Bearer&expires_in=86400&refresh_token=6100627e3f9202c0960a6ab5bfd704939c9163589 2c70dd263664221&re_expires_in=86400&r1_expires_in=86400&r2_expires_in=86400&taobao_user_id=263664221&taobao_user_nick=Merchant test account 17&w1_expires_in=86400&w2_expires_in=86400&state=1 212&top_sign=3429C556FCD3F3FC52547DD31021592F

Note:
Except for top_sign, the parameters returned here are the same as the server-side flow authorization return parameters. They will not be described in detail here. For details, please refer to the instructions in Server-side flow.
top_sign is a signature parameter generated by the system. Authorization using Client-side flow requires consistency verification of this parameter.


4) Verify the authorization signature

That is, verify whether the return parameters are consistent with top_sign. In the returned parameters as above, arrange all keys and values ​​after the pound sign except top_sign in alphabetical order of the parameters, splice them together in the form of key1 value key2 value...., and then add AppSecret before and after it (assuming AppSecret =69a1469a1469a1469a14a9bf269a14), then convert it to utf-8 encoding, then perform md5 encryption, and finally convert all to uppercase.
md5(utf-8:AppSecret k1 v1 k2 v2 ... kn vn AppSecret).


If the parameters are returned as follows, take the parameters after the # sign and concatenate them and add AppSecret to the end to get the following result:
69a1469a1469a1469a14a9bf269a14access_token6101227f5e8c230696ac93a77b3de7daacb154c6ad98106263664 221token_typeBearer
expires_in86400refresh_token6100627e3f9202c0960a6ab5bfd704939c91635892c70dd263664221re_expires_in86400r1_expires_in86400
r2expires_in86400taobao_user_id263664221taobao_user_nick merchant test account 17w1_expires_in86400&w2_expires_in86400&state121269a1469a1469a1469a14a9bf269a14

Perform md 5 is encrypted (refer to API call sample code) and converted to uppercase to get: 3429C556FCD3F3FC52547DD31021592F, which is consistent with top_sign.

Logout

The logout process currently only supports web access. Its function is to clear the cookies of taobao.com, not to cancel the user's authorization. Access on WAP does not work.

1. Request entrance address

1. Formal environment: https://oauth.taobao.com/logoff
2. Sandbox environment: https://oauth.tbsandbox.com/logoff

2. Exit steps

Just splice the exit url (such as https://oauth.taobao.com/logoff?client_id=12304977&view=web) and access it. After exiting, you will jump to the Taobao homepage.

Refresh authorization

The refresh_token obtained through authorization can be used to refresh the r2 duration of the access token.
Since r1 or w1 is usually the same as the subscription period and generally does not need to be refreshed, w2 must be extended through re-authorization, so refresh_token is generally only used to extend the validity period of r2.
The operation method is similar to obtaining access token, only the request parameters are different, the instructions are as follows:

QQ截图20170213145927.png

Related instructions

1. Authorization duration description

The validity period of the access_token obtained through authorization (expires_in) is related to the tag type (such as IT tools, merchant backend systems, etc.) and status (such as formal environment, online, etc.) as follows.
Note: When the actual api is called, the application authorization duration is more accurately controlled. For details, please refer to (2. Security Level Description); in addition, application development such as "Third Party IT Tools" is online The latter are all published on fuwu.taobao.com. Sellers need to order and use it. The corresponding authorization period will be the same as the order period. If the purchase is for 1 month, the access_token obtained will be valid for 1 month.

QQ截图20170213145956.png

2. Security level description

In order to be more flexible on the data open to the Taobao open platform Security control reduces the risk of user data leakage or malicious modification, and introduces the concept of security levels.
Taobao Open Platform marks API (or API fields) and applications with four security levels: r1, r2, w1, w2 and 0,1,2,3 respectively. Corresponding to r1, r2, w1, and w2, 4 expiration times are added when the access token (session key) is issued: r1_expires_in, r2_expires_in, w1_expires_in, w2_expires_in. These four values ​​are used to represent the validity period of this access token calling APIs (or fields) at each level, as follows: (Applications subject to security level restrictions include: third-party IT tools, service provider backend systems, and store module backends. ;Seller-owned applications such as merchant backend systems and new businesses will not be affected for the time being.)

##Level 2R124 hoursThe same subscription periodisThe online application is consistent with the subscription period, and the official environment test is valid for 24 hoursLevel 2R224 hours72 hoursYesThe online application is consistent with the ordering time, formal environment test Valid for 24 hoursLevel 2W124 hoursSame ordering periodisThe online application has the same duration as the subscription, and the official environment test is valid for 24 hours Level 2W230 minutes30 minutesNoLevel 1R124 hoursSame subscription durationYesThe online application is consistent with the subscription duration, and the formal environment test is valid for 24 hoursLevel 1R224 hours24 hoursNoLevel 1W124 hoursSame as the subscription timeYesThe online application is consistent with the subscription time, and the official environment test is valid for 24 hoursLevel 1W25 minutes5 minutesNoLevel 0R130 minutes30 minutesNoLevel 0R20 minutes0 minutesNoLevel 0W130 minutes30 minutesNoLevel 0W20 minutes0 minutesNo

Sample code

1. Example of obtaining access_token

The sample codes are all implemented based on sdk. Please refer to the instructions for downloading and using sdk.

1. JAVA example

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.taobao.api.internal.util.WebUtils; //引用top sdk
 public class open_oauth {
    public static void main(String[] args) {
      String url="https://oauth.taobao.com/token";
      Map<String,String> props=new HashMap<String,String>();
      props.put("grant_type","authorization_code");
/*测试时,需把test参数换成自己应用对应的值*/
      props.put("code","test");
      props.put("client_id","test");
      props.put("client_secret","test");
      props.put("redirect_uri","http://www.test.com");
      props.put("view","web");
      String s="";
      try{s=WebUtils.doPost(url, props, 30000, 30000);
      System.out.println(s);
      }catch(IOException e){
          e.printStackTrace();}
    } }


##2. PHP example

<?php
/*测试时,需把test参数换成自己应用对应的值*/

 $url = 'https://oauth.taobao.com/token';
 $postfields= array('grant_type'=>'authorization_code',
 'client_id'=>'test',
 'client_secret'=>'test',
 'code'=>'test',
 'redirect_uri'=>'http://www.test.com');
 $post_data = '';
 
 foreach($postfields as $key=>$value){
 $post_data .="$key=".urlencode($value)."&";}
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
 curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
 
 //指定post数据
 curl_setopt($ch, CURLOPT_POST, true);

 //添加变量
 curl_setopt($ch, CURLOPT_POSTFIELDS, substr($post_data,0,-1));
 $output = curl_exec($ch);
 $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
 echo $httpStatusCode;
 curl_close($ch);
 var_dump($output);
 
?>


3. .NET example

namespace Oauth2._0
{
    class Program 
    { 
    static void Main(string[] args)
        {
            WebUtils webUtils = new WebUtils(); 
            IDictionary<string, string> pout = new Dictionary<string, string>(); 
            pout.Add("grant_type", "authorization_code"); 
            pout.Add("client_id", "test"); 
            pout.Add("client_secret", "test"); 
            pout.Add("code", "test");
            pout.Add("redirect_uri", "http://www.test.com"); 
            string output = webUtils.DoPost("https://oauth.taobao.com/token", pout); 
            Console.Write(output); 
            Console.ReadLine();       
        }
    } 
}


##2. refresh_token refresh example

The following This is a Java example based on SDK. For other languages, you can refer to the token acquisition method, which is similar. At the same time, when testing, you need to replace the test parameter with the actual value corresponding to your application.

  import java.io.IOException;
  import java.util.HashMap;
  import java.util.Map;
  import com.taobao.api.internal.util.WebUtils;
 
  public class test_refresh {
     
  public static void main(String[] args) {
    String url="https://oauth.taobao.com/token";
    Map<String,String> props=new HashMap<String,String>();
    props.put("grant_type","refresh_token");
    props.put("refresh_token","test");
    props.put("client_id","test");
    props.put("client_secret","test");
    String s="";
    try{s=WebUtils.doPost(url, props, 30000, 30000);
    System.out.println(s);
    }catch(IOException e){
        e.printStackTrace();
    }
    }

The above converts responseJson into an object, or directly extracts the access_token field and the new refresh token from it

refresh_token return result content example

Security levelAPI levelFormal environment testOnline and runningCan it be refreshedRefresh refresh duration
Level 3R124 hours Same as The ordering time is The online application is consistent with the ordering time, and the formal environment test is valid for 24 hours
Level 3R2 24 hoursSame subscription timeYesThe online application is consistent with the subscription time, and the official environment test is valid for 24 hours
Level 3W124 hoursSame ordering timeYeshas been launched for application and ordering The duration is the same, the formal environment test is valid for 24 hours
Level 3W224 hoursSame as the order duration YesThe online application has the same duration as the order, and the formal environment test is valid for 24 hours

FAQ

1. When authorizing to obtain the token, the appkey has been passed in, but the client_id is empty error is still reported?
Another key parameter of authorization, client_secret, is wrong. This error will be reported. Focus on checking

2. Is it necessary to perform authorization testing in the sandbox first?

There is no such requirement. It can be the method of "first sandbox test authorization, and then the formal environment"; it can also be the method of "test authorization in the formal environment" directly.

3. Commonly used authorization related What are the documents?

  • Multiple store management: View
  • Quick authorization tool: View
  • Methods to improve security level: View
  • Detailed description of security level: View

4. Reference for more authorization issues and error codes: View

FAQ

  • There is no FAQ
# about this document yet. ##
{
"w2_expires_in": 0,
"taobao_user_id": "263685215",
"taobao_user_nick": "Merchant test account 52",
"w1_expires_in": 1800,
"re_expires_in": 0,
"r2_expires_in": 0,
"expires_in": 86400,
"token_type": "Bearer",
"refresh_token": "6200e1909ca29b04685c49d67f5ZZ3675347c0c6d5abccd263685215",
"access_token": "6200819d9366af1383023a19907ZZf9048e4c14fd56333b263685215",
"r1_expires_in": 1800
}