Custom Auth filter not being invoked in spring security

I have implement a custom authentication filter to log the user in and it's not being invoked when I try to hit the login endpoint using postman. here is the code for the CustomAuthFilter:
4 Replies
JavaBot
JavaBot8mo ago
This post has been reserved for your question.
Hey @Milk Packet! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
Milk Packet
Milk PacketOP8mo ago
@RequiredArgsConstructor
public class CustomAuthFilter extends UsernamePasswordAuthenticationFilter {
private final AuthenticationManager authenticationManager;

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
try {
LoginDTO userLoginRequest = new ObjectMapper().readValue(request.getInputStream(), LoginDTO.class);

String email = userLoginRequest.getEmail();
String password = userLoginRequest.getPassword();

if (email == null || email.isEmpty()) {
throw new AuthenticationServiceException("Invalid email");
}

if (password == null || password.isEmpty()) {
throw new AuthenticationServiceException("Password cannot be empty");
}

UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(email, password);
return authenticationManager.authenticate(authenticationToken);
} catch (IOException e) {
throw new AuthenticationServiceException("Failed to parse authentication request body", e);
}
}

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws ServletException, IOException {
UserDetails userDetails = (UserDetails) authResult.getPrincipal();

SecurityContextHolder.getContext().setAuthentication(authResult);

chain.doFilter(request, response);
}
}
@RequiredArgsConstructor
public class CustomAuthFilter extends UsernamePasswordAuthenticationFilter {
private final AuthenticationManager authenticationManager;

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
try {
LoginDTO userLoginRequest = new ObjectMapper().readValue(request.getInputStream(), LoginDTO.class);

String email = userLoginRequest.getEmail();
String password = userLoginRequest.getPassword();

if (email == null || email.isEmpty()) {
throw new AuthenticationServiceException("Invalid email");
}

if (password == null || password.isEmpty()) {
throw new AuthenticationServiceException("Password cannot be empty");
}

UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(email, password);
return authenticationManager.authenticate(authenticationToken);
} catch (IOException e) {
throw new AuthenticationServiceException("Failed to parse authentication request body", e);
}
}

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws ServletException, IOException {
UserDetails userDetails = (UserDetails) authResult.getPrincipal();

SecurityContextHolder.getContext().setAuthentication(authResult);

chain.doFilter(request, response);
}
}
this is the code and this is my security config
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfig {

// some code

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http, AuthenticationConfiguration authenticationConfiguration) throws Exception {
CustomAuthFilter customAuthFilter = new CustomAuthFilter(authenticationManager(authenticationConfiguration));

http
.cors(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(request ->
request.requestMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
)
// .formLogin(form ->
// form.loginPage("/api/auth/login")
// .loginProcessingUrl("/api/auth/login")
// .permitAll()
// )
.logout(logout ->
logout.logoutUrl("/api/auth/logout")
.logoutSuccessUrl("/api/auth/login")
.permitAll()
)
.sessionManagement(s ->
s.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.sessionFixation().migrateSession()
.invalidSessionUrl("/api/auth/login")
.sessionAuthenticationErrorUrl("/api/auth/login")
.maximumSessions(1)
.maxSessionsPreventsLogin(true)
.expiredUrl("/api/auth/login")
)
.addFilterBefore(customAuthFilter, UsernamePasswordAuthenticationFilter.class);

return http.build();
}

// some code
}
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfig {

// some code

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http, AuthenticationConfiguration authenticationConfiguration) throws Exception {
CustomAuthFilter customAuthFilter = new CustomAuthFilter(authenticationManager(authenticationConfiguration));

http
.cors(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(request ->
request.requestMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
)
// .formLogin(form ->
// form.loginPage("/api/auth/login")
// .loginProcessingUrl("/api/auth/login")
// .permitAll()
// )
.logout(logout ->
logout.logoutUrl("/api/auth/logout")
.logoutSuccessUrl("/api/auth/login")
.permitAll()
)
.sessionManagement(s ->
s.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.sessionFixation().migrateSession()
.invalidSessionUrl("/api/auth/login")
.sessionAuthenticationErrorUrl("/api/auth/login")
.maximumSessions(1)
.maxSessionsPreventsLogin(true)
.expiredUrl("/api/auth/login")
)
.addFilterBefore(customAuthFilter, UsernamePasswordAuthenticationFilter.class);

return http.build();
}

// some code
}
any help, please?
dan1st
dan1st8mo ago
Why are you using a filter instead of an AuthenticationProvider here?
JavaBot
JavaBot8mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.
Want results from more Discord servers?
Add your server