AEM Cloud Service - Sample OAuth Authentication using Apache Httpclient

Goal

Sample code to make a connection to OAuth Identity Server, authenticate and get the Bearer token...


Service Interface

package app.eaem.api.core.services;

import org.json.JSONObject;

public interface EAEMOAuthService {
    public String getBearerToken() throws Exception;

    public JSONObject getPhotoNames();
}


Service Implementation

package app.eaem.api.core.services.impl;

import app.eaem.api.core.services.EAEMOAuthService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.osgi.services.HttpClientBuilderFactory;
import org.json.JSONObject;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.AttributeType;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

@Component(service = EAEMOAuthService.class)
@Designate(ocd = EAEMOAuthServiceImpl.EAEMOAuthConfiguration.class)
public class EAEMOAuthServiceImpl implements EAEMOAuthService {
    private static final Logger log = LoggerFactory.getLogger(EAEMOAuthServiceImpl.class);

    private String eaemIdentityServerUrl = "";
    private String clientId = "";
    private String clientSecret = "";
    private String scope = "";
    private String eaemAppUrl = "";

    private String bearerToken = "";
    private long tokenExpiryDate = 0;

    @Reference
    private transient HttpClientBuilderFactory httpClientBuilderFactory;

    private transient CloseableHttpClient httpClient;

    @Activate
    @Modified
    protected void activate(final EAEMOAuthConfiguration config) {
        eaemIdentityServerUrl = config.eaem_identity_server_url();
        clientId = config.eaem_client_id();
        clientSecret = config.eaem_client_secret();
        scope = config.eaem_scope();
        eaemAppUrl = config.eaem_app_url();

        final HttpClientBuilder builder = httpClientBuilderFactory.newBuilder();

        final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000)
                                .setSocketTimeout(30000).build();

        builder.setDefaultRequestConfig(requestConfig);

        httpClient = builder.build();
    }

    public JSONObject getPhotoNames(){
        JSONObject photos = new JSONObject();

        try{
            photos = new JSONObject(makeRequest(eaemAppUrl + "/api/Photos"));
        }catch(Exception e){
            log.error("Error getting leads", e);
        }

        return photos;
    }

    public String getBearerToken() throws Exception{
        long rightNow = new Date().getTime();

        if(StringUtils.isNotEmpty(bearerToken) && (rightNow < tokenExpiryDate)){
            return bearerToken;
        }

        Form form = Form.form();
        form.add("grant_type", "client_credentials");
        form.add("client_id", clientId);
        form.add("client_secret", clientSecret);
        form.add("scope", scope);

        String authResponse = Request.Post(eaemIdentityServerUrl)
                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .bodyForm(form.build()).execute().returnContent().asString();

        if(StringUtils.isEmpty(authResponse)){
            throw new Exception("Error authenticating with id and secret");
        }

        JSONObject bearerObj = new JSONObject(authResponse);
        bearerToken = bearerObj.getString("access_token");
        tokenExpiryDate = new Date().getTime() + (bearerObj.getInt("expires_in") * 1000);

        return bearerToken;
    }

    private String makeRequest(String uri) throws Exception{
        return Request.Get(uri)
                .addHeader("Authorization", "Bearer " + getBearerToken())
                .execute().returnContent().asString();
    }

    @ObjectClassDefinition(name = "OAuth EAEM Configuration")
    public @interface EAEMOAuthConfiguration {

        @AttributeDefinition(
                name = "EAEM Identity Server Url",
                description = "EAEM Identity Server Url",
                defaultValue = "https://eaem-idsvr-dev.somehost.com/connect/token",
                type = AttributeType.STRING)
        String eaem_identity_server_url();

        @AttributeDefinition(
                name = "EAEM App URL",
                description = "EAEM App URL",
                defaultValue = "https://eaem-app.somehost.com",
                type = AttributeType.STRING)
        String eaem_app_url();

        @AttributeDefinition(
                name = "EAEM Client Id",
                description = "EAEM Client Id",
                type = AttributeType.STRING)
        String eaem_client_id();

        @AttributeDefinition(
                name = "EAEM Client Secret",
                description = "EAEM Client Secret",
                type = AttributeType.STRING)
        String eaem_client_secret();

        @AttributeDefinition(
                name = "EAEM App Scope",
                description = "EAEM App Scope",
                defaultValue = "photos:eaemorg",
                type = AttributeType.STRING)
        String eaem_scope();
    }
}

No comments:

Post a Comment