spriing security test中自带的注解@WithMockUser
如果不使用自定义Authentication
,这是一个绝佳的选择。
但是项目中总有一些特殊的情况,就需要我们自定义实现:
首先创建一个自定义的注解
@WithSecurityContext factory属性指向一个自定义Facotry
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory.class)
public @interface WithMockUser
{
}
下面实现我们的自定义Facotry
final public class WithMockCustomUserSecurityContextFactory implements WithSecurityContextFactory<WithMockUser>
{
// 读取properties 配置
@Value("${mock.user}")
private String user;
// 读取properties 配置
@Value("${mock.role}")
private String role;
@Override
public SecurityContext createSecurityContext(WithMockUser annotation)
{