Nggunakake REST-sure kanggo Nyoba conto aliran OAuth 2.0

OAuth 2.0 nyedhiyakake patang aliran sing beda, nanging target utama saben aliran yaiku entuk akses_token lan gunakake kanggo ngakses sumber daya sing dilindhungi.

Papat aliran sing beda yaiku:

  • Grant Kode Otorisasi
  • Alur Grant implisit
  • Kredensial Klien
  • Aliran Grant Sandi

Tutorial iki nyedhiyakake conto kode kanthi nggunakake REST-sure kanggo nyoba aliran OAuth 2.0, Grant Code Grant lan aliran Credential Client.




Aliran Grant Kode Otorisasi

Iki minangka aliran sing paling umum yen kode ditanggepi lan digunakake kanggo entuk access_token . Kode iki disurung menyang aplikasi front-end (ing browser) sawise pangguna mlebu. Access_token ditanggepi ing sisih server, ngotentikasi klien nganggo sandhi lan kode sing dipikolehi.

Proses telung langkah:


  • 1 - Entuk Kode Auth
  • 2 - Entuk Token Akses
  • 3 - Gunakake Token Akses (kanggo ngakses sumber daya sing dilindhungi)

Entuk Kode Auth

Langkah kapisan kanggo njaluk 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);
} }

Entuk Token Akses

Sawise entuk kode otorisasi, banjur bisa njaluk 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);
}

Nggunakake Token Akses

Pungkasane, yen duwe valid access_token, banjur bisa njaluk panjaluk marang sumber sing dilindhungi:

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

Kita uga bisa ngirim token akses minangka Authorization Header nganggo Bearer awalan:


Contone:

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


Aliran Kredensial Klien

Aliran kredensial klien ora ana UI (browser) sing gegandhengan lan umume digunakake kanggo otorisasi Machine-to-Machine.

Yen wis REST, iki bakal katon kaya:

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


Kesimpulan

Ing kene, kita nyedhiyakake conto kode kanthi yakin tenan babagan carane njaluk access_token nggunakake aliran OAuth 2.0. Sawise entuk access_token kita banjur bisa njaluk panjaluk marang sumber daya sing dilindhungi.


Muga-muga sampeyan bisa migunani babagan ing ndhuwur.