如何使用jwtdecoder在本地验证jwt?

sycxhyv7  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(985)

规则:我必须使用jwtdecoder实现。我们使用不同的jwt验证。主要是外部的。这是我们第一次进行内部jwt创建编码,然后通过验证进行解码。

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

所以以前,它是通过外部api登录的,它们给出一个令牌,然后根据请求,我们使用jwkseturi创建的jwtdecoder验证该令牌。
我现在的问题是我需要为我们的内部令牌创建一个jwtdecoder。我是这样做的。

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;
    }

至于它是 JwtDecoder 实施,我就是这样做的:

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;
    }

现在我知道这不合情理了。我不确定在令牌创建中在何处使用密钥,并且在创建解码器时遇到问题。有没有更合适的方法?

velaa5lx

velaa5lx1#

问题解决了。我基本上创建了我自己的jwtdecoder实现(实际上只是将jwtdecoder实现到我自己的类中),重写了 decode 方法,并自行实现了如何验证令牌(例如,获取声明和检查到期)

相关问题