io.jsonwebtoken.Jwt Java Examples

The following examples show how to use io.jsonwebtoken.Jwt. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JjwtVerifierTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@Override
protected void validateToken(String token, RSAPublicKey publicKey, String issuer, int expGracePeriodSecs) throws Exception {
    JwtParser parser = Jwts.parser()
        .setSigningKey(publicKey)
        .requireIssuer(issuer)
        ;
    if(expGracePeriodSecs > 0) {
        parser = parser.setAllowedClockSkewSeconds(expGracePeriodSecs);
    }

    Jwt jwt = parser.parse(token);
    String alg = jwt.getHeader().get("alg").toString();
    if(alg == null || !alg.equals(SignatureAlgorithm.RS256.getValue())) {
        throw new SignatureException("Non-RS256 alg: "+alg);
    }
    Jws<Claims> claims = parser.parseClaimsJws(token);
}
 
Example #2
Source File: JjwtDeserializerTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void foo() {
    final Map<String, Object> claims = new HashMap<>();
    claims.put(Claims.ISSUER, KNOWN_ISS);
    claims.put(Claims.SUBJECT, KNOWN_SUB);
    final String compact = Jwts.builder()
            .serializeToJsonWith(JjwtSerializer.getInstance())
            .setClaims(claims)
            .setExpiration(KNOWN_EXP)
            .compact();

    final Jwt jwt = Jwts.parser()
            .deserializeJsonWith(JjwtDeserializer.getInstance())
            .parse(compact);

    final Object jwtBody = jwt.getBody();

    Assertions.assertThat(jwtBody).isInstanceOf(Claims.class);
    Assertions.assertThat(((Claims) jwtBody).get(Claims.ISSUER)).isEqualTo(KNOWN_ISS);
    Assertions.assertThat(((Claims) jwtBody).get(Claims.SUBJECT)).isEqualTo(KNOWN_SUB);
    Assertions.assertThat(((Claims) jwtBody).get(Claims.EXPIRATION)).isEqualTo((int) (KNOWN_EXP.getTime() / 1000L));
}
 
Example #3
Source File: AuthenticationProviderTokenTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializeSecretKey() {
    SecretKey secretKey = AuthTokenUtils.createSecretKey(SignatureAlgorithm.HS256);

    String token = Jwts.builder()
            .setSubject(SUBJECT)
            .signWith(secretKey)
            .compact();

    @SuppressWarnings("unchecked")
    Jwt<?, Claims> jwt = Jwts.parser()
            .setSigningKey(AuthTokenUtils.decodeSecretKey(secretKey.getEncoded()))
            .parse(token);

    assertNotNull(jwt);
    assertNotNull(jwt.getBody());
    assertEquals(jwt.getBody().getSubject(), SUBJECT);
}
 
Example #4
Source File: AuthenticationProviderTokenTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializeKeyPair() throws Exception {
    KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256);

    String privateKey = AuthTokenUtils.encodeKeyBase64(keyPair.getPrivate());
    String publicKey = AuthTokenUtils.encodeKeyBase64(keyPair.getPublic());

    String token = AuthTokenUtils.createToken(AuthTokenUtils.decodePrivateKey(Decoders.BASE64.decode(privateKey), SignatureAlgorithm.RS256),
            SUBJECT,
            Optional.empty());

    @SuppressWarnings("unchecked")
    Jwt<?, Claims> jwt = Jwts.parser()
            .setSigningKey(AuthTokenUtils.decodePublicKey(Decoders.BASE64.decode(publicKey), SignatureAlgorithm.RS256))
            .parse(token);

    assertNotNull(jwt);
    assertNotNull(jwt.getBody());
    assertEquals(jwt.getBody().getSubject(), SUBJECT);
}
 
Example #5
Source File: DefaultJwtParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Jwt<Header, String> parsePlaintextJwt(String plaintextJwt) {
    return parse(plaintextJwt, new JwtHandlerAdapter<Jwt<Header, String>>() {
        @Override
        public Jwt<Header, String> onPlaintextJwt(Jwt<Header, String> jwt) {
            return jwt;
        }
    });
}
 
Example #6
Source File: DefaultJwtParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Jwt<Header, Claims> parseClaimsJwt(String claimsJwt) {
    try {
        return parse(claimsJwt, new JwtHandlerAdapter<Jwt<Header, Claims>>() {
            @Override
            public Jwt<Header, Claims> onClaimsJwt(Jwt<Header, Claims> jwt) {
                return jwt;
            }
        });
    } catch (IllegalArgumentException iae) {
        throw new UnsupportedJwtException("Signed JWSs are not supported.", iae);
    }
}
 
Example #7
Source File: AuthenticationProviderToken.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Jwt<?, Claims> authenticateToken(final String token) throws AuthenticationException {
    try {
        Jwt<?, Claims> jwt = Jwts.parser()
                .setSigningKey(validationKey)
                .parse(token);

        if (audienceClaim != null) {
            Object object = jwt.getBody().get(audienceClaim);
            if (object == null) {
                throw new JwtException("Found null Audience in token, for claimed field: " + audienceClaim);
            }

            if (object instanceof List) {
                List<String> audiences = (List<String>) object;
                // audience not contains this broker, throw exception.
                if (!audiences.stream().anyMatch(audienceInToken -> audienceInToken.equals(audience))) {
                    throw new AuthenticationException("Audiences in token: [" + String.join(", ", audiences)
                                                      + "] not contains this broker: " + audience);
                }
            } else if (object instanceof String) {
                if (!object.equals(audience)) {
                    throw new AuthenticationException("Audiences in token: [" + object
                                                      + "] not contains this broker: " + audience);
                }
            } else {
                // should not reach here.
                throw new AuthenticationException("Audiences in token is not in expected format: " + object);
            }
        }

        return jwt;
    } catch (JwtException e) {
        throw new AuthenticationException("Failed to authentication token: " + e.getMessage());
    }
}
 
Example #8
Source File: ConfigCheckingJwtHandler.java    From apiman-plugins with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> onPlaintextJwt(@SuppressWarnings("rawtypes") Jwt<Header, String> jwt) {
    if (config.getRequireSigned()) {
        super.onPlaintextJwt(jwt);
    }
    return Collections.emptyMap();
}
 
Example #9
Source File: DefaultJwtParser.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@Override
public Jwt<Header, String> parsePlaintextJwt(String plaintextJwt) {
    return parse(plaintextJwt, new JwtHandlerAdapter<Jwt<Header, String>>() {
        @Override
        public Jwt<Header, String> onPlaintextJwt(Jwt<Header, String> jwt) {
            return jwt;
        }
    });
}
 
Example #10
Source File: DefaultJwtParser.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@Override
public Jwt<Header, Claims> parseClaimsJwt(String claimsJwt) {
    try {
        return parse(claimsJwt, new JwtHandlerAdapter<Jwt<Header, Claims>>() {
            @Override
            public Jwt<Header, Claims> onClaimsJwt(Jwt<Header, Claims> jwt) {
                return jwt;
            }
        });
    } catch (IllegalArgumentException iae) {
        throw new UnsupportedJwtException("Signed JWSs are not supported.", iae);
    }
}
 
Example #11
Source File: AuthenticationProviderToken.java    From pulsar with Apache License 2.0 4 votes vote down vote up
private String getPrincipal(Jwt<?, Claims> jwt) {
    return jwt.getBody().get(roleClaim, String.class);
}
 
Example #12
Source File: ConfigCheckingJwtHandler.java    From apiman-plugins with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String, Object> onClaimsJwt(@SuppressWarnings("rawtypes") Jwt<Header, Claims> jwt) {
    return config.getRequireSigned() ? super.onClaimsJwt(jwt) : jwt.getBody();
}
 
Example #13
Source File: ImmutableJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public Jwt parse(String jwt) throws ExpiredJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
    return this.jwtParser.parse(jwt);
}
 
Example #14
Source File: ImmutableJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public Jwt<Header, String> parsePlaintextJwt(String plaintextJwt) throws UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
    return this.jwtParser.parsePlaintextJwt(plaintextJwt);
}
 
Example #15
Source File: ImmutableJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public Jwt<Header, Claims> parseClaimsJwt(String claimsJwt) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
    return this.jwtParser.parseClaimsJwt(claimsJwt);
}
 
Example #16
Source File: RNPureJwtModule.java    From react-native-pure-jwt with MIT License 3 votes vote down vote up
private void getResponse(Jwt parsed, Promise callback) {
    ObjectMapper mapper = new ObjectMapper();

    Map<String, Object> headersMap = mapper.convertValue(parsed.getHeader(), DefaultClaims.class);
    Map<String, Object> payload = mapper.convertValue(parsed.getBody(), DefaultClaims.class);

    WritableMap response = Arguments.createMap();

    response.putMap("headers", Arguments.makeNativeMap(headersMap));
    response.putMap("payload", Arguments.makeNativeMap(payload));

    callback.resolve(response);
}