Based on the two posts I made a similar request in Java. Thanks to the input from theses posts, I managed to create something that works with Spring Boot.
I tried this out and it worked, what I want to do next is saving the token in database and checking if it’s valid so that I do not need to do a new request for every test.
I use this token for my in testing in Spring boot. The Junit test’s will create a in memory database and start the application and then I will call the endpoint to get a access token so that I can send it to my secured endpoints and confirm that everything is working properly.
public String createToken() {
final String DOMAIN = "https://{oktaDomain}.com/";
final String CLIENT_ID = "{clientId}";
final String REDIRECT_URI = "{redirectUri}";
final String USERNAME = "username@mail.com";
final String PASSWORD = "password";
final EntityLogin entityLogin = new EntityLogin(USERNAME, PASSWORD);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
final WebTarget authentication = ClientBuilder.newClient().target(DOMAIN + "/api/v1/authn");
final Response response = authentication
.request(String.valueOf(MediaType.APPLICATION_JSON))
.post(Entity.json(entityLogin));
final String[] responseFromAuthentication = response.readEntity(String.class).split(":");
final String sessionToken = responseFromAuthentication[5].subSequence(1, 56).toString();
final WebTarget authorization = ClientBuilder.newClient()
.target(DOMAIN + "/oauth2/default/v1/authorize")
.queryParam("response_type", "token")
.queryParam("scope", "openid")
.queryParam("state", "TEST")
.queryParam("nonce", "TEST")
.queryParam("client_id", CLIENT_ID)
.queryParam("redirect_uri", REDIRECT_URI)
.queryParam("sessionToken", sessionToken);
final String accessToken = authorization.request().get().getLocation().getFragment().substring(13);
return accessToken.substring(0, accessToken.indexOf("&"));
}
private class EntityLogin {
private String username;
private String password;
}