Spring Security (series) - GitHub SSO #5
Let GitHub handle the headache of your user management.
Brief
I always wanted to know how that magic 'Sign in using your GitHub account' works. After some research I found that it's actually not complicated at all.
Implementation
First, you need to go to GitHub and register your application at https://github.com/settings/developers
You will need to generate a clientSecret
, which you will need along with the clientId
in the security configuration.
Let's create the simplest application possible.
We'll have a controller returning a static html page. The controller should only be accessed by logged in users.
We need to add the oauth2-client
dependency in our build.gradle
file.
The security configuration is really straight-forward.
- As always, we'll extend
WebSecurityConfigurerAdapter
and override theconfigure(HttpSecurity http)
. - Add a
ClientRegistration
bean in Spring'sClientRegistrationRepository
containing details about reaching GitHub.
You should never store your credentials directly in code, they should be injected from a Vault or some other secret storage implementation.
You can also create your custom ClientRegistration
where you would need to add details about the authorization server. See below details about the Github client.
Aaand that's all the code you need. Let's see it live.
If you now go into your browser at localhost:8080/hello
, you should be redirected to the GitHub login form. After providing correct credentials of your account, you will be prompted to authorize the browser to access your backend application.
Finally, you should see the beautifully designed web page standing behind your controller.
Like always, checkout the full code here.
Stay tuned! 🚀