繁体   English   中英

如何在Spring Boot上使用Spring Security测试Rest服务?

[英]How to test a Rest Service with Spring Security on Spring Boot?

我正在从事一个项目,该项目涉及在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);
}

}

这应该有效,只需将URL放入.antMatcher().permitAll()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM