Я создал этот фильтр для расшифровки имени пользователя и пароля, а затем Spring Boot может продолжить аутентификацию пользователя < /p>
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import jakarta.servlet.http.HttpServletRequest;
import com.example.demo.controller.HybridController;
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
public CustomAuthenticationFilter(AuthenticationManager authenticationManager) {
super.setAuthenticationManager(authenticationManager);
}
HybridController hybridController = new HybridController();
private String decrypt(String data) {
try {
return hybridController.Hybrid_Data_Decryption(data);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
@Override
protected String obtainPassword(HttpServletRequest request) {
String decPassword = decrypt(super.obtainPassword(request));
return decPassword;
}
@Override
protected String obtainUsername(HttpServletRequest request) {
String decUsername = decrypt(super.obtainUsername(request));
return decUsername;
}
}
< /code>
Я использую Spring Boot 3.2.4, и ее конфигурация выполняется следующим образом < /p>
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.header.writers.XXssProtectionHeaderWriter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@EnableWebSecurity
public class SpringSecurity {
@Bean
static PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
AuthSuccessHandler authSuccessHandler() {
return new AuthSuccessHandler();
}
@Bean
SecurityFilterChain filterChain(HttpSecurity http, AuthenticationManager authenticationManager)
throws Exception {
CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter(
authenticationManager);
http.addFilterBefore(customAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
http.addFilterBefore(new SessionCookieFilter(), UsernamePasswordAuthenticationFilter.class);
http
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/")
.permitAll()
.requestMatchers("/user/**").hasRole("USER"))
.formLogin(
form -> form
.loginPage("/login")
.loginProcessingUrl("/login")
.failureUrl("/login?error")
.successHandler(this.authSuccessHandler())
.permitAll())
.logout(
logout -> logout
.logoutRequestMatcher(
new AntPathRequestMatcher("/logout"))
.permitAll())
.sessionManagement(session -> session
.sessionFixation().newSession()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.maximumSessions(1));
return http.build();
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http,
CustomUsersDetailsService userDetailsService,
PasswordEncoder passwordEncoder) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder = http
.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
return authenticationManagerBuilder.build();
}
}
< /code>
Проблема заключается в том, что этот код способен расшифровать входящее имя пользователя и пароль, а пружина способна аутентифицировать пользователя, но вместо перенаправления на панель желаемой страницы он продолжает перенаправление на страницу входа в систему. < /p>
Вот несколько журналов для справки: < /p>
Securing POST /login
2025-02-09T15:20:54.055+05:30 DEBUG 8028 --- [nio-8181-exec-5] o.s.s.a.dao.DaoAuthenticationProvider : Authenticated user
2025-02-09T15:20:54.056+05:30 DEBUG 8028 --- [nio-8181-exec-5] o.s.s.web.DefaultRedirectStrategy : Redirecting to http://localhost:8181/error?continue
2025-02-09T15:20:54.063+05:30 DEBUG 8028 --- [nio-8181-exec-1] o.s.security.web.FilterChainProxy : Securing GET /error?continue
2025-02-09T15:20:54.065+05:30 DEBUG 8028 --- [nio-8181-exec-1] o.s.s.w.s.HttpSessionRequestCache : Loaded matching saved request http://localhost:8181/error?continue
2025-02-09T15:20:54.067+05:30 DEBUG 8028 --- [nio-8181-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2025-02-09T15:20:54.070+05:30 DEBUG 8028 --- [nio-8181-exec-1] o.s.s.w.s.HttpSessionRequestCache : Saved request http://localhost:8181/error?continue to session
2025-02-09T15:20:54.070+05:30 DEBUG 8028 --- [nio-8181-exec-1] o.s.s.web.DefaultRedirectStrategy : Redirecting to http://localhost:8181/login
Подробнее здесь: https://stackoverflow.com/questions/794 ... entication
Дешифруя имя пользователя и пароль перед аутентификацией Spring Boot Start Authentication ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Дешифруя имя пользователя и пароль перед аутентификацией Spring Boot Start Authentication
Anonymous » » в форуме JAVA - 0 Ответы
- 10 Просмотры
-
Последнее сообщение Anonymous
-