|
| 1 | +package org.baeldung; |
| 2 | +import static org.junit.Assert.assertEquals; |
| 3 | + |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.Map; |
| 6 | + |
| 7 | +import org.junit.Test; |
| 8 | +import org.springframework.http.HttpHeaders; |
| 9 | +import org.springframework.http.HttpStatus; |
| 10 | + |
| 11 | +import io.restassured.RestAssured; |
| 12 | +import io.restassured.response.Response; |
| 13 | + |
| 14 | +public class UserInfoEndpointLiveTest { |
| 15 | + |
| 16 | + @Test |
| 17 | + public void givenAccessToken_whenAccessUserInfoEndpoint_thenSuccess() { |
| 18 | + String accessToken = obtainAccessTokenUsingAuthorizationCodeFlow("john","123"); |
| 19 | + Response response = RestAssured.given().header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken).get("http://localhost:8081/auth/user/me"); |
| 20 | + |
| 21 | + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); |
| 22 | + assertEquals("john", response.jsonPath().get("name")); |
| 23 | + } |
| 24 | + |
| 25 | + private String obtainAccessTokenUsingAuthorizationCodeFlow(String username, String password) { |
| 26 | + final String authServerUri = "http://localhost:8081/auth"; |
| 27 | + final String redirectUrl = "http://www.example.com/"; |
| 28 | + final String authorizeUrl = authServerUri + "/oauth/authorize?response_type=code&client_id=SampleClientId&redirect_uri=" + redirectUrl; |
| 29 | + final String tokenUrl = authServerUri + "/oauth/token"; |
| 30 | + |
| 31 | + // user login |
| 32 | + Response response = RestAssured.given().formParams("username", username, "password", password).post(authServerUri + "/login"); |
| 33 | + final String cookieValue = response.getCookie("JSESSIONID"); |
| 34 | + |
| 35 | + // get authorization code |
| 36 | + RestAssured.given().cookie("JSESSIONID", cookieValue).get(authorizeUrl); |
| 37 | + response = RestAssured.given().cookie("JSESSIONID", cookieValue).post(authorizeUrl); |
| 38 | + assertEquals(HttpStatus.FOUND.value(), response.getStatusCode()); |
| 39 | + final String location = response.getHeader(HttpHeaders.LOCATION); |
| 40 | + final String code = location.substring(location.indexOf("code=") + 5); |
| 41 | + |
| 42 | + // get access token |
| 43 | + Map<String, String> params = new HashMap<String, String>(); |
| 44 | + params.put("grant_type", "authorization_code"); |
| 45 | + params.put("code", code); |
| 46 | + params.put("client_id", "SampleClientId"); |
| 47 | + params.put("redirect_uri", redirectUrl); |
| 48 | + response = RestAssured.given().auth().basic("SampleClientId", "secret").formParams(params).post(tokenUrl); |
| 49 | + return response.jsonPath().getString("access_token"); |
| 50 | + } |
| 51 | +} |
0 commit comments