Skip to content

Commit

Permalink
Merge spring boot actuator
Browse files Browse the repository at this point in the history
  • Loading branch information
linxiaoxin committed Jun 14, 2024
1 parent 69628a0 commit 43020f5
Show file tree
Hide file tree
Showing 7 changed files with 176 additions and 7 deletions.
6 changes: 6 additions & 0 deletions src/main/java/com/quemistry/auth_ms/Application.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class Application {
Expand All @@ -10,4 +12,8 @@ public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.quemistry.auth_ms.config;

import org.springframework.context.annotation.Configuration;

@Configuration
public class RestClientConfig {

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/v1/auth")
Expand All @@ -26,7 +23,7 @@ public ResponseEntity<UserProfile> getAccess(@RequestBody TokenRequest request){

//create cookie and return code with response
HttpHeaders headers = new HttpHeaders();
headers.add("Set-Cookie", String.format("quemistry_session=%s; Max-Age=86400; Path=/; HttpOnly",tokenResponse.getAccessToken()));
headers.add("Set-Cookie", String.format("quemistry_session=%s; Max-Age=86400; Path=/; HttpOnly",tokenResponse));

if(tokenResponse == null)
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
Expand All @@ -36,4 +33,10 @@ public ResponseEntity<UserProfile> getAccess(@RequestBody TokenRequest request){

return ResponseEntity.status(HttpStatus.OK).headers(headers).body(user);
}

@PostMapping("SignOut")
public ResponseEntity signOut(){
//System.out.println(token.getEmail());
return ResponseEntity.ok("Logout");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.quemistry.auth_ms.model.TokenRequest;
import com.quemistry.auth_ms.model.TokenResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
Expand All @@ -20,11 +21,13 @@ public class AuthenticationServiceImpl implements AuthenticationService {
@Value("${quemistry.cognito.url}")
private String QUEMISTRY_COGNITO_URL;

@Autowired
private RestTemplate restTemplate;

@Override
public TokenResponse getAccessToken(TokenRequest request) {
final String tokenUri = QUEMISTRY_COGNITO_URL+"/oauth2/token";
final String tokenUri = "https://quemistry.auth.ap-southeast-1.amazoncognito.com/oauth2/token";

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED.toString());

Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ spring.application.name=auth_ms

spring.docker.compose.enabled=false
quemistry.cognito.url=https://quemistry.auth.ap-southeast-1.amazoncognito.com

sonar.gradle.skipCompile=true
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package com.quemistry.auth_ms.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.quemistry.auth_ms.model.TokenRequest;
import com.quemistry.auth_ms.model.TokenResponse;
import com.quemistry.auth_ms.model.UserProfile;
import com.quemistry.auth_ms.service.AuthenticationService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.mockito.BDDMockito.given;
@WebMvcTest(AuthenticationController.class)
public class AuthenticationControllerTest {

@Autowired
private MockMvc mockMvc;
@MockBean
private AuthenticationService authenticationService;

private TokenRequest tokenRequest;

private TokenResponse tokenResponse;

private UserProfile user;
@BeforeEach
void init(){
tokenRequest = new TokenRequest();
tokenRequest.setClientId("testclientId");
tokenRequest.setAuthCode("testAuthCode");
tokenRequest.setCodeVerifier("testCodeVerifier");
tokenRequest.setRedirectUrl("testUrl");

//output
tokenResponse = new TokenResponse();
tokenResponse.setIdToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJlbWFpbCI6InRlc3RVc2VyQGVtYWlsLmNvbSJ9.cI8ybuRu1FP7_jR9-mHuS2w9EBVueQRMR5DeF2C3pWc");
tokenResponse.setEmail("[email protected]");

user = new UserProfile();
user.setEmail("[email protected]");
}
@Test
void givenGetAccessToken_Success() throws Exception{

given(authenticationService.getAccessToken(tokenRequest)).willReturn(tokenResponse);
ObjectMapper mapper = new ObjectMapper();


var result = mockMvc.perform(post("/v1/auth")
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsString(tokenRequest)))
.andExpect(status().isOk())
.andReturn();

var setCookieHeader = result.getResponse().getHeader("Set-Cookie");
Assertions.assertNotNull(setCookieHeader);

}

@Test
void givenSignOut_Success() throws Exception{

HttpHeaders headers = new HttpHeaders();
headers.add("Set-Cookie", String.format("quemistry_session=%s; Max-Age=86400; Path=/; HttpOnly",tokenResponse));

mockMvc.perform(post("/v1/auth/SignOut")
.contentType(MediaType.APPLICATION_JSON)
.headers(headers))
.andExpect(status().isOk());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package com.quemistry.auth_ms.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.quemistry.auth_ms.model.TokenRequest;
import com.quemistry.auth_ms.model.TokenResponse;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.net.URISyntaxException;

@WebMvcTest(AuthenticationService.class)
public class AuthenticationServiceImplTest {

@Value("${quemistry.cognito.url}")
private String QUEMISTRY_COGNITO_URL;

@Mock
private RestTemplate restTemplate;

@InjectMocks
private AuthenticationServiceImpl authenticationService;

@Test
void givenGetAccessToken_Success() throws Exception{
TokenResponse tokenResponse = new TokenResponse();

//idtoken with email set as [email protected]
tokenResponse.setIdToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJlbWFpbCI6InRlc3RVc2VyQGVtYWlsLmNvbSJ9.cI8ybuRu1FP7_jR9-mHuS2w9EBVueQRMR5DeF2C3pWc");

String tokenUri = "https://quemistry.auth.ap-southeast-1.amazoncognito.com/oauth2/token";

ObjectMapper mapper = new ObjectMapper();

TokenRequest tokenRequest = new TokenRequest();
tokenRequest.setClientId("testclientId");
tokenRequest.setAuthCode("testAuthCode");
tokenRequest.setCodeVerifier("testCodeVerifier");
tokenRequest.setRedirectUrl("testUrl");

HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED.toString());

MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.add("grant_type","authorization_code");
formData.add("redirect_uri",tokenRequest.getRedirectUrl());
formData.add("client_id",tokenRequest.getClientId());
formData.add("code",tokenRequest.getAuthCode());
formData.add("code_verifier",tokenRequest.getCodeVerifier());
HttpEntity<MultiValueMap<String, String>> formEntity = new HttpEntity<>(formData, headers);

Mockito.when(restTemplate.postForEntity(tokenUri, formEntity, TokenResponse.class))
.thenReturn(new ResponseEntity(tokenResponse, HttpStatus.OK));

var result = authenticationService.getAccessToken(tokenRequest);
tokenResponse.setEmail("[email protected]");
Assertions.assertEquals(result, result );
}
}

0 comments on commit 43020f5

Please sign in to comment.