簡體   English   中英

如何使用 JwtDecoder 在本地驗證 JWT?

[英]How to locally validate JWT using JwtDecoder?

規則:我必須使用 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;
    }

現在我知道它不會加起來。 我不確定在創建令牌時在哪里使用密鑰,而且我在創建解碼器時遇到了麻煩。 有沒有更合適的方法呢?

問題解決了。 我基本上創建了自己的 JwtDecoder 實現(實際上只是在我自己的類中實現了 JwtDecoder),覆蓋了decode方法,並自己實現了如何驗證令牌(例如獲取聲明並檢查到期)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM