Пользователи могут получить доступ ко всем конечным точкам после установки antMachers в Spring Security. - PullRequest
0 голосов
/ 18 марта 2020

Я разрабатываю приложение для начальной загрузки, и его конфигурация безопасности для пружин выглядит следующим образом:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter  {
@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            .authorizeRequests()
            .antMatchers("/actuator/**", "/login*", "/logout*")
            .permitAll();

        httpSecurity
            .cors().and()
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/taas/v1/**").hasRole("admin")
            .antMatchers("/taas/v1/teams", "/taas/v1/profiles", "/taas/v1/tests/summary").hasRole("tester")
            .antMatchers( "/taas/v1/teams", "/taas/v1/tests/summary").hasRole("user")
            .anyRequest().authenticated()
            .and()
            .exceptionHandling().accessDeniedHandler(customAccessDeniedHandler)
            .and()
            .httpBasic()
            .and()
            .formLogin()
            .successHandler(customAuthenticationSuccessHandler)
            .failureHandler(customAuthenticationFailureHandler)
            .and()
            .logout()
                .logoutSuccessHandler(customLogoutSuccessHandler())
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID");
    }
}

Несмотря на то, что я установил шаблон URL для каждой роли. Все пользователи могут получить доступ ко всем конечным точкам, как указано в antMatchers (). Пользователь с ролью user не должен иметь доступ к /taas/v1/profiles. Но когда я пытаюсь получить доступ к этой конечной точке, войдя в систему как user, я получаю ответ, но ожидаемый ответ - 403 forbidden.

. Я прошу кого-нибудь предоставить мне обходной путь.

Ответы [ 2 ]

0 голосов
/ 26 марта 2020

Я решил эту проблему, внеся небольшие изменения в antMatchers (). Ниже приведен измененный код.

Основная проблема заключается в том, что шаблон antMatcher () не должен содержать путь к контексту, см. Не работает antMatcher безопасности Spring

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter  {
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {

        httpSecurity
            .cors()
                .and()
            .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/profiles").hasAnyRole("TESTER")
                .antMatchers( "/teams", "/tests/summary").hasAnyRole("USER", "TESTER", "ADMIN")
                .anyRequest().authenticated()
                .and().csrf().disable()
            .exceptionHandling()
                .accessDeniedHandler(customAccessDeniedHandler)
                .and()
            .httpBasic()
                .and()
            .formLogin()
                .successHandler(customAuthenticationSuccessHandler)
                .failureHandler(customAuthenticationFailureHandler)
                .and()
            .sessionManagement()
                .invalidSessionUrl("/invalidSession.html")
                .maximumSessions(1).sessionRegistry(sessionRegistry()).and()
                .sessionFixation().none()
                .and()
            .logout()
                .logoutSuccessHandler(customLogoutSuccessHandler())
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID");
    }
}

0 голосов
/ 18 марта 2020

Пожалуйста, подтвердите код, которым вы делитесь, потому что, как вы упомянули. user с ролью пользователь не должен иметь доступ к /ptaas/v1/profiles. Но когда я пытаюсь получить доступ к этой конечной точке, войдя в систему как пользователь.

Там, где ваше сопоставление говорит, что вы не настроили доступ к user role как дано.

.antMatchers( "/taas/v1/teams", "/taas/v1/tests/summary").hasRole("user")

Согласно вашим комментариям это должно было быть .antMatchers( "/taas/v1/teams", "/taas/v1/tests/summary", "/ptaas/v1/profiles").hasRole("user")

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