【问题标题】:How to get jwt token generated by api to my app using HttpClient in java?java - 如何使用Java中的HttpClient将api生成的jwt令牌获取到我的应用程序?
【发布时间】:2021-03-23 06:29:32
【问题描述】:

我有一个基于用户名和密码生成 JWT 令牌的工作休息 API。 URI:http://localhost:8080/user/authenticate

这会生成令牌:eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiLJKJJsaWNlbnNvciIsImV4cCI6MTYxNjQ0MjYyNiwiaWF0IjoxNjE2NDA2NjI2fQ.vPQZqiMgM6WzeJPKD8GV-91JIaHALVwMfLwTqXLRt8YLKnNUnOBK

我正在使用 HttpClient 将请求从我的桌面应用程序发送到我的服务器。我想从我的桌面端发送用户名和密码并获取上面生成的令牌,以便我可以将它用于其他请求?如何在 java 中使用 HttpClient 在下面的代码中做到这一点?

    HttpRequest request = HttpRequest.newBuilder()
            .POST()
            .uri(URI.create("http://localhost:8080/user/authenticate"))
            .setHeader("Authorization", "Bearer ") // add request header
            .header("Content-Type", "application/json")
            .build();

    HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

【问题讨论】:

  • 你有什么问题?请阅读How to Ask
  • 您可能需要发布有关您的设置等的更多信息。这取决于您的身份提供者,但假设它提供了获取访问令牌的服务,您只需要使用正确的凭据调用它并获取令牌返回(您可能想要阅读 OAuth 流程 - 假设它是 OAuth)。请注意,您通常无法获得与其他应用程序相同的令牌,因为这会带来安全风险。
  • 在此处查看有关如何使用基本身份验证发送 JWT 请求的信息:baeldung.com/httpclient-4-basic-authentication

标签: java spring-boot rest httpclient


【解决方案1】:

正如 cmets 所指出的,问题中没有足够的信息。

下面的代码将用户名和密码发送到您的服务器并读取响应正文并将其打印到标准输出(将用户名/密码替换为实际值):

import java.net.URI;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Test {

    public static void main(String[] args) throws Exception {
        String auth = "username:password";
        byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8));
        String authHeader = "Basic " + new String(encodedAuth);

        HttpRequest request = HttpRequest.newBuilder()
                .POST(HttpRequest.BodyPublishers.noBody())
                .uri(URI.create("http://localhost:8080/user/authenticate"))
                .setHeader("Authorization", authHeader)
                .header("Content-Type", "application/json")
                .build();


        HttpClient httpClient = HttpClient.newHttpClient();
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println("response = " + response.body());

       }
    }

【讨论】:

    猜你喜欢
    • 2017-11-23
    • 2020-05-15
    • 2021-02-03
    • 2021-08-26
    • 2018-06-24
    • 2022-10-06
    • 1970-01-01
    • 2021-03-14
    • 2015-11-25
    相关资源
    最近更新 更多