Created
September 18, 2024 10:22
-
-
Save mcihad/9c6cdbaf697f185bb4c1dbc40ded48b9 to your computer and use it in GitHub Desktop.
This file contains 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
package com.example.demo.services; | |
import io.jsonwebtoken.Claims; | |
import io.jsonwebtoken.Jws; | |
import io.jsonwebtoken.Jwts; | |
import io.jsonwebtoken.SignatureAlgorithm; | |
import io.jsonwebtoken.security.Keys; | |
import org.springframework.beans.factory.annotation.Value; | |
import org.springframework.stereotype.Service; | |
import javax.crypto.SecretKey; | |
import javax.crypto.spec.SecretKeySpec; | |
import java.security.Key; | |
import java.time.Instant; | |
import java.time.temporal.ChronoUnit; | |
import java.util.Base64; | |
import java.util.Date; | |
import java.util.List; | |
import java.util.UUID; | |
@Service | |
public class JWTService { | |
@Value("${secretKey}") | |
private String secretKey; | |
public String createJWT() { | |
Key key = new SecretKeySpec(Base64.getDecoder().decode(secretKey), | |
"HmacSHA256"); | |
return Jwts.builder() | |
.header() | |
.keyId(UUID.randomUUID().toString()) | |
.and() | |
.claim("id", UUID.randomUUID().toString()) | |
.claim("tenantId",UUID.randomUUID().toString()) | |
.claim("roles", List.of("ADMIN","USER")) | |
.issuer("https://www.example.com") | |
.signWith(key) | |
.issuedAt(Date.from(Instant.now())) | |
.expiration(Date.from(Instant.now().plus(10, ChronoUnit.MINUTES))) | |
.compact(); | |
} | |
public Jws<Claims> parseJwt(String jwt) { | |
Key key = new SecretKeySpec(Base64.getDecoder().decode(secretKey), | |
"HmacSHA256"); | |
var secretKey = Keys.hmacShaKeyFor(Base64.getDecoder().decode(this.secretKey)); | |
return Jwts.parser() | |
.verifyWith(secretKey) | |
.build() | |
.parseSignedClaims(jwt); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment