Пользовательский AuthenticationSuccessHandler Spring Security игнорируется, и я не могу войти в сеансJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Пользовательский AuthenticationSuccessHandler Spring Security игнорируется, и я не могу войти в сеанс

Сообщение Anonymous »

Я делаю простое приложение Spring Boot, но у меня проблема с сеансом. Я хотел бы установить «customerId», когда клиент входит в приложение, но это не работает, и мой идентификатор клиента всегда равен нулю. Вот мой код:
// Это моя безопасность

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

@Configuration
@EnableWebSecurity
public class SecurityConfig {

private final CustomerService customerService;
private final PasswordEncoder passwordencoder;
private final CustomAuthenticationSuccessHandler successHandler;

@Autowired
public SecurityConfig(CustomerService customerService, PasswordEncoder passwordencoder,
CustomAuthenticationSuccessHandler successHandler) {
this.customerService = customerService;
this.passwordencoder = passwordencoder;
this.successHandler = successHandler;
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http, CustomerRepositor customerRepository) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(authorize -> authorize
.anyRequest().permitAll()
)
.formLogin(form -> form
.loginPage("/api/login")
.successHandler(successHandler)
)
.httpBasic(Customizer.withDefaults())
.exceptionHandling(exception -> exception
.accessDeniedHandler((request, response, customAccessDeniedException) -> {
response.setStatus(403);
response.getWriter().write("Access denied! Sorry, you haven't got permission " +
"to access this page!");
})
)
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
);
return http.build();
}
@Bean
public AuthenticationManager authManager(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder =
http.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder
.userDetailsService(customerService)
.passwordEncoder(passwordencoder);
return authenticationManager Builder.build();
}

Может быть, метод не находит адрес электронной почты в моей базе данных?

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

 @Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler   {

private final CustomerRepository customerRepository;

@Autowired
public CustomAuthenticationSuccessHandler(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse    response, Authentication authentication) throws IOException, ServletException {
HttpSession session = request.getSession();

UserDetails userDetails = (UserDetails) authentication.getPrincipal();
Customer customer = customerRepository.findByEmail(userDetails.getUsername());
session.setAttribute("customerId", customer.getId());

response.sendRedirect("/api/login");
}
}
Я использую в PostMan способ входа в систему «Basic Auth».

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

@RestController
@RequestMapping("/api")
public class LoginController {

private final Logger log = LoggerFactory.getLogger(LoginController.class);

@GetMapping("/login")
public ResponseEntity getLoggedInUser(HttpSession session) {
Object customerId = session.getAttribute("customerId");
log.info("User has logged in");
return new ResponseEntity("CustomerId: " + customerId, HttpStatus.OK);
}
Запрос в моем репозитории:

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

@Repository
public interface CustomerRepository extends JpaRepository {

@Query("SELECT c FROM Customer c WHERE c.email = :email")
Customer findByEmail(@Param("email") String email);
Может ли кто-нибудь мне помочь?

Подробнее здесь: https://stackoverflow.com/questions/792 ... cant-set-i
Ответить

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

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

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

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

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