Sebenzisa i-REST-eqinisekisiwe kuvavanyo lwe-OAuth 2.0 yeMizekelo yokuhamba

I-OAuth 2.0 ibonelela ngeendlela ezine zokuhamba, kodwa eyona njongo iphambili yokuhamba nganye kukuba fumana ukufikelela_umqondiso kwaye uyisebenzise ukufikelela kwimithombo ekhuselweyo.

Ukuhamba okune ezahlukeneyo zezi:

  • Isibonelelo seKhowudi yokugunyazisa
  • Ukuhamba kwesiBonelelo
  • Ukuqinisekiswa kwabathengi
  • Ukuhamba kweGrant password

Olu qeqesho lubonelela ngemizekelo yekhowudi kusetyenziswa ukuqinisekiswa kwakhona ukuvavanya ukuhamba kwe-OAuth 2.0, iSibonelelo seKhowudi yokuGunyazisa kunye nokuHamba kwabaThengi abaKhuselekileyo.




Ukuhamba kweKhowudi yokuGunyazisa

Olu lolona hlobo lokuhamba luxhaphakileyo apho ikhowudi ikhutshwa khona kwaye isetyenziselwa ukufumana ifayile ye- ukufikelela_ uphawu . Le khowudi inyanzeliswa kwisicelo sokungena ngaphambili (kwisikhangeli) emva kokuba umsebenzisi engenile. I-access_token ikhutshiwe kwicala leseva, eqinisekisa umxhasi ngegama eligqithisiweyo kunye nekhowudi efunyenweyo.

Inkqubo yamanyathelo amathathu:


  • 1 -Fumana iKhowudi yeAuth
  • 2 -Fumana iThokheni yokuFikelela
  • 3-Sebenzisa iTokheni yokuFikelela (ukufikelela kwimithombo ekhuselweyo)

Fumana ikhowudi yeAuth

Inyathelo lokuqala kukufumana code:

import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.response.Response; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; import java.util.Base64; public class RestAssuredOAuth2 {
public static String clientId = 'some_client_id';
public static String redirectUri = 'some_redirect_uri';
public static String scope = 'some_scope';
public static String username = 'some_email';
public static String password = 'some_password';
public static String encode(String str1, String str2) {
return new String(Base64.getEncoder().encode((str1 + ':' + str2).getBytes()));
}
public static Response getCode() {
String authorization = encode(username, password);

return


given()




.header('authorization', 'Basic ' + authorization)




.contentType(ContentType.URLENC)




.formParam('response_type', 'code')




.queryParam('client_id', clientId)




.queryParam('redirect_uri', redirectUri)




.queryParam('scope', scope)




.post('/oauth2/authorize')




.then()




.statusCode(200)




.extract()




.response();
}
public static String parseForOAuth2Code(Response response) {
return response.jsonPath().getString('code');
}
@BeforeAll
public static void setup() {
RestAssured.baseURI = 'https://some-url.com';
}
@Test
public void iShouldGetCode() {
Response response = getCode();
String code = parseForOAuth2Code(response);

Assertions.assertNotNull(code);
} }

Fumana iToken yokuFikelela

Nje ukuba sifumane ikhowudi yesigunyaziso, emva koko singacela access_token:

public static Response getToken(String authCode) {
String authorization = encode(username, password);
return
given()

.header('authorization', 'Basic ' + authorization)

.contentType(ContentType.URLENC)

.queryParam('code', authCode)

.queryParam('redirect_uri', redirectUri)

.queryParam('grant_type', grantType)

.post('/oauth2/token')

.then()

.statusCode(200)

.extract()

.response();
}
public static String parseForAccessToken(Response loginResponse) {
return loginResponse.jsonPath().getString('access_token');
}
@Test
public void iShouldGetToken() {
Response tokenResponse = getToken(code);
String accessToken = parseForAccessToken(tokenResponse);
Assertions.assertNotNull(accessToken);
}

Sebenzisa iTokheni yokuFikelela

Okokugqibela, xa sinesemthethweni access_token, emva koko sinokwenza izicelo kwizixhobo ezikhuselweyo:

public static void getUsers() {
given().auth()
.oauth2(accessToken)
.when()
.get('/users')
.then()
.statusCode(200); }

Sinokuthumela ithokheni yokufikelela njenge Authorization Header kunye Bearer isimaphambili:


Umzekelo:

public static void getUsers() {
given()
.header('Authorization', 'Bearer ' + accessToken)
.when()
.get('/users')
.then()
.statusCode(200); }


Ukuhamba kwabaNtu abaKhuselekileyo

Ukuhamba kwesiqinisekiso somthengi akunayo i-UI (isikhangeli) esibandakanyekayo kwaye sisetyenziselwa ukugunyaziswa ngomatshini ukuya kumatshini.

Ekuqinisekiseni REST, oku kuya kujongeka njengoku:

import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.response.Response; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; import static io.restassured.RestAssured.requestSpecification; public class RestAssuredOAuth2 {
public static Response response;
private String userAdminClientId = System.getenv('M2M_USER_ADMIN_CLIENT_ID');
private String userAdminClientSecret = System.getenv('M2M_USER_ADMIN_CLIENT_SECRET');
private String oauth2Payload = '{ ' +

' 'client_id': '' + userAdminClientId + '', ' +

' 'client_secret': '' + userAdminClientSecret + '', ' +

' 'audience': 'https://some-url.com/user', ' +

' 'grant_type': 'client_credentials', ' +

' 'scope': 'user:admin' }';
private static String createUserPayload = '{ ' +

' 'username': 'api-user', ' +

' 'email': 'api-user@putsbox.com', ' +

' 'password': 'Passw0rd123!', ' +

' 'firstName': 'my-first-name', ' +

' 'lastName': 'my-last-name', ' +

' 'roles': ['read'] }';
public void userAdminConfigSetup() {
requestSpecification = given().auth().oauth2(getAccessToken(oauth2Payload))


.header('Accept', ContentType.JSON.getAcceptHeader())


.contentType(ContentType.JSON);
}
public String getAccessToken(String payload) {
return given()


.contentType(ContentType.JSON)


.body(payload)


.post('/token')


.then().extract().response()


.jsonPath().getString('access_token');
}
@BeforeAll
public static void setup() {
RestAssured.baseURI = 'https://some-url.com';
}
@Test
public void createUser() {
userAdminConfigSetup();
response = given(requestSpecification)


.body(createUserPayload)


.post('/user')


.then().extract().response();

Assertions.assertEquals(201, response.statusCode());
} }


Isiphelo

Apha, sibonelele ngemizekelo yekhowudi nge-REST-eqinisekisiwe ngendlela yokufumana access_token usebenzisa ukuhamba kwe-OAuth 2.0. Nje ukuba sifumane access_token sinokwenza izicelo kwimithombo ekhuselweyo.


Ndiyathemba ukuba ufumene oku kuluncedo lungentla.