首页 > 解决方案 > 如何使 Spring Security 在单元测试中工作?

问题描述

我很难理解如何使用该层测试Spring Boot应用程序。Spring Security

我问过类似的问题如何Spring Security使用MockitoJUnit跑步者强制执行?以及如何Spring Security分层模拟客户用户服务细节?

  1. 我有一个自定义实现,UserDetailsService它从数据库中获取数据,所以很自然,我想在单元测试阶段从其他地方获取它

  2. 我想测试我的网络层以查看是否Spring Security有效以及所有其他用例是否也有效。

我怎样才能完成上述两项任务?

SecurityConfig班级:

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/",
            "/csrf",
            "/swagger-resources",
            "/swagger-resources/**",
            "/configuration/ui",
            "/configuration/security",
            "/swagger-ui.html",
            "/webjars/**"
    };

    @Autowired
    @Qualifier("customUserDetailsService")
    private UserDetailsService userDetailsService;

    private final static Integer bCryptEncryptionLevel = 8;

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

    public SecurityConfig() {
        super();
    }

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
        authManagerBuilder.authenticationProvider(authenticationProvider());
        authManagerBuilder.userDetailsService(userDetailsService)
                .passwordEncoder(bCryptPasswordEncoder());
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(bCryptPasswordEncoder());
        return authenticationProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                    .antMatchers(AUTH_WHITELIST).permitAll()
                    // allow default swagger docket
                    .regexMatchers("\\A/v2/api-docs\\Z").permitAll()
                    // require auth for any other swagger docket
                    .regexMatchers("\\A/v2/api-docs?.*\\Z").authenticated()
                    .antMatchers("/**").authenticated()
                .and()
                .httpBasic()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

CustomUserDetailsService班级:

@Service("customUserDetailsService")
@Profile("!test")
public class CustomUserDetailsService implements UserDetailsService {
    private final static Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);

    private StringRedisTemplate redisTemplate;
    private RedisProperties redisProperties;

    @Autowired
    public CustomUserDetailsService(RedisProperties redisProperties, StringRedisTemplate redisTemplate) {
        this.redisProperties = redisProperties;
        this.redisTemplate = redisTemplate;
    }


    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        // Do queries to DB and return user if such user exists
    }
}

我还将CustomUserDetailsServiceTest用于单元测试目的的类添加到同一个包中,但位于src/test/java

@Service("customUserDetailsService")
@Profile("test")
public class CustomUserDetailsServiceTest implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        @SuppressWarnings("serial")
        Map<Object, Object> entries = new HashMap<Object, Object>(){{
            put("username", username);
            put("password_hash", "$2a$08$YjMcOsLmbbUB4DYPxqSAxOa3STLjEDovwd2..Uidwp.asyhSi8Y5u");
            put("role", "ADMIN");
        }};
        UserEntity user = new UserEntity(entries);
        return new HiccasoftApiUser(user);
    }
}

customUserDetailsService在测试 Web 层时,如何在单元测试中使用自定义实现?

标签: javaspringspring-bootunit-testingspring-security

解决方案


推荐阅读