Skip to content

Commit

Permalink
#27 Feat: IdentityCheckTest ์ˆ˜์ •
Browse files Browse the repository at this point in the history
  • Loading branch information
pjhcsols committed Oct 6, 2024
1 parent 7198f72 commit dba1bd5
Show file tree
Hide file tree
Showing 5 changed files with 344 additions and 116 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.InputStreamReader;
Expand All @@ -15,20 +19,24 @@

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest
//@SpringBootTest
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class AccessTokenTest {

@Autowired
private RestTemplate restTemplate;

private static final String TOKEN_URL = "https://oauth.codef.io/oauth/token";
private static final String CLIENT_ID = "9f515c3f-8df3-41b7-9da1-e08192131b3d";
private static final String CLIENT_SECRET = "d0c5a8b8-2858-4059-acff-289f42892f47";
private static final String CLIENT_ID = "86640213-3b83-461a-97ab-2491d68a2052";
private static final String CLIENT_SECRET = "8721d0b3-37ea-4484-8d65-6418a61fd1a1";

@Test
void shouldPublishAccessTokenSuccessfully() throws Exception {
HashMap<String, String> tokenResponse = publishToken(CLIENT_ID, CLIENT_SECRET);

assertThat(tokenResponse).isNotNull();
assertThat(tokenResponse.get("access_token")).isNotNull();

System.out.println("Access Token: " + tokenResponse.get("access_token"));
}

Expand Down
102 changes: 102 additions & 0 deletions web3-credential-server/src/test/java/web3/api/identity/GetToken.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package web3.api.identity;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Base64;
import java.util.HashMap;

public class GetToken {

private static final String OAUTH_DOMAIN = "https://oauth.codef.io";
private static final String GET_TOKEN = "/oauth/token";

public static void main(String[] args) {
String clientId = "86640213-3b83-461a-97ab-2491d68a2052";
String clientSecret = "8721d0b3-37ea-4484-8d65-6418a61fd1a1";

// ํ† ํฐ ๋ฐœ๊ธ‰
HashMap<String, String> tokenMap = publishToken(clientId, clientSecret);

if (tokenMap != null && tokenMap.containsKey("access_token")) {
// ๋ฐœ๊ธ‰๋œ ์•ก์„ธ์Šค ํ† ํฐ
String accessToken = tokenMap.get("access_token");
System.out.println("Access Token: " + accessToken);
} else {
System.out.println("Failed to get access token");
}
}

public static String getAccessToken(String clientId, String clientSecret) {
HashMap<String, String> tokenMap = publishToken(clientId, clientSecret);
if (tokenMap != null && tokenMap.containsKey("access_token")) {
return tokenMap.get("access_token");
} else {
throw new RuntimeException("Failed to get access token");
}
}

public static HashMap<String, String> publishToken(String clientId, String clientSecret) {
BufferedReader br = null;
try {
URL url = new URL(OAUTH_DOMAIN + GET_TOKEN);
String params = "grant_type=client_credentials&scope=read";

HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

String auth = clientId + ":" + clientSecret;
byte[] authEncBytes = Base64.getEncoder().encode(auth.getBytes());
String authStringEnc = new String(authEncBytes);
String authHeader = "Basic " + authStringEnc;
con.setRequestProperty("Authorization", authHeader);
con.setDoInput(true);
con.setDoOutput(true);

OutputStream os = con.getOutputStream();
os.write(params.getBytes());
os.flush();
os.close();

int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
br = new BufferedReader(new InputStreamReader(con.getInputStream()));
} else {
return null;
}

String inputLine;
StringBuffer responseStr = new StringBuffer();
while ((inputLine = br.readLine()) != null) {
responseStr.append(inputLine);
}
br.close();

ObjectMapper mapper = new ObjectMapper();
HashMap<String, String> tokenMap = mapper.readValue(URLDecoder.decode(responseStr.toString(), "UTF-8"),
new TypeReference<HashMap<String, String>>() {
});

return tokenMap;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
// Ignored
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
package web3.api.identity;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.Base64;
import java.util.HashMap;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.when;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class GetTokenTest {

private static final String TOKEN_URL = "https://oauth.codef.io/oauth/token";
private static final String CLIENT_ID = "86640213-3b83-461a-97ab-2491d68a2052";
private static final String CLIENT_SECRET = "8721d0b3-37ea-4484-8d65-6418a61fd1a1";

// RestTemplate์„ Mocking
@MockBean
private RestTemplate restTemplate;

@Test
public void testPublishToken_Success() {
try {
// ๊ฐ€์งœ ์‘๋‹ต ์„ค์ • (JSON ํ˜•์‹์˜ Access Token ๋ฐ˜ํ™˜)
String mockResponse = "{ \"access_token\": \"mock_access_token\", \"token_type\": \"bearer\" }";

// ResponseEntity ์ƒ์„ฑ (๋ชจํ‚น๋œ ์‘๋‹ต)
ResponseEntity<String> mockResponseEntity = new ResponseEntity<>(mockResponse, HttpStatus.OK);

// RestTemplate.exchange๊ฐ€ ํ˜ธ์ถœ๋  ๋•Œ mockResponseEntity๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ์„ค์ •
when(restTemplate.exchange(
anyString(),
eq(HttpMethod.POST),
any(HttpEntity.class),
eq(String.class)))
.thenReturn(mockResponseEntity);

// ์‹ค์ œ ํ† ํฐ ๋ฐœ๊ธ‰ ํ•จ์ˆ˜ ํ˜ธ์ถœ
HashMap<String, String> tokenMap = publishToken(CLIENT_ID, CLIENT_SECRET);

// ์‘๋‹ต ๊ฒ€์ฆ
assertThat(tokenMap).isNotNull();
assertThat(tokenMap.containsKey("access_token")).isTrue();
assertThat(tokenMap.get("access_token")).isEqualTo("mock_access_token");

System.out.println("Access Token: " + tokenMap.get("access_token"));
} catch (Exception e) {
fail("Exception occurred: " + e.getMessage());
}
}

/**
* RestTemplate์„ ์‚ฌ์šฉํ•˜์—ฌ ํ† ํฐ์„ ๋ฐœ๊ธ‰๋ฐ›๋Š” ๋ฉ”์„œ๋“œ
*
* @param clientId OAuth2 Client ID
* @param clientSecret OAuth2 Client Secret
* @return ํ† ํฐ ์‘๋‹ต ๋ฐ์ดํ„ฐ๊ฐ€ ํฌํ•จ๋œ HashMap
*/
public HashMap<String, String> publishToken(String clientId, String clientSecret) {
try {
// Base64 ์ธ์ฝ”๋”ฉ๋œ ์ธ์ฆ ํ—ค๋” ์ƒ์„ฑ
String auth = clientId + ":" + clientSecret;
String authHeader = "Basic " + Base64.getEncoder().encodeToString(auth.getBytes());

// HTTP ์š”์ฒญ ํ—ค๋” ์„ค์ •
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.set("Authorization", authHeader);

// ์š”์ฒญ ๋ฐ”๋”” ์„ค์ • (grant_type ์„ค์ •)
String body = "grant_type=client_credentials&scope=read";

// HttpEntity๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์š”์ฒญ ํ—ค๋” ๋ฐ ๋ฐ”๋””๋ฅผ ์„ค์ •
HttpEntity<String> requestEntity = new HttpEntity<>(body, headers);

// Mock๋œ RestTemplate ์‚ฌ์šฉ (์‹ค์ œ API ํ˜ธ์ถœ X)
ResponseEntity<String> response = restTemplate.exchange(
TOKEN_URL,
HttpMethod.POST,
requestEntity,
String.class
);

// ์‘๋‹ต ๋ณธ๋ฌธ ์ถœ๋ ฅ ๋ฐ ํ™•์ธ
String responseBody = response.getBody();
System.out.println("Response Body: " + responseBody);

// ์‘๋‹ต ๋ณธ๋ฌธ์„ JSON ํ˜•ํƒœ๋กœ ํŒŒ์‹ฑํ•˜์—ฌ HashMap์œผ๋กœ ๋ฐ˜ํ™˜
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(responseBody, new TypeReference<HashMap<String, String>>() {});
} catch (Exception e) {
System.err.println("Exception occurred: " + e.getMessage());
return null;
}
}
}
// ์•„๋ž˜ ์ฝ”๋“œ๋Š” Spring ํ™˜๊ฒฝ ์•„๋‹ˆ์–ด๋„ ๋…๋ฆฝ์ ์œผ๋กœ ์‹คํ–‰ ๊ฐ€๋Šฅํ•œ ์œ ๋‹› ํ…Œ์ŠคํŠธ
// package web3.api.identity;

// import org.junit.jupiter.api.Test;

// import java.util.HashMap;

// import static org.assertj.core.api.Assertions.assertThat;
// import static org.assertj.core.api.Assertions.fail;

// public class GetTokenTest {

// private String clientId = "86640213-3b83-461a-97ab-2491d68a2052";
// private String clientSecret = "8721d0b3-37ea-4484-8d65-6418a61fd1a1";
// private String invalidClientId = "invalid-client-id";
// private String invalidClientSecret = "invalid-client-secret";

// @Test
// public void testPublishToken_Success() {
// try {
// HashMap<String, String> tokenMap = GetToken.publishToken(clientId, clientSecret);
// assertThat(tokenMap).isNotNull();
// assertThat(tokenMap.containsKey("access_token")).isTrue();
// System.out.println("Access Token: " + tokenMap.get("access_token"));
// } catch (Exception e) {
// fail("Exception occurred: " + e.getMessage());
// }
// }

// @Test
// public void testPublishToken_Failure() {
// try {
// HashMap<String, String> tokenMap = GetToken.publishToken(invalidClientId, invalidClientSecret);
// assertThat(tokenMap).isNull();
// } catch (Exception e) {
// // Expected exception caught, test passed.
// assertThat(e.getMessage()).contains("Failed to get access token");
// }
// }
// }
Loading

0 comments on commit dba1bd5

Please sign in to comment.