【问题标题】:How to test a Rest Service with Spring Security on Spring Boot?如何在 Spring Boot 上使用 Spring Security 测试 Rest 服务?
【发布时间】:2018-09-28 02:40:03
【问题描述】:

我正在开展一个项目,该项目涉及在 Spring Boot 上创建一个 rest 服务,该服务最终将与 Angular Web App 和 Discord Bot 一起使用。

我目前正在处理后端并尝试对端点进行单元测试。由于最终未登录的用户只能发出 GET 请求。但是,由于某种原因,当我对端点进行单元测试时,它会以错误 403 的形式返回。即使我告诉 Spring Security 允许任何请求。

安全配置

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {

    //http.authorizeRequests().antMatchers("/api/*").permitAll();
    http.authorizeRequests().anyRequest().permitAll();
    //      .authorizeRequests()
    //          .antMatchers("/api/**/rule","/api/**/rules" )
    //              .permitAll()
    //              .anyRequest()
    //              .permitAll()
    //      .and()
    //          .formLogin()
    //              .loginPage("/login")
    //              .permitAll()
    //      .and()
    //          .logout()
    //              .permitAll();
}

@Autowired
public void configureAuth(AuthenticationManagerBuilder auth) throws Exception{
    auth
        .inMemoryAuthentication()
            .withUser("admin").password("password").roles("ADMIN", "USER", "EDITOR").and()
            .withUser("user").password("password").roles("USER", "EDITOR");
}



    }

JUnit 测试

@RunWith(SpringRunner.class)
@SpringBootTest()
@AutoConfigureMockMvc
public class TestSFRuleController {

ObjectMapper mapper = new ObjectMapper();


@Autowired
MockMvc mvc;

@Autowired
SFRuleRepo repo;

@Before
public void setUp(){
    repo.deleteAll();

}

@Test
@WithMockUser(username = "admin")
public void testInsertNewRule() throws Exception {
    SFRule rule = new SFRule("test insert rule", "test desc");
    String json = mapper.writeValueAsString(rule);
    mvc.perform(
            post(StarfinderController.PREFIX_URL + StarfinderController.RULE_URL)
            .content(json))
            .andExpect(status()
                    .isOk())
            .andExpect(jsonPath("$.id").isNotEmpty())
            .andExpect(jsonPath("$.name").value("test insert rule"));

}

}

控制器

@RestController
@RequestMapping("/api/sf")
public class StarfinderController {


@Autowired
SFRuleRepo ruleRepo;

public static final String PREFIX_URL = "/api/sf";

public static final String RULE_URL = "/rule";
public static final String RULES_URL = "/rules";

public static final String RULE_REPO = "RULE";


public static final String PAGE = "page";
public static final String COUNT = "count";

@GetMapping(RULE_URL)
public Rule getRule(@RequestParam(value = "name", required = true) String name) {

    return ruleRepo.findByName(name);

}

@GetMapping(RULES_URL)
public List<Rule> getRules(@RequestParam(value = "tag", required = false, defaultValue = "") String tagName,
        @RequestParam(value = "page", required = false) int page,
        @RequestParam(value = "count", required = false) int count) {

    if (!tagName.isEmpty()) {
        // noop

    } else {
        //TODO: add support for page and count

        List<Rule> list = new LinkedList<Rule>();
        list.addAll(ruleRepo.findAll());
        return list;
    }

    return null;

}

@PostMapping(RULE_URL)
public Rule addRule(SFRule rule) {
    return ruleRepo.save(rule);
}

@PutMapping(RULE_URL)
public Rule updateRule(SFRule rule) {
    Optional<SFRule> savedRule = ruleRepo.findById(rule.getId());

    if (savedRule.isPresent()) {
        SFRule sv = savedRule.get();
        sv.setName(rule.getName());
        sv.setDesc(rule.getDesc());
        return ruleRepo.save(sv);
    } else {
        return null;
    }

}

@DeleteMapping(RULE_URL)
public void deleteRule(SFRule rule) {
    ruleRepo.delete(rule);
}

}

【问题讨论】:

  • http.authorizeRequests().permitAll().and().authorizeRequests()..anyRequest()..authenticated() 怎么样?
  • 你能展示一下控制器吗?
  • 按要求添加了控制器代码。此外,如果设置了弹簧安全性,以便给定任何请求,请允许它。那为什么我仍然从 JUnit 收到 403 错误代码?因为那个配置不会基本上关闭所有拒绝网页吗?
  • 原来,我的控制器配置错误,因为它没有使用我认为的 url。我认为为 RestController 放入一个变量还包括一个用于控制器的 RequestMapping。但不是这样,它现在能够执行 GET 请求,但是在测试 POST 时它似乎不起作用。具有相同的错误代码。

标签: java spring spring-boot spring-security junit4


【解决方案1】:

这应该可以,只需将网址放入.antMatcher().permitAll()

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/targetURL/**").permitAll()     
}

【讨论】:

    猜你喜欢
    • 2012-05-10
    • 2021-07-08
    • 2017-05-23
    • 2021-03-15
    • 2014-04-13
    • 2020-01-02
    • 2015-12-09
    • 2021-02-08
    • 2017-10-21
    相关资源
    最近更新 更多