Spring Boot - Specifi c URL-адрес AccessDecisionVoter - PullRequest
0 голосов
/ 30 апреля 2020

Я хочу применить указанные c правила безопасности к 2 URL-адресам в моем приложении Spring Boot.

Я хочу использовать AccessDecisionVoter для управления этим.
Все работает хорошо ... событие слишком хорошо.

Мои новые правила применяются к моим 2 указанным c URL, но, к сожалению, к всем моим URL .

Мой AccessDecisionManager Объявление:

    @Bean
    public AccessDecisionManager playerResourceDecisionManager() {
        List<AccessDecisionVoter<? extends Object>> decisionVoters = Arrays.asList(
            new AuthenticatedVoter(),
            hashSerialSecurityVoter
        );
        return new UnanimousBased(decisionVoters);
    }

Вот мой SecurityConfig основной код

        http.csrf()
        .disable().cors().and().exceptionHandling()
        // All Login Stuff
        .authenticationEntryPoint(new Http403ForbiddenEntryPoint() {})
            .and().authenticationProvider(getProvider())
                .formLogin().loginProcessingUrl("/login")
                    .successHandler(new AuthentificationLoginSuccessHandler())
                    .failureHandler(new SimpleUrlAuthenticationFailureHandler())
            .and().logout().logoutUrl("/logout")
                .logoutSuccessHandler(new AuthentificationLogoutSuccessHandler())
                .invalidateHttpSession(true).and().authorizeRequests()

         ...
        // Spring boot actuator - App Status
        .antMatchers("/actuator/*").permitAll()

        // Static Token end points
        .antMatchers("/my-filtered-url1", "/sub/my-filtered-url2/*")
            .permitAll()
            .accessDecisionManager(playerResourceDecisionManager())
            /* Here is the problem : 
             *   I want this accessDescisionManager apply only on my antMatchers
             *    (2 specific URLs), 
             * But it runs on every app calls.
             */

        .antMatchers(HttpMethod.POST, "/log/*").permitAll() 
        /* Login */
        .antMatchers("/login").permitAll()
        .antMatchers("/auth/**").permitAll()
        .antMatchers(HttpMethod.POST,"/user/lost-password").permitAll()

        .antMatchers("/user").hasAuthority("ADMIN")

        .anyRequest().authenticated();


Я бы предпочел не указывать указанный c код в моем hashSerialSecurityVoter классе с объявлением URL. Как я могу это сделать?

С уважением.

1 Ответ

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

Настройка конфигурации безопасности работает следующим образом:

  • http - это строитель (тип HttpSecurity).

  • Когда вы Позвоните authorizeRequests(), это даст вам 2-го строителя (ExpressionInterceptUrlRegistry).

  • Когда вы позвоните antMatchers(), это даст вам третьего строителя (AuthorizedUrl).

  • Когда вы звоните permitAll(), он возвращает вас второму строителю.

Это означает, что вы звоните accessDecisionManager() на *Registry строитель, а не AuthorizedUrl строитель, то есть вызов является глобальным, не связанным с сопоставителем.

Ваши отступы неверны, и поэтому вы запутались:

    .antMatchers("/my-filtered-url1", "/sub/my-filtered-url2/*")
        .permitAll()
    .accessDecisionManager(playerResourceDecisionManager())

Доступ Менеджер и его основные избиратели не несут ответственности за указание, какие правила доступа должны применяться к конкретному URL-адресу, что является заданием выражения доступа , примененного к AuthorizedUrl, например

  • permitAll() - сокращение от access("permitAll")

  • authenticated() - сокращение от access("authenticated")

  • hasRole("ADMIN") - сокращение от access("hasRole('ROLE_ADMIN')")

  • * 106 2 *hasAuthority("HASHSERIAL") - Сокращение от access("hasAuthority('HASHSERIAL')")
  • . , .

Итак, если вы хотите, чтобы пользовательский AccessDecisionVoter голосовал по определенным URL-адресам, то вы реализуете метод supports(ConfigAttribute attribute), чтобы избиратель распознал определенный атрибут, вы регистрируете избирателя. глобально, а затем укажите, что для определенных URL это необходимо:

    .antMatchers("/my-filtered-url1", "/sub/my-filtered-url2/*")
        .hasAuthority("HASHSERIAL")
class HashSerialSecurityVoter implements AccessDecisionVoter<Object> {

    public boolean supports(ConfigAttribute attribute) {
        if ((attribute.getAttribute() != null)
                && attribute.getAttribute().equals("HASHSERIAL")) {
            return true;
        }
        else {
            return false;
        }
    }

    public boolean supports(Class<?> clazz) {
        return true;
    }

    public int vote(Authentication authentication, Object object,
                    Collection<ConfigAttribute> attributes) {
        // Your logic here
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...