Как настроить разные пути с помощью Spring Security? - PullRequest
0 голосов
/ 14 мая 2019

Я изо всех сил пытаюсь настроить безопасность для некоторых других путей, которые у меня есть.

Мне нужна эта структура:

/actuator/health <-- open
/api/** <-- hasAnyAuthority
/auth/** <-- basic authentication
all others no access

Пока это то, что у меня есть

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .antMatcher("/**") // If you want to override the security provided by Spring Boot.
            .addFilter(preAuthFilter())
            .cors()
                .and()
            .csrf().disable()
            .authorizeRequests()
                .antMatchers("/actuator/health").permitAll()
                .antMatchers("/api/**").hasAnyAuthority("something")
                .antMatchers("/auth/**").authenticated()
                .and()
            .httpBasic();
    }

Я хотел бы добавить .anyRequest().denyAll(), но это не представляется возможным после httpBasic().

Может кто-нибудь подтвердить, что приведенный выше код будет таким же, как я хотел бы?

1 Ответ

0 голосов
/ 15 мая 2019

Пример того, как разделить конфигурацию по пути:

@Configuration
public class ApiSecurityConfiguration extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/api/**")
            .authorizeRequests()
                .antMatchers("/api/public/**", "/api/register").anonymous() //if you need to allow some path in api
                .antMatchers("/api/**", "/api/register/**").hasRole("API_USER")
            .and()
                .formLogin()
                    .loginPage("/api/")
                    .failureHandler(failureHandler())
                    .loginProcessingUrl("/api/login")
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .successHandler(successHandler())
            .and()
                .logout()
                    .logoutUrl("/api/logout")
                    .logoutSuccessUrl("/api/")
                    .invalidateHttpSession(true)
            .and()
                .rememberMe()
                    .key("something")
            .and()
                .csrf().disable()
            .exceptionHandling()
                .accessDeniedPage("/api/loginfailed");
    }
}

Второй путь:

@Configuration
public class AuthSecurityConfiguration extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/auth/**")
            .authorizeRequests()
                .antMatchers("/auth/register").anonymous()
                .antMatchers("/auth/**", "/auth/register/**").hasRole("USER")
            .and()
                .formLogin()
                    .loginPage("/auth/")
                    .failureHandler(failureHandler())
                    .loginProcessingUrl("/auth/login")
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .successHandler(successHandler())
            .and()
                .logout()
                    .logoutUrl("/auth/logout")
                    .logoutSuccessUrl("/auth/")
                    .invalidateHttpSession(true)
            .and()
                .rememberMe()
                    .key("something")
            .and()
                .csrf().disable()
            .exceptionHandling()
                .accessDeniedPage("/auth/loginfailed");
    }
}

Теперь, поскольку вы не добавили защиту для /actuator/health, вы можете оставить ее безодин или вы можете сделать другой адаптер для него и разрешить доступ каждому.

Также вы должны использовать защиту csrf, это легко реализовать.

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