Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring security 如何使用基本身份验证对Spring启动进行集成测试?_Spring Security_Spring Boot - Fatal编程技术网

Spring security 如何使用基本身份验证对Spring启动进行集成测试?

Spring security 如何使用基本身份验证对Spring启动进行集成测试?,spring-security,spring-boot,Spring Security,Spring Boot,我有一个简单的SpringBoot(1.3.5)应用程序,它有一个简单的集成测试,在我引入SpringBootStarter安全性之前一直有效。我已经在application.properties中设置了security.user.name和security.user.password,这似乎是我保护端点所需的全部密码(如果可能的话,我不希望通过添加不必要的角色或安全配置来使事情复杂化)。但是现在集成测试失败了。我的测试班: @RunWith(SpringJUnit4ClassRunner.cl

我有一个简单的SpringBoot(1.3.5)应用程序,它有一个简单的集成测试,在我引入SpringBootStarter安全性之前一直有效。我已经在application.properties中设置了security.user.name和security.user.password,这似乎是我保护端点所需的全部密码(如果可能的话,我不希望通过添加不必要的角色或安全配置来使事情复杂化)。但是现在集成测试失败了。我的测试班:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest(randomPort = true)
public class MyTestsIT {

    private TestRestTemplate template = new TestRestTemplate();
    private URL base;

    @Value("${security.user.name}")
    private String username;

    @Value("${security.user.password}")
    private String password;

    @Value("${local.server.port}")
    private int port;

    @Before
    public void beforeTest() throws MalformedURLException {
        base = new URL("http://" + username + ":" + password + "@localhost:" + port);
    }

    @Test
    public void testHello() throws IllegalStateException, IOException {
        System.err.println(base.toString() + "/hello");
        ResponseEntity<String> response = template.getForEntity(base.toString() + "/hello", String.class);
        assertEquals("Incorrect HTTP status returned", HttpStatus.OK, response.getStatusCode());
        String body = response.getBody();
        assertEquals("Incorrect response string.", "Hello World!", body);
    }
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(类=Application.class)
@WebIntegrationTest(随机端口=true)
公共类MyTestsIT{
私有TestRestTemplate=新TestRestTemplate();
专用URL库;
@值(${security.user.name})
私有字符串用户名;
@值(${security.user.password}”)
私有字符串密码;
@值(${local.server.port}”)
专用int端口;
@以前
public void beforeTest()引发了错误的FormedUrlexception{
base=新URL(“http://”+username+:“+password+”@localhost:“+port”);
}
@试验
public void testHello()引发IllegalStateException,IOException{
System.err.println(base.toString()+“/hello”);
ResponseEntity response=template.getForEntity(base.toString()+“/hello”,String.class);
assertEquals(“返回的HTTP状态不正确”,HttpStatus.OK,response.getStatusCode());
String body=response.getBody();
assertEquals(“不正确的响应字符串”,“Hello World!”,正文);
}
}
println语句显示正确的url,与我运行应用程序时在curl中使用的url相同:

卷曲


返回状态的断言在401中失败,我做错了什么?

D'oh!我一把问题贴出来,就在网上找到了答案。不知道为什么我之前的搜索没有成功。对不起,这里有噪音,希望这能帮助其他人

@Before
public void beforeTest() throws MalformedURLException {
    template = new TestRestTemplate(username, password);
    base = new URL("http://localhost:" + port);
}
@组件
公共类ServerMockUtils{
@值(${user.name.auth}”)
私有字符串userNameAuth;
@值(${password.name.auth}”)
私有字符串passwordNameAuth;
公共MappingBuilder makeMappingBuilderSuccess(MappingBuilder MappingBuilder){
返回mappingBuilder
.withHeader(“接受”,匹配(“应用程序/json”))
.withQueryParam(“格式”,equalTo(“json”))
.withBasicAuth(this.userNameAuth,this.passwordNameAuth);
}
}
公共类MockForRestControllerConfig{
@自动连线
私有服务器mockutils服务器mockutils;
@值(${api.url.external.server}”)
私有字符串apirltoExternalServer;
public void setupStubForProcessingRequest(int-portExternalServerMock){
字符串addressHost=“127.0.0.1”;
配置(addressHost、portExternalServerMock);
setupResponseInCaseSuccessProcessingRequest();
}
私有void setupResponseInCaseSuccessProcessingRequest(){
UrlPathPattern UrlPathPattern=urlPathEqualTo(this.apirlToExternalServer);
MappingBuilder MappingBuilder=get(urlPathPattern);
MappingBuilder mappingBuilderWithHeader=serverMockUtils.makeMappingBuilderSuccess(MappingBuilder);
int statusOk=HttpStatus.OK.value();
ResponseDefinitionBuilder ResponseDefinitionBuilder=aResponse()。
带状态(状态OK)
.withHeader(“内容类型”、“应用程序/json”)
.withBodyFile(“json/json.json”);
MappingBuilder responseForReturn=mappingBuilderWithHeader.willReturn(responseDefinitionBuilder);
stubFor(responseForReturn);
}
}
public ResponseEntity向外部服务器发送请求(int-portexternalserver-mock){
字符串fullUrlToExternalServer=makeFullUrlToExternalServer(portExternalServerMock);
UriComponentsBuilder UriComponentsBuilder=buildUriToExternalServer(fullUrlToExternalServer);
字符串uriWithParamsToExternalServer=uriComponentsBuilder.toUriString();
HttpHeaders requestHttpHeaders=getHeadersHttpHeaders();
HttpEntity requestHttpEntity=新HttpEntity(null,requestHttpHeaders);
返回testRestTemplate.exchange(
uriWithParamsToExternalServer,
HttpMethod.GET,
请求HttpEntity,
ExternalServerDto.class
);
}
私有字符串makeFullUrlToExternalServer(int-PorterExternalServerMock){
字符串prefixUrlToExternalServer=”http://127.0.0.1:";
返回prefixUrlToExternalServer+
portExternalServerMock+
this.apirltoExternalServer;
}
私有HttpHeaders getHeadersHttpHeaders(){
var requestHttpHeaders=新的HttpHeaders();
requestHttpHeaders.add(“接受”,MediaType.APPLICATION\u JSON\u值);
addBasicAuth(请求HttpHeader);
返回请求HttpHeader;
}
专用UriComponentsBuilder构建器urlToExternalServer(字符串urlToExternalServer){
返回UriComponentsBuilder.fromHttpUrl(urlToExternalServer)
.queryParam(“格式”、“json”)
}
私有void addBasicAuth(HttpHeaders HttpHeaders){
字符串auth=this.userNameAuth+“:”+this.passwordNameAuth;
字节[]encodedAuth=Base64.encodeBase64(
auth.getBytes(StandardCharsets.US_ASCII));
字符串authHeader=“Basic”+新字符串(encodedAuth);
添加(“授权”,authHeader);
}
  • pom.xml

org.springframework.boot
弹簧启动启动器数据rest
org.springframework.boot
SpringBootStarterWeb
org.springframework.boot
弹簧起动试验
测试
com.jayway.jsonpath
json路径