public Optional<Tokens> getUserTokens(String code) throws IOException, ParseException {
final ClientAuthentication basicAuth = new ClientSecretBasic(new ClientID(clientId), new Secret(clientSecret));
final URI redirectUri = fromUri(redirectUrl).build();
final AuthorizationCodeGrant authzGrant = new AuthorizationCodeGrant(new AuthorizationCode(code), redirectUri);
final TokenRequest tokenRequest = new TokenRequest(getTokenUrl(discoveryUrl), basicAuth, authzGrant);
final TokenResponse response = OIDCTokenResponseParser.parse(tokenRequest.toHTTPRequest().send());
if (response.indicatesSuccess()) {
final Tokens tokens = response.toSuccessResponse().getTokens();
// TODO check if the id is not fake
return Optional.of(tokens);
} else {
LOG.error("Could not retrieve client token: {}", response.toErrorResponse().getErrorObject());
return Optional.empty();
}
}
@Override
public SsoAuthenticated processLoginResponse() {
HttpServletRequest request = (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest();
try {
AuthenticationResponse authenticationResponse = AuthenticationResponseParser.parse(
new URI(request.getRequestURI() + "?" + request.getQueryString()));
if (authenticationResponse instanceof AuthenticationErrorResponse) {
throw buildException(((AuthenticationErrorResponse)authenticationResponse).getErrorObject());
} else {
AuthenticationSuccessResponse authenticationSuccessResponse =
(AuthenticationSuccessResponse)authenticationResponse;
String state = (String) Session.get().getAttribute(SESSION_ATTR_STATE);
if (state == null || !state.equals(authenticationSuccessResponse.getState().getValue()))
throw new AuthenticationException("Unsolicited OIDC authentication response");
AuthorizationGrant codeGrant = new AuthorizationCodeGrant(
authenticationSuccessResponse.getAuthorizationCode(), getCallbackUri());
ClientID clientID = new ClientID(getClientId());
Secret clientSecret = new Secret(getClientSecret());
ClientAuthentication clientAuth = new ClientSecretBasic(clientID, clientSecret);
TokenRequest tokenRequest = new TokenRequest(
new URI(getCachedProviderMetadata().getTokenEndpoint()), clientAuth, codeGrant);
HTTPResponse httpResponse = tokenRequest.toHTTPRequest().send();
if (httpResponse.getStatusCode() == HTTPResponse.SC_OK) {
JSONObject jsonObject = httpResponse.getContentAsJSONObject();
if (jsonObject.get("error") != null)
throw buildException(TokenErrorResponse.parse(jsonObject).getErrorObject());
else
return processTokenResponse(OIDCAccessTokenResponse.parse(jsonObject));
} else {
ErrorObject error = TokenErrorResponse.parse(httpResponse).getErrorObject();
if (error != null) {
throw buildException(error);
} else {
String message = String.format("Error requesting OIDC token: http status: %d",
httpResponse.getStatusCode());
throw new AuthenticationException(message);
}
}
}
} catch (ParseException | URISyntaxException|SerializeException|IOException e) {
throw new RuntimeException(e);
}
}