我目前无法测试,但这是一个 可能的 解决方案。
查看@WithUserDetails实现:
@WithSecurityContext(factory = WithUserDetailsSecurityContextFactory.class)public @interface WithUserDetails { ...}final class WithUserDetailsSecurityContextFactory implements WithSecurityContextFactory<WithUserDetails> { private BeanFactory beans; @Autowired public WithUserDetailsSecurityContextFactory(BeanFactory beans) { this.beans = beans; } public SecurityContext createSecurityContext(WithUserDetails withUser) { String beanName = withUser.userDetailsServiceBeanName(); UserDetailsService userDetailsService = StringUtils.hasLength(beanName) ? this.beans.getBean(beanName, UserDetailsService.class) : this.beans.getBean(UserDetailsService.class); String username = withUser.value(); Assert.hasLength(username, "value() must be non empty String"); UserDetails principal = userDetailsService.loadUserByUsername(username); Authentication authentication = new UsernamePasswordAuthenticationToken( principal, principal.getPassword(), principal.getAuthorities()); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authentication); return context; }}
@Target({ElementType.METHOD, ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Inherited@documented@WithSecurityContext(factory = WithoutUserFactory.class)public @interface WithoutUser {}public class WithoutUserFactory implements WithSecurityContextFactory<WithoutUser> { public SecurityContext createSecurityContext(WithoutUser withoutUser) { return SecurityContextHolder.createEmptyContext(); }}
其他可获得的注释:
WithAnonymousUser,
WithMockUser,
WithSecurityContext(和
WithUserDetails)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)