Home > HttpClient > Autenticación con OpenSSO y HttpClient

Autenticación con OpenSSO y HttpClient

October 25th, 2009

Hola amigos,

Acá comparto una porción de código que use para poder autenticarme a servidor OpenSSO y obtener un el subjectId del usuario usando HttpClient de Jakarta Commons.

Este ejemplo esta basado en este articulo:

REST based Identity Services in OpenSSO, acá se describen los distintos RestFul services que provee OpenSSO

El ejemplo proveído es simplemente un método que recibe como parámetros nombre de usuario y password el cual después usando el PostMethod de HttpClient obtiene el un subjectId.

Aparte también pueden ver un método de utilidad que sirve para leer un InputStream y convertirlo a un String.

    public String authenticate(String username, String password) {
        Configuration configuration = Configuration.getIntance();
        PostMethod postMethod = new PostMethod("http://localhost:8080/opensso/identity/authenticate");
 
        HttpClient httpClient = new HttpClient();
        postMethod.addParameter("username",username);
        postMethod.addParameter("password",password);
        postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 
        try {
            httpClient.executeMethod(postMethod);
        } catch (IOException e) {
            throw new RuntimeException("No se puede llamar a servicio de autenticación de OpenSSO");
        }
 
        String response = null;
        try {
            response = readInputStreamAsString(postMethod.getResponseBodyAsStream());
        } catch (IOException e) {
            throw new RuntimeException("No se puede leer respuesta.",e);
        }
        postMethod.releaseConnection();
        return response.substring("token.id=".length()).trim();
    }
 
    private String readInputStreamAsString(InputStream inputStream)
            throws java.io.IOException {
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        char[] buf = new char[1024];
        int numRead = 0;
        while ((numRead = reader.read(buf)) != -1) {
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            buf = new char[1024];
        }
        reader.close();
        return fileData.toString();
    }

Básicamente al llamar al servicio de autenticación, este te retorna un String parecido al siguiente:

token.id=123445656qwerreqerqwerqwre345

Donde “123445656qwerreqerqwerqwre345″, es el identificador del usuario para poder ser usado en una sesión de OpenSSO, es por eso que después hacemos un substring para separar el separarlo.

Esto seria por hoy :) hasta la próxima.

Renan Huanca HttpClient