java - 如何使 Spring Security 在单元测试中工作?
问题描述
我很难理解如何使用该层测试Spring Boot
应用程序。Spring Security
我问过类似的问题如何Spring Security
使用MockitoJUnit
跑步者强制执行?以及如何Spring Security
分层模拟客户用户服务细节?
我有一个自定义实现,
UserDetailsService
它从数据库中获取数据,所以很自然,我想在单元测试阶段从其他地方获取它我想测试我的网络层以查看是否
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 层时,如何在单元测试中使用自定义实现?
解决方案
推荐阅读
- json - TableView 未填充数据,但正在处理 JSON 文件
- c - 如何将数组中的字符串转换为无符号整数?
- java - 在Java中使用整数值对字符串列表进行排序
- sql - Oracle (ORA-02270):尝试过其他答案,但无法弄清楚
- android - 在选项卡式活动中滑动以解锁
- qt - 为 Raspberry Pi 3 交叉编译 Qt 5.10.1 未编译 webEngine
- php - 特殊字符输入返回空白字符串
- c# - 如何在水晶报表中显示上标数字
- python - 我想使用 python 将 .wav 文件从我当前的系统复制到 linux 服务器
- android - 三星 Galaxy S8 android 版本 8.0.0 中未生成 FCM 实例 ID