io.jsonwebtoken.JwtParser Java Examples

The following examples show how to use io.jsonwebtoken.JwtParser. 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: DefaultJwtParserBuilder.java    From jjwt with Apache License 2.0 6 votes vote down vote up
@Override
public JwtParser build() {

    // Only lookup the deserializer IF it is null. It is possible a Deserializer implementation was set
    // that is NOT exposed as a service and no other implementations are available for lookup.
    if (this.deserializer == null) {
        // try to find one based on the services available:
        this.deserializer = Services.loadFirst(Deserializer.class);
    }

    return new ImmutableJwtParser(
            new DefaultJwtParser(signingKeyResolver,
                                 key,
                                 keyBytes,
                                 clock,
                                 allowedClockSkewMillis,
                                 expectedClaims,
                                 base64UrlDecoder,
                                 deserializer,
                                 compressionCodecResolver));
}
 
Example #2
Source File: KeycloakEnvironmentInitializationFilter.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Inject
public KeycloakEnvironmentInitializationFilter(
    SessionStore sessionStore,
    JwtParser jwtParser,
    KeycloakUserManager userManager,
    KeycloakProfileRetriever keycloakProfileRetriever,
    RequestTokenExtractor tokenExtractor,
    PermissionChecker permissionChecker,
    KeycloakSettings settings) {
  super(sessionStore, tokenExtractor);
  this.jwtParser = jwtParser;
  this.userManager = userManager;
  this.keycloakProfileRetriever = keycloakProfileRetriever;
  this.permissionChecker = permissionChecker;
  this.keycloakSettings = settings;
}
 
Example #3
Source File: JwtHelper.java    From kisso with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * 验证签名并解析
 * </p>
 */
public static JwtParser verifyParser() {
    try {
        SSOConfig config = SSOConfig.getInstance();
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.forName(config.getSignAlgorithm());
        if (SSOConstants.RSA.equals(signatureAlgorithm.getFamilyName())) {
            if(null == RSA_PUBLICKEY) {
                ClassPathResource resource = new ClassPathResource(config.getRsaCertStore());
                RSA_PUBLICKEY = RsaKeyHelper.getRsaPublicKey(resource.getInputStream());
            }
            // RSA 签名验证
            return Jwts.parserBuilder().setSigningKey(RSA_PUBLICKEY).build();
        }
        // 普通签名验证
        SecretKey secretKey = getSecretKey(config.getSignKey(), signatureAlgorithm);
        return Jwts.parserBuilder().setSigningKey(secretKey).build();
    } catch (Exception e) {
        throw new KissoException("verifyParser error.", e);
    }
}
 
Example #4
Source File: JwsClaimsExtractor.java    From juiser with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("Duplicates")
@Override
public Claims apply(String headerValue) {
    JwtParser parser = Jwts.parser();

    if (signingKeyBytes != null) {
        parser.setSigningKey(signingKeyBytes);
    } else if (signingKey != null) {
        parser.setSigningKey(signingKey);
    } else if (signingKeyResolver != null) {
        parser.setSigningKeyResolver(signingKeyResolver);
    }

    if (this.allowedClockSkewSeconds != null) {
        parser.setAllowedClockSkewSeconds(this.allowedClockSkewSeconds);
    }

    return parser.parseClaimsJws(headerValue).getBody();
}
 
Example #5
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 #6
Source File: SmsVerificationJwtVerifier.java    From daming with Apache License 2.0 6 votes vote down vote up
/**
 * @param jwt, JWT issued by daming.
 * @return claims that contains verified mobile and scope.
 * @see #verify(String, String)
 */
@Deprecated
public SmsVerificationClaims verify(String jwt) {
    if (jwt == null) {
        throw new BadSmsVerificationJwtException("The jwt must not be null");
    }
    try {
        JwtParser parser = Jwts.parser()
                .setSigningKey(publicKey);
        if (clock != null) {
            parser = parser.setClock(clock);
        }
        Jws<Claims> claims = parser
                .parseClaimsJws(jwt);
        String mobile = claims.getBody().get("mobile", String.class);
        String scope = claims.getBody().get("scope", String.class);
        return new SmsVerificationClaims(mobile, scope);
    } catch (Exception err) {
        throw new BadSmsVerificationJwtException(err.getMessage(), err);
    }
}
 
Example #7
Source File: DefaultJwtParser.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@Override
public JwtParser require(String claimName, Object value) {
    Assert.hasText(claimName, "claim name cannot be null or empty.");
    Assert.notNull(value, "The value cannot be null for claim name: " + claimName);
    expectedClaims.put(claimName, value);
    return this;
}
 
