StudentLoanManagement
JwtUtil.java
Go to the documentation of this file.
1package com.student_loan.security;
2
3import io.jsonwebtoken.*;
4import io.jsonwebtoken.security.Keys;
5import org.springframework.stereotype.Component;
6import java.security.Key;
7import java.util.Date;
8
9import javax.crypto.SecretKey;
10
11import java.util.Base64;
12
13@Component
14public class JwtUtil {
15 // Not the best practice to put the secret key in the code
16 // We will do it this way for now to ease the process
17 private static final String SECRET_KEY = "c29tZXZlcnlzZWN1cmVhbmRsb25nYmFzZTY0a2V5MTIzNDU2";
18 private static final long EXPIRATION_TIME = 86400000; // 1 day in miliseconds
19
20 private final Key key = Keys.hmacShaKeyFor(Base64.getDecoder().decode(SECRET_KEY));
21
22 public String generateToken(String email) {
23 return Jwts.builder()
24 .setSubject(email)
25 .setIssuedAt(new Date())
26 .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
27 .signWith(key, SignatureAlgorithm.HS256)
28 .compact();
29 }
30
31 public String extractEmail(String token) {
32 return Jwts.parserBuilder()
33 .setSigningKey(key)
34 .build()
35 .parseClaimsJws(token)
36 .getBody()
37 .getSubject();
38 }
39
40 public boolean validateToken(String token) {
41 try {
42 Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token);
43 return true;
44 } catch (Exception e) {
45 return false;
46 }
47 }
48}
String extractEmail(String token)
Definition JwtUtil.java:31
boolean validateToken(String token)
Definition JwtUtil.java:40
String generateToken(String email)
Definition JwtUtil.java:22