@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(); }
@Test public void testLoginGood() { final CredentialsEntity entity = getCredentialsEntity(); when(credentialsRepository.findByUsername(eq(entity.getUsername()))).thenReturn(entity); when(passwordEncoder.matches(eq(entity.getPassword()), eq(entity.getPassword()))).thenReturn(true); final Authorization authorization = authenticationService.login(entity.getUsername(), entity.getPassword()); assertThat(authorization.getId()).isEqualTo(entity.getId()); assertThat(authorization.getToken()).isNotNull(); final JwtParser parser = Jwts.parser().setSigningKey(apiKey); final Claims body = parser.parseClaimsJws(authorization.getToken()).getBody(); assertThat(body.getSubject()).isNotNull().isEqualTo(entity.getId()); assertThat(body.getIssuer()).isNotNull().isEqualTo(AuthenticationService.class.getName()); assertThat(body.getIssuedAt()).isNotNull(); assertThat(body.getNotBefore()).isNotNull(); assertThat(body.getExpiration()).isNotNull(); assertThat(body.get("roles")).isNotNull(); assertThat(body.get("roles").toString().trim()).isEqualTo(entity.getRoles().toString().trim()); }
@Test public void Can_fail_parse_a_jwt_token() throws JwtInvalidTokenException { final String token = someString(); final JwtParser parser = mock(JwtParser.class); final JwtParser secretParser = mock(JwtParser.class); final JwtException exception = new JwtException(someString()); // Given given(parserFactory.create()).willReturn(parser); given(parser.setSigningKey(publicKey)).willReturn(secretParser); given(secretParser.parseClaimsJws(token)).willThrow(exception); expectedException.expect(JwtInvalidTokenException.class); expectedException.expectCause(is(exception)); // When decryptor.decrypt(token, Object.class); }
@Test public void Can_fail_to_parse_an_empty_jwt_token() throws JwtInvalidTokenException { final JwtParser parser = mock(JwtParser.class); final JwtParser secretParser = mock(JwtParser.class); final IllegalArgumentException exception = new IllegalArgumentException(); // Given given(parserFactory.create()).willReturn(parser); given(parser.setSigningKey(publicKey)).willReturn(secretParser); given(secretParser.parseClaimsJws("")).willThrow(exception); expectedException.expect(JwtInvalidTokenException.class); expectedException.expectCause(is(exception)); // When decryptor.decrypt("", Object.class); }
/** * <p> * 验证签名并解析 * </p> */ public static JwtParser verifyParser() { try { SSOConfig config = SSOConfig.getInstance(); SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.forName(config.getSignAlgorithm()); if (SSOConstants.SIGN_RSA.equals(signatureAlgorithm.getFamilyName())) { ClassPathResource resource = new ClassPathResource(config.getRsaCertstore()); String publicKey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream())); // RSA 签名验证 return Jwts.parser().setSigningKey(RsaKeyHelper.parsePublicKey(publicKey)); } // 普通签名验证 return Jwts.parser().setSigningKey(config.getSignkey()); } catch (Exception e) { throw new KissoException("verifyParser error.", e); } }
/** * {@inheritDoc} */ @Override public boolean verifyJwt(String jwt) { boolean verified = false; try { Assert.hasText(jwt, "JWT can't be null or empty!!"); JwtParser jwtParser = Jwts.parser().requireIssuer(this.jwtConfig.issuer()); this.setSigningKey(jwtParser); Jws<Claims> claimsJws = jwtParser.parseClaimsJws(jwt); verified = !this.jwtConfig.validateClaims() || this.claimsValidator != null && this.claimsValidator.validate(claimsJws.getBody()); } catch (RuntimeException ex) { // For reducing noise in the logs, set this config to false. if (this.jwtConfig.printJwtExceptionTrace()) { LOGGER.error(ex.getMessage(), ex); } else { LOGGER.error(ex.getMessage()); } } return verified; }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { try { String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION); String token = authorizationHeader.substring("Bearer".length()).trim(); final Key key = KeyGenerator.getKey(deskDroidService.getApplicationContext()); final JwtParser jwtParser = Jwts.parser().setSigningKey(key); jwtParser.parseClaimsJws(token); } catch (Exception e) { requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build()); } }
@Test public void testJwtParser() throws Exception { final Key key = mock(Key.class); final JwtParser jwtParser = configuration.jwtParser(key); assertThat(jwtParser).isNotNull(); }
@Test public void Can_parse_a_jwt_token() throws IOException { final String token = someString(); final Class<Object> type = Object.class; final JwtParser parser = mock(JwtParser.class); final JwtParser secretParser = mock(JwtParser.class); @SuppressWarnings("unchecked") final Jws<Claims> jws = mock(Jws.class); final Claims claims = mock(Claims.class); final Map map = mock(Map.class); final Object expected = new Object(); // Given given(parserFactory.create()).willReturn(parser); given(parser.setSigningKey(publicKey)).willReturn(secretParser); given(secretParser.parseClaimsJws(token)).willReturn(jws); given(jws.getBody()).willReturn(claims); given(claims.get(PRINCIPAL, Map.class)).willReturn(map); given(objectMapper.convertValue(map, type)).willReturn(expected); // When final Object actual = decryptor.decrypt(token, type); // Then assertThat(actual, is(expected)); }
@Test public void Can_create_a_jwt_parser() { // When final JwtParser actual = new JJwtParserFactory().create(); // Then assertThat(actual, not(nullValue())); }
@Test public void test() throws Exception { ClassPathResource resource = new ClassPathResource("jwt.jks"); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(resource.getInputStream(), "letkisso".toCharArray()); Key key = keystore.getKey("jwtkey", "keypassword".toCharArray()); Map<String, Object> claims = new HashMap<>(); claims.put("user", "cope"); String jwtToken = Jwts.builder() .setClaims(claims) .setIssuedAt(new Date()) .signWith(SignatureAlgorithm.RS512, key) .compact(); System.out.println(jwtToken); ClassPathResource resourcePk = new ClassPathResource("public.cert"); String publicKey; try { publicKey = new String(FileCopyUtils.copyToByteArray(resourcePk.getInputStream())); } catch (IOException e) { throw new RuntimeException(e); } JwtParser jwtParser = Jwts.parser().setSigningKey(RsaKeyHelper.parsePublicKey(publicKey)); Claims claimsPk = jwtParser.parseClaimsJws(jwtToken).getBody(); Assert.assertNotNull(claimsPk); Assert.assertEquals(claimsPk.get("user"), "cope"); }
private void setSigningKey(JwtParser jwtParser) { if (this.rsaPrivateKey == null) { jwtParser.setSigningKey(this.hmacSecretKey); } else { jwtParser.setSigningKey(this.rsaPrivateKey); } }
private Map<String, Object> validateJwt(String token, ApiRequest request, JWTPolicyBean config) throws ExpiredJwtException, PrematureJwtException, MalformedJwtException, SignatureException, InvalidClaimException { 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)); }
@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; }
@Bean @ConditionalOnMissingBean(JwtParser.class) public JwtParser jwtParser(@NotNull final Key apiKey) { return Jwts.parser().setSigningKey(apiKey); }
JwtAuthenticationProvider(@NotNull final JwtParser jwtParser) { this.jwtParser = jwtParser; }
@Override public JwtParser create() { return Jwts.parser(); }
public JsonWebToken(JwtParser jwtParser, String bearer) { this.jwtParser = jwtParser; this.bearer = bearer; }
public JwtParser must() { return this.jwtParser; }
@Override public JwtParser requireIssuedAt(Date issuedAt) { expectedClaims.setIssuedAt(issuedAt); return this; }
@Override public JwtParser requireIssuer(String issuer) { expectedClaims.setIssuer(issuer); return this; }
@Override public JwtParser requireAudience(String audience) { expectedClaims.setAudience(audience); return this; }
@Override public JwtParser requireSubject(String subject) { expectedClaims.setSubject(subject); return this; }
@Override public JwtParser requireId(String id) { expectedClaims.setId(id); return this; }
@Override public JwtParser requireExpiration(Date expiration) { expectedClaims.setExpiration(expiration); return this; }
@Override public JwtParser requireNotBefore(Date notBefore) { expectedClaims.setNotBefore(notBefore); return this; }
@Override public JwtParser setClock(Clock clock) { Assert.notNull(clock, "Clock instance cannot be null."); this.clock = clock; return this; }
@Override public JwtParser setAllowedClockSkewSeconds(long seconds) { this.allowedClockSkewMillis = Math.max(0, seconds * MILLISECONDS_PER_SECOND); return this; }
@Override public JwtParser setSigningKey(byte[] key) { Assert.notEmpty(key, "signing key cannot be null or empty."); this.keyBytes = key; return this; }
@Override public JwtParser setSigningKey(String base64EncodedKeyBytes) { Assert.hasText(base64EncodedKeyBytes, "signing key cannot be null or empty."); this.keyBytes = TextCodec.BASE64.decode(base64EncodedKeyBytes); return this; }
@Override public JwtParser setSigningKey(Key key) { Assert.notNull(key, "signing key cannot be null."); this.key = key; return this; }
@Override public JwtParser setSigningKeyResolver(SigningKeyResolver signingKeyResolver) { Assert.notNull(signingKeyResolver, "SigningKeyResolver cannot be null."); this.signingKeyResolver = signingKeyResolver; return this; }
@Override public JwtParser setCompressionCodecResolver(CompressionCodecResolver compressionCodecResolver) { Assert.notNull(compressionCodecResolver, "compressionCodecResolver cannot be null."); this.compressionCodecResolver = compressionCodecResolver; return this; }
JwtParser create();