Example #8
Source File: JWTPolicy.java    From apiman-plugins with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> validateJwt(String token, JWTPolicyBean config)
        throws ExpiredJwtException, PrematureJwtException, MalformedJwtException, SignatureException, InvalidClaimException {

    // check if we have to use jwk(s)
    if (urlValidator.isValid(config.getSigningKeyString())){
        if (provider == null){
            provider = getNewJwksProvider(config.getSigningKeyString());
        }

        Jwk jwk;
        try {
            jwk = provider.get(config.getKid());
            if (config.getSigningKey() == null || !(config.getSigningKey().equals(jwk.getPublicKey()))) {
                config.setSigningKey(jwk.getPublicKey());
            }
        } catch (JwkException e) {
           throw new SignatureException("JWK was not found with kid: " + config.getKid(), e);
        }
    }

    JwtParser parser = Jwts.parser()
            .setSigningKey(config.getSigningKey())
            .setAllowedClockSkewSeconds(config.getAllowedClockSkew());

    // Set all claims
    config.getRequiredClaims().stream() // TODO add type variable to allow dates, etc
        .forEach(requiredClaim -> parser.require(requiredClaim.getClaimName(), requiredClaim.getClaimValue()));

    return parser.parse(token, new ConfigCheckingJwtHandler(config));
}
 
Example #9
Source File: Auth0JwtParserTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void testParse() throws Exception {
    // mock internal parser
    Auth0JwtParser parser = new Auth0JwtParser(baseKeyStore, "https://athenz-oauth-example.auth0.com/.well-known/jwks.json");
    JwtParser jwtParserMock = Mockito.mock(JwtParser.class);
    Field f = parser.getClass().getSuperclass().getDeclaredField("parser");
    f.setAccessible(true);
    f.set(parser, jwtParserMock);

    // parse error
    Mockito.when(jwtParserMock.parseClaimsJws(null)).thenThrow(new NullPointerException());
    assertThrows(OAuthJwtAccessTokenException.class, () -> parser.parse(null));

    // parse success
    String jwtString = "dummy-jwt-string";
    Jws<Claims> jws = new Jws<Claims>() {
        public JwsHeader getHeader() { return null; }
        public Claims getBody() { return null; }

        @Override
        public String getSignature() {
            return "dummy-jwt-signature";
        }
    };
    Mockito.when(jwtParserMock.parseClaimsJws(jwtString)).thenReturn(jws);
    OAuthJwtAccessToken token = parser.parse(jwtString);
    assertNotNull(token);
    assertTrue(token instanceof Auth0Jwt);
    assertEquals(token.getSignature(), "dummy-jwt-signature");
}
 
Example #10
Source File: DefaultOAuthJwtAccessTokenParserTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void testParse() throws Exception {
    // mock internal parser
    DefaultOAuthJwtAccessTokenParser parser = new DefaultOAuthJwtAccessTokenParser(baseKeyStore, this.classLoader.getResource("jwt_jwks.json").toString());
    JwtParser jwtParserMock = Mockito.mock(JwtParser.class);
    Field f = parser.getClass().getDeclaredField("parser");
    f.setAccessible(true);
    f.set(parser, jwtParserMock);

    // parse error
    Mockito.when(jwtParserMock.parseClaimsJws(null)).thenThrow(new NullPointerException());
    assertThrows(OAuthJwtAccessTokenException.class, () -> parser.parse(null));

    // parse success
    String jwtString = "dummy-jwt-string";
    Jws<Claims> jws = new Jws<Claims>() {
        public JwsHeader getHeader() { return null; }
        public Claims getBody() { return null; }

        @Override
        public String getSignature() {
            return "dummy-jwt-signature";
        }
    };
    Mockito.when(jwtParserMock.parseClaimsJws(jwtString)).thenReturn(jws);
    OAuthJwtAccessToken token = parser.parse(jwtString);
    assertNotNull(token);
    assertTrue(token instanceof DefaultOAuthJwtAccessToken);
    assertEquals(token.getSignature(), "dummy-jwt-signature");
}
 
Example #11
Source File: JWTTokenService.java    From securing-rest-api-spring-security with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, String> untrusted(final String token) {
  final JwtParser parser = Jwts
    .parser()
    .requireIssuer(issuer)
    .setClock(this)
    .setAllowedClockSkewSeconds(clockSkewSec);

  // See: https://github.com/jwtk/jjwt/issues/135
  final String withoutSignature = substringBeforeLast(token, DOT) + DOT;
  return parseClaims(() -> parser.parseClaimsJwt(withoutSignature).getBody());
}
 
Example #12
Source File: KeycloakModule.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void configure() {

  bind(HttpJsonRequestFactory.class)
      .to(org.eclipse.che.multiuser.keycloak.server.KeycloakHttpJsonRequestFactory.class);
  bind(TokenValidator.class).to(KeycloakTokenValidator.class);
  bind(KeycloakConfigurationService.class);

  bind(ProfileDao.class).to(KeycloakProfileDao.class);
  bind(JwkProvider.class).toProvider(KeycloakJwkProvider.class);
  bind(JwtParser.class).toProvider(KeycloakJwtParserProvider.class);
  bind(PersonalAccountUserManager.class).to(KeycloakUserManager.class);

  bind(OAuthAPI.class).toProvider(OAuthAPIProvider.class);
}
 
Example #13
Source File: Fabric8AuthServiceClient.java    From rh-che with Eclipse Public License 2.0 5 votes vote down vote up
@Inject
public Fabric8AuthServiceClient(
    @Named("che.fabric8.auth.endpoint") String baseAuthUrl,
    KeycloakSettings keycloakSettings,
    JwtParser jwtParser) {
  super(keycloakSettings, jwtParser);
  this.githubTokenEndpoint = baseAuthUrl + GITHUB_TOKEN_API_PATH;
  this.githubLinkEndpoint = baseAuthUrl + GITHUB_LINK_API_PATH;
}
 
Example #14
Source File: DefaultJwtValidator.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private BinaryValidationResult validateWithPublicKey(final JsonWebToken jsonWebToken, final Key publicKey) {
    final JwtParser jwtParser = Jwts.parser();
    jwtParser.deserializeJsonWith(JjwtDeserializer.getInstance())
            .setSigningKey(publicKey)
            .parse(jsonWebToken.getToken());

    return BinaryValidationResult.valid();
}
 
Example #15
Source File: JWTTokenService.java    From securing-rest-api-spring-security with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, String> verify(final String token) {
  final JwtParser parser = Jwts
    .parser()
    .requireIssuer(issuer)
    .setClock(this)
    .setAllowedClockSkewSeconds(clockSkewSec)
    .setSigningKey(secretKey);
  return parseClaims(() -> parser.parseClaimsJws(token).getBody());
}
 
Example #16
Source File: DefaultJwtParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JwtParser require(String claimName, Object value) {
    Assert.hasText(claimName, "claim name cannot be null or empty.");
    Assert.notNull(value, "The value cannot be null for claim name: " + claimName);
    expectedClaims.put(claimName, value);
    return this;
}
 
Example #17
Source File: ImmutableJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public JwtParser deserializeJsonWith(Deserializer<Map<String, ?>> deserializer) {
    throw doNotMutate();
}
 
Example #18
Source File: DefaultJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public JwtParser deserializeJsonWith(Deserializer<Map<String, ?>> deserializer) {
    Assert.notNull(deserializer, "deserializer cannot be null.");
    this.deserializer = deserializer;
    return this;
}
 
Example #19
Source File: DefaultJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public JwtParser base64UrlDecodeWith(Decoder<String, byte[]> base64UrlDecoder) {
    Assert.notNull(base64UrlDecoder, "base64UrlDecoder cannot be null.");
    this.base64UrlDecoder = base64UrlDecoder;
    return this;
}
 
Example #20
Source File: ImmutableJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public JwtParser base64UrlDecodeWith(Decoder<String, byte[]> base64UrlDecoder) {
    throw doNotMutate();
}
 
Example #21
Source File: DefaultJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public JwtParser requireIssuedAt(Date issuedAt) {
    expectedClaims.setIssuedAt(issuedAt);
    return this;
}
 
Example #22
Source File: ImmutableJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public JwtParser setCompressionCodecResolver(CompressionCodecResolver compressionCodecResolver) {
    throw doNotMutate();
}
 
Example #23
Source File: ImmutableJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public JwtParser setSigningKeyResolver(SigningKeyResolver signingKeyResolver) {
    throw doNotMutate();
}
 
Example #24
Source File: ImmutableJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public JwtParser setSigningKey(Key key) {
    throw doNotMutate();
}
 
Example #25
Source File: ImmutableJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public JwtParser setSigningKey(String base64EncodedSecretKey) {
    throw doNotMutate();
}
 
Example #26
Source File: ImmutableJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public JwtParser setSigningKey(byte[] key) {
    throw doNotMutate();
}
 
Example #27
Source File: ImmutableJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public JwtParser setAllowedClockSkewSeconds(long seconds) {
    throw doNotMutate();
}
 
Example #28
Source File: DefaultJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public JwtParser requireAudience(String audience) {
    expectedClaims.setAudience(audience);
    return this;
}
 
Example #29
Source File: DefaultJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public JwtParser setSigningKey(String base64EncodedSecretKey) {
    Assert.hasText(base64EncodedSecretKey, "signing key cannot be null or empty.");
    this.keyBytes = Decoders.BASE64.decode(base64EncodedSecretKey);
    return this;
}
 
Example #30
Source File: DefaultJwtParser.java    From jjwt with Apache License 2.0 4 votes vote down vote up
@Override
public JwtParser setSigningKey(Key key) {
    Assert.notNull(key, "signing key cannot be null.");
    this.key = key;
    return this;
}