未应用Spring Security配置

问题描述 投票:1回答:1

我具有以下配置,其中我需要为HTTPBasic端点配置/api/v1/**身份验证,并且我想为form网址格式配置/users/身份验证。当我使用以下配置运行时,Web请求的配置运行正常,但API的配置运行不正常。没有应用安全性。我要去哪里错了?

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    @Order(1)
    @Configuration
    public static class MVCSecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Bean
        public BCryptPasswordEncoder getBCryptPasswordEncoder() {
            return new BCryptPasswordEncoder();
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.
                    antMatcher("/users/**")
                    .csrf()
                        .and()
                    .authorizeRequests()
                    .antMatchers(
                            "/resources/**", "/users/register", "/users/signup", "/users/confirm", "/users/user-action", "/users/reset-password", "/confirm", "/webjars/**")
                    .permitAll()
                    .antMatchers("/users/**")
                    .hasRole("USER")
                    .anyRequest()
                    .authenticated()
                    .and()
                    .formLogin().loginPage("/login").usernameParameter("username").passwordParameter("password");

            http
                    .authorizeRequests()
                    .antMatchers("/api/v1/users/**")
                    .hasRole("USER")
                    .anyRequest()
                    .authenticated()
                    .and()
                    .httpBasic();
        }
    }
java spring-security spring-security-rest
1个回答
2
投票

我已将您的代码用于以下配置:

@EnableWebSecurity
public class SecurityConfiguration {

public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/api/v1/users/**")
           .authorizeRequests().anyRequest()
           .hasRole("USER").and().httpBasic();
    }

}

@Configuration
@Order(2)
public class MVCSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().and().authorizeRequests()
                .antMatchers("/resources/**", "/users/register", "/users/signup", "/users/confirm",
                        "/users/user-action", "/users/reset-password", "/confirm", "/webjars/**").permitAll()
        .antMatchers("/users/**").hasRole("USER")
        .and()
        .formLogin().usernameParameter("username").passwordParameter("password");
    }
}

}

查看Spring Security和示例代码here的文档。

© www.soinside.com 2019 - 2024. All rights reserved.