source: bus-n-go-pavel-216049/bus-n-go-backend/src/main/kotlin/mk/ukim/finki/busngobackend/config/JwtService.kt

Last change on this file was baf4cc4, checked in by ppaunovski <paunovskipavel@…>, 3 months ago

split group project and individual project into two separate folders

  • Property mode set to 100644
File size: 1.8 KB
Line 
1package mk.ukim.finki.busngobackend.config
2
3import io.jsonwebtoken.Claims
4import io.jsonwebtoken.Jwts
5import io.jsonwebtoken.security.Keys
6import org.springframework.security.core.userdetails.UserDetails
7import org.springframework.stereotype.Service
8import java.security.Key
9import java.util.Date
10
11@Service
12class JwtService {
13 private val secretKey =
14 Keys.hmacShaKeyFor(
15 "hu55nfa3pRrBRV4DIlvKVDMrg7jnqla9".toByteArray(),
16 )
17
18 fun extractUsername(token: String): String? = extractClaim(token, Claims::getSubject)
19
20 fun <T> extractClaim(
21 token: String,
22 claimsResolver: (Claims) -> T,
23 ): T {
24 val claims = extractAllClaims(token)
25 return claimsResolver(claims)
26 }
27
28 fun generateToken(
29 extraClaims: Map<String, Any> = emptyMap(),
30 userDetails: UserDetails,
31 ): String =
32 Jwts
33 .builder()
34 .claims()
35 .subject(userDetails.username)
36 .issuedAt(Date(System.currentTimeMillis()))
37 .expiration(Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
38 .add(extraClaims)
39 .and()
40 .signWith(getSignInKey())
41 .compact()
42
43 fun isTokenValid(
44 token: String,
45 userDetails: UserDetails,
46 ): Boolean {
47 val username = extractUsername(token)
48 return username == userDetails.username && !isTokenExpired(token)
49 }
50
51 private fun isTokenExpired(token: String): Boolean = extractExpiration(token).before(Date())
52
53 private fun extractExpiration(token: String): Date = extractClaim(token, Claims::getExpiration)
54
55 private fun extractAllClaims(token: String): Claims =
56 Jwts
57 .parser()
58 .verifyWith(secretKey)
59 .build()
60 .parseSignedClaims(token)
61 .payload
62
63 private fun getSignInKey(): Key = secretKey
64}
Note: See TracBrowser for help on using the repository browser.