Spring Security:使用 Hibernate 和 Spring Data JPA 查找用户进行身份验证

问题描述 投票:0回答:1

我是 Spring Boot/Security 的初学者。我在使用自定义登录页面从 MySQL 数据库获取用户进行身份验证时遇到问题。

我已经配置了自定义 UserDetailsService 类,并且我很确定我与 SecurityConfig 类的映射有效,但每次我尝试使用数据库中的现有用户登录时,DEBUG 日志记录错误总是显示“找不到用户” '这是调试消息:

Hibernate: select u1_0.id,u1_0.email,u1_0.full_name,u1_0.password from user_info_table u1_0 where     u1_0.email=?
2024-04-08T17:36:56.795-04:00 DEBUG 28416 --- [Finance_Tracker] [io-8080-exec-10] o.s.s.a.dao.DaoAuthenticationProvider    : Failed to find user ''

它总是让我回到我的login.html页面,因为它从不进行身份验证,但我希望它重定向到我的仪表板页面。请帮忙,我真的很感激。谢谢!

安全配置类别:

    @EnableWebSecurity
    @Configuration
    public class SecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return new UserInfoUserDetailsService();
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider dao = new DaoAuthenticationProvider();
        dao.setUserDetailsService(userDetailsService());
        dao.setPasswordEncoder(passwordEncoder());
        return dao;
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests( authorization -> authorization
                        .requestMatchers("/welcome", "/register", "/login").permitAll()
                        .requestMatchers("/welcome/**").authenticated()
                )
                .formLogin( login -> login
                        .loginPage("/login")
                        .defaultSuccessUrl("/dashboard", true)
                        .permitAll()
                );

        return http.build();
    }

}

自定义用户详细信息-服务类别

@Component
public class UserInfoUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;
    private static final Logger logger = LoggerFactory.getLogger(UserInfoUserDetailsService.class);


    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        logger.debug("Attempting to load user by email: {}", email);

        User user = userRepository.findByEmail(email)
                .orElseThrow(() -> new UsernameNotFoundException("No user found with email: " + email));

        return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(),
                Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));
    }
}

用户模型类别:

@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
@Table(name = "user_info_table")
public class User {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    private Long id;

    @Column(name = "full_name")
    private String fullName;

    @Column(name = "email")
    private String email;

    @Column(name = "password")
    private String password;

}

用户控制器

@Controller
public class UserController {

    private UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/welcome")
    public String displayWelcomePage() {
        return "welcome";
    }

    @GetMapping("/register")
    public String displayRegistrationPage() {
        return "registration";
    }

    @PostMapping("/register")
    public String registerUserToDatabase(@ModelAttribute User user, 
RedirectAttributes redirect) {
        userService.saveUser(user);
        redirect.addFlashAttribute("successMessage", "Successful Registration!");
        return "redirect:/login";
    }

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @GetMapping("/dashboard")
    public String displayDashboardPage() {
         return "dashboard";
     }
 }
04-09T14:40:45.533-04:00 DEBUG 21460 --- [Finance_Tracker] [nio-8080-exec-7] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-04-09T14:40:54.251-04:00 DEBUG 21460 --- [Finance_Tracker] [nio-8080-exec-8] o.s.security.web.FilterChainProxy        : Securing POST /login
Hibernate: select u1_0.id,u1_0.email,u1_0.full_name,u1_0.password from user_info_table u1_0 where u1_0.email=?
2024-04-09T14:40:55.090-04:00 DEBUG 21460 --- [Finance_Tracker] [nio-8080-exec-8] o.s.s.a.dao.DaoAuthenticationProvider    : Failed to find user ''
2024-04-09T14:40:55.090-04:00 DEBUG 21460 --- [Finance_Tracker] [nio-8080-exec-8] o.s.s.web.DefaultRedirectStrategy        : Redirecting to /login?error
2024-04-09T14:40:55.102-04:00 DEBUG 21460 --- [Finance_Tracker] [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : Securing GET /login?error
2024-04-09T14:40:55.102-04:00 DEBUG 21460 --- [Finance_Tracker] [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : Secured GET /login?error
2024-04-09T14:40:55.102-04:00 DEBUG 21460 --- [Finance_Tracker] [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet        : GET "/login?error", parameters={masked}
2024-04-09T14:40:55.102-04:00 DEBUG 21460 --- [Finance_Tracker] [nio-8080-exec-9] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.diazdevin.finance_tracker.controller.UserController#loginPage()
2024-04-09T14:40:55.102-04:00 DEBUG 21460 --- [Finance_Tracker] [nio-8080-exec-9] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, application/xhtml+xml, image/avif, image/webp, image/apng, application/xml;q=0.9, */*;q=0.8]
2024-04-09T14:40:55.106-04:00 DEBUG 21460 --- [Finance_Tracker] [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet        : Completed 200 OK
2024-04-09T14:40:55.106-04:00 DEBUG 21460 --- [Finance_Tracker] [nio-8080-exec-9] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-04-09T14:40:55.200-04:00 DEBUG 21460 --- [Finance_Tracker] [io-8080-exec-10] o.s.security.web.FilterChainProxy        : Securing GET /favicon.ico
2024-04-09T14:40:55.205-04:00 DEBUG 21460 --- [Finance_Tracker] [io-8080-exec-10] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-04-09T14:40:55.206-04:00 DEBUG 21460 --- [Finance_Tracker] [io-8080-exec-10] o.s.s.web.DefaultRedirectStrategy        : Redirecting to http://localhost:8080/login
2024-04-09T14:40:55.215-04:00 DEBUG 21460 --- [Finance_Tracker] [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : Securing GET /login
2024-04-09T14:40:55.215-04:00 DEBUG 21460 --- [Finance_Tracker] [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : Secured GET /login
2024-04-09T14:40:55.215-04:00 DEBUG 21460 --- [Finance_Tracker] [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : GET "/login", parameters={}
2024-04-09T14:40:55.215-04:00 DEBUG 21460 --- [Finance_Tracker] [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.diazdevin.finance_tracker.controller.UserController#loginPage()
2024-04-09T14:40:55.215-04:00 DEBUG 21460 --- [Finance_Tracker] [nio-8080-exec-1] o.s.w.s.v.ContentNegotiatingViewResolver : Selected '*/*' given [image/avif, image/webp, image/apng, image/svg+xml, image/*, */*;q=0.8]
2024-04-09T14:40:55.215-04:00 DEBUG 21460 --- [Finance_Tracker] [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed 200 OK
2024-04-09T14:40:55.215-04:00 DEBUG 21460 --- [Finance_Tracker] [nio-8080-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext

登录页面视图

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login Form</title>
</head>
<body>

    <div th:if="${successMessage}">
        <p th:text="${successMessage}" style="color:green"></p>
    </div>

<form th:action="@{/login}" method="get">
    <input type="text" name="email" placeholder="ENTER EMAIL: : " required>
    <input type="text" name="password" placeholder="ENTER PASSWORD: " required>

    <button type="submit">LOGIN</button>
</form>
</body>
</html>

新日志

2024-04-09T18:02:12.054-04:00 DEBUG 29216 --- [Finance_Tracker] [nio-8080-exec-8] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-04-09T18:02:18.959-04:00 DEBUG 29216 --- [Finance_Tracker] [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : Securing GET /login?email=steve7%40gmail.com&password=apple
2024-04-09T18:02:18.972-04:00 DEBUG 29216 --- [Finance_Tracker] [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : Secured GET /login?email=steve7%40gmail.com&password=apple
2024-04-09T18:02:18.980-04:00 DEBUG 29216 --- [Finance_Tracker] [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : GET "/login?email=steve7%40gmail.com&password=apple", parameters={masked}
2024-04-09T18:02:18.980-04:00 DEBUG 29216 --- [Finance_Tracker] [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.diazdevin.finance_tracker.controller.UserController#loginPage()
2024-04-09T18:02:18.980-04:00 DEBUG 29216 --- [Finance_Tracker] [nio-8080-exec-3] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, application/xhtml+xml, image/avif, image/webp, image/apng, application/xml;q=0.9, */*;q=0.8]
2024-04-09T18:02:18.980-04:00 DEBUG 29216 --- [Finance_Tracker] [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Completed 200 OK
2024-04-09T18:02:18.980-04:00 DEBUG 29216 --- [Finance_Tracker] [nio-8080-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-04-09T18:02:19.048-04:00 DEBUG 29216 --- [Finance_Tracker] [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Securing GET /favicon.ico
2024-04-09T18:02:19.048-04:00 DEBUG 29216 --- [Finance_Tracker] [nio-8080-exec-2] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-04-09T18:02:19.048-04:00 DEBUG 29216 --- [Finance_Tracker] [nio-8080-exec-2] o.s.s.web.DefaultRedirectStrategy        : Redirecting to http://localhost:8080/login

network logs

image 1

image 2

post request image

spring-boot spring-mvc spring-security spring-data-jpa basic-authentication
1个回答
0
投票

我也遇到同样的问题,你解决了吗,告诉我你是怎么解决的?

© www.soinside.com 2019 - 2024. All rights reserved.