鉴权认证机制

2023年11月14日

      

简介

      鉴权的主要目的是获取Access_token。Access_token是用户的访问令牌,承载了用户的身份、权限等信息。鉴权主要分为以下两步:

      1.获取AK/SK

      2.获取Access_token

  •       代码形式→适用于有计算机基础的用户
  •       网页调试工具→适用于零基础的用户
  •       在线调试工具(推荐)→快速调试接口效果

1. 获取AK/SK

      当您成功创建应用后,在对应产品页签下选择“应用列表”,可查看已创建的应用。

      平台将会分配给您此应用的相关凭证,主要为AppID、API Key、Secret Key。以上三个信息是您应用实际开发的重要凭证,每个应用各不相同,为了您的财产和服务安全请您妥善保管

      另外,我们为您提供了教学视频,您可以直接浏览视频获取详细教程。

2. 获取 Access_token

      百度AI开放平台使用OAuth2.0授权调用开放API,调用API时必须在URL中带上Access_token参数,Access token默认有效期为30天,获取Access_token的流程如下:

      请求URL数据格式

      向授权服务地址https://aip.baidubce.com/oauth/2.0/token发送请求(推荐使用POST),并在URL中带上以下参数:

  •       grant_type: 必须参数,固定为client_credentials;
  •       client_id: 必须参数,应用的API Key;
  •       client_secret: 必须参数,应用的Secret Key;

      例如:

      https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=Va5yQRHlA4Fq5eR3LT0vuXV4&client_secret=0rDSjzQ20XUj5itV6WRtznPQSzr5pVw2&

      获取Access_token的两种方式

      接下来为您提供两种获取Access_token的方法,您可以按照自己的需求进行选择。

