What is OAuth?
OAuth is an open-standard authorization protocol. It allows one service (a client) to access another service (a resource server) on behalf of the user, without sharing user credentials.
There are various OAuth flows:
Authorization Code Grant (for apps with user interaction)
Client Credentials Grant (for server-to-server, no user login)
Password Grant (deprecated)
Implicit Grant (deprecated)
Step-by-step Explanation
Get the Access Token
Send a
POST
request to the token endpoint (/oauth/token
)Provide:
client_id
client_secret
grant_type=client_credentials
Use the Access Token to Access the API
Add the
Authorization: Bearer <access_token>
headerCall the protected API
import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.response.Response; import java.util.HashMap; import java.util.Map; public class OAuth2Test { public static void main(String[] args) { // Step 1: Get OAuth2 token String tokenUrl = "https://example.com/oauth/token"; // Replace with real token URL Map<String, String> params = new HashMap<>(); params.put("grant_type", "client_credentials"); params.put("client_id", "your-client-id"); params.put("client_secret", "your-client-secret"); Response tokenResponse = RestAssured .given() .contentType(ContentType.URLENC) .formParams(params) .when() .post(tokenUrl) .then() .statusCode(200) .extract() .response(); String accessToken = tokenResponse.jsonPath().getString("access_token"); System.out.println("Access Token: " + accessToken); // Step 2: Use token to access protected API String protectedUrl = "https://reqres.in/api/users?page=2"; RestAssured .given() .auth() .oauth2(accessToken) // Add Bearer token .when() .get(protectedUrl) .then() .statusCode(200) .log().body(); } }
Important Points:
auth().oauth2(token)
adds theAuthorization: Bearer <token>
header.For token endpoint, many real APIs use URLs like:
https://api.example.com/oauth2/token
No comments:
Post a Comment