Uchishandisa REST-yakavimbiswa kuyedza OAuth 2.0 kuyerera Mienzaniso

OAuth 2.0 inopa mana akasiyana kuyerera, asi chikuru chinangwa chekuyerera kwega kwega ndiko tora yekuwana_chiratidzo uye ishandise kuwana zviwanikwa zvakachengetedzwa.

Izvo zvina zvinoyerera zvakasiyana ndeizvi:

  • Mvumo Kodhi Grant
  • Yakazara Grant Kuyerera
  • Mutengi Kuzivikanwa
  • Password Grant Kuyerera

Iyi dzidziso inopa mienzaniso yekodhi uchishandisa REST-yakavimbiswa kuyedza iyo OAuth 2.0 kuyerera, Authorization Code Grant uye Client Credential kuyerera.

Mvumo Kodhi Grant Kuyerera

Uku ndiko kuyerera kunowanzoitika uko kodhi inoburitswa uye inoshandiswa kuwana iyo access_token . Iyi kodhi inosundirwa kune yekumberi-kumagumo kunyorera (pane bhurawuza) mushure mekunge mushandisi apinda mukati. Iyo yekuwana_token inopihwa padivi re server, ichisimbisa mutengi ne password yayo uye nekodhi yakawanikwa.

Matanho matatu matanho.

  • 1 - Tora Auth Code
  • 2 - Get Yekuwana Chiratidzo
  • 3 - Shandisa Access Token (kuwana zviwanikwa zvakachengetedzwa)

Tora Auth Code

Nhanho yekutanga kutora iyo 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);
} }

Wana Chiratidzo Chekuwana

Kana tangowana kodhi yemvumo, tinogona kukumbira 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);
}

Uchishandisa Access Token

Chekupedzisira, kana isu tine anoshanda access_token, tinogona kuita zvikumbiro kuzvidziviriro zviwanikwa:

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

Tinogona zvakare kutumira chiratidzo chekuwana se Authorization Header ne Bearer chivakashure:

Semuyenzaniso:

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

Mutengi Kuzivikanwa Kuyerera

Iyo yevatengi inozivikanwa yekuyerera haina UI (browser) inobatanidzwa uye inonyanya kushandiswa kuMuchina-kuMuchina mvumo.

Mune REST-yakavimbiswa, izvi zvinoita kunge:

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());
} }

Mhedziso

Pano, isu takapa mienzaniso yekodhi ine REST-yakavimbiswa maitiro ekuwana access_token kushandisa OAuth 2.0 kuyerera. Kana tangowana iyo access_token tinogona ipapo kukumbira kune zvakachengetedzwa zviwanikwa.

Ndinovimba wawana zviri pamusoro zvinobatsira.