• 【AGC】AGC鉴权认证模式获取clientToken的方法


     近期有开发者在使用API方式接入Indexing服务时提出疑问,如何获取clientToken。其实AGC认证模式是基于clientToken鉴权方式,由云侧网关与AGC微服务实现的一套OAuth2标准鉴权体系。访问网关的后端服务需要具备有效的clientId以及clientSecret,才能通过云侧网关的鉴权校验,并对业务接口发起有效地调用。下面介绍两种获取clientToken的方法。

    获取clientId和clientSecret

    两种方法的前提都是需要先获取到clientId和clientSecret。

    登录AGC控制台,选择“用户与访问”。选择“API密钥 > Connect API”,点击“创建”,新建API客户端。

    cke_293.png

    api地址和请求参数

    api地址:https://connect-api.cloud.huawei.com/api/oauth2/v1/token

    cke_872.png

    方法1:postman获取clientToken

    第一种方法很简单,直接使用postman,在Body中输入grant_type、client_id和client_secret的键值对,无需添加Headers,使用post方式直接发起请求,即可获得clientToken。

    cke_1696.png

    方法2:项目中使用代码调用api获取clientToken

    调用示例:

    1. public static String getToken(String domain, String clientId, String clientSecret) {
    2. String token = null;
    3. try {
    4. HttpPost post = new HttpPost(domain + "/oauth2/v1/token");
    5. JSONObject keyString = new JSONObject();
    6. keyString.put("client_id", "18893***83957248");
    7. keyString.put("client_secret", "B15B497B44E080EBE2C4DE4E74930***52409516B2A1A5C8F0FCD2C579A8EB14");
    8. keyString.put("grant_type", "client_credentials");
    9. StringEntity entity = new StringEntity(keyString.toString(), Charset.forName("UTF-8"));
    10. entity.setContentEncoding("UTF-8");
    11. entity.setContentType("application/json");
    12. post.setEntity(entity);
    13. CloseableHttpClient httpClient = HttpClients.createDefault();
    14. HttpResponse response = httpClient.execute(post);
    15. int statusCode = response.getStatusLine().getStatusCode();
    16. if (statusCode == HttpStatus.SC_OK) {
    17. BufferedReader br =
    18. new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Consts.UTF_8));
    19. String result = br.readLine();
    20. JSONObject object = JSON.parseObject(result);
    21. token = object.getString("access_token");
    22. }
    23. post.releaseConnection();
    24. httpClient.close();
    25. } catch (Exception e) {
    26. }
    27. return token;
    28. }

    调用成功后返回正确的响应,得到clientToken与有效期:

    1. HTTP/1.1 200 OK
    2. Content-Type: application/json; charset=utf-8
    3. {
    4. "access_token": "eyJhbGciOiJIUzU****************",
    5. "expires_in": 172800
    6. }

     欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh

  • 相关阅读:
    git管理-最详细Gitflow讲解
    jenkins
    暴力求解欲哭无泪之保安问题
    JAVA8接口使用问题
    html问卷调查
    安防视频监控平台EasyCVR出现“no space left on device磁盘空间不足”是什么原因?该如何解决?
    爬虫项目-爬取股吧(东方财富)评论
    神经网络训练样本 加权,神经网络训练模型描述
    JAVA-----注释、字面量、关键字、制表符
    华为机试 - 德州扑克
  • 原文地址:https://blog.csdn.net/weixin_44708240/article/details/126554716