весенний метод защиты http.formLogin.loginPage не будет перехватывать POST-запрос с сервера реагировать на js 3000 - PullRequest
0 голосов
/ 25 сентября 2019
 protected void configure(HttpSecurity http) throws Exception {
    http
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .csrf().disable()
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("login/")
                .usernameParameter("email")
                .permitAll()
            .and()
            .logout()
                .logoutSuccessHandler(new LogoutController())
                .logoutUrl("/secure_api_v1/accounts/sign_out")
            .and()
            .addFilterAfter(new AuthTokenFilter(new AntPathRequestMatcher("secure_api_v1/**"), customUserDetailsService), UsernamePasswordAuthenticationFilter.class);
}

вот мой конфиг безопасности ... я пытаюсь подключить мой интерфейс реагирования js к обработчику входа в Spring Security, но он перенаправляет меня на 127.0.0.1:8080/login, но, так как это проект реагирования js, он работаетна порту 3000, и я должен перенаправить на 127.0.0.1:3000/login или оставить перенаправление, чтобы реагировать сам JS ... но я не знаю, как это сделать здесь весной (

вот как мой контроллер входа в системунастроено:

@RestController
@RequestMapping("/secure_api_v1/accounts/sign_in")
public class LoginController {

    private final AuthenticationManager authenticationManager;

    private final UserRepo userRepo;
    private final PasswordEncoder passwordEncoder;
    private final CustomUserDetailsService customUserDetailsService;

    public LoginController(CustomUserDetailsService customUserDetailsService, AuthenticationManager authenticationManager, PasswordEncoder passwordEncoder, UserRepo userRepo) {
        this.customUserDetailsService = customUserDetailsService;
        this.authenticationManager = authenticationManager;
        this.passwordEncoder = passwordEncoder;
        this.userRepo = userRepo;
    }

    @PostMapping
    public ResponseEntity<JsonResponse> authenticate(AuthentificationRequest authenticationRequest, HttpServletResponse response, HttpServletRequest request) {
        try {
            String username = authenticationRequest.getEmail();
            String password = authenticationRequest.getPassword();

            GenerateToken tokenGenerator = new GenerateToken(passwordEncoder, customUserDetailsService);
            String token = tokenGenerator.getToken(username, password);
            TokenAuthentication authentication = new TokenAuthentication(token);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            Cookie cookie = new Cookie("csrftoken", token);
            cookie.setMaxAge(7 * 24 * 60 * 60);
            cookie.setHttpOnly(true);
            cookie.setPath("/");
//            cookie.setSecure(true);
            response.addCookie(cookie);
            UserDetails userDetails = this.customUserDetailsService.loadUserByUsername(username);
            User user = (User) userDetails;
            user.setToken(token);
            userRepo.save(user);
            List<String> roles = new ArrayList<String>();

            for (GrantedAuthority authority : userDetails.getAuthorities()) {
                roles.add(authority.toString());
            }

            return new ResponseEntity<>(new JsonResponse(true, "Пользователь успешно вошел"), HttpStatus.OK);

        } catch (BadCredentialsException bce) {
            return new ResponseEntity<>(new JsonResponse(false, "Пользователь не найден"), HttpStatus.UNPROCESSABLE_ENTITY);

        } catch (Exception e) {
            return new ResponseEntity<>(new JsonResponse(false, "Ошибка"),HttpStatus.EXPECTATION_FAILED);
        }

    }

}
...