0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

(調査中)Javaの HttpClient を使用したKeycloakからBearerトークンを取得

Last updated at Posted at 2024-06-17
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class KeycloakService {

    public ResponseEntity<String> getToken() {
        String keycloakUrl = "http://your-keycloak-url/auth/realms/your-realm-name/protocol/openid-connect/token";
        String clientId = "your-client-id";
        String clientSecret = "your-client-secret";

        HttpClient httpClient = HttpClient.newHttpClient();

        // リクエストパラメータを準備
        Map<String, String> params = Map.of(
                "grant_type", "client_credentials",
                "client_id", clientId,
                "client_secret", clientSecret
        );

        // URLエンコードされたクエリストリングを作成
        String requestBody = params.entrySet().stream()
                .map(p -> URLEncoder.encode(p.getKey(), StandardCharsets.UTF_8)
                        + "=" + URLEncoder.encode(p.getValue(), StandardCharsets.UTF_8))
                .collect(Collectors.joining("&"));

        // POSTリクエストを作成
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(keycloakUrl))
                .header("Content-Type", "application/x-www-form-urlencoded")
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();

        try {
            // リクエストを送信してレスポンスを取得
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

            // HttpResponseをResponseEntityに変換
            HttpHeaders headers = new HttpHeaders();
            response.headers().map().forEach((key, values) -> headers.put(key, values));

            return new ResponseEntity<>(response.body(), headers, HttpStatus.valueOf(response.statusCode()));
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?