After implementing spring security (basic form authentication), I am unable to get the current request using RequestContextHolder.getRequestAttributes(), which worked fine before.
The problem is that RequestContextHolder.getRequestAttributes() is null and I need to get an extra parametere (the tenant id) from the login request in order to select the correct database.
Here's my code:
Security
@EnableWebSecurity
public class Security extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserDetailsService myUserDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/assets/**")
.permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/dashboard/login")
.defaultSuccessUrl("/dashboard/home")
.permitAll()
.and()
.logout()
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider
= new DaoAuthenticationProvider();
authProvider.setUserDetailsService(myUserDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(11);
}
}
CurrentTenantIdentifierResolverImpl
public class CurrentTenantIdentifierResolverImpl implements CurrentTenantIdentifierResolver {
Logger log = LogManager.getLogger(CurrentTenantIdentifierResolverImpl.class);
@Override
public String resolveCurrentTenantIdentifier() {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpSession session = attr.getRequest().getSession(false); // true == allow create
if (session != null) {
String tenant = (String) session.getAttribute("tenant");
log.trace("Tenant default resolved in session is: " + tenant);
if (tenant != null) {
return tenant;
}
}
String request = attr.getRequest().getRequestURI();
String tenant = attr.getRequest().getParameter("tenant");
if (request.equals("/dashboard/login") && tenant != null) {
return tenant;
}
//otherwise return default tenant
log.trace("Tenant default not resolved in session");
return null;
}
@Override
public boolean validateExistingCurrentSessions() {
return true;
}
}
I had accidentally deleted a class that was vital. Simply adding it back solved the issue.
@Configuration
@WebListener
public class MyRequestContextListener extends RequestContextListener {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With