简体   繁体   中英

How to locally validate JWT using JwtDecoder?

Rule: I must use the JwtDecoder implementation. We're using different jwt validations. Mostly external. This is the first time we're doing internal JWT creation encoding and then decoding with validation.

    private JwtDecoder sampleDecoder(String issuerUri, String jwkUri) {
        OAuth2TokenValidator<Jwt> jwtValidator = JwtValidators.createDefaultWithIssuer(issueUri);
        NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkUri).build();
        jwtDecoder.setJwtValidator(jwtValidator);
        return jwtDecoder;
    }

So previously, it was login via the external API, they give a token, then per request we validate that token using the JwtDecoder created with the JwkSetUri.

The problem I'm having now is I need to create a JwtDecoder for our internally made token. Here's how I made the token.

    public String createToken(String mobileNumber) throws JOSEException {
        JWTClaimsSet jwtClaimsSet = new JWTClaimsSet.Builder()
                .issuer(securityProperties.getConciergeIssuer())
                .claim("mobileNumber", mobileNumber)
                .claim("roles", "ADMIN")
                .build();
        ECKey ecKey = new ECKeyGenerator(Curve.P_256)
                .keyID("123")
                .generate();
        JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.ES256)
                .type(JOSEObjectType.JWT)
                .keyID(ecKey.getKeyID())
                .build();
        SignedJWT jwt = new SignedJWT(jwsHeader, jwtClaimsSet);
        jwt.sign(new ECDSASigner(ecKey.toECPrivateKey()));
        String token = jwt.serialize();
        return token;
    }

And as for it's JwtDecoder implementation, this is how I did it:

    private JwtDecoder customDecoder(String issuer) {
        OAuth2TokenValidator<Jwt> jwtValidator = JwtValidators.createDefaultWithIssuer(issuer);
        byte[] decoded = Base64.getDecoder().decode(securityProperties.getConciergeSecret());
        NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder
                .withSecretKey(new SecretKeySpec(decoded, 0, decoded.length, "AES"))
                .build();
        jwtDecoder.setJwtValidator(jwtValidator);
        return jwtDecoder;
    }

Now I know it does not add up. I'm not sure where to use the secret key in token creation, and i'm having trouble creating the decoder. Is there a more proper way for this?

Problem solved. I basically created my own implementation of JwtDecoder (literally just implemented JwtDecoder into my own class), overrode the decode method, and made my own implementation of how to validate the token (eg get the claims and check expiry)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM