休息保证承载认证 [英] Rest Assured Bearer authentication
问题描述
我刚开始使用Rest Assured,Java和Api测试,所以请对我保持谨慎.当我使用放心的方式来测试使用承载身份验证的api时,测试将失败,从而导致:- java.net.ConnectException:连接被拒绝:connect
I am new to using Rest Assured,Java and Api testing so please be gentle with me. When I use rest assured to test an api that uses Bearer authentication the tests fail resulting in:- java.net.ConnectException: Connection refused: connect
我知道问题可能与身份验证有关,但不确定如何使用承载者".我四处搜寻,并认为我需要以某种方式使用我的用户名和密码进行初始请求.然后取回令牌以用于承载身份验证. 有人可以帮我做一个简单的例子吗?
I know the issue is likely to do with the authentication but am unsure on how to use "Bearer". I searched around and believe that somehow I need to make an initial request using my username and password. Then get a token back to be used for bearer authentication. Please can someone help me to do this with a very simple example?
我的代码是
import com.jayway.restassured.RestAssured;
import static com.jayway.restassured.RestAssured.*;
import static org.hamcrest.Matchers.hasItem;
@BeforeTest
public void setUp() {
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
RestAssured.authentication = preemptive().basic("username","password");
}
@Test
public void successfulTest() {
given()
.contentType("application/json; charset=UTF-8");
when().
get("http://mydomain/testpath/Id=2").
then().
statusCode(200);
}
推荐答案
Response response =
given()
.headers(
"Authorization",
"Bearer " + bearerToken,
"Content-Type",
ContentType.JSON,
"Accept",
ContentType.JSON)
.when()
.get(url)
.then()
.contentType(ContentType.JSON)
.extract()
.response();
这篇关于休息保证承载认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!