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);
}
}
}
(調査中)Javaの HttpClient を使用したKeycloakからBearerトークンを取得
Last updated at Posted at 2024-06-17
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme