Created
December 9, 2024 14:41
-
-
Save iKunalChhabra/206a8275e34e8a944adc0bfbd17e2ddf to your computer and use it in GitHub Desktop.
JSON Web Token in Kotlin
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
| package org.example | |
| import io.jsonwebtoken.Jwts | |
| import io.jsonwebtoken.security.Keys | |
| import java.time.Duration | |
| import java.util.* | |
| fun main() { | |
| // val secretKey = SIG.HS512.key().build().encoded | |
| val secretKey = "JNu4i@rL����&�#�k\"�\u000Bv0��hn����xH)�\u007FZ�]�&\u0013�]\u0011>8�qB~M�bA�1\u0017Y�U�K" | |
| val jwt = Jwts.builder() | |
| .claims() | |
| .issuer("Kunal Chhabra Company") | |
| .id("123") | |
| .issuedAt(Date()) | |
| .expiration(Date(Date().time + Duration.ofMinutes(15).toMillis())) | |
| .subject("Kunal Chhabra") | |
| .add("role", "admin") | |
| .add("email", "[email protected]") | |
| .and().signWith(Keys.hmacShaKeyFor(secretKey.toByteArray())) | |
| .compact() | |
| println(jwt) | |
| val jwtString = "eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJLdW5hbCBDaGhhYnJhIENvbXBhbnkiLCJqdGkiOiIxMjMiLCJpYXQiOjE3MzM3NTQ4MzQsImV4cCI6MTczMzc1NTczNCwic3ViIjoiS3VuYWwgQ2hoYWJyYSIsInJvbGUiOiJhZG1pbiIsImVtYWlsIjoia3VuYWxAa3VuYWwuY29tIn0.8h6b4ww9nC3q8aOdnXaFGQdrRWMzYxmOi9JcgTmEa8mV3Lf1Fo__EcuN03b6p_-pKbUmed8Fvq7wRPAY5KQuAA" | |
| val claims = Jwts.parser().verifyWith(Keys.hmacShaKeyFor(secretKey.toByteArray())).build().parseSignedClaims(jwtString) | |
| val email = claims.payload.get("email").toString() | |
| println(email) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment