For one of our internal pet-projects at Codurance, we decided to have authentication and authorisation using Google+ Sign-in. Google+ Sign-In is able to authenticate anyone with a Google email account (gmail or business) using OAuth 2.0. However, we wanted to restrict the application to Codurance craftsmen only, that means, people with a Codurance email address.
The application had also to redirect us to the desired URL, in case we tried to access a deep URL without being authenticated.
In this project we are using:
- Scalatra as a web micro-framework
- Jade as template engine
- sbt as our build tool.
- json4s for JSON manipulation
- Newman as HTTP client library
First we need to add an AuthenticationFilter to our Scalatra application.
Then, in the AuthenticationFilter, we need to redirect to the sign-in page when we don't have a user in the session. We also need to exclude the pages and URLs that don't need a user to be logged in.
For more information about filters, check the Scalatra documentation.
Then we need a sign-in page, that is displayed when the user is not authenticated.
This should be enough to trigger the Google authentication form when clicking on the Sign-In button. Once the authentication is done, the callback function will send us a POST with the "authCode".
We then need a controller that will respond to all these requests, displays the respective pages, and do the authorisation.
The MainController responds to "/authorise", which invokes the authorisation function defined inside CoduranceAuthorisation. Note that we receive the "authCode" from the Google+ authentication. Once the user was authenticated, we had to make the application available just for users using a Codurance email. For that, we had to invoke the Google+ People API to get more information (email address, domain, etc).
The authorise function would then check if the user belongs to the Codurance domain and add her to the session.
Note that in the GOOGLE_PLUS_PEOPLE_URL we specify all the fields we are interested in, including the domain and emails.
GooglePlusJSONResponseParser is a class that we created to parse the JSON response and convert into a User object. We are not showing it in order to keep this post short and focused. You can create your own JSON parser. :)
IMPORTANT: Don't forget to import add the Google+ APIs to your sbt build file.
That's about it. You now can display the name of the user on all your pages, using a default layout.
Ready to be inspired?
Thank you for signing up
Join our newsletter for expert tips and inspirational case studies
Your welcome email is on its way! You can pick the emails you’d like to receive by clicking the link to the Preference Centre.