Spring Boot OAuth2 with Discord as provider pt. II
Some time ago, we published a blog about logging in to your application using Discord as the provider. To refresh your memory, this was not possible with the default implementation of Spring Security’s OAuth2 library because it did not send a User-Agent
HTTP header, which Discord requires. We ended up writing custom implementations for OAuth2AccessTokenResponseClient
and OAuth2UserService
, where we would find ourselves copying the original class and adding an extra line of code that would set the User-Agent
header. While this was not a great solution, it worked! 🚀
What has changed?
With the release of Spring Security 5.1, it is now possible to customize the authorize and token requests, allowing us to add the User-Agent
header without the need of copying and adjusting the original classes. Instead, we can just set custom Converters on both the OAuth2AccessTokenResponseClient
and OAuth2UserService
. Those converters can then augment the requests by adding a User-Agent
header.
Getting started
The prerequisites have not changed. Please refer to our previous post on this subject on how to obtain a Client ID and Client Secret. Once you have those, you can configure your application to use those credentials. Here is the application.yml
:
Note the
client-id
andclient-secret
parameters. You will need to provide the values you have got from registering your application at discord. If you don’t want to put this information in yourapplication.yml
, you can pass them as environment variables:SPRING_SECURITY_OAUTH2_CLIENT_REGISTRATION_DISCORD_CLIENT_ID
andSPRING_SECURITY_OAUTH2_CLIENT_REGISTRATION_DISCORD_CLIENT_SECRET
.
The converters
Spring security already comes with default converters that create standard representations of an OAuth 2.0 Access Token Request. So, all we need to do is extend those converters and add a User-Agent
header to those requests. First, let’s write a utility class that adds the header to a request:
Note that this utility creates a new RequestEntity
. This is required because the headers of the original request are immutable, so we need to construct a new instance with our adjusted headers.
Then, we can create custom converters that call this new utility. We’ve chosen to extend these classes directly in our configuration:
Now each request made by the TokenResponseClient
and OAuth2UserService
will have the User-Agent
header added.
This is all that we need in order to use Spring Security OAuth2 with Discord! We have updated our demo application to use this new version of Spring Security, so you can check that out. 🎉