【问题标题】:How to get Token with javajava获取token的方法
【发布时间】:2021-02-11 18:40:52
【问题描述】:

我是 JWT 的新手,所以我需要从 webService(GET 方法)获取带有 JAVA 代码的令牌。

在 postMan 中,我能够获得令牌(在屏幕截图下方)。

我使用了这个 java 代码,但经常返回 Response Code : 403

String url = "https://WEBSERVICE_LINK";
    try {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        con.setRequestMethod("GET");
        this.log.info("Sending 'GET' request to URL : " + url);

        con.setRequestProperty("Authorization", Base64.getEncoder().encodeToString((username + ":" + pwd).getBytes()));

        con.setRequestProperty("Accept", "application/json");
        int responseCode = con.getResponseCode();
        this.log.info("Response Code : " + responseCode);

        StringBuilder response;
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String inputLine;
            response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        }

        String reponseString = response.toString();
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(reponseString);

        // Isoler et transmettre le Token
        this.token = jsonNode.get("token") != null ? jsonNode.get("token").asText() : null;
        this.log.info("Token : " + this.token);

谢谢

【问题讨论】:

  • 你试过在token前加Bearer吗?像这样 - “Bearer” + authToken
  • 我需要令牌所以你的意思是这样con.setRequestProperty("Authorization", "Bearer " + Base64.getEncoder().encodeToString((username + ":" + pwd).getBytes())); ?
  • 是的,尝试在令牌前添加 Bearer
  • 我也有RESPONSE 403,尽管它在邮递员中使用相同的登录名和密码

标签: java jwt


【解决方案1】:

您似乎忘记了 Authorization 标头值中的 Basic 前缀:

con.setRequestProperty(
  "Authorization",
  "Basic " + Base64.getEncoder().encodeToString((username + ":" + pwd).getBytes())
);

【讨论】:

  • 我曾经添加过这个,但我总是遇到同样的问题con.setRequestProperty ("Authorization", "Basic c3BNjpVNWJlNW0zTA==");
  • c3BNjpVNWJlNW0zTA== 看起来不正确,它没有解码为 <username>:<password>
  • (并且小心地在网上发布密码;)
  • 我也用了这个private final String auth = "Basic " + Base64.getEncoder().encodeToString((username + ":" + pwd).getBytes()); 然后con.setRequestProperty("Authorization", this.auth); 我也有同样的问题
  • 这应该可以,你确定usernamepwd 保持预期值吗?
猜你喜欢
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
  • 2017-01-07
  • 2017-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-14
相关资源
最近更新 更多