I have this old code:
Dependencies:
implementation 'org.springframework.security:spring-security-jwt:1.1.1.RELEASE'
implementation 'org.springframework.security.oauth:spring-security-oauth2:2.5.2.RELEASE'
Code:
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.oauth2.common.util.JsonParser;
import org.springframework.security.oauth2.common.util.JsonParserFactory;
private String extractCredentials(String accessTokenCookieValue) {
Jwt jwt = JwtHelper.decode(accessTokenCookieValue);
JsonParser objectMapper = JsonParserFactory.create();
return objectMapper.parseMap(jwt.getClaims()).get("credentials").toString();
}
Do you know how I can migrate the to the latest version of Spring Security 6?
I tried to use:
import org.springframework.boot.json.JsonParser;
import org.springframework.security.oauth2.jwt.Jwt;
But I can't get dependencies for JwtHelper
and JsonParserFactory
:
You can use NimbusJwtDecoder
. Note that it will also verify the signature, so you will need to provide a public key or a source of public keys to use it successfully.
For example, you might construct one like this:
NimbusJwtDecoder decoder = NimbusJwtDecoder
.fromIssuerLocation("https://authz.example.org/issuer").build();
And then you can decode like so:
Jwt jwt = decoder.decode(accessTokenCookieValue);
return jwt.getClaim("credentials").toString();
That said, you might see if calling NimbusJwtDecoder
directly is needed in the first place. Spring Security often invokes this for you, depending on whether you are a Client application or a Resource Server.