Skip to content

Commit

Permalink
create JWT tokens for integration tests
Browse files Browse the repository at this point in the history
  • Loading branch information
yasasghari committed Feb 29, 2024
1 parent 6afbd49 commit 2eba254
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,17 @@ public String applicationPage() {
public ResponseEntity<Object> handleApplicationStatus(@RequestHeader("Authorization") String header, @RequestBody ApplicationStatusDTO applicationStatusDTO, HttpServletRequest request) {
//IP address of the machine requesting to set/update application status.
String IP = request.getRemoteAddr();

String jwtToken = header.replace("Bearer ", "");
System.out.println("token" + jwtToken);
//Error messages in case of an invalid person_id or an invalid status or an invalid JWT token.
String jwtTokenErrorMessage = jwtAuthService.jwtAuth(header);
String personIdErrorMessage = applicationStatusService.isPersonIdValid(applicationStatusDTO.getPerson_id());
String statusErrorMessage = applicationStatusService.isStatusValid(applicationStatusDTO.getStatus());

//Validation process to make sure person_id and status received is correct.
if ("UNAUTHORIZED".equals(jwtTokenErrorMessage)) {
System.out.println("token invalid");
logger.error("The person with IP address: {} has unauthorized access with the provided JWT token ", IP);
return new ResponseEntity<>(new ErrorDTO(jwtTokenErrorMessage), HttpStatus.BAD_REQUEST);
} else if ("INVALID_DATA".equals(personIdErrorMessage)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;

import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

Expand All @@ -27,7 +26,7 @@ public class JwtAuthService {
/**
* Config variable JWT secret from Heroku.
*/
@Value("${JWT_SECRET}")
@Value("${JWT_SECRET:FKi2FTPuzT6XzXZnDjR4Z2X5Uu2+C3yNq3BgtHJvd4g=}")
private String JWT_SECRET;

/**
Expand All @@ -48,14 +47,33 @@ public String jwtAuth(String header) {
Claims claims = parseJwtClaims.getBody();
Integer roleValue = claims.get("role", Integer.class);
if (roleValue != null && roleValue.equals(1)) {
System.out.println("role 1");
logger.info("Authorized user");
return "AUTHORIZED";
} else {
logger.info("Unauthorized user");
System.out.println("role isnt 1");
return "UNAUTHORIZED";
}
} catch (Exception e) {
System.out.println("deep shit");
return "UNAUTHORIZED";
}
}

/**
* Creates JWT tokens to use during integration testing.
* @return JWT tokens encoded using HS256 algorithm.
*/
public String jwtCreateTestTokens(){
SecretKeySpec keyTest = new SecretKeySpec(JWT_SECRET.getBytes(),
SignatureAlgorithm.HS256.getJcaName());
return Jwts.builder()
.claim("usage", "login")
.claim("id", 5)
.claim("username", "MaxwellBailey")
.claim("role", 1)
.signWith(keyTest)
.compact();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.example.applicationstatusservice.model.dto.ApplicationStatusDTO;
import com.example.applicationstatusservice.model.dto.PersonDTO;
import com.example.applicationstatusservice.repository.PersonRepository;
import com.example.applicationstatusservice.service.JwtAuthService;
import com.example.applicationstatusservice.service.PersonService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
Expand All @@ -18,7 +19,6 @@
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

import static org.junit.jupiter.api.Assertions.assertEquals;

/**
Expand Down Expand Up @@ -53,6 +53,14 @@ public class ApplicationStatusControllerIntegrationTest {
@Autowired
private ApplicationStatusController applicationStatusController;

/**
* JwtAuthService is an autowired instance containing logic for authentication
* and authorization of jwt tokens.
* {@code @Autowired} provides automatic dependency injection.
*/
@Autowired
private JwtAuthService jwtAuthService;

/**
* PersonService is an autowired instance containing business-logic for person-related operations.
* {@code @Autowired} provides automatic dependency injection.
Expand All @@ -66,9 +74,6 @@ public class ApplicationStatusControllerIntegrationTest {
@Autowired
PersonRepository personRepository;

String testToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2FnZSI6ImxvZ2luIiwiaWQiOjUsInJvbGUiOjEsInVzZXJuYW1lIjoiTWF4d2VsbEJhaWxleSIsImV4cCI6MTcwOTE1NjE2MSwiaWF0IjoxNzA5MTUyNTYxfQ.sevPgpuRvgWU2nDjORn3KYSIJwC_5IvWkWDuOcHKz-0";
String testHeader = "Bearer " + testToken;

/**
* The method sets the property JDBC URL spring.datasource.url
* dynamically for the postgreSQL container.
Expand Down Expand Up @@ -109,7 +114,8 @@ void saveAPerson() {
void personIdValid() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("X-Forwarded-For", "127.0.0.1");

String testToken = jwtAuthService.jwtCreateTestTokens();
String testHeader = "Bearer " + testToken;
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(5L, "Pending");
ResponseEntity<Object> resp = applicationStatusController.handleApplicationStatus(testHeader, applicationStatusDTO, req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
Expand All @@ -122,7 +128,8 @@ void personIdValid() throws Exception {
void personIdInvalid() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("X-Forwarded-For", "127.0.0.1");

String testToken = jwtAuthService.jwtCreateTestTokens();
String testHeader = "Bearer " + testToken;
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(4000L, "Pending");
ResponseEntity<Object> resp = applicationStatusController.handleApplicationStatus(testHeader, applicationStatusDTO, req);
assertEquals(HttpStatus.BAD_REQUEST, resp.getStatusCode());
Expand All @@ -135,7 +142,8 @@ void personIdInvalid() throws Exception {
void statusPendingValid() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("X-Forwarded-For", "127.0.0.1");

String testToken = jwtAuthService.jwtCreateTestTokens();
String testHeader = "Bearer " + testToken;
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(9L, "Pending");
ResponseEntity<Object> resp = applicationStatusController.handleApplicationStatus(testHeader, applicationStatusDTO, req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
Expand All @@ -148,7 +156,8 @@ void statusPendingValid() throws Exception {
void statusAcceptValid() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("X-Forwarded-For", "127.0.0.1");

String testToken = jwtAuthService.jwtCreateTestTokens();
String testHeader = "Bearer " + testToken;
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(1L, "Accept");
ResponseEntity<Object> resp = applicationStatusController.handleApplicationStatus(testHeader, applicationStatusDTO, req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
Expand All @@ -161,7 +170,8 @@ void statusAcceptValid() throws Exception {
void statusRejectValid() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("X-Forwarded-For", "127.0.0.1");

String testToken = jwtAuthService.jwtCreateTestTokens();
String testHeader = "Bearer " + testToken;
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(3L, "Reject");
ResponseEntity<Object> resp = applicationStatusController.handleApplicationStatus(testHeader, applicationStatusDTO, req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
Expand All @@ -174,7 +184,8 @@ void statusRejectValid() throws Exception {
void statusInvalid() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("X-Forwarded-For", "127.0.0.1");

String testToken = jwtAuthService.jwtCreateTestTokens();
String testHeader = "Bearer " + testToken;
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(4L, "random");
ResponseEntity<Object> resp = applicationStatusController.handleApplicationStatus(testHeader, applicationStatusDTO, req);
assertEquals(HttpStatus.BAD_REQUEST, resp.getStatusCode());
Expand All @@ -187,7 +198,8 @@ void statusInvalid() throws Exception {
void jwtTokenValid() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("X-Forwarded-For", "127.0.0.1");

String testToken = jwtAuthService.jwtCreateTestTokens();
String testHeader = "Bearer " + testToken;
ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(6L, "Pending");
ResponseEntity<Object> resp = applicationStatusController.handleApplicationStatus(testHeader, applicationStatusDTO, req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
Expand All @@ -201,10 +213,8 @@ void jwtTokenValid() throws Exception {
void jwtTokenInValid() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("X-Forwarded-For", "127.0.0.1");

String testToken = "yJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2FnZSI6ImxvZ2luIiwiaWQiOjUsInJvbGUiOjEsInVzZXJuYW1lIjoiTWF4d2VsbEJhaWxleSIsImV4cCI6MTcwOTE1NjE2MSwiaWF0IjoxNzA5MTUyNTYxfQ.sevPgpuRvgWU2nDjORn3KYSIJwC_5IvWkWDuOcHKz-0";
String testToken = "INVALID_TOKEN";
String testHeader = "Bearer " + testToken;

ApplicationStatusDTO applicationStatusDTO = new ApplicationStatusDTO(4L, "Pending");
ResponseEntity<Object> resp = applicationStatusController.handleApplicationStatus(testHeader, applicationStatusDTO, req);
assertEquals(HttpStatus.BAD_REQUEST, resp.getStatusCode());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public class ApplicationStatusIntegrationTest {
private ApplicationStatusService applicationStatusService;

/**
* ApplicationStatusService is an autowired instance containing logic for authentication
* JwtAuthService is an autowired instance containing logic for authentication
* and authorization of jwt tokens.
* {@code @Autowired} provides automatic dependency injection.
*/
Expand Down Expand Up @@ -172,7 +172,7 @@ void statusInvalid() throws Exception {
*/
@Test
void jwtTokenValid() throws Exception {
String testToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2FnZSI6ImxvZ2luIiwiaWQiOjUsInJvbGUiOjEsInVzZXJuYW1lIjoiTWF4d2VsbEJhaWxleSIsImV4cCI6MTcwOTE1NjE2MSwiaWF0IjoxNzA5MTUyNTYxfQ.sevPgpuRvgWU2nDjORn3KYSIJwC_5IvWkWDuOcHKz-0";
String testToken = jwtAuthService.jwtCreateTestTokens();
String testHeader = "Bearer " + testToken;
assertEquals("AUTHORIZED", jwtAuthService.jwtAuth(testHeader));
}
Expand All @@ -182,7 +182,7 @@ void jwtTokenValid() throws Exception {
*/
@Test
void jwtTokenInValid() throws Exception {
String testToken = "yJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2FnZSI6ImxvZ2luIiwiaWQiOjUsInJvbGUiOjEsInVzZXJuYW1lIjoiTWF4d2VsbEJhaWxleSIsImV4cCI6MTcwOTE1NjE2MSwiaWF0IjoxNzA5MTUyNTYxfQ.sevPgpuRvgWU2nDjORn3KYSIJwC_5IvWkWDuOcHKz-0";
String testToken = "INVALID_TOKEN";
String testHeader = "Bearer " + testToken;
assertEquals("UNAUTHORIZED", jwtAuthService.jwtAuth(testHeader));
}
Expand Down

0 comments on commit 2eba254

Please sign in to comment.