Picasso and Keycloak

So over the weekend I was trying to use Picasso to cleanly load images served by a server secured using KeyCloak. This was surprisingly easy using AeroGear’s authz library.

I needed the following dependencies in my apps build.gradle file
[code lang=”groovy”]
//AGDroid deps
compile ‘org.jboss.aerogear:aerogear-android-core:2.1.0’
compile ‘org.jboss.aerogear:aerogear-android-security:2.1.0’
compile ‘org.jboss.aerogear:aerogear-android-store:2.1.0’
compile ‘org.jboss.aerogear:aerogear-android-authz:2.1.0’
//Picasso deps
compile ‘com.squareup.picasso:picasso:2.5.2’
compile ‘com.squareup.okhttp:okhttp:2.4.+’
compile ‘com.squareup.okio:okio:1.5.0’
[/code]

And I configure Picasso with the following
[code lang=”java”]
OkHttpClient picassoClient = new OkHttpClient();

picassoClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
ModuleFields fields = AuthorizationManager.getModule("KeyCloakAuthz").loadModule(null, null, null);
Pair<String, String> header = fields.getHeaders().get(0);
Request newRequest = chain.request().newBuilder()
.addHeader(header.first, header.second)
.build();
return chain.proceed(newRequest);
}
});

picasso = new Picasso.Builder(appContext).downloader(new OkHttpDownloader(picassoClient)).build();
[/code]

*KeyCloakAuthz* is a AuthzModule protecting my server. You can find out more about them on the AeroGear website.