Spring Security antMatcher с HttpMethod.POST не работает - PullRequest
0 голосов
/ 25 января 2020

Редактировать:

Thx Томас Андольф! Это работает, когда я использую встроенный tomcat в Springboot Spring, который я запустил на IntelliJ и в части angular с визуальным студийным кодом. Но это не работает, когда я публикую sh войну с предоставленным котом на моем Raspberry Pi ...

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests(authorizeRequests ->
                        authorizeRequests.antMatchers(HttpMethod.POST, "/rest/gender").permitAll()
                        .antMatchers(HttpMethod.POST, "/rest/login").permitAll()
                        .antMatchers(HttpMethod.POST, "/rest/names").permitAll()
                        .anyRequest().authenticated()
                )
                .httpBasic()
                .authenticationEntryPoint(authEntryPoint)
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

Часть проекта angular опубликована в tomcat/webapps/ROOT.
Война опубликована в tomcat/webapps/baby-project-api.

Я использую tomcat/conf/Catalina/localhost/rewrite.config следующим образом:

RewriteRule ^/rest/(.+)$ /baby-project-api/rest/$1

Оригинальный вопрос

Я пытаюсь использовать Basi c Аутентификация на API с безопасностью весенней загрузки и мне нужно, чтобы какой-то путь не был защищен.

POST /rest/login не защищен с помощью конфигурации,
GET /rest/gender защищен, и это то, что я хочу

Любая идея, почему POST / остальные / пол все еще защищены?

Есть мой WebSecurityConfig:

@Configuration
@EnableAutoConfiguration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationEntryPoint authEntryPoint;

    @Autowired
    private IParentRepository parentRepository;

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.POST, "/rest/gender").permitAll()
                .antMatchers(HttpMethod.POST, "/rest/login").permitAll()
                .antMatchers(HttpMethod.POST, "/rest/names").permitAll()
                .anyRequest().authenticated()
                .and().httpBasic()
                .authenticationEntryPoint(authEntryPoint);
                //.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        final List<Parent> parents = parentRepository.findAll();
        InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> mngConfig = auth.inMemoryAuthentication();

        for (Parent parent : parents) {
            mngConfig.withUser(User.withUsername(parent.getUsername()).password(parent.getPassword()).roles("ADMIN").build());
        }

    }
}```

POST /rest/login is not secured with the config,  
GET /rest/gender is secured and that's what i want

Any idea why POST /rest/gender is still secured ?

Ответы [ 2 ]

2 голосов
/ 25 января 2020

Вы можете попробовать сделать так, как они это делают в документации и посмотреть, работает ли она.

protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests(authorizeRequests -> 
                authorizeRequests.antMatchers(HttpMethod.POST, "/rest/gender").permitAll();
                authorizeRequests.antMatchers(HttpMethod.POST, "/rest/login").permitAll();
                authorizeRequests.antMatchers(HttpMethod.POST, "/rest/names").permitAll();
                authorizeRequests.anyRequest().authenticated();
            )
            .httpBasic()
            .authenticationEntryPoint(authEntryPoint);
}
0 голосов
/ 05 февраля 2020

В конце концов, я не нашел хорошего решения таким способом.

Я открываю все API и ограничил некоторые части с предварительной авторизацией:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .anyRequest().permitAll()
            .and().httpBasic()
            .authenticationEntryPoint(authEntryPoint)
            .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

И на контроллере :

@RestController
@PreAuthorize("isAuthenticated()")
@RequestMapping("/rest/gender")
public class GenderController {

[...]
// protected by the @ on the class
@GetMapping(value = "")
    public List<Gender> listerGender(final SecurityContextHolderAwareRequestWrapper request){
        return genderService.listerGender(request);
    }

 @PreAuthorize("permitAll()")
    @PostMapping(value = "", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Void> creerGender(@Valid @RequestBody Gender gender){
        return this.genderService.creerGender(gender);
    }

Я думаю, мы можем сделать это чище, но, по крайней мере, это работает

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...