8

I want to authenticate a user (using his username and password) in an Android App using aerogear with a server using Keycloak. I haven't been able to do it, help me please.

I currently can authenticate the user without aerogear, but I want to use this library since it can help me to refresh the token when is needed. I authenticate the user making a POST call to the server like this (but from android):

 curl -X POST http://127.0.0.1:8080/auth/realms/example/protocol/openid-connect/token  
 -H "Content-Type: application/x-www-form-urlencoded" -d "username=auser" -d 'password=apassword' -d 'grant_type=password' 
 -d 'client_id=clientId' -d 'client_secret=secret'

So the information I have is:

  • Authentication URL, ie http://127.0.0.1:8080/auth/realms/example/protocol/openid-connect/token
  • username, the username of the user
  • password, the password of the user
  • client_id, and client_secret of the Keycloak server

What I have tried with Aerogear is this:

private void authz() {
    try {

        AuthzModule authzModule = AuthorizationManager.config("KeyCloakAuthz", OAuth2AuthorizationConfiguration.class)
                .setBaseURL(new URL("http://127.0.0.1:8080/"))
                .setAuthzEndpoint("/realms/example/protocol/openid-connect/auth")
                .setAccessTokenEndpoint("/realms/example/protocol/openid-connect/token")
                .setAccountId("keycloak-token")
                .setClientId("clientId")
                .setClientSecret("secret")
                .setRedirectURL("http://oauth2callback")
                .setScopes(Arrays.asList("openid"))
                .addAdditionalAuthorizationParam((Pair.create("grant_type", "password")))
                .addAdditionalAuthorizationParam((Pair.create("username", "aUserName")))
                .addAdditionalAuthorizationParam((Pair.create("password", "aPassword")))
                .asModule();


        authzModule.requestAccess(this, new Callback<String>() {
            @Override
            public void onSuccess(String o) {
                Log.d("TOKEN ", o);
            }

            @Override
            public void onFailure(Exception e) {
                System.err.println("Error!!");
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
            }
        });

    } catch (Exception e) {

        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

However this doesn't do anything. What I don't understand is:

  1. How can I specify that I'm doing and OpenID Connect with Keycloak in Aerogear?
  2. How and where can I send the username and password?
  3. How can I specify the grant_type? (My HTTP POST to the server does not work if I don't include this, so it's important)

Any help would be very much appreciated

ACBM
  • 657
  • 1
  • 10
  • 26
  • Maybe these resources could help: https://aerogear.org/docs/guides/aerogear-android/authz/ https://github.com/aerogear/aerogear-android-cookbook/tree/master/GDrive – Apostolos Emmanouilidis Oct 13 '16 at 11:26
  • Thanks Tolis, I've reviewed both resources. In fact, the code I presented is based on the second link you sended but still I haven't been able to solve my problem. Thanks anyway :) – ACBM Oct 14 '16 at 01:31
  • You're welcome. Would you please provide some info on whether the failure callback is called? Is your Android manifest properly configured? Also, I suppose that you're not using 127.0.0.1 base URL on your Android client, right? – Apostolos Emmanouilidis Oct 14 '16 at 06:42

3 Answers3

6

If you go with the standard Authorization Code flow with access type = public client (no clientSecret) then you may take a look at my example Android native app.

In short, you could open up a browser window in a WebView, get the authorization code by parsing the query parameter from the returned url and exchange it (the code) for the token via a POST request.

If you use Retrofit, then here is the REST interface:

interface IKeycloakRest {
    @POST("token")
    @FormUrlEncoded
    fun grantNewAccessToken(
        @Field("code")         code: String,
        @Field("client_id")    clientId: String,
        @Field("redirect_uri") uri: String,
        @Field("grant_type")   grantType: String = "authorization_code"
    ): Observable<KeycloakToken>

    @POST("token")
    @FormUrlEncoded
    fun refreshAccessToken(
        @Field("refresh_token") refreshToken: String,
        @Field("client_id")     clientId: String,
        @Field("grant_type")    grantType: String = "refresh_token"
    ): Observable<KeycloakToken>

    @POST("logout")
    @FormUrlEncoded
    fun logout(
        @Field("client_id")     clientId: String,
        @Field("refresh_token") refreshToken: String
    ): Completable
}

data class KeycloakToken(
    @SerializedName("access_token")       var accessToken: String? = null,
    @SerializedName("expires_in")         var expiresIn: Int? = null,
    @SerializedName("refresh_expires_in") var refreshExpiresIn: Int? = null,
    @SerializedName("refresh_token")      var refreshToken: String? = null
)

And its instantiation:

val rest: IKeycloakRest = Retrofit.Builder()
            .baseUrl("https://[KEYCLOAK-URL]/auth/realms/[REALM]/protocol/openid-connect/")
            .addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
            .create(IKeycloakRest::class.java)
maslick
  • 2,903
  • 3
  • 28
  • 50
2

I am using AeroGear as well, and I notice I had the same problem. Then what I did was (beside other configuration information as Tolis Emmanouilidis said) to add the Auth service in your Manifest.

Try adding <service android:name="org.jboss.aerogear.android.authorization.oauth2.OAuth2AuthzService"/> in your manifest

Once you do that, it is working properly and you can retrieve the Bearer token.

zapotec
  • 2,628
  • 4
  • 31
  • 53
0

i have implemented it on my project inside my keycloakHelper class.

public class KeycloakHelper {

static
{
    try
    {
        AuthorizationManager
                .config("KeyCloakAuthz", OAuth2AuthorizationConfiguration.class)
                .setBaseURL(new URL(EndPoints.HTTP.AUTH_BASE_URL))
                .setAuthzEndpoint("/auth/realms/***/protocol/openid-connect/auth")
                .setAccessTokenEndpoint("/auth/realms/ujuzy/protocol/openid-connect/token")
                .setRefreshEndpoint("/auth/realms/***/protocol/openid-connect/token")
                .setAccountId("account")
                .setClientId("account")
                .setRedirectURL("your base url")
                .addAdditionalAuthorizationParam((Pair.create("grant_type", "password")))
                .asModule();

        PipeManager.config("kc-upload", RestfulPipeConfiguration.class)
                .module(AuthorizationManager.getModule("KeyCloakAuthz"))
                .requestBuilder(new MultipartRequestBuilder());

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

public static void connect(final Activity activity, final Callback callback)
 {
    if (!DetectConnection.checkInternetConnection(activity))
        return;

    try {
        final AuthzModule authzModule = AuthorizationManager.getModule("KeyCloakAuthz");
        authzModule.requestAccess(activity, new Callback<String>()
        {
            @SuppressWarnings("unchecked")
            @Override
            public void onSuccess(String s)
            {
                callback.onSuccess(s);
            }

            @Override
            public void onFailure(Exception e)
            {
               // authzModule.refreshAccess();
                authzModule.isAuthorized();
                if (!e.getMessage().matches(OAuthWebViewDialog.OAuthReceiver.DISMISS_ERROR))
                {
                    //authzModule.refreshAccess();
                    authzModule.deleteAccount();
                }
                callback.onFailure(e);

            }
        });

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

public static boolean isConnected()
{
    return AuthorizationManager.getModule("KeyCloakAuthz").isAuthorized();
}

}

When you want user to login (input email & password)

public void LoginUser() {
    KeycloakHelper.connect(getActivity(), new Callback() {
        @Override
        public void onSuccess(Object o) {
            //YOU WILL GET YOUR TOKEN HERE IF USER IS ALREADY SIGNED IN. 
            //IF USER IS NOT SIGNED IN, AEROGEAR WILL PROMPT A WEBVIEW DIALOG
            //WHERE THE USER WILL INPUT THERE EMAIL AND PASSWORD
        }

        @Override
        public void onFailure(Exception e) {
                               
        }
    });
}

Happy coding :)

johnwebi
  • 1
  • 4