方式一:通过代码的形式获取Access_token

      以下为您提供示例代码。这里以python语言为例进行演示。

  1.       打开python编译器,输入Access_token示例代码【python】。
  •       Python
  •       Java
  •       PHP
  •       C#
  •       Go
  •       Node.js
  •       C++

      import requests import json defmain(): url ="https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=xxxxxx&client_secret=xxxxx" payload ="" headers ={'Content-Type':'application/json','Accept':'application/json'} response = requests.request("POST", url, headers=headers, data=payload)print(response.text)if __name__ =='__main__': main()

      packagebaidu.com;import okhttp3.*;importorg.json.JSONObject;importjava.io.*;classSample{staticfinalOkHttpClient HTTP_CLIENT =newOkHttpClient().newBuilder().build();publicstaticvoidmain(String[]args)throwsIOException{MediaType mediaType =MediaType.parse("application/json");RequestBody body =RequestBody.create(mediaType,"");Request request =newRequest.Builder().url("https://aip.baidubce.com/oauth/2.0/token?client_id=&client_secret=&grant_type=client_credentials").method("POST", body).addHeader("Content-Type","application/json").addHeader("Accept","application/json").build();Response response = HTTP_CLIENT.newCall(request).execute();System.out.println(response.body().string());}}

      <?phpclassSample{publicfunctionrun(){$curl=curl_init();curl_setopt_array($curl,array(CURLOPT_URL=>"https://aip.baidubce.com/oauth/2.0/token?client_id=&client_secret=&grant_type=client_credentials",CURLOPT_TIMEOUT=>30,CURLOPT_RETURNTRANSFER=>true,CURLOPT_CUSTOMREQUEST=>'POST',CURLOPT_HTTPHEADER=>array('Content-Type: application/json','Accept: application/json'),));$response=curl_exec($curl);curl_close($curl);return$response;}}$rtn=(newSample())->run();print_r($rtn);

      using System; using System.IO; using RestSharp; namespace SampleApplication { public class Sample { public static void Main(string[] args) { var client = new RestClient($"https://aip.baidubce.com/oauth/2.0/token?client_id=&client_secret=&grant_type=client_credentials"); client.Timeout = -1; var request = new RestRequest(Method.POST); request.AddHeader("Content-Type", "application/json"); request.AddHeader("Accept", "application/json"); var body = @""; request.AddParameter("application/json", body, ParameterType.RequestBody); IRestResponse response = client.Execute(request); Console.WriteLine(response.Content); } } }

      package main import("fmt""io/ioutil""net/http""strings")funcmain(){ url :="https://aip.baidubce.com/oauth/2.0/token?client_id=&client_secret=&grant_type=client_credentials" payload := strings.NewReader(``) client :=&http.Client {} req, err := http.NewRequest("POST", url, payload)if err !=nil{ fmt.Println(err)return} req.Header.Add("Content-Type","application/json") req.Header.Add("Accept","application/json") res, err := client.Do(req)if err !=nil{ fmt.Println(err)return}defer res.Body.Close() body, err := ioutil.ReadAll(res.Body)if err !=nil{ fmt.Println(err)return} fmt.Println(string(body))}

      const request = require('request') async function main() { var options = { 'method': 'POST', 'url': 'https://aip.baidubce.com/oauth/2.0/token?client_id=&client_secret=&grant_type=client_credentials', 'headers': { 'Content-Type': 'application/json', 'Accept': 'application/json' } }; request(options, function (error, response) { if (error) throw new Error(error); console.log(response.body); }); } main();

      #include <stdio.h> #include <iostream> #include <string.h> #include <curl/curl.h> #include <json/json.h> #include <fstream> inline size_t onWriteData(void * buffer, size_t size, size_t nmemb, void * userp) { std::string * str = dynamic_cast<std::string *>((std::string *)userp); str->append((char *)buffer, size * nmemb); return nmemb; } int main(int argc, char *argv[]) { std::string result; CURL *curl; CURLcode res; curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_easy_setopt(curl, CURLOPT_URL, "https://aip.baidubce.com/oauth/2.0/token?client_id=&client_secret=&grant_type=client_credentials"); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https"); struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Content-Type: application/json"); headers = curl_slist_append(headers, "Accept: application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); const char *data = ""; curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &result); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, onWriteData); res = curl_easy_perform(curl); std::cout<<result; } curl_easy_cleanup(curl); return (int)res; }

  1.       在【官网获取的AK】和【官网获取的SK】中输入创建应用后获取的AK、SK。

  1.       输入完成后运行代码,服务器将返回json文本参数,如下:
  •       access_token:要获取的Access Token;

  •       expires_in:Access Token的有效期(秒为单位,有效期30天);

  •       其他参数忽略,暂时不用;
  1.       若请求错误,服务器将返回的JSON文本包含以下参数:
  •       error: 错误码;关于错误码的详细信息请参考下方鉴权认证错误码。
  •       error_description: 错误描述信息,帮助理解和解决发生的错误。

      例如,认证失败返回:

      { "error": "invalid_client", "error_description": "unknown client id" }

      鉴权认证错误码

      error
      error_description
      解释

      invalid_client
      unknown client id
      API Key不正确

      invalid_client
      Client authentication failed
      Secret Key不正确

方式二:使用网页调试工具获取Access_token

      依次在网页调试工具中输入:

  •       grant_type: 必须参数,固定为client_credentials;
  •       client_id: 必须参数,应用的API Key;
  •       client_secret: 必须参数,应用的Secret Key;

      具体的参数,您可以在控制台应用列表中看到,如果您还不熟悉,请您查看上一步“获取AK/SK”。

      输入完成后,点击send,返回json字符串,获取Access_token。例如图中获取的access_token为24.a7179f3da2d56a81d0af25931c67efee.2592000.1627131472.282335-24130966。

      另外,为您提供教学视频。您可以点击视频查看详细步骤。

方式三:在线调试工具(推荐)

      您可以在 示例代码中心 中快速调试接口,可进行签名验证、查看在线调用的请求内容和返回结果、示例代码的自动生成。

3. 密钥安全提示与止损方法

      1.注意请勿将您的AK/SK以及生成的Access token与他人共享或硬编码到APP及终端,为保护您的资源安全,平台可能会针对恶意滥用token进行禁用。

      2.使用http协议兑换token有被截获sk的风险。如发生凭证(即AK/SK或Access token)泄露,请及时在【应用详情】页更新应用的Secret Key。 请注意:更新后历史生成的Access_token将立即失效,请及时更新运营环境中的Secret Key,避免影响服务调用。

使用Access Key ID/Secret Access Key的开发者注意

      如果您使用的是“安全认证/Access Key ”中的Access Key ID 和 Secret Access Key的开发者,则不能使用获取Access Token的方式鉴权,具体鉴权认证机制参考“百度云鉴权认证机制”。