Public Access
Changed from JWT token to public/privat key
This commit is contained in:
1 parent
874f8dee58
commit
8505faa578
6 files changed
+167
-133
No files matched your search
@@ -11,5 +11,12 @@ import org.springframework.context.annotation.Configuration;
|
||||
@ConfigurationProperties(prefix = "security.jwt")
|
||||
public class JwtConfig {
|
||||
|
||||
private String secret;
|
||||
/** Base64-encoded PKCS8 DER Ed25519 private key. Used to sign JWTs. */
|
||||
private String privateKey;
|
||||
|
||||
/** Base64-encoded X.509 DER Ed25519 public key. Embedded so JWKS can publish it. */
|
||||
private String publicKey;
|
||||
|
||||
/** Key identifier set in the JWS `kid` header. Enables future rotation. */
|
||||
private String kid;
|
||||
}
|
||||
@@ -2,35 +2,46 @@ package auth_service.configuration.security;
|
||||
|
||||
import auth_service.modules.login.service.TokenGenerator;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Service responsible for generating and validating JSON Web Tokens (JWT).
|
||||
* Signing: EdDSA (Ed25519). Auth holds the private key and signs; Core holds only the public key and verifies.
|
||||
*/
|
||||
@Service
|
||||
public class JwtService implements TokenGenerator {
|
||||
|
||||
// Token validity: 24 hours in milliseconds
|
||||
private static final long JWT_EXPIRATION_MS = 86400000;
|
||||
private static final String ED25519 = "Ed25519";
|
||||
|
||||
private final JwtConfig jwtConfig;
|
||||
private PrivateKey privateKey;
|
||||
private PublicKey publicKey;
|
||||
|
||||
public JwtService(JwtConfig jwtConfig) {
|
||||
this.jwtConfig = jwtConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a secure JWT for the authenticated user.
|
||||
*
|
||||
* @return A signed JWT string
|
||||
*/
|
||||
@PostConstruct
|
||||
void init() {
|
||||
this.privateKey = decodePrivateKey(jwtConfig.getPrivateKey());
|
||||
this.publicKey = decodePublicKey(jwtConfig.getPublicKey());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String generateToken(String userId, String email, Long steamId) {
|
||||
var builder = Jwts.builder()
|
||||
.header().keyId(jwtConfig.getKid()).and()
|
||||
.subject(email)
|
||||
.claim("userId", userId)
|
||||
.issuedAt(new Date(System.currentTimeMillis()))
|
||||
@@ -41,13 +52,13 @@ public class JwtService implements TokenGenerator {
|
||||
}
|
||||
|
||||
return builder
|
||||
.signWith(getSigningKey())
|
||||
.signWith(privateKey, Jwts.SIG.EdDSA)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public String extractEmail(String token) {
|
||||
return Jwts.parser()
|
||||
.verifyWith(getSigningKey())
|
||||
.verifyWith(publicKey)
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload()
|
||||
@@ -56,7 +67,7 @@ public class JwtService implements TokenGenerator {
|
||||
|
||||
public String extractUserId(String token) {
|
||||
return Jwts.parser()
|
||||
.verifyWith(getSigningKey())
|
||||
.verifyWith(publicKey)
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload()
|
||||
@@ -65,7 +76,7 @@ public class JwtService implements TokenGenerator {
|
||||
|
||||
public Long extractSteamId(String token) {
|
||||
return Jwts.parser()
|
||||
.verifyWith(getSigningKey())
|
||||
.verifyWith(publicKey)
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload()
|
||||
@@ -75,7 +86,7 @@ public class JwtService implements TokenGenerator {
|
||||
public boolean isTokenValid(String token) {
|
||||
try {
|
||||
Jwts.parser()
|
||||
.verifyWith(getSigningKey())
|
||||
.verifyWith(publicKey)
|
||||
.build()
|
||||
.parseSignedClaims(token);
|
||||
return true;
|
||||
@@ -84,12 +95,21 @@ public class JwtService implements TokenGenerator {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the cryptographic key used for signing the token.
|
||||
*/
|
||||
private SecretKey getSigningKey() {
|
||||
String secretKey = jwtConfig.getSecret();
|
||||
byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
|
||||
return Keys.hmacShaKeyFor(keyBytes);
|
||||
private static PrivateKey decodePrivateKey(String base64Pkcs8Der) {
|
||||
try {
|
||||
byte[] keyBytes = Base64.getDecoder().decode(base64Pkcs8Der);
|
||||
return KeyFactory.getInstance(ED25519).generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Failed to decode Ed25519 private key", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static PublicKey decodePublicKey(String base64X509Der) {
|
||||
try {
|
||||
byte[] keyBytes = Base64.getDecoder().decode(base64X509Der);
|
||||
return KeyFactory.getInstance(ED25519).generatePublic(new X509EncodedKeySpec(keyBytes));
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Failed to decode Ed25519 public key", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,12 @@ spring:
|
||||
|
||||
security:
|
||||
jwt:
|
||||
secret: "NzC9tQP1eTp496SxoVYslH1bqn81Tbfz74NjkFqdcVe7wayjcRN8IeZvJWd1s6NEWgwEXe9rdccvOn2HtJ4fdq"
|
||||
# Dev-only Ed25519 keypair. DO NOT use in production — regenerate per-env with:
|
||||
# openssl genpkey -algorithm Ed25519 -outform DER | base64 -w0
|
||||
# openssl pkey -inform DER -in <(base64 -d <<< "$PRIV") -pubout -outform DER | base64 -w0
|
||||
private-key: "MC4CAQAwBQYDK2VwBCIEIG9nxZFw9Fj7lGUqA7oi94oo/xollxwlZIZENlpfp+tc"
|
||||
public-key: "MCowBQYDK2VwAyEAPSmUISg0IUO1LrRPhF8RZAT/Yjh9HEVf5hzR84AL1Zw="
|
||||
kid: "tbp-auth-dev"
|
||||
|
||||
auth:
|
||||
registration:
|
||||
|
||||
@@ -44,7 +44,9 @@ management:
|
||||
# Security stuff
|
||||
security:
|
||||
jwt:
|
||||
secret: ${JWT_SECRET}
|
||||
private-key: ${JWT_PRIVATE_KEY}
|
||||
public-key: ${JWT_PUBLIC_KEY}
|
||||
kid: ${JWT_KID:tbp-auth-1}
|
||||
|
||||
# Custom properties for CORS
|
||||
app:
|
||||
|
||||
@@ -1,109 +1,109 @@
|
||||
package auth_service.configuration.security;
|
||||
|
||||
import auth_service.shared.test.AbstractUnitTest;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Tests for JwtService.
|
||||
*/
|
||||
class JwtServiceTest extends AbstractUnitTest {
|
||||
|
||||
@Mock
|
||||
private JwtConfig jwtConfig;
|
||||
|
||||
private JwtService jwtService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(jwtConfig.getSecret()).thenReturn("verysecretkeythatmustbeatleast32characterslongforhmacsha");
|
||||
jwtService = new JwtService(jwtConfig);
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateToken_Success() {
|
||||
// Arrange
|
||||
var userId = "0815";
|
||||
var email = "test@example.com";
|
||||
|
||||
// Act
|
||||
var token = jwtService.generateToken(userId, email, null);
|
||||
|
||||
// Assert
|
||||
assertNotNull(token);
|
||||
assertFalse(token.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractEmail_Success() {
|
||||
// Arrange
|
||||
var userId = "0815";
|
||||
var email = "test@example.com";
|
||||
var token = jwtService.generateToken(userId, email, null);
|
||||
|
||||
// Act
|
||||
var extractedEmail = jwtService.extractEmail(token);
|
||||
|
||||
// Assert
|
||||
assertEquals(email, extractedEmail);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractUserId_Success() {
|
||||
// Arrange
|
||||
var userId = "0815";
|
||||
var email = "test@example.com";
|
||||
var token = jwtService.generateToken(userId, email, null);
|
||||
|
||||
// Act
|
||||
var extractedUserId = jwtService.extractUserId(token);
|
||||
|
||||
// Assert
|
||||
assertEquals(userId, extractedUserId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractSteamId_Success() {
|
||||
// Arrange
|
||||
var userId = "0815";
|
||||
var email = "test@example.com";
|
||||
var steamId = 123456789L;
|
||||
var token = jwtService.generateToken(userId, email, steamId);
|
||||
|
||||
// Act
|
||||
var extractedSteamId = jwtService.extractSteamId(token);
|
||||
|
||||
// Assert
|
||||
assertEquals(steamId, extractedSteamId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void isTokenValid_Success() {
|
||||
// Arrange
|
||||
var userId = "0815";
|
||||
var email = "test@example.com";
|
||||
var token = jwtService.generateToken(userId, email, null);
|
||||
|
||||
// Act
|
||||
var isValid = jwtService.isTokenValid(token);
|
||||
|
||||
// Assert
|
||||
assertTrue(isValid);
|
||||
}
|
||||
|
||||
@Test
|
||||
void isTokenValid_Failure() {
|
||||
// Arrange
|
||||
var invalidToken = "invalid-token";
|
||||
|
||||
// Act
|
||||
var isValid = jwtService.isTokenValid(invalidToken);
|
||||
|
||||
// Assert
|
||||
assertFalse(isValid);
|
||||
}
|
||||
}
|
||||
package auth_service.configuration.security;
|
||||
|
||||
import auth_service.shared.test.AbstractUnitTest;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
|
||||
import java.security.KeyFactory;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.PublicKey;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.util.Base64;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
|
||||
/**
|
||||
* Tests for JwtService (EdDSA / Ed25519).
|
||||
*/
|
||||
class JwtServiceTest extends AbstractUnitTest {
|
||||
|
||||
private static final String KID = "test-key-1";
|
||||
|
||||
@Mock
|
||||
private JwtConfig jwtConfig;
|
||||
|
||||
private JwtService jwtService;
|
||||
private PublicKey publicKey;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
KeyPair keyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair();
|
||||
String privateB64 = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
|
||||
String publicB64 = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
|
||||
|
||||
lenient().when(jwtConfig.getPrivateKey()).thenReturn(privateB64);
|
||||
lenient().when(jwtConfig.getPublicKey()).thenReturn(publicB64);
|
||||
lenient().when(jwtConfig.getKid()).thenReturn(KID);
|
||||
|
||||
publicKey = KeyFactory.getInstance("Ed25519")
|
||||
.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicB64)));
|
||||
|
||||
jwtService = new JwtService(jwtConfig);
|
||||
jwtService.init();
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateToken_Success() {
|
||||
var token = jwtService.generateToken("0815", "test@example.com", null);
|
||||
|
||||
assertNotNull(token);
|
||||
assertFalse(token.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateToken_setsKidHeader() {
|
||||
var token = jwtService.generateToken("0815", "test@example.com", null);
|
||||
|
||||
var header = Jwts.parser()
|
||||
.verifyWith(publicKey)
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getHeader();
|
||||
|
||||
assertEquals(KID, header.getKeyId());
|
||||
assertEquals("EdDSA", header.getAlgorithm());
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractEmail_Success() {
|
||||
var email = "test@example.com";
|
||||
var token = jwtService.generateToken("0815", email, null);
|
||||
|
||||
assertEquals(email, jwtService.extractEmail(token));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractUserId_Success() {
|
||||
var userId = "0815";
|
||||
var token = jwtService.generateToken(userId, "test@example.com", null);
|
||||
|
||||
assertEquals(userId, jwtService.extractUserId(token));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractSteamId_Success() {
|
||||
var steamId = 123456789L;
|
||||
var token = jwtService.generateToken("0815", "test@example.com", steamId);
|
||||
|
||||
assertEquals(steamId, jwtService.extractSteamId(token));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isTokenValid_Success() {
|
||||
var token = jwtService.generateToken("0815", "test@example.com", null);
|
||||
|
||||
assertTrue(jwtService.isTokenValid(token));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isTokenValid_Failure() {
|
||||
assertFalse(jwtService.isTokenValid("invalid-token"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user