下面列出了java.security.interfaces.RSAKey#com.auth0.jwt.interfaces.DecodedJWT 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private Optional<DecodedJWT> refreshAccessToken() {
final HttpResponse<JsonNode> response = Unirest.post( TOKEN_URL ) //
.field( OAUTH_GRANT_TYPE, OAUTH_REFRESH_TOKEN ) //
.field( OAUTH_REFRESH_TOKEN, handler.getOfflineToken() ) //
.field( OAUTH_CLIENT_ID, client ) //
.asJson();
if ( response.isSuccess() ) {
final JSONObject object = response.getBody().getObject();
try {
return Optional.of( verifier.verify( object.getString( OAUTH_ACCESS_TOKEN ) ) );
} catch ( final Exception e ) {
log.error( "Error verifying access token: {}", e.getMessage() );
log.debug( "Details: ", e );
}
}
log.error( "Error retrieving access token: {}", response.getStatusText() );
return Optional.empty();
}
@Override
public void check(DecodedJWT jwt) throws InsufficientAuthenticationException {
AuthenticationType authenticationType = AuthenticationType.valueOf(settingsService.getSonosLinkMethod());
// no need for extra checks because there isn't a link code
if (authenticationType == AuthenticationType.ANONYMOUS) {
return;
}
String linkcode = jwt.getClaim(CLAIM_LINKCODE).asString();
SonosLink sonosLink = sonosLinkDao.findByLinkcode(linkcode);
if (!StringUtils.equals(jwt.getSubject(), sonosLink.getUsername())
|| !StringUtils.equals(linkcode, sonosLink.getLinkcode())
|| !StringUtils.equals(jwt.getClaim(CLAIM_HOUSEHOLDID).asString(), sonosLink.getHouseholdId())) {
throw new InsufficientAuthenticationException("Sonos creds not valid");
}
}
@Override
public String readUserIdentifier(HttpServletRequest request) {
try {
String jwtToken = request.getParameter(SsoServiceInterface.USER_ID);
if (jwtToken == null) {
logger.debug("JWT token not found in request");
return null;
}
LogMF.debug(logger, "JWT token in input is [{0}]", jwtToken);
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT decodedJWT = verifier.verify(jwtToken);
logger.debug("JWT token verified properly");
Claim userIdClaim = decodedJWT.getClaim(SsoServiceInterface.USER_ID);
LogMF.debug(logger, "User id detected is [{0}]", userIdClaim.asString());
assertNotEmpty(userIdClaim, "User id information is missing!!!");
return jwtToken;
} catch (JWTVerificationException e) {
throw new SpagoBIRuntimeException("Invalid JWT token!", e);
}
}
@Override
public void handle(Request request, Response response) throws Exception {
String authorizationHeader = request.headers("Authorization");
if (authorizationHeader == null) {
AuthenticationUtilities.setUserAsAnonymous(request);
} else {
String token = authorizationHeader.replaceFirst("Bearer ", "");
DecodedJWT decodedToken = JWT.decode(token);
JWTVerifier verifier = selectVerifier(decodedToken);
DecodedJWT decodedJWT = verifier.verify(token);
AuthenticationUtilities.setUser(request, decodedJWT.getSubject());
}
}
@Override
public void verify(DecodedJWT jwt) throws SignatureVerificationException {
byte[] signatureBytes = Base64.decodeBase64(jwt.getSignature());
try {
RSAPublicKey publicKey = keyProvider.getPublicKeyById(jwt.getKeyId());
if (publicKey == null) {
throw new IllegalStateException("The given Public Key is null.");
}
boolean valid = crypto.verifySignatureFor(getDescription(), publicKey, jwt.getHeader(), jwt.getPayload(), signatureBytes);
if (!valid) {
throw new SignatureVerificationException(this);
}
} catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalStateException e) {
throw new SignatureVerificationException(this, e);
}
}
@Override
public GatewayFilter apply(NameValueConfig config) {
return (exchange, chain) -> {
try {
String token = this.extractJWTToken(exchange.getRequest());
DecodedJWT decodedJWT = this.jwtVerifier.verify(token);
ServerHttpRequest request = exchange.getRequest().mutate().
header(X_JWT_SUB_HEADER, decodedJWT.getSubject()).
build();
return chain.filter(exchange.mutate().request(request).build());
} catch (JWTVerificationException ex) {
logger.error(ex.toString());
return this.onError(exchange, ex.getMessage());
}
};
}
@Override
public void verify(DecodedJWT jwt) throws SignatureVerificationException {
byte[] signatureBytes = Base64.decodeBase64(jwt.getSignature());
try {
ECPublicKey publicKey = keyProvider.getPublicKeyById(jwt.getKeyId());
if (publicKey == null) {
throw new IllegalStateException("The given Public Key is null.");
}
boolean valid = crypto.verifySignatureFor(getDescription(), publicKey, jwt.getHeader(), jwt.getPayload(), JOSEToDER(signatureBytes));
if (!valid) {
throw new SignatureVerificationException(this);
}
} catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalStateException e) {
throw new SignatureVerificationException(this, e);
}
}
@Test
public void succeedsWithValidTokenUsingDefaultClockAndHttpsDomain() {
String token = JWT.create()
.withSubject("auth0|sdk458fks")
.withAudience(AUDIENCE)
.withIssuedAt(getYesterday())
.withExpiresAt(getTomorrow())
.withIssuer("https://" + DOMAIN + "/")
.withClaim("nonce", "nonce")
.sign(Algorithm.HMAC256("secret"));
DecodedJWT decodedJWT = JWT.decode(token);
SignatureVerifier verifier = mock(SignatureVerifier.class);
when(verifier.verifySignature(token)).thenReturn(decodedJWT);
IdTokenVerifier.init("https://" + DOMAIN + "/", AUDIENCE, verifier)
.build()
.verify(token, "nonce");
}
private DecodedJWT jwt() {
if (jwt == null) {
// Decoding a token is expensive and involves construction of at least one Jackson ObjectMapper instance
// TODO Cache encoder/decoder as static field in AthenzAccessToken
jwt = JWT.decode(this.value);
}
return jwt;
}
@Test
public void shouldAcceptECDSA256Algorithm() throws Exception {
String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g";
ECKey key = (ECKey) PemUtils.readPublicKeyFromFile(PUBLIC_KEY_FILE_EC_256, "EC");
DecodedJWT jwt = JWT.require(Algorithm.ECDSA256(key))
.build()
.verify(token);
assertThat(jwt, is(notNullValue()));
}
@Test
public void shouldAcceptRSA512Algorithm() throws Exception {
String token = "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.mvL5LoMyIrWYjk5umEXZTmbyIrkbbcVPUkvdGZbu0qFBxGOf0nXP5PZBvPcOu084lvpwVox5n3VaD4iqzW-PsJyvKFgi5TnwmsbKchAp7JexQEsQOnTSGcfRqeUUiBZqRQdYsho71oAB3T4FnalDdFEpM-fztcZY9XqKyayqZLreTeBjqJm4jfOWH7KfGBHgZExQhe96NLq1UA9eUyQwdOA1Z0SgXe4Ja5PxZ6Fm37KnVDtDlNnY4JAAGFo6y74aGNnp_BKgpaVJCGFu1f1S5xCQ1HSvs8ZSdVWs5NgawW3wRd0kRt_GJ_Y3mIwiF4qUyHWGtsSHu_qjVdCTtbFyow";
RSAKey key = (RSAKey) PemUtils.readPublicKeyFromFile(PUBLIC_KEY_FILE_RSA, "RSA");
DecodedJWT jwt = JWT.require(Algorithm.RSA512(key))
.build()
.verify(token);
assertThat(jwt, is(notNullValue()));
}
@Test
public void shouldGetStringToken() throws Exception {
DecodedJWT jwt = JWT.decode("eyJhbGciOiJIUzI1NiJ9.e30.XmNK3GpH3Ys_7wsYBfq4C3M6goz71I7dTgUkuIa5lyQ");
assertThat(jwt, is(notNullValue()));
assertThat(jwt.getToken(), is(notNullValue()));
assertThat(jwt.getToken(), is("eyJhbGciOiJIUzI1NiJ9.e30.XmNK3GpH3Ys_7wsYBfq4C3M6goz71I7dTgUkuIa5lyQ"));
}
@Test
public void shouldGetCustomClaimOfTypeDouble() throws Exception {
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoyMy40NX0.7pyX2OmEGaU9q15T8bGFqRm-d3RVTYnqmZNZtxMKSlA";
DecodedJWT jwt = JWT.decode(token);
Assert.assertThat(jwt, is(notNullValue()));
Assert.assertThat(jwt.getClaim("name").asDouble(), is(23.45));
}
@Test
public void shouldGetJWTAsDetails() throws Exception {
String token = JWT.create()
.withIssuer("auth0")
.sign(hmacAlgorithm);
PreAuthenticatedAuthenticationJsonWebToken auth = usingToken(token);
assertThat(auth, is(notNullValue()));
assertThat(auth.getDetails(), is(notNullValue()));
assertThat(auth.getDetails(), is(instanceOf(DecodedJWT.class)));
}
/**
* Description: 解密jwt
*
* @param token token
* @param secret secret
* @return java.util.Map<java.lang.String , com.auth0.jwt.interfaces.Claim>
* @author fanxb
* @date 2019/3/4 18:14
*/
public static Map<String, Claim> decode(String token, String secret) {
if (token == null || token.length() == 0) {
throw new CustomException("token为空:" + token);
}
Algorithm algorithm = Algorithm.HMAC256(secret);
JWTVerifier jwtVerifier = JWT.require(algorithm).build();
DecodedJWT decodedJWT = jwtVerifier.verify(token);
return decodedJWT.getClaims();
}
@Test
public void shouldValidateJWTId() throws Exception {
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJqd3RfaWRfMTIzIn0.0kegfXUvwOYioP8PDaLMY1IlV8HOAzSVz3EGL7-jWF4";
DecodedJWT jwt = JWTVerifier.init(Algorithm.HMAC256("secret"))
.withJWTId("jwt_id_123")
.build()
.verify(token);
assertThat(jwt, is(notNullValue()));
}
private List<MediaFileWithUrlInfo> getSongs(HttpServletRequest request, Share share, Player player) {
Date expires = null;
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication instanceof JWTAuthenticationToken) {
DecodedJWT token = jwtSecurityService.verify((String) authentication.getCredentials());
expires = token.getExpiresAt();
}
Date finalExpires = expires;
List<MediaFileWithUrlInfo> result = new ArrayList<>();
List<MusicFolder> musicFolders = settingsService.getMusicFoldersForUser(player.getUsername());
if (share != null) {
for (MediaFile file : shareService.getSharedFiles(share.getId(), musicFolders)) {
if (file.getFile().exists()) {
if (file.isDirectory()) {
List<MediaFile> childrenOf = mediaFileService.getChildrenOf(file, true, false, true);
result.addAll(childrenOf.stream().map(mf -> addUrlInfo(request, player, mf, finalExpires)).collect(Collectors.toList()));
} else {
result.add(addUrlInfo(request, player, file, finalExpires));
}
}
}
}
return result;
}
@Test
public void shouldDecodeAStringToken() throws Exception {
String token = "eyJhbGciOiJIUzI1NiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.mZ0m_N1J4PgeqWmi903JuUoDRZDBPB7HwkS4nVyWH1M";
DecodedJWT jwt = JWT.decode(token);
assertThat(jwt, is(notNullValue()));
}
/**
* 校验token是否正确
*
* @param token Token
* @param secret 私钥
* @return boolean 是否正确
* @author Wang926454
* @date 2018/8/31 9:05
*/
public static boolean verify(String token, String secret) {
try {
Algorithm algorithm = Algorithm.HMAC256(secret);
JWTVerifier verifier = JWT.require(algorithm)
.build();
DecodedJWT jwt = verifier.verify(token);
return true;
} catch (UnsupportedEncodingException e) {
e.getMessage();
}
return false;
}
@Test
public void shouldValidateExpiresAtIfPresent() throws Exception {
Clock clock = mock(Clock.class);
when(clock.getToday()).thenReturn(new Date(DATE_TOKEN_MS_VALUE));
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0Nzc1OTJ9.isvT0Pqx0yjnZk53mUFSeYFJLDs-Ls9IsNAm86gIdZo";
JWTVerifier.BaseVerification verification = (JWTVerifier.BaseVerification) JWTVerifier.init(Algorithm.HMAC256("secret"));
DecodedJWT jwt = verification
.build(clock)
.verify(token);
assertThat(jwt, is(notNullValue()));
}
private void verifyJwtToken(Response response) throws NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException, JWTVerificationException {
TokenEntity responseToken = response.readEntity(TokenEntity.class);
assertEquals("BEARER", responseToken.getType().name());
String token = responseToken.getToken();
Algorithm algorithm = Algorithm.HMAC256("myJWT4Gr4v1t33_S3cr3t");
JWTVerifier jwtVerifier = JWT.require(algorithm).build();
DecodedJWT jwt = jwtVerifier.verify(token);
assertEquals(jwt.getSubject(),"[email protected]");
assertEquals(jwt.getClaim("firstname").asString(),"Jane");
assertEquals(jwt.getClaim("iss").asString(),"gravitee-management-auth");
assertEquals(jwt.getClaim("sub").asString(),"[email protected]");
assertEquals(jwt.getClaim("email").asString(),"[email protected]");
assertEquals(jwt.getClaim("lastname").asString(),"Doe");
}
@Test
public void shouldGetType() throws Exception {
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.e30.WdFmrzx8b9v_a-r6EHC2PTAaWywgm_8LiP8RBRhYwkI";
DecodedJWT jwt = JWT.require(Algorithm.HMAC256("secret"))
.build()
.verify(token);
assertThat(jwt, is(notNullValue()));
assertThat(jwt.getType(), is("JWS"));
}
public static void validate(String token) throws JWTVerificationException {
if (!Optional.of(JWT.require(MCRJWTUtil.getJWTAlgorithm())
.withAudience(AUDIENCE)
.build().verify(token))
.map(DecodedJWT::getId)
.map(MCRSessionMgr::getSession)
.isPresent()) {
throw new JWTVerificationException("MCRSession is invalid.");
}
}
@Test
public void succeedsAndIgnoresExpiredTokenException() {
SignatureVerifier verifier = new SymmetricSignatureVerifier("secret");
DecodedJWT decodedJWT = verifier.verifySignature(EXPIRED_HS_JWT);
assertThat(decodedJWT, notNullValue());
}
public CompletableFuture<DecodedJWT> verify(String token) {
final DecodedJWT unverifiedJwt;
try {
unverifiedJwt = JWT.decode(token);
} catch (JWTVerificationException e) {
return CompletableFuturesExtra.exceptionallyCompletedFuture(e);
}
return getAlgorithm(unverifiedJwt.getKeyId())
.thenApply(
alg -> {
JWTVerifier verifier = JWT.require(alg).build();
return verifier.verify(token);
});
}
@Test
public void shouldGetCustomArrayClaimOfTypeInteger() throws Exception {
String token = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjpbMSwyLDNdfQ.UEuMKRQYrzKAiPpPLhIVawWkKWA1zj0_GderrWUIyFE";
DecodedJWT jwt = JWT.decode(token);
Assert.assertThat(jwt, is(notNullValue()));
Assert.assertThat(jwt.getClaim("name").asArray(Integer.class), arrayContaining(1, 2, 3));
}
@Override
public String getUsername(String token) {
if (StringUtil.isEmpty(token)) {
return null;
}
return this.parseToken(token)
.map(DecodedJWT::getSubject)
.orElse(null);
}
/**
* 获取JWT 私有声明
* @param jwt
* @param payload
* @return
*/
private Payload getPrivateClaim(DecodedJWT jwt, Payload payload) {
Map<String, String> claims = new HashMap<String, String>();
jwt.getClaims().forEach((k,v)->{
String asString = v.asString();
claims.put(k, asString);
});
payload.setClaims(claims);
return payload;
}
@Test
public void testWithProperKey() throws IllegalArgumentException, UnsupportedEncodingException {
CustomJWToken tokenObj = new CustomJWToken(TestTokens.hs256_token);
JWTVerifier verifier = JWT.require(AlgorithmLinker.getVerifierAlgorithm(tokenObj.getAlgorithm(), "secret")).build();
DecodedJWT test = verifier.verify(TestTokens.hs256_token);
test.getAlgorithm();
}
private Optional<DecodedJWT> parseToken(String token) {
try {
return Optional.of(JWT.decode(token));
} catch (Exception e) {
return Optional.empty();
}
}