Search in sources :

Example 1 with AzureAd2OidcConfiguration

use of org.pac4j.oidc.config.AzureAd2OidcConfiguration in project pac4j by pac4j.

the class AzureAd2Client method getAccessTokenFromRefreshToken.

/**
 * <p>Refresh the access token</p>
 * <p>https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow#refresh-the-access-token</p>
 */
@Override
public String getAccessTokenFromRefreshToken(final AzureAdProfile azureAdProfile) {
    final var azureConfig = (AzureAd2OidcConfiguration) getConfiguration();
    HttpURLConnection connection = null;
    try {
        final Map<String, String> headers = new HashMap<>();
        headers.put(HttpConstants.CONTENT_TYPE_HEADER, HttpConstants.APPLICATION_FORM_ENCODED_HEADER_VALUE);
        headers.put(HttpConstants.ACCEPT_HEADER, HttpConstants.APPLICATION_JSON);
        // get the token endpoint from discovery URI
        final var tokenEndpointURL = azureConfig.findProviderMetadata().getTokenEndpointURI().toURL();
        connection = HttpUtils.openPostConnection(tokenEndpointURL, headers);
        final var out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8));
        out.write(azureConfig.makeOauth2TokenRequest(azureAdProfile.getRefreshToken().getValue()));
        out.close();
        final var responseCode = connection.getResponseCode();
        if (responseCode != 200) {
            throw new TechnicalException("request for access token failed: " + HttpUtils.buildHttpErrorMessage(connection));
        }
        var body = HttpUtils.readBody(connection);
        final Map<String, Object> res = objectMapper.readValue(body, typeRef);
        return (String) res.get("access_token");
    } catch (final IOException e) {
        throw new TechnicalException(e);
    } finally {
        HttpUtils.closeConnection(connection);
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) TechnicalException(org.pac4j.core.exception.TechnicalException) HashMap(java.util.HashMap) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) AzureAd2OidcConfiguration(org.pac4j.oidc.config.AzureAd2OidcConfiguration) BufferedWriter(java.io.BufferedWriter)

Aggregations

BufferedWriter (java.io.BufferedWriter)1 IOException (java.io.IOException)1 OutputStreamWriter (java.io.OutputStreamWriter)1 HttpURLConnection (java.net.HttpURLConnection)1 HashMap (java.util.HashMap)1 TechnicalException (org.pac4j.core.exception.TechnicalException)1 AzureAd2OidcConfiguration (org.pac4j.oidc.config.AzureAd2OidcConfiguration)1