OKTA 访问令牌使用令牌端点 url returns http 401 错误

OKTA access token using token endpoint url returns http 401 error

我是 OKTA 的新手。 使用下面的代码获取访问令牌..但在此行中出现 401 未授权错误

inputBuff = new BufferedReader(new InputStreamReader(httpsClient.getInputStream()));

String oktaURL = "https://xxx.oktapreview.com/oauth2/default/v1/token";
            String urlParameters = “client_id=” + clientId+“grant_type=authorization_code&redirect_uri=”+“http://:8192/app”+"&code="+oktaCode;
            URL url1 = new URL(oktaURL);
            StringBuffer response = null;
            String output1;

            log.info("The url to get the access token:"+url1.toString());
            if (url1.getProtocol() != null && url1.getProtocol().startsWith("https")){
                
                //String encodedData = DatatypeConverter.printBase64Binary((clientId + ":" + clientSecret).getBytes("UTF-8"));
                //String authorizationHeaderString = "Authorization: Basic " + encodedData;
                
                httpsClient = (HttpsURLConnection) url1.openConnection();
                httpsClient.setRequestMethod("POST");
                httpsClient.setRequestProperty("Accept","application/json");    
                httpsClient.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes()));
                httpsClient.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
                httpsClient.setInstanceFollowRedirects(false);
                
                log.info ("Send the POST request");
                // Send post request
                httpsClient.setDoOutput(true);
                try (DataOutputStream opStream = new DataOutputStream(httpsClient.getOutputStream())) {                     
                    opStream.writeBytes(urlParameters);
                    opStream.flush();
                }
                
                inputBuff = new BufferedReader(new InputStreamReader(httpsClient.getInputStream())); // throwing 401 here.
                log.info("Read from the input stream");

                response = new StringBuffer();
                while ((output1 = inputBuff.readLine()) != null) {
                    response.append(output1);
                }
            }

            if (response != null) {
                String theString = response.toString();
                log.trace("Info:"+theString);
            }

我可以通过 /authorize URL 导航到 OKTA 服务器的登录页面,然后身份验证成功并返回到我的应用程序。现在正在尝试获取访问令牌。请在 java.

中帮助解决这个问题

我刚刚查看了 okta 日志,它在验证成功日志的右上方显示。

您忘记在实际的 client_id 之后添加 &,因此您的字符串应该类似于

String urlParameters = 
    "client_id=" + clientId +
    "&grant_type=authorization_code" + 
    "&redirect_uri=" + "http://:8192/app" + 
    "&code=" + oktaCode;

解决问题,有2个问题。

  1. 已从授权 header
  2. 中指定的 urlParameters 中删除 client_id
  3. 删除了 /token 端点的默认值,因为它没有在我的 /authorize 端点中提供。