Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save muhdkhokhar/63496ab1e6cb4fdf2067ecfa1cf9fbfe to your computer and use it in GitHub Desktop.
Save muhdkhokhar/63496ab1e6cb4fdf2067ecfa1cf9fbfe to your computer and use it in GitHub Desktop.
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
public class OAuth2TokenGenerator {
private static final String TOKEN_URL = "https://your-auth-server.com/oauth/token";
private static final String CLIENT_ID = "your-client-id";
private static final String CLIENT_SECRET = "your-client-secret";
private static final String GRANT_TYPE = "client_credentials"; // or other grant types
private static final String SCOPE = "your-scope";
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
ObjectMapper objectMapper = new ObjectMapper();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
Map<String, String> params = new HashMap<>();
params.put("client_id", CLIENT_ID);
params.put("client_secret", CLIENT_SECRET);
params.put("grant_type", GRANT_TYPE);
params.put("scope", SCOPE);
StringBuilder requestBody = new StringBuilder();
params.forEach((key, value) -> requestBody.append(key).append("=").append(value).append("&"));
requestBody.deleteCharAt(requestBody.length() - 1); // Remove trailing '&'
HttpEntity<String> entity = new HttpEntity<>(requestBody.toString(), headers);
ResponseEntity<String> response = restTemplate.exchange(
TOKEN_URL,
HttpMethod.POST,
entity,
String.class
);
if (response.getStatusCode().is2xxSuccessful()) {
try {
JsonNode jsonResponse = objectMapper.readTree(response.getBody());
String accessToken = jsonResponse.get("access_token").asText();
System.out.println("Access Token: " + accessToken);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Error: " + response.getStatusCode());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment