Невозможно пройти аутентификацию с помощью UsernameAndPasswordToken и установить Cook ie с помощью Spring Security - PullRequest
1 голос
/ 10 июля 2020

Я создаю приложение Spring Boot / ReactJS, и у меня возникает следующая проблема с аутентификацией пользователя и генерацией JSSESSIONID.

Мой класс SecurityConfig выглядит следующим образом:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder());
    }

    @Override
    @Bean(BeanIds.AUTHENTICATION_MANAGER)
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated()

                .and()
                .logout().deleteCookies("JSESSIONID")

                .and()
                .rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400)

                .and()
                .csrf().disable();
    }

    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder();}

}

И мой LoginController:

@RestController
@RequestMapping(path="/",produces = "application/json")
@CrossOrigin(origins="*")
public class LoginController {

    private final AuthenticationManager authenticationManager;

    public LoginController(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @PostMapping("/login")
    @ResponseStatus(HttpStatus.OK)
    public void login(HttpServletRequest req, @RequestBody LoginRequest loginRequest) {
        UsernamePasswordAuthenticationToken authReq
                = new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword());
        Authentication auth = authenticationManager.authenticate(authReq);

        SecurityContext sc = SecurityContextHolder.getContext();
        sc.setAuthentication(auth);
        HttpSession session = req.getSession(true);
        session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, sc);
    }

}

И когда я вызываю запрос, у меня возникает исключение BadCredentials при вызове authenticationManager.authenticate (authReq), потому что журнал содержимого authReq org.springframework.security.authentication. UsernamePasswordAuthenticationToken@6582813: Заказчик: Павел; Учетные данные: [ЗАЩИЩЕНО]; Проверено: ложь; Подробности: null; Нет прав доступа

Я пропустил здесь какую-то часть конфигурации?

...