Spring Security продолжает запрашивать логин при использовании RequestParam - PullRequest
0 голосов
/ 08 апреля 2020

Я пытаюсь создать внутреннюю часть своего приложения, и я хочу использовать контроллеры отдыха и защитить их с помощью Spring Security. Это конфиг:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(corsConfigurationSource()).and().csrf().
                disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic();
    }

У меня также есть два контроллера:

@GetMapping(path = "/testOFWork")
    public AuthBean test() {
        System.out.println("worked");
        return new AuthBean("You are authenticated already");
    }

@GetMapping(path = "/getUserInfo")
    public User getInfo(@RequestParam(value = "username") String user) {
        return dao.getByUserName(user);
    }

Первый работает отлично. Когда я пытаюсь добраться до него: весна просит меня войти. Я делаю это, и он показывает мне сообщение. Но когда я пытаюсь добраться до второго, он просто спрашивает у меня логин. И если я пытаюсь go до первого, который работал отлично, он просит меня войти снова. Экспериментально я выяснил, что RequestParam вызывает эту проблему. Я понимаю, что проблема может быть в самой конфигурации, но я не могу ее получить.

Спасибо за ответ заранее! "

РЕДАКТИРОВАТЬ Вот полный класс конфигурации:

@Autowired
    UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(corsConfigurationSource()).and().csrf().
                disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic();
    }


    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        List<String> allowOrigins = Arrays.asList("*");
        configuration.setAllowedOrigins(allowOrigins);
        configuration.setAllowedMethods(singletonList("*"));
        configuration.setAllowedHeaders(singletonList("*"));
        //in case authentication is enabled this flag MUST be set, otherwise CORS requests will fail
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

1 Ответ

1 голос
/ 08 апреля 2020

Вы говорите своей весенней безопасности, чтобы проверить, аутентифицирован ли пользователь для любого запроса в .antMatchers (HttpMethod.OPTIONS, "/**").

РЕДАКТИРОВАТЬ

Ваш код должен выглядеть следующим образом:

 http.authorizeRequests()
          .antMatchers("/securityNone").permitAll()
          .anyRequest().authenticated()
          .and()
          .httpBasic()
          .authenticationEntryPoint(authenticationEntryPoint);

        http.addFilterAfter(new CustomFilter(),
          BasicAuthenticationFilter.class);

Вам необходимо отделить незащищенный доступ от защищенного

...