- Implemented expiration check

- Added Expiration test
This commit is contained in:
Max W. 2024-04-07 23:47:47 +02:00
parent 278b613230
commit a4c71eccb1
2 changed files with 19 additions and 3 deletions

View File

@ -40,7 +40,10 @@ public class AuthenticationService {
this.secretKey = Keys.hmacShaKeyFor(encodedKey);
}
public String authenticate(String username, String password) {
public String authenticate(String username, String password, long... expirationTime/*FOR TESTING VALIDITY*/) {
if(expirationTime.length > 0) {
this.expirationTime = expirationTime[0];
}
Optional<User> user = userRepository.retrieveUserByUsername(username);
if (user.isPresent() && passwordEncoder.matches(password, user.get().getPassword())) {
return generateToken(username);
@ -64,8 +67,8 @@ public class AuthenticationService {
public boolean validateToken(String token) {
try {
Jwt<?,?> jwt = Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token);
// TODO: Check if token is expired
return true;
Claims claims = (Claims) jwt.getPayload();
return !claims.getExpiration().before(new Date()); // Checks if the token is expired too
} catch (Exception e) {
return false;
}

View File

@ -11,6 +11,7 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.util.Date;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
@ -26,6 +27,9 @@ public class AuthenticationServiceTest {
@Autowired
private AuthenticationService authenticationService;
@Value("${secureapi.jwt.expiration}")
private long expirationTime;
private User mockUser;
private String username = "testUser";
private String password = "testPass";
@ -55,4 +59,13 @@ public class AuthenticationServiceTest {
String invalidToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0VXNlciJ9.WrongSignature";
assertFalse(authenticationService.validateToken(invalidToken), "Token validation should return false for an invalid token");
}
@Test
public void whenTokenIsExplicitlyExpired_thenValidateTokenShouldReturnFalse() throws InterruptedException {
long testExpirationTime = 1; // 1 millisecond
String token = authenticationService.authenticate("testUser", "testPass", testExpirationTime);
assertNotNull(token, "Token should not be null");
Thread.sleep(2); // Wait for 2 milliseconds to ensure the token has expired (Bad practice but easy)
assertFalse(authenticationService.validateToken(token), "Expired token should not be valid");
}
}