Hello everybody,

I'm struggling to implement a keycloak login from my Android app. What I want to do is to simulate what a browser does (request a resource, be redirected to keycloak login page and get an access token later on). From what I've seen from the OAuth2 protocol, I need to firstly get the authorization code and later on request the access token with that code. I wouldn't like my Android app to be registered as a client itself, so I've registered my web service as public.

Here I start the intent to launch the Android browser pointing to the keycloak authorization address (/openid-connect/auth):

Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://192.168.0.230:8080/auth/realms/master/protocol/" +
    "openid-connect/auth?response_type=code&client_id=web_service&redirect_uri=android://app"));
startActivity(i);

When I enter the credentials successfully, I'm given a code in the redirection url, coming back to my app:

Uri data = getIntent().getData();
if (data != null) {
    String accessCode= data.getQueryParameter("code");
    System.out.println("Authorization code:" + accessCode);
}

The code looks like bC8OM0TwfbhYouM34M3RY2aZRYTywXZVAvKFABgvVRc.693363de-d6b5-4f88-b545-c6603023ee4c

Then I would like to get an access token with that code! I use a Rest Template for that, making a POST request to the /openid-connect/token endpoint:

ResponseEntity rssResponse = template.exchange(
        "http://192.168.0.230:8080/auth/realms/master/protocol/" +
                "openid-connect/token?grant_type=authoritation_code&client_id=web_service&code="+accessCode,
        HttpMethod.POST,
        null,
        Object.class);

However, I'm given a 401 unauthorized exception. What am I doing wrong? Thanks in advanced ;-)

--
Aritz Maeztu Otaņo
Departamento Desarrollo de Software

Pol. Ind. Mocholi. C/Rio Elorz, Nave 13E 31110 Noain (Navarra)
Telf.: 948 21 40 40
Fax.: 948 21 40 41

Antes de imprimir este e-mail piense bien si es necesario hacerlo: El medioambiente es cosa de todos.