I've created this filter to decrypt the username and password and then spring boot can proceed with authentication of user
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import jakarta.servlet.http.HttpServletRequest;
import com.example.demo.controller.HybridController;
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
public CustomAuthenticationFilter(AuthenticationManager authenticationManager) {
super.setAuthenticationManager(authenticationManager);
}
HybridController hybridController = new HybridController();
private String decrypt(String data) {
try {
return hybridController.Hybrid_Data_Decryption(data);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
@Override
protected String obtainPassword(HttpServletRequest request) {
String decPassword = decrypt(super.obtainPassword(request));
return decPassword;
}
@Override
protected String obtainUsername(HttpServletRequest request) {
String decUsername = decrypt(super.obtainUsername(request));
return decUsername;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
String username = obtainUsername(request);
username = (username != null) ? username.trim() : "";
String password = obtainPassword(request);
password = (password != null) ? password : "";
Admin admin = adminRepository.findByUsername(username.toLowerCase()).orElse(null);
Authentication authentication = null;
if (admin != null) {
authentication = this.getAuthenticationManager()
.authenticate(new UsernamePasswordAuthenticationToken(username,
password, mapRolesToAuthorities(admin.getRoles())));
}
SecurityContextHolder.getContext().setAuthentication(authentication);
request.getSession().setAttribute(
"SPRING_SECURITY_CONTEXT",
SecurityContextHolder.getContext());
return authentication;
}
private Collection<? extends GrantedAuthority> mapRolesToAuthorities(List<Role> roles) {
return roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
}
}
I'm using Spring Boot 3.2.4, and it's configuration is done as follows
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.header.writers.XXssProtectionHeaderWriter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@EnableWebSecurity
public class SpringSecurity {
@Bean
static PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
AuthSuccessHandler authSuccessHandler() {
return new AuthSuccessHandler();
}
@Bean
SecurityFilterChain filterChain(HttpSecurity http, AuthenticationManager authenticationManager)
throws Exception {
CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter(
authenticationManager);
http.addFilterBefore(customAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
http.addFilterBefore(new SessionCookieFilter(), UsernamePasswordAuthenticationFilter.class);
http
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/")
.permitAll()
.requestMatchers("/user/**").hasRole("USER"))
.formLogin(
form -> form
.loginPage("/login")
.loginProcessingUrl("/login")
.failureUrl("/login?error")
.successHandler(this.authSuccessHandler())
.permitAll())
.logout(
logout -> logout
.logoutRequestMatcher(
new AntPathRequestMatcher("/logout"))
.permitAll())
.sessionManagement(session -> session
.sessionFixation().newSession()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.maximumSessions(1));
return http.build();
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http,
CustomUsersDetailsService userDetailsService,
PasswordEncoder passwordEncoder) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder = http
.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
return authenticationManagerBuilder.build();
}
}
The problem is that this code is able to decrypt the incoming username and password and spring is able to authenticate the user but instead of redirecting to dashboard of desired page it keeps redirecting to login page.
Here are some logs for reference:
Securing POST /login
2025-02-09T15:20:54.055+05:30 DEBUG 8028 --- [nio-8181-exec-5] o.s.s.a.dao.DaoAuthenticationProvider : Authenticated user
2025-02-09T15:20:54.056+05:30 DEBUG 8028 --- [nio-8181-exec-5] o.s.s.web.DefaultRedirectStrategy : Redirecting to http://localhost:8181/error?continue
2025-02-09T15:20:54.063+05:30 DEBUG 8028 --- [nio-8181-exec-1] o.s.security.web.FilterChainProxy : Securing GET /error?continue
2025-02-09T15:20:54.065+05:30 DEBUG 8028 --- [nio-8181-exec-1] o.s.s.w.s.HttpSessionRequestCache : Loaded matching saved request http://localhost:8181/error?continue
2025-02-09T15:20:54.067+05:30 DEBUG 8028 --- [nio-8181-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2025-02-09T15:20:54.070+05:30 DEBUG 8028 --- [nio-8181-exec-1] o.s.s.w.s.HttpSessionRequestCache : Saved request http://localhost:8181/error?continue to session
2025-02-09T15:20:54.070+05:30 DEBUG 8028 --- [nio-8181-exec-1] o.s.s.web.DefaultRedirectStrategy : Redirecting to http://localhost:8181/login
Updated LOGS are
2025-02-09T17:30:22.961+05:30 DEBUG 21040 --- [nio-8181-exec-3] o.s.security.web.FilterChainProxy : Securing POST /login
2025-02-09T17:30:23.071+05:30 DEBUG 21040 --- [nio-8181-exec-3] o.s.s.a.dao.DaoAuthenticationProvider : Authenticated user
2025-02-09T17:30:26.375+05:30 DEBUG 21040 --- [nio-8181-exec-3] o.s.s.web.DefaultRedirectStrategy : Redirecting to /
2025-02-09T17:30:26.382+05:30 DEBUG 21040 --- [nio-8181-exec-8] o.s.security.web.FilterChainProxy : Securing GET /
2025-02-09T17:30:26.383+05:30 DEBUG 21040 --- [nio-8181-exec-8] o.s.security.web.FilterChainProxy : Secured GET /
2025-02-09T17:30:26.383+05:30 DEBUG 21040 --- [nio-8181-exec-8] w.c.HttpSessionSecurityContextRepository : Retrieved SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [Username
It's able to authenticate the user as per debugging. I don't where I'm missing things.