Search code examples
javaazureauthenticationoauthjava-6

How to make Azure Authentication work on Java 6


I am working on a legacy project with Java and JSP running on Java 1.6. I need to integrate a new method of authentication based on Azure Active Directory. The library that has been used in other similar projects is adal4j. Sadly this project is so old that it is running with Java 1.6, and sadly it cannot easily be ported in Java 7.

I am trying to find an alternative library to use to authenticate the user and get the token. I found azure-identity but it requires Java 7 (actually Java 8 since a few years).

Any suggestion on what I could use?

Best regards


Solution

  • In the end, I followed the guidelines here to POST a request to Azure and get the Authentication Token, and I made a simple class in Java that makes this request.

    https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow#get-a-token

    Here's the code for the authentication

    package mypackage.auth;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.Reader;
    import java.io.UnsupportedEncodingException;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.LinkedHashMap;
    import java.util.Map;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    
    public class Auth {
        
        private String authority;
        private String resource;
        private AuthCredentials credentials;        
        
        // **** CONSTRUCTORS ****
    
        public Auth() {
            
            this.authority = null;
            this.credentials = new AuthCredentials();
            this.resource = null;
        }
        
        public Auth(String authority, String clientID, String secret, String resource) {
            
            this.authority = authority;
            this.credentials = new Auth(clientID, secret);
            this.resource = resource;
        }
        
        public Auth(String authority, AuthCredentials credentials, String resource) {
            
            this.authority = authority;
            this.credentials = credentials;
            this.resource = resource;
        }
    
        // **** METHODS ****
    
        public JSONObject authenticate() throws IOException {
            
            Map<String, Object> params = getRequestParams();
            byte[] body = buildRequest(params);
            JSONObject response = post(body);
            
            return response;        
        }
        
        // Request Parameters for Microsoft AD Authentication
        private Map<String, Object> getRequestParams () {
            
            Map<String,Object> params = new LinkedHashMap<String, Object>();
            params.put("client_id", credentials.getClientId());
            params.put("scope", resource + "/.default");
            params.put("resource", resource);
            params.put("client_secret", credentials.getSecret());
            params.put("grant_type", "client_credentials");
            
            return params;
        }
        
        // HTTP Post to Microsoft AD auth API
        private JSONObject post(byte[] body) throws IOException {
            
            URL url = new URL(authority);       
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(body.length));
            conn.setDoOutput(true);
            conn.getOutputStream().write(body);
            
            Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            
            StringBuilder sb = new StringBuilder();
            for (int c; (c = in.read()) >= 0;)
                sb.append((char)c);
            String response = sb.toString();    
            JSONObject json = stringToJSON(response);
            
            return json;
        }   
    
        // Request builder, builds url encoded request based on the params map
        private byte[] buildRequest(Map<String, Object> params) throws UnsupportedEncodingException {       
            
            StringBuilder postData = new StringBuilder();
            for (Map.Entry<String,Object> param : params.entrySet()) {
                if (postData.length() != 0) postData.append('&');
                postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                postData.append('=');
                postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
            }
            byte[] postDataBytes = postData.toString().getBytes("UTF-8");   
            
            return postDataBytes;
        }
        
        private JSONObject stringToJSON (String string) throws JSONException {
            
            JSONObject jsonObject = new JSONObject(string);
            return jsonObject;
        }
        
        // **** GETTERS SETTERS ****
    
        public String getAuthority() {
            return authority;
        }
    
        public void setAuthority(String authority) {
            this.authority = authority;
        }
    
        public String getClientID() {
            return credentials.getClientId();
        }
    
        public void setClientID(String clientID) {
            this.credentials.setClientId(clientID);
        }
    
        public String getSecret() {
            return credentials.getSecret();
        }
    
        public void setSecret(String secret) {
            this.credentials.setSecret(secret);
        }
    
        public AuthCredentials getCredentials() {
            return credentials;
        }
    
        public void setCredentials(AuthCredentials credentials) {
            this.credentials = credentials;
        }
        
    }
    
     
    

    On my API client I get the authentication token like this:

     public String authenticateClient() throws IOException {
            
        JSONObject response = auth.authenticate();
        this.token = response.get("access_token").toString();
        return this.token;
    }