forked from Decathlon/tzatziki
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOAuth2TokenFetcher.java
More file actions
74 lines (63 loc) · 3 KB
/
OAuth2TokenFetcher.java
File metadata and controls
74 lines (63 loc) · 3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.decathlon.tzatziki.utils;
import io.restassured.response.Response;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import static io.restassured.RestAssured.given;
/**
* Utility class for fetching OAuth2 access tokens using the client credentials flow.
* <p>
* This class performs HTTP POST requests to OAuth2 token endpoints to obtain
* access tokens. It throws immediately on any failure.
* </p>
*/
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class OAuth2TokenFetcher {
private static final String GRANT_TYPE_CLIENT_CREDENTIALS = "client_credentials";
/**
* Fetches an access token from the OAuth2 token endpoint using client credentials flow.
*
* @param clientId the OAuth2 client ID
* @param clientSecret the OAuth2 client secret
* @param tokenUrl the OAuth2 token endpoint URL
* @return the access token
* @throws AssertionError if the token request fails or the response is invalid
*/
public static String fetchAccessToken(String clientId, String clientSecret, String tokenUrl) {
log.debug("Fetching OAuth2 access token for clientId: {} from: {}", clientId, tokenUrl);
// Resolve the token URL through HttpWiremockUtils to support mocked endpoints
String resolvedTokenUrl = HttpWiremockUtils.target(tokenUrl);
log.debug("Resolved token URL: {}", resolvedTokenUrl);
try {
Response response = given()
.contentType("application/x-www-form-urlencoded")
.formParam("grant_type", GRANT_TYPE_CLIENT_CREDENTIALS)
.formParam("client_id", clientId)
.formParam("client_secret", clientSecret)
.post(resolvedTokenUrl);
int statusCode = response.getStatusCode();
if (statusCode < 200 || statusCode >= 300) {
throw new AssertionError(
"OAuth2 token request failed for clientId: " + clientId +
". Status: " + statusCode +
". Response: " + response.getBody().asString());
}
String accessToken = response.jsonPath().getString("access_token");
if (accessToken == null || accessToken.isBlank()) {
throw new AssertionError(
"OAuth2 token response does not contain 'access_token' for clientId: " + clientId +
". Response: " + response.getBody().asString());
}
log.debug("Successfully fetched OAuth2 access token for clientId: {}", clientId);
return accessToken;
} catch (Error e) {
if (e instanceof AssertionError) {
throw e;
}
throw new AssertionError(
"Failed to fetch OAuth2 access token for clientId: " + clientId +
" from: " + tokenUrl + ". Error: " + e.getMessage(), e);
}
}
}