Я изучаю Spring и изучаю традиционную аутентификацию пользователя/пароля с помощью Spring Security.
В настоящее время я использую собственную страницу входа. В моем контроллере я могу проверять учетные данные пользователей с помощью моего userService.
Фрагмент LoginController:
/**
* Displays the login page.
*
* This method is invoked when a user requests the login page. It initializes
* the login form and adds it to the model.
*
*
* @param model the model to be used in the view.
* @return the name of the login view (Thymeleaf template).
*/
@GetMapping("/login")
public String loginGet(Model model) {
log.info("loginGet: Get login page");
model.addAttribute("loginForm", new LoginForm());
return "login";
}
/**
* Processes the login form submission.
*
* This method handles POST requests when a user submits the login form. It checks
* the validity of the submitted form and validates the user's credentials.
* On success, it redirects to the search page; on failure, it reloads the login page with an error.
*
*
* @param loginForm the login form submitted by the user.
* @param result the result of the form validation.
* @param attrs attributes to be passed to the redirect.
* @param httpSession the HTTP session for storing the authenticated user.
* @param model the model to add error messages, if necessary.
* @return the name of the view to render.
*/
@PostMapping("/login")
public String loginPost(@Valid @ModelAttribute LoginForm loginForm, BindingResult result,
RedirectAttributes attrs, HttpSession httpSession, Model model) {
log.info("loginPost: User '{}' attempted login", loginForm.getUsername());
// Check for validation errors in the form submission
if (result.hasErrors()) {
log.info("loginPost: Validation errors: {}", result.getAllErrors());
return "login";
}
// Validate the username and password
if (!loginService.validateUser(loginForm.getUsername(), loginForm.getPassword())) {
log.info("loginPost: Username and password don't match for user '{}'", loginForm.getUsername());
model.addAttribute("errorMessage", "That username and password don't match.");
return "login"; // Reload the form with an error message
}
// If validation is successful, retrieve the user and set the session
User foundUser = userService.getUser(loginForm.getUsername());
attrs.addAttribute("username", foundUser.getUsername());
httpSession.setAttribute("currentUser", foundUser);
log.info("loginPost: User '{}' logged in", foundUser.getUsername());
return "redirect:/search"; // Redirect to the search page after successful login
}
Однако, когда пользователь перенаправляется на страницу поиска, выдается ошибка 403, поскольку у пользователя нет доступа к странице поиска. Я думал, что мой класс SecurityConfig настроен правильно, где пользователь, не вошедший в систему, может получить доступ к страницам входа и регистрации, но все остальные страницы могут просматриваться только вошедшими в систему пользователями.
SecurityConfig :
@Configuration
@EnableWebSecurity
public class SecurityConfig {
private final CustomUserDetailsService userDetailsService;
public SecurityConfig(final CustomUserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
/**
* Bean for password encoding using BCrypt.
*
* @return a BCryptPasswordEncoder instance for encoding passwords.
*/
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* Configures the security filter chain for the application.
*
* @param http the HttpSecurity object to configure.
* @return the configured SecurityFilterChain.
* @throws Exception if an error occurs while configuring the security settings.
*/
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers(
"/",
"/login",
"/register",
"/js/**",
"/css/**",
"/images/**").permitAll()
.anyRequest().authenticated());
http.logout(lOut -> {
lOut.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login?logout")
.permitAll();
});
http.csrf().disable();
return http.build();
}
@Bean
public AuthenticationManager authManager(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder =
http.getSharedObject(AuthenticationManagerBuilder.class);
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationManagerBuilder.authenticationProvider(authenticationProvider);
return authenticationManagerBuilder.build();
}
}
CustomUserDetailsService:
@Service
public class CustomUserDetailsService implements UserDetailsService {
private static final Logger log = LoggerFactory.getLogger(CustomUserDetailsService.class);
private final UserRepository userRepository;
public CustomUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
log.info("loadUserByUsername: username={}", username);
final List user = userRepository.findByUsernameIgnoreCase(username);
if(user.size() != 1) {
throw new UsernameNotFoundException("User not found");
}
return new CustomUserDetails(user.getFirst());
}
}
CustomUserDetails:
public record CustomUserDetails(User user) implements UserDetails {
@Override
public Collection
Подробнее здесь: https://stackoverflow.com/questions/791 ... rity-login
Все еще получаю ошибку 403 после входа в систему Spring Security ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение