使用spring-security-test自定义注解测试SpringBoot应用

 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)
    {
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 引入依赖 在pom.xml文件中添加spring-boot-starter-security依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 配置安全策略 在application.properties中配置安全策略: ```properties # 关闭基本认证 security.basic.enabled=false # 允许所有用户访问所有端点 security.require-ssl=false security.enable-csrf=false ``` 3. 创建用户服务 创建一个实现UserDetailsService接口的用户服务,用于加载用户信息: ```java @Service public class UserDetailsServiceImpl implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // 这里可以从数据库或其他地方加载用户信息 if ("admin".equals(username)) { return new User("admin", "{noop}admin", Collections.singletonList(new SimpleGrantedAuthority("ROLE_ADMIN"))); } else if ("user".equals(username)) { return new User("user", "{noop}user", Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))); } else { throw new UsernameNotFoundException("用户不存在"); } } } ``` 4. 配置安全过滤器 在配置类中添加@EnableWebSecurity和@Configuration注解,并继承WebSecurityConfigurerAdapter,然后配置安全过滤器: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") // /admin/** 接口需要 ADMIN 角色 .antMatchers("/user/**").hasRole("USER") // /user/** 接口需要 USER 角色 .anyRequest().authenticated() // 其他接口需要认证 .and() .formLogin() .loginProcessingUrl("/login") // 登录接口路径 .defaultSuccessURL("/index") // 登录成功后跳转到 /index 接口 .failureUrl("/login?error") // 登录失败跳转到 /login?error 接口 .permitAll() // 允许所有用户访问登录接口 .and() .logout() .logoutUrl("/logout") // 退出登录接口路径 .logoutSuccessUrl("/login?logout") // 退出登录成功后跳转到 /login?logout 接口 .permitAll(); // 允许所有用户访问退出登录接口 } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } } ``` 5. 创建控制器 创建控制器,用于测试接口访问权限: ```java @RestController public class TestController { @GetMapping("/admin/hello") public String adminHello() { return "Hello, Admin!"; } @GetMapping("/user/hello") public String userHello() { return "Hello, User!"; } @GetMapping("/hello") public String hello() { return "Hello, World!"; } } ``` 6. 测试接口 启动应用,然后使用管理员账户(admin/admin)和普通用户账户(user/user)访问不同的接口: - http://localhost:8080/admin/hello 只有管理员能访问,需要管理员账户登录。 - http://localhost:8080/user/hello 只有普通用户能访问,需要普通用户账户登录。 - http://localhost:8080/hello 所有用户都能访问,不需要登录。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值