【Coze】Coze JWTOAuth对接

package com.jpaas.coze;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

import com.coze.openapi.client.auth.OAuthToken;
import com.coze.openapi.service.auth.JWTOAuth;
import com.coze.openapi.service.auth.JWTOAuthClient;
import com.coze.openapi.service.service.CozeAPI;

/*
This example is about how to use the service jwt oauth process to acquire user authorization.

Firstly, users need to access https://www.coze.com/open/oauth/apps. For the cn environment,
users need to access https://www.coze.cn/open/oauth/apps to create an OAuth App of the type
of Service application.
The specific creation process can be referred to in the document:
https://www.coze.com/docs/developer_guides/oauth_jwt. For the cn environment, it can be
accessed at https://www.coze.cn/docs/developer_guides/oauth_jwt.
After the creation is completed, the client ID, private key(.pem), and public key id, can be obtained.
For the client secret and public key id, users need to keep it securely to avoid leakage.
* */
public class JWTOAuthServer {

    public static void main(String[] args) {

        // The default access is api.coze.com, but if you need to access api.coze.cn,
        // please use base_url to configure the api endpoint to access
        String cozeAPIBase = System.getenv("COZE_API_BASE");
        if (cozeAPIBase == null || cozeAPIBase.isEmpty()) {
            cozeAPIBase = "api.coze.cn";
        }
        String jwtOauthClientID = System.getenv("COZE_JWT_OAUTH_CLIENT_ID");
        String jwtOauthPrivateKey = System.getenv("COZE_JWT_OAUTH_PRIVATE_KEY");
        String jwtOauthPrivateKeyFilePath = System.getenv("COZE_JWT_OAUTH_PRIVATE_KEY_FILE_PATH");
        String jwtOauthPublicKeyID = System.getenv("COZE_JWT_OAUTH_PUBLIC_KEY_ID");
        //    jwtOauthPublicKeyID+="123";
        JWTOAuthClient oauth = null;
        try {
            jwtOauthPrivateKey =
                    new String(
                            Files.readAllBytes(Paths.get(jwtOauthPrivateKeyFilePath)), StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }

    /*
    The jwt oauth type requires using private to be able to issue a jwt token, and through
    the jwt token, apply for an access_token from the coze service. The sdk encapsulates
    this procedure, and only needs to use get_access_token to obtain the access_token under
    the jwt oauth process.
    Generate the authorization token
    The default ttl is 900s, and developers can customize the expiration time, which can be
    set up to 24 hours at most.
    * */
        try {
            oauth =
                    new JWTOAuthClient.JWTOAuthBuilder()
                            .clientID(jwtOauthClientID)
                            .privateKey(jwtOauthPrivateKey)
                            .publicKey(jwtOauthPublicKeyID)
                            .baseURL(cozeAPIBase)
                            .build();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        try {
            OAuthToken resp = oauth.getAccessToken();
            System.out.println(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    /*
    The jwt oauth process does not support refreshing tokens. When the token expires,
    just directly call get_access_token to generate a new token.
    * */
        CozeAPI coze =
                new CozeAPI.Builder()
                        .auth(JWTOAuth.builder().jwtClient(oauth).build())
                        .baseURL(cozeAPIBase)
                        .build();
        // you can also specify the scope and session for it
    }
}

package example.workflow;

import java.util.HashMap;
import java.util.Map;

import com.coze.openapi.client.workflows.run.RunWorkflowReq;
import com.coze.openapi.client.workflows.run.RunWorkflowResp;
import com.coze.openapi.service.auth.TokenAuth;
import com.coze.openapi.service.service.CozeAPI;

/*
This example describes how to use the workflow interface to chat.
* */
public class RunWorkflowExample {

  public static void main(String[] args) {
    // Get an access_token through personal access token or oauth.
    String token = System.getenv("COZE_API_TOKEN");
    TokenAuth authCli = new TokenAuth(token);

    // Init the Coze client through the access_token.
    CozeAPI coze =
        new CozeAPI.Builder()
            .baseURL(System.getenv("COZE_API_BASE"))
            .auth(authCli)
            .readTimeout(10000)
            .build();
    ;

    String workflowID = System.getenv("WORKFLOW_ID");

    // if your workflow need input params, you can send them by map
    Map<String, Object> data = new HashMap<>();
    data.put("param name", "param values");
    RunWorkflowReq req = RunWorkflowReq.builder().workflowID(workflowID).parameters(data).build();

    RunWorkflowResp resp = coze.workflows().runs().create(req);
    System.out.println(resp);
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星星点点洲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值