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

Java 如何在Spring Boot上使用Spring Security测试Rest服务?,java,spring,spring-boot,spring-security,junit4,Java,Spring,Spring Boot,Spring Security,Junit4,我正在从事一个项目,该项目涉及在Spring Boot上创建一个rest服务,该服务最终将与Angular Web应用程序和Discord机器人一起使用 我目前正在后端工作,并尝试对端点进行单元测试。即使未登录,用户也只能发出GET请求。然而,由于某种原因,每当我对端点进行单元测试时,它都会返回错误403。即使我告诉Spring Security允许任何请求 安全配置 @Configuration @EnableWebSecurity public class SecurityConfig ex

我正在从事一个项目,该项目涉及在Spring Boot上创建一个rest服务,该服务最终将与Angular Web应用程序和Discord机器人一起使用

我目前正在后端工作,并尝试对端点进行单元测试。即使未登录,用户也只能发出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);
}

}
@RestController
@请求映射(“/api/sf”)
公共类StarfinderController{
@自动连线
SFRuleRepo ruleRepo;
公共静态最终字符串前缀_URL=“/api/sf”;
公共静态最终字符串规则_URL=“/RULE”;
公共静态最终字符串规则\u URL=“/RULES”;
公共静态最终字符串规则\u REPO=“RULE”;
公共静态最终字符串PAGE=“PAGE”;
公共静态最终字符串计数=“计数”;
@GetMapping(规则\ URL)
公共规则getRule(@RequestParam(value=“name”,required=true)字符串名){
返回ruleRepo.findByName(名称);
}
@GetMapping(规则\u URL)
public List getRules(@RequestParam(value=“tag”,required=false,defaultValue=”“)字符串标记名,
@RequestParam(value=“page”,required=false)int page,
@RequestParam(value=“count”,required=false)int count){
如果(!tagName.isEmpty()){
//努普
}否则{
//TODO:添加对页面和计数的支持
列表=新建LinkedList();
list.addAll(ruleRepo.findAll());
退货清单;
}
返回null;
}
@后期映射(规则\u URL)
公共规则addRule(SFRule){
返回规则repo.save(规则);
}
@PutMapping(规则\u URL)
公共规则更新程序(SFRule){
可选的savedRule=ruleRepo.findById(rule.getId());
if(savedRule.isPresent()){
SFRule sv=savedRule.get();
sv.setName(rule.getName());
sv.setDesc(rule.getDesc());
返回规则报告保存(sv);
}否则{
返回null;
}
}
@删除映射(规则\u URL)
公共作废删除规则(SFRule){
规则报告。删除(规则);
}
}

这应该行得通,只需将URL放入
.antMatcher().permitAll()


http.authorizeRequests().permitAll()和().authorizeRequests()…anyRequest()…authenticated()如何?能否显示控制器?按请求添加控制器代码。另外,如果spring安全设置为允许任何请求,则允许它。那为什么我仍然从JUnit得到403错误代码呢?因为这个配置不会基本上关闭所有网页吗?事实证明,我的控制器配置错误,因为它没有使用我认为是的url。我认为为RestController输入一个变量还包括一个控制器的RequestMapping。但事实并非如此,它现在可以执行GET请求,但在测试POST时,它似乎不起作用。使用相同的错误代码。
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/targetURL/**").permitAll()     
}