Pure Spring Security user authentication doesn’t work

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật