Skip to main content

Java

Used Constants:

    private static String OIDC_AUTH_END_POINT = "https://tenantname.aws1.test1.com/auth/realms/{tenantname}/protocol/openid-connect/auth";
private static String OIDC_CLIENT = "test";
private static String OIDC_CLIENT_SECRET = "dfd3092a-a6dc-4e94-9662-f451033074d4";
private static String OIDC_TOKEN_ENDPOINT = "https://tenantname.aws1.test1.com/auth/realms/{tenantname}/protocol/openid-connect/token";

/auth/oidc (POST)

   public String getNonce() {
String generatedString = RandomStringUtils.random(10, true, true);
return generatedString;
}

@GetMapping("/auth/oidc")
public Map<String, String> oidc(@RequestParam String redirectURI) {
String composedUrl = String.format("%s?client_id=%s&redirect_uri=%s&scope=openid&response_type=code&response_mode=query&nonce=%s", OIDC_AUTH_END_POINT, OIDC_CLIENT, redirectURI, getNonce());
Map<String, String> response = Map.of("client_id", OIDC_CLIENT, "auth_url", OIDC_AUTH_END_POINT, "composed_url", composedUrl);
return response;
}

/auth/code (POST)

    @Autowired
UserRepository userRepository;

@PostMapping(path = "/auth/code", consumes = "application/json", produces = "application/json")
public ResponseEntity code(@RequestBody CodeDTO codeDTO) throws JSONException {
RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("client_id", OIDC_CLIENT);
map.add("grant_type", "authorization_code");
map.add("code", codeDTO.getCode());
map.add("client_secret", OIDC_CLIENT_SECRET);
map.add("redirect_uri", codeDTO.getRedirectUrl());


HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
ResponseEntity<String> response =
restTemplate.exchange(OIDC_TOKEN_ENDPOINT,
HttpMethod.POST,
entity,
String.class);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response.getBody());
} catch (JSONException err) {
}
String idToken = jsonObject.getString("id_token");
if (idToken == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
DecodedJWT jwt = JWT.decode(idToken);
String email = jwt.getClaim("email").asString();
User user = userRepository.findByEmailAddress(email);
if (user == null) {
return ResponseEntity.status(HttpStatus.ACCEPTED).build();

} else {
return ResponseEntity.ok(user);
}


}
}

class CodeDTO {
String code;
String redirectUrl;

public CodeDTO(String code, String redirectUrl) {
this.code = code;
this.redirectUrl = redirectUrl;
}

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public String getRedirectUrl() {
return redirectUrl;
}

public void setRedirectUrl(String redirectUrl) {
this.redirectUrl = redirectUrl;
}

info