2

I am following a tutorial to implement JWT authentication with spring boot and java. But in my case I want to do it with Kotlin.

I am able to generate a jwt token but having issues when extracting claims from a jwt token.

In this tutorial there is a generic function to extract claims from a token.

public <T> T extractClaim(String token, Function<Claims, T> claimsResolver {
    final Claims claims = extractAllClaims(token);
    return claimResolver.apply(claims);
}

private Claims extractAllClaims(String token) {
    return Jwts.parser().setSigningKey(KEY).parseClaimsJws(token).getBody();
}

public String extractUsername(String token) {
    return extractClaim(token, Claims::getSubject);
}

I have written this in kotlin as follows.

fun <T> extractClaim(token: String, claimResolver: Function<Claims, T>): T {
    val claims = extractAllClaims(token)
    return claimResolver.apply(claims)
}

private fun extractAllClaims(token: String): Claims {
    return Jwts.parser().setSigningKey(key).parseClaimsJws(token).body
}

fun extractUsername(token: String): String {
    return extractClaim(token, Claims::getSubject)
}

I'm getting an error from Function<Claims, T> saying

One type argument expected for interface Function

Also I can see there are other options such as KFunction and KFunction1.

I am not much experienced in Kotlin and can someone help me to figure out the issue here or suggest a better way of doing this.

Ruchira Nawarathna
  • 1,137
  • 17
  • 30
  • Are you importing the right `Function` class? – gidds Dec 03 '20 at 08:33
  • @gidds you are correct. I was importing wrong class. Now I changed it to java.util.function.Function. But Now I get Required Function> but Found KFunction1 from extractUsername method Claims::getSubject – Ruchira Nawarathna Dec 03 '20 at 10:14

1 Answers1

2

Function types are some different in Kotlin, try with this:

fun <T> extractClaim(token: String, claimsResolver: (Claims) -> T): T {
    val claims: Claims = extractAllClaims(token)
    return claimsResolver(claims)
}
Alireza MH
  • 573
  • 8
  • 25