Springboot не запускает пользовательскую аутентификацию для моего метода loaduserbyusernameJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Springboot не запускает пользовательскую аутентификацию для моего метода loaduserbyusername

Сообщение Anonymous »

Я реализовал механизм аутентификации для своего приложения.
Итак, если пользователь является администратором и указаны правильные имя пользователя и пароль, то пользователь должен пройти аутентификацию, и администратору должна быть отображена домашняя страница. Но в моем случае, даже если указаны правильные имя пользователя и пароль, даже в этом случае элемент управления перенаправляется на страницу входа, а не на домашнюю страницу.
Ниже приведены дополнительные сведения: -
Страница входа:-

Код: Выделить всё






Login & Registration Form | CoderGirl






Login



[url=#]Forgot password?[/url]



Don't have an account?
Signup




Signup







Already have an account?
Login






домашняя страница:-

Код: Выделить всё






Product Management




Welcome to the Product Management System

Add Product
Remove Product
Modify Product
View Product

[url=/logout]Logout[/url]



контроллер:-

Код: Выделить всё

@Controller
public class LoginController {

@Autowired
private UserService userService;

@Autowired
private CustomUserDetailsService customservice;

@Autowired
private PasswordEncoder passwordEncoder;

@GetMapping("/login")
public String loginPage() {
return "index"; // Render the login.html page
}

@GetMapping("/logout")
public String logoutPage() {
return "index";  // Render the logout.html page
}

@PostMapping("/home")
public String login(@RequestParam String username, @RequestParam String password) {
// Retrieve user from the database
System.out.println("login endpoint");
User user = userService.findByUsername(username);

Iterator iterator = user.getRoles().iterator();
while (iterator.hasNext()) {
Role fruit = iterator.next();
System.out.println(fruit.getRoleName());
}

if (user != null && passwordEncoder.matches(password, user.getPassword())) {
System.out.println("authentication complete");
return "home";  // Password matches, redirect to home
} else {
System.out.println("authentication incomplete");
return "index";  // Invalid login, return to login page
}
}
}
Это моя конфигурация безопасности:-

Код: Выделить всё

@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Autowired
private CustomUserDetailsService customUserDetailsService; // Inject the custom user details service

@Bean
public PasswordEncoder passwordEncoder() {
System.out.println("inside password encoder");
return new BCryptPasswordEncoder(); // Passwords should be hashed using BCrypt
}

@Bean
public DaoAuthenticationProvider authenticationProvider() {
System.out.println("inside authentication provider");
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(customUserDetailsService); // Use injected CustomUserDetailsService
authProvider.setPasswordEncoder(passwordEncoder()); // Set password encoder
return authProvider;
}

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
System.out.println("inside authentication manager");
return authenticationConfiguration.getAuthenticationManager();
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
System.out.println("inside securityFilterChain");
http
.authorizeHttpRequests()
.requestMatchers("/css/**", "/js/**", "/images/**", "/static/**").permitAll()
.requestMatchers("/login", "/register", "*.css").permitAll() // Public access to login and register
.requestMatchers("/add-product", "/modify-product", "/remove-product").hasRole("ADMIN") // Restrict product modification to ADMIN roles
.requestMatchers("/view-product").authenticated() // Requires users to be authenticated
.anyRequest().authenticated() // All other requests need to be authenticated
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home", true) // Redirect to home after login
.failureUrl("/login")
.and()
.logout()
.logoutSuccessUrl("/logout") // Redirect after logout
.permitAll()
.and()
.sessionManagement() // Configure session management
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) // Default policy
.maximumSessions(1) // Limit the number of concurrent sessions per user
.expiredUrl("/login?expired") // Redirect to login page if session expires
.and()
.and()
.csrf().disable(); // Disable CSRF for non-browser clients or API access

return http.build();
}
}
пользовательский сервис сведений о пользователе:-

Код: Выделить всё

@Service
public class CustomUserDetailsService implements UserDetailsService {

@Autowired
private UserRepository userRepository;

public CustomUserDetailsService() {
System.out.println("CustomUserDetailsService has been initialized.");
}

// Map roles to authorities, adding 'ROLE_' prefix
private Collection

Подробнее здесь: [url]https://stackoverflow.com/questions/79128771/springboot-not-triggering-custom-authentication-for-my-loaduserbyusername-method[/url]
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»