鉴权认证
语音技术主要支持两种鉴权方式:access_token鉴权机制和API Key鉴权机制。二者分别支持的功能范围和适用的用户群体如下:
鉴权机制 | 支持的功能范围 | 适用群体 |
---|---|---|
access_token鉴权机制 | 包括语音技术在内的AI开放能力的所有能力。不支持AI开放能力之外的产品 | 仅使用AI开放能力的客户 |
API Key鉴权机制 | AI开放能力的公有云接口,暂不支持离线SDK 同时支持大模型服务与开发平台ModelBuilder、大模型应用开发平台AppBuilder的接口调用 |
要同时使用AI开放能力、ModelBuilder和AppBuilder的客户;或此前在其他平台使用过大模型服务,现在迁移到百度智能云的客户,使用API Key可无缝迁移 |
需要注意,两种鉴权机制选择其中一种即可,不能在一次请求中同时使用多种鉴权机制。
以下为您分别介绍两种鉴权机制使用方式。
一、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
;
例如:
1https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=Va5yQRHlA4Fq5eR3LT0vuXV4&client_secret=0rDSjzQ20XUj5itV6WRtznPQSzr5pVw2&
获取Access_token的两种方式
接下来为您提供两种获取Access_token的方法,您可以按照自己的需求进行选择。
方式一:通过代码的形式获取Access_token
以下为您提供示例代码。这里以python语言为例进行演示。
- 打开python编译器,输入Access_token示例代码【python】。
1import requests
2import json
3
4
5def main():
6
7 url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=xxxxxx&client_secret=xxxxx"
8
9 payload = ""
10 headers = {
11 'Content-Type': 'application/json',
12 'Accept': 'application/json'
13 }
14
15 response = requests.request("POST", url, headers=headers, data=payload)
16
17 print(response.text)
18
19
20if __name__ == '__main__':
21 main()
1package baidu.com;
2
3import okhttp3.*;
4import org.json.JSONObject;
5
6import java.io.*;
7
8class Sample {
9
10 static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
11
12 public static void main(String []args) throws IOException{
13 MediaType mediaType = MediaType.parse("application/json");
14 RequestBody body = RequestBody.create(mediaType, "");
15 Request request = new Request.Builder()
16 .url("https://aip.baidubce.com/oauth/2.0/token?client_id=&client_secret=&grant_type=client_credentials")
17 .method("POST", body)
18 .addHeader("Content-Type", "application/json")
19 .addHeader("Accept", "application/json")
20 .build();
21 Response response = HTTP_CLIENT.newCall(request).execute();
22 System.out.println(response.body().string());
23
24 }
25}
1<?php
2class Sample {
3
4 public function run() {
5 $curl = curl_init();
6 curl_setopt_array($curl, array(
7 CURLOPT_URL => "https://aip.baidubce.com/oauth/2.0/token?client_id=&client_secret=&grant_type=client_credentials",
8 CURLOPT_TIMEOUT => 30,
9 CURLOPT_RETURNTRANSFER => true,
10 CURLOPT_CUSTOMREQUEST => 'POST',
11
12
13 CURLOPT_HTTPHEADER => array(
14 'Content-Type: application/json',
15 'Accept: application/json'
16 ),
17
18 ));
19 $response = curl_exec($curl);
20 curl_close($curl);
21 return $response;
22 }
23}
24
25$rtn = (new Sample())->run();
26print_r($rtn);
1using System;
2using System.IO;
3using RestSharp;
4namespace SampleApplication {
5 public class Sample {
6
7
8 public static void Main(string[] args) {
9 var client = new RestClient($"https://aip.baidubce.com/oauth/2.0/token?client_id=&client_secret=&grant_type=client_credentials");
10 client.Timeout = -1;
11 var request = new RestRequest(Method.POST);
12 request.AddHeader("Content-Type", "application/json");
13 request.AddHeader("Accept", "application/json");
14 var body = @"";
15 request.AddParameter("application/json", body, ParameterType.RequestBody);
16 IRestResponse response = client.Execute(request);
17 Console.WriteLine(response.Content);
18
19 }
20 }
21}
1package main
2
3import (
4 "fmt"
5 "io/ioutil"
6 "net/http"
7 "strings"
8)
9
10func main() {
11
12 url := "https://aip.baidubce.com/oauth/2.0/token?client_id=&client_secret=&grant_type=client_credentials"
13 payload := strings.NewReader(``)
14 client := &http.Client {}
15 req, err := http.NewRequest("POST", url, payload)
16
17 if err != nil {
18 fmt.Println(err)
19 return
20 }
21 req.Header.Add("Content-Type", "application/json")
22 req.Header.Add("Accept", "application/json")
23
24 res, err := client.Do(req)
25 if err != nil {
26 fmt.Println(err)
27 return
28 }
29 defer res.Body.Close()
30
31 body, err := ioutil.ReadAll(res.Body)
32 if err != nil {
33 fmt.Println(err)
34 return
35 }
36 fmt.Println(string(body))
37}
1const request = require('request')
2
3async function main() {
4 var options = {
5 'method': 'POST',
6 'url': 'https://aip.baidubce.com/oauth/2.0/token?client_id=&client_secret=&grant_type=client_credentials',
7 'headers': {
8 'Content-Type': 'application/json',
9 'Accept': 'application/json'
10 }
11 };
12
13 request(options, function (error, response) {
14 if (error) throw new Error(error);
15 console.log(response.body);
16 });
17}
18
19main();
1#include <stdio.h>
2#include <iostream>
3#include <string.h>
4#include <curl/curl.h>
5#include <json/json.h>
6#include <fstream>
7
8
9inline size_t onWriteData(void * buffer, size_t size, size_t nmemb, void * userp)
10{
11 std::string * str = dynamic_cast<std::string *>((std::string *)userp);
12 str->append((char *)buffer, size * nmemb);
13 return nmemb;
14}
15
16
17int main(int argc, char *argv[])
18{
19 std::string result;
20 CURL *curl;
21 CURLcode res;
22 curl = curl_easy_init();
23 if(curl) {
24 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
25 curl_easy_setopt(curl, CURLOPT_URL, "https://aip.baidubce.com/oauth/2.0/token?client_id=&client_secret=&grant_type=client_credentials");
26 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
27 curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
28 struct curl_slist *headers = NULL;
29 headers = curl_slist_append(headers, "Content-Type: application/json");
30 headers = curl_slist_append(headers, "Accept: application/json");
31 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
32 const char *data = "";
33 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
34 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &result);
35 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, onWriteData);
36 res = curl_easy_perform(curl);
37 std::cout<<result;
38 }
39 curl_easy_cleanup(curl);
40 return (int)res;
41}
- 在【官网获取的AK】和【官网获取的SK】中输入创建应用后获取的AK、SK。
- 输入完成后运行代码,服务器将返回json文本参数,如下:
- access_token:要获取的Access Token;
- expires_in:Access Token的有效期(秒为单位,有效期30天);
- 其他参数忽略,暂时不用;
- 若请求错误,服务器将返回的JSON文本包含以下参数:
- error: 错误码;关于错误码的详细信息请参考下方鉴权认证错误码。
- error_description: 错误描述信息,帮助理解和解决发生的错误。
例如,认证失败返回:
1{
2 "error": "invalid_client",
3 "error_description": "unknown client id"
4}
鉴权认证错误码
error | error_description | 解释 |
---|---|---|
invalid_client | unknown client id | API Key不正确 |
invalid_client | Client authentication failed | Secret Key不正确 |
方式二:使用网页调试工具(例如postman)获取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,避免影响服务调用。
二、API Key鉴权机制
API Key是百度智能云全新推出的鉴权方式,主要面向以下两个目标:
- 跨产品调用服务。同一个API Key可同时调用AI开放能力(文字识别、人脸识别、语音技术等)、大模型服务与开发平台ModelBuilder、大模型应用开发平台AppBuilder的接口服务,降低您接入AI服务的成本。
- 简化调用步骤。API Key既可直接使用明文调用接口进行鉴权,也可以换成短期APIkey后再进行鉴权。 为了更高的安全性,减少API Key的明文泄露风险,建议您使用短期APIkey的鉴权方式。
有关API Key的具体介绍和使用方法,请您参考API Key鉴权机制。