Issue
For a Spring Boot based web application serving REST APIs protected by OAuth 2, how to intercept access tokens before forwarding a request to a method?
In details,
The application is enabled as a resource server by @EnableResourceServer
, and its API is protected by OAuth 2 (specifically, Cloud Foundry User Account and Authentication).
Now for any request to a method with @RequestMapping
, it requires an access token obtained from OAuth 2. For example,
curl -H "Authorization: Bearer [token]" [api]
To achieve fine-grained access control,
Upon a request's arrival, I would like to parse the access token, and based the content of the access token (specifically, Scope
) forward or deny the request to go forward, hopefully, in a central place (perhaps kind of Inteceptor
). How to achieve that?
Solution
You can add a custom filter before authentication
e.g.
@Configuration
public class CustomWebSecurityConfigurerAdapter
extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(
new CustomFilter(), BasicAuthenticationFilter.class);
}
}
http://www.baeldung.com/spring-security-custom-filter
Answered By - StanislavL
Answer Checked By - Pedro (JavaFixing Volunteer)