'Add request header after successfull authentication in Spring
I have an app where authentication of JWT token is done using spring security custom filter. The configuration looks as below to invoke the customer filter which does the authentication.
<security:http entry-point-ref="authenticationEntryPoint">
<security:custom-filter after="BASIC_AUTH_FILTER" ref="TokenValidationFilter" />
<security:session-management>
<security:concurrency-control max-sessions="1" />
</security:session-management>
<security:csrf disabled="true"/>
<security:anonymous enabled="false"/>
</security:http>
I extended AbstractAuthenticationProcessingFilter class and implemented TokenValidationFilter and able to authenticate the token received in request header. After successfull authentication, I want to call an another external API and get few values and append them in current request header. AbstractAuthenticationProcessingFilter class offers successfulAuthentication method as callback where I can do the external call and modify the request header. But I want to have a separate class or filter which needs to be invoked after successfull authentication for code maintainablility. Please let me know whether Spring offers any option for this. I am newbie to Spring and searched multiple sites but could not figure out how to approach this. Any suggestion would be much helpful.Thanks
Solution 1:[1]
Please look into AuthenticationSuccessHandler.
It allows you to control the response when login is successful.
Here is an example:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
...
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
...
.formLogin()
.loginPage("/login")
.usernameParameter("email")
.permitAll()
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// You have access to request, respnse, and authentication object containing all the user details.
response.addHeader("Header_Name", value);
}
})
...
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gaurav |
