Skip to content

Commit

Permalink
Jwt token update
Browse files Browse the repository at this point in the history
  • Loading branch information
vinodbalakumar committed Oct 5, 2024
1 parent 299c323 commit 8675f73
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 14 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ This project demonstrates a simple JWT (JSON Web Token) authentication service b
- [Installation](#installation)
- [Configuration](#configuration)
- [Endpoints](#endpoints)
- [Testing the JWT Authentication](#testing-the-jwt-authentication)
- [Testing the JWT Authentication](#testing-the-jwt-authentication) stateless jwt token: means not managing session with server
- [License](#license)

## Technologies Used
Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
<version>0.12.0</version>
</dependency>

<!-- MySQL Driver -->
Expand Down
40 changes: 29 additions & 11 deletions src/main/java/com/java/vls/employee/portal/jwt/JwtUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
Expand All @@ -16,7 +18,17 @@
@Component
public class JwtUtil {

private String SECRET_KEY = "vinod"; // Keep this secure
private SecretKey secretKey;

private static final long EXPIRATION_TIME = 864_000_000; // 10 days

private static final SecretKey KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);

// Constructor to initialize the secret key
public JwtUtil(@Value("${jwt.secret}") String secret) {
byte[] decodedKey = Base64.getDecoder().decode(secret);
this.secretKey = Keys.hmacShaKeyFor(decodedKey);
}

// Extract username from token
public String extractUsername(String token) {
Expand All @@ -34,26 +46,32 @@ public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
}

private Claims extractAllClaims(String token) {
return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
return Jwts.parser().setSigningKey(secretKey).build().parseClaimsJws(token).getBody();
}

private Boolean isTokenExpired(String token) {
return extractExpiration(token).before(new Date());
}



// Generate token for user
public String generateToken(String username) {
Map<String, Object> claims = new HashMap<>();
return createToken(claims, username);
return createToken(username);
}

private String createToken(Map<String, Object> claims, String subject) {
return Jwts.builder().setClaims(claims).setSubject(subject)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) // Token validity: 10 hours
.signWith(SignatureAlgorithm.HS256, SECRET_KEY).compact();
public String createToken(String username) {
return Jwts.builder()
.subject(username)
.issuedAt(new Date(System.currentTimeMillis()))
.expiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(secretKey)
.compact();
// .signWith(SignatureAlgorithm.HS256, SECRET_KEY).compact();

}


// Validate token
public Boolean validateToken(String token, String username) {
final String tokenUsername = extractUsername(token);
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,4 @@ spring.jpa.properties.hibernate.use_sql_comments=false
#logging.level.org.hibernate.SQL=DEBUG
#logging.level.org.hibernate.type.descriptor.sql.BasicTypeDescriptor=TRACE


jwt.secret=wgacTUNAIW6QZpFyUwLG1K227MS3on3pSfhvIYrN/aw=
14 changes: 14 additions & 0 deletions src/test/java/com/java/vls/employee/portal/JwtKeyGenerator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.java.vls.employee.portal;

import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import javax.crypto.SecretKey;
import java.util.Base64;

public class JwtKeyGenerator {
public static void main(String[] args) {
SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256); // Generate a strong key for HS256
String encodedKey = Base64.getEncoder().encodeToString(key.getEncoded());
System.out.println("Base64 Encoded Secret Key: " + encodedKey);
}
}

0 comments on commit 8675f73

Please sign in to comment.