Security with KeyCloak and Google Services on Android

The KeyCloak project is a phenomenal resource for authentication and authorization services for almost any application. The default use case for it involves using OAuth redirects to send a client to a web page hosted by KeyCloak or a trusted Identity Provider, perform a log in, and the exchange tokens on the client application. This prevents potentially untrusted clients from stealing logins from users while also allowing trustworthy applications to log in using a third party. This is how websites are able to use social logins from Google, Facebook, Github, etc. However on Android the operating system provides many ways to manage log ins locally via an account picker. Google goes one step further and can provide tokens via its client sdk.

Because Google will provide a application with a token directly, we can bypass the website redirect skip on Android with Keycloak by using “External to Internal Token Exchange“. The Keycloak documentation will walk you through setting up the IdP, but you have to make sure that you configure the Google IdP as a “OpenID Connect v1.0” provider and not as a “Google” provider. Fortunately you can use Google’s well-known OpenID configuration to prepopulate most of the fields. One thing I had to change was flipping “Disable User Info” to “ON”. In order to fetch the user info, Google needs an bearer token that Keycloak does not provide.

I’ve made a simple Android application which exchanges a Google token for a Keycloak token here. The source code is on my GitHub and a demo is on my YouTube channel.