Last active
March 26, 2024 07:40
-
-
Save bastman/68ad481c8612631c76044f91db525d26 to your computer and use it in GitHub Desktop.
kotlin parse jwt untrusted - ignore signature
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
// see: https://github.com/auth0-blog/spring-boot-jwts/blob/master/src/main/java/com/example/security/TokenAuthenticationService.java | |
//Example: | |
val json:String= JwtUntrusted.parseClaimsUntrustedToJson("Bearer xxx") | |
object JwtUntrusted { | |
// requires (gradle): compile group: 'io.jsonwebtoken', name: 'jjwt', version: '0.9.0' | |
private val JSON = jacksonObjectMapper() | |
fun removeSignature(jwt:String) = jwt.replaceAfterLast(".", "").trim() | |
fun removeBearer(jwt:String) = jwt.removePrefix("Bearer").trim() | |
fun parseClaimsUntrusted(jwt: String) = | |
jwt.let { removeSignature(it) } | |
.let { removeBearer(it) } | |
.let { Jwts.parser().parseClaimsJwt(it) } | |
fun parseClaimsUntrustedToJson(jwt:String) = | |
jwt.let { parseClaimsUntrusted(it) } | |
.let { JSON.writeValueAsString(it) } | |
fun createToken(subject: String, expireIn:Duration): String { | |
val expireAt=Instant.now() + expireIn | |
val secret = "mysecret" | |
return Jwts.builder() | |
.setSubject(subject) | |
.setClaims(mapOf( | |
"c1" to "C1", | |
"c2" to "C2" | |
)) | |
.setAudience("myaudience") | |
.setExpiration(Date.from(expireAt)) | |
.signWith(SignatureAlgorithm.HS512, secret) | |
.compact() | |
} | |
fun createTokenFromPayload(payload: TokenPayload): String { | |
val secret = "mysecret" | |
return Jwts.builder() | |
.setPayload(JSON.writeValueAsString(payload)) | |
.signWith(SignatureAlgorithm.HS512, secret) | |
.compact() | |
} | |
data class TokenPayload( | |
val iss:String?=null, | |
val sub:String?=null, | |
val aud:List<String>?=null, | |
val iat:Long?=null, | |
val exp:Long?=null, | |
val azp:String?=null, | |
val scope:String?=null | |
) { | |
companion object { | |
fun of( | |
iss:String?=null, | |
sub:String?=null, | |
aud:List<String>?=null, | |
iat:Instant?=null, | |
exp:Instant?=null, | |
azp:String?=null, | |
scope:String?=null | |
) = TokenPayload(iss=iss, sub = sub, aud = aud, iat = iat?.epochSecond, exp = exp?.epochSecond, azp = azp, scope = scope) | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment