-
Notifications
You must be signed in to change notification settings - Fork 5
7 jwt service implementation #8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
DevEpso
wants to merge
2
commits into
main
Choose a base branch
from
7-jwt-service-implementation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
112 changes: 112 additions & 0 deletions
112
apigateway/src/main/java/vaultweb/apigateway/service/JwtService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| package vaultweb.apigateway.service; | ||
|
|
||
| import io.jsonwebtoken.Claims; | ||
| import io.jsonwebtoken.JwtException; | ||
| import io.jsonwebtoken.JwtParser; | ||
| import io.jsonwebtoken.Jwts; | ||
| import io.jsonwebtoken.io.Decoders; | ||
| import io.jsonwebtoken.security.Keys; | ||
| import java.util.Date; | ||
| import javax.crypto.SecretKey; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.stereotype.Service; | ||
|
|
||
| @Service | ||
| public class JwtService { | ||
|
|
||
| @Value("${jwt.secret}") | ||
| private String SECRET_KEY; | ||
|
|
||
| private JwtParser parser = Jwts.parser() | ||
| .verifyWith(getSigningKey()) | ||
| .build(); | ||
|
|
||
| private static final long EXPIRATION_TIME_MILLIS = 3600000; // 1 hour | ||
|
|
||
| /** | ||
| * Creates a secret key to sign JWT tokens. | ||
| * <p> | ||
| * It always creates the exact same key, with the same secret key. | ||
| * This method decodes the secret key from the application.properties file into a BASE 64 encoded string. | ||
| * It is done to ensure that the secret is properly formed, since {@code SECRET_KEY} could contain non UTF-8 characters. | ||
| * @return {@code SecretKey} | ||
| */ | ||
| private SecretKey getSigningKey() { | ||
| byte[] keyBytes = Decoders.BASE64.decode(SECRET_KEY); | ||
| return Keys.hmacShaKeyFor(keyBytes); | ||
| } | ||
|
|
||
| /** | ||
| * Checks if the token is valid. | ||
| * <p> | ||
| * It verifies the token's signature and expiration time. | ||
| * @param token the token to be validated | ||
| * @return {@code true} if the token is valid, {@code false} otherwise | ||
| */ | ||
| public boolean isValid(final String token) { | ||
| return isUnmodified(token) && !isExpired(token); | ||
| } | ||
|
|
||
| /** | ||
| * Generates a JWT token. | ||
| * <p> | ||
| * The generated token is valid for {@code EXPIRATION_TIME_MILLIS} milliseconds. | ||
| * Additionally, the token is always signed with the {@code SECRET_KEY} to ensure its integrity. | ||
| * The token is always going to contain the user's id and name. | ||
| * @param id of the user | ||
| * @param username of the user | ||
| * @return the generated signed jwt token as a {@link String} | ||
| */ | ||
| public String generateToken(final Integer id, final String username) { | ||
| return Jwts.builder() | ||
| .subject(username) | ||
| .claim("userId", id) | ||
| .issuedAt(new Date()) | ||
| .expiration( | ||
| new Date(System.currentTimeMillis() + EXPIRATION_TIME_MILLIS) | ||
| ) | ||
| .signWith(getSigningKey()) | ||
| .compact(); | ||
| } | ||
|
|
||
| /** | ||
| * Extracts all claims from the given token. | ||
| * @param token the token to extract claims from | ||
| * @return the extracted claims as a {@link Claims} object | ||
| */ | ||
| private Claims extractAllClaims(final String token) { | ||
| return this.parser.parseSignedClaims(token).getPayload(); | ||
| } | ||
|
|
||
| /** | ||
| * Extracts the expiration date of the token. | ||
| * @param token the token to extract claims from | ||
| * @return the expiration date of the token and return it as a {@link Date} | ||
| */ | ||
| private Date extractExpiration(final String token) { | ||
| return extractAllClaims(token).getExpiration(); | ||
| } | ||
|
|
||
| /** | ||
| * Checks if the token is expired. | ||
| * @param token the token to check | ||
| * @return true if the token is expired and false otherwise | ||
| */ | ||
| private boolean isExpired(final String token) { | ||
| return this.extractExpiration(token).before(new Date()); | ||
| } | ||
|
|
||
| /** | ||
| * Checks if the token is unmodified. | ||
| * @param token the token to check | ||
| * @return true if the token is unmodified and false otherwise | ||
| */ | ||
| private boolean isUnmodified(final String token) { | ||
| try { | ||
| this.parser.parseSignedClaims(token); | ||
| return true; | ||
| } catch (final JwtException e) { | ||
| return false; | ||
| } | ||
| } | ||
| } | ||
4 changes: 0 additions & 4 deletions
4
apigateway/src/main/java/vaultweb/apigateway/util/JwtUtil.java
This file was deleted.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
SECRET_KEY is injected by Spring after object construction via @value("${jwt.secret}").
This means that when the JwtParser is initialized at field level, SECRET_KEY is still null, causing getSigningKey() to be called with null, leading to a potential NullPointerException.
Consider initializing the parser lazily (e.g., in a getter) or inside a @PostConstruct method after the secret has been set.