I have a very simple pure Spring web application with a login page (and it shouldn’t use SpringBoot). I would like to authenticate the user and after that the user could go forward to its appropriate page.
I try to read the written material about these things and watch videos but I’m just stuck here.
My SecurityConfig file looks like this:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final CustomUserDetailsService userDetailsService;
public SecurityConfig(CustomUserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/users/add_or_edit", "/users/delete").hasRole("Admin")
.antMatchers("/auth/home").hasAnyRole("Admin", "User")
.antMatchers("/", "/auth/login", "/auth/logout", "/register", "/error").permitAll()
.anyRequest().authenticated()
.and()
.csrf().ignoringAntMatchers("/auth/login")
.and().formLogin()
.loginPage("/auth/login")
.loginProcessingUrl("/auth/login") // Ensure this is correctly set
.defaultSuccessUrl("/auth/home", true)
.failureUrl("/auth/login?error")
.permitAll();
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
The important part of AuthController looks like this:
@Controller
@RequestMapping("/auth")
public class AuthController {
private final AuthenticationManager authenticationManager;
private final CustomUserDetailsService customUserDetailsService;
public AuthController(AuthenticationManager authenticationManager, CustomUserDetailsService customUserDetailsService) {
this.authenticationManager = authenticationManager;
this.customUserDetailsService = customUserDetailsService;
}
@GetMapping("/login")
public String showLoginPage() {
return LOGIN;
}
@PostMapping("/login")
public String handleLogin(@RequestParam(LOGIN) String login,
@RequestParam(PASSWORD) String password,
HttpSession session) {
try {
CustomUserDetails userDetails = (CustomUserDetails) customUserDetailsService.loadUserByUsername(login);
if (userDetails == null) {
throw new UsernameNotFoundException("User not found");
}
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(login, password, userDetails.getAuthorities());
Authentication authentication = authenticationManager.authenticate(authToken);
if (authentication == null) {
throw new AuthenticationException("Authentication failed") {
};
}
SecurityContextHolder.getContext().setAuthentication(authentication);
session.setAttribute(USER, userDetails.getUser());
return "redirect:/auth/home";
} catch (Exception e) {
logger.error(e.getMessage(), e);
session.setAttribute(ERROR_MESSAGE, "Login or Password is not appropriate. Please try it again.");
return LOGIN;
}
}
I have this class:
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
It doesn’t even reach the @PostMapping part. Do you have any idea what the problem could be?
This is the error log what I get when I push ‘Ok’ on the login page:
application | 2024-07-16 14:27:54 DEBUG FilterChainProxy:208 - Securing GET /index.jsp
application | 2024-07-16 14:27:54 DEBUG SecurityContextPersistenceFilter:104 - Set SecurityContextHolder to empty SecurityContext
application | 2024-07-16 14:27:54 DEBUG AnonymousAuthenticationFilter:100 - Set SecurityContextHolder to anonymous SecurityContext
application | 2024-07-16 14:27:54 DEBUG SessionManagementFilter:116 - Request requested invalid session id 49F7335CADDDB9828458FF2A20D4ADF6
application | 2024-07-16 14:27:54 DEBUG FilterSecurityInterceptor:247 - Failed to authorize filter invocation [GET /index.jsp] with attributes [authenticated]
application | 2024-07-16 14:27:54 DEBUG HttpSessionRequestCache:75 - Saved request http://localhost:8080/ to session
application | 2024-07-16 14:27:54 DEBUG DefaultRedirectStrategy:57 - Redirecting to http://localhost:8080/auth/login
application | 2024-07-16 14:27:54 DEBUG HttpSessionSecurityContextRepository:357 - Did not store empty SecurityContext
application | 2024-07-16 14:27:54 DEBUG HttpSessionSecurityContextRepository:357 - Did not store empty SecurityContext
application | 2024-07-16 14:27:54 DEBUG SecurityContextPersistenceFilter:120 - Cleared SecurityContextHolder to complete request
application | 2024-07-16 14:27:54 DEBUG FilterChainProxy:208 - Securing GET /auth/login
application | 2024-07-16 14:27:54 DEBUG SecurityContextPersistenceFilter:104 - Set SecurityContextHolder to empty SecurityContext
application | 2024-07-16 14:27:54 DEBUG AnonymousAuthenticationFilter:100 - Set SecurityContextHolder to anonymous SecurityContext
application | 2024-07-16 14:27:54 DEBUG FilterSecurityInterceptor:210 - Authorized filter invocation [GET /auth/login] with attributes [permitAll]
application | 2024-07-16 14:27:54 DEBUG FilterChainProxy:323 - Secured GET /auth/login
application | 2024-07-16 14:27:54 DEBUG DispatcherServlet:119 - GET "/auth/login", parameters={}
application | 2024-07-16 14:27:54 DEBUG RequestMappingHandlerMapping:522 - Mapped to com.example.spring.controller.AuthController#showLoginPage()
application | 2024-07-16 14:27:54 DEBUG JstlView:309 - View name 'login', model {}
application | 2024-07-16 14:27:54 DEBUG JstlView:169 - Forwarding to [/WEB-INF/views/login.jsp]
application | 2024-07-16 14:27:55 DEBUG HttpSessionSecurityContextRepository:360 - Did not store anonymous SecurityContext
application | 2024-07-16 14:27:55 DEBUG DispatcherServlet:1131 - Completed 200 OK
application | 2024-07-16 14:27:55 DEBUG HttpSessionSecurityContextRepository:360 - Did not store anonymous SecurityContext
application | 2024-07-16 14:27:55 DEBUG SecurityContextPersistenceFilter:120 - Cleared SecurityContextHolder to complete request
application | 2024-07-16 14:27:58 DEBUG FilterChainProxy:208 - Securing POST /auth/login
application | 2024-07-16 14:27:58 DEBUG SecurityContextPersistenceFilter:104 - Set SecurityContextHolder to empty SecurityContext
application | Hibernate: select user0_.id as id1_1_, user0_.birthday as birthday2_1_, user0_.email as email3_1_, user0_.first_name as first_na4_1_, user0_.last_name as last_nam5_1_, user0_.login as login6_1_, user0_.pass as pass7_1_, user0_.role_id as role_id8_1_ from users user0_ where user0_.login=?
application | 2024-07-16 14:27:58 DEBUG DaoAuthenticationProvider:136 - Failed to find user ''
application | 2024-07-16 14:27:58 DEBUG DefaultRedirectStrategy:57 - Redirecting to /auth/login?error
application | 2024-07-16 14:27:58 DEBUG HttpSessionSecurityContextRepository:357 - Did not store empty SecurityContext
application | 2024-07-16 14:27:58 DEBUG HttpSessionSecurityContextRepository:357 - Did not store empty SecurityContext
application | 2024-07-16 14:27:58 DEBUG SecurityContextPersistenceFilter:120 - Cleared SecurityContextHolder to complete request
application | 2024-07-16 14:27:58 DEBUG FilterChainProxy:208 - Securing GET /auth/login?error
application | 2024-07-16 14:27:58 DEBUG SecurityContextPersistenceFilter:104 - Set SecurityContextHolder to empty SecurityContext
application | 2024-07-16 14:27:58 DEBUG AnonymousAuthenticationFilter:100 - Set SecurityContextHolder to anonymous SecurityContext
application | 2024-07-16 14:27:58 DEBUG FilterSecurityInterceptor:210 - Authorized filter invocation [GET /auth/login?error] with attributes [permitAll]
application | 2024-07-16 14:27:58 DEBUG FilterChainProxy:323 - Secured GET /auth/login?error
application | 2024-07-16 14:27:58 DEBUG DispatcherServlet:119 - GET "/auth/login?error", parameters={masked}
application | 2024-07-16 14:27:58 DEBUG RequestMappingHandlerMapping:522 - Mapped to com.example.spring.controller.AuthController#showLoginPage()
application | 2024-07-16 14:27:58 DEBUG JstlView:309 - View name 'login', model {}
application | 2024-07-16 14:27:58 DEBUG JstlView:169 - Forwarding to [/WEB-INF/views/login.jsp]
application | 2024-07-16 14:27:58 DEBUG HttpSessionSecurityContextRepository:360 - Did not store anonymous SecurityContext
application | 2024-07-16 14:27:58 DEBUG DispatcherServlet:1131 - Completed 200 OK
application | 2024-07-16 14:27:58 DEBUG HttpSessionSecurityContextRepository:360 - Did not store anonymous SecurityContext
application | 2024-07-16 14:27:58 DEBUG SecurityContextPersistenceFilter:120 - Cleared SecurityContextHolder to complete request
WebSecurityConfigurerAdapter used only because I’m a very-very beginner and that was the one which seemed to start to work, just a little bit.
If I can provide anything that could be useful in the solution, please let me know.
7
So apologies, everybody. I’m still very bad at this but the problem was this part at the configure method: .loginPage(“/auth/login”)
If I understand correctly, it triggers the DaoAuthenticationProvider to try to authenticate the user but there it won’t have any information about the user.
After removing that part, it seems to work correctly. There are other problems in my code but those seems to be correctable easier.