Source Code Tracing — Spring Security OAuth Config / Exception Handling

Jeffrey Chen
2 min readJul 12, 2020

--

If you have spring-security-oauth2 on your classpath, it’s easy to set up Resource Server by auto-configuration. But I would like to change the default behavior of exception handling, so I am trying to adopt some custom config in this post.

Creating a Resource Server is easy, just add dependencies and add@EnableResourceServer in the configuration class, then provide some configuration to allow the server to decode access tokens.

After that, spring security will insert OAuth2AuthenticationProcessingFilter into SpringSecurityFilterChain. This filter will do the authentication by the token.

If the authentication is failed, it will through OAuth2Exception. When such exception be catch, Spring Security will do two things. First, it will publish a failed event, then it will call commence method of AuthenticationEntryPoint.

The default AuthenticationEntryPoint is OAuth2AuthenticationEntryPoint, it will translate the exception to ResponseEntity<OAuth2Exception>. So, if you want to customize the exception handling logic, you must implement your own AuthenticationEntryPoint. For example,

Then, change the default configuration of your resource server by extends the ResourceServerConfigurerAdapter.

Now, when the OAuth2Exception be thrown during the authentication process, your custom commence method will be called.

One more thing you should notice is there is a

public void configure(HttpSecurity http)

method in the ResourceServerConfigurerAdapter which also existed in WebSecurityConfigurerAdapter. What’s the difference between these two and why can we configure HttpSecurity properly? I will give you more details in the next post. See you there.

--

--

Jeffrey Chen

Software engineer who’s dream is to become an athletes