Search code examples
mavenplayframeworkkeycloakdeadbolt

Integrating Keycloak into Play2 project


I want to integrate Keycloak authentication into a Play2 project. Here is what I did until this point:

  • I downloaded Keycloak: keycloak-1.6.1.Final.zip, unpacked, run it and set up by creating a test realm and some roles
  • I downloaded, configured and run the example js-console (https://github.com/keycloak/keycloak/tree/master/examples/js-console)
  • I was able to create a user and to log in with the js-console. The user show up in the keycloak admin as expected
  • Now I would like to protect my backend also, which is a Play2 project with maven build (using the play2-maven-plugin: https://code.google.com/p/play2-maven-plugin/)
  • The backend publishes a REST API, and these calls need to be available only for authenticated users posessing several roles.

Until this point I was unable to find a solution to do this. I came across Deadbolt, which can declaratively express the restrictions that need to be applied to the users and the roles, but I was unable to find an adapter for keycloak to use with Play2.

Is there anybody who did something similar? I guess a solution would be to create a custom adapter, by configuring and then calling the core Keycloak methods.

Does anybody have some thoughts on creating this "Keycloak Standalone Adapter"?


Solution

  • It depends on which authentication mechanism you want to use (openid-connect or SAML). For the application I was working on we chose openid-connect. At the moment, the only play2 library which supported the protocol was https://github.com/pac4j/play-pac4j. The tricky part was figuring out the way keycloak was encoding the information in the token it sent back to the play server. It does it by doing Base64 encoding. We translated the algorithm from the keycloak-js-adapter to extract the user information. After that, we can use Security trait or create a custom request wrapper which will contain the authorized user information.