java.security.interfaces.RSAKey#com.auth0.jwt.interfaces.DecodedJWT源码实例Demo

下面列出了java.security.interfaces.RSAKey#com.auth0.jwt.interfaces.DecodedJWT 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: recheck   文件: RetestAuthentication.java

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");
    }
}
 
源代码3 项目: Knowage-Server   文件: JWTSsoService.java

@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);
	}
}
 
源代码4 项目: waltz   文件: JWTAuthenticationFilter.java

@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());
    }
}
 
源代码5 项目: java-jwt   文件: RSAAlgorithm.java

@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);
    }
}
 
源代码6 项目: spring-jwt-gateway   文件: JWTFilter.java

@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());
        }
    };
}
 
源代码7 项目: java-jwt   文件: ECDSAAlgorithm.java

@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);
    }
}
 
源代码8 项目: auth0-java   文件: IdTokenVerifierTest.java

@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");
}
 
源代码9 项目: vespa   文件: AthenzAccessToken.java

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;
}
 
源代码10 项目: java-jwt   文件: JWTTest.java

@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()));
}
 
源代码11 项目: java-jwt   文件: JWTTest.java

@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()));
}
 
源代码12 项目: java-jwt   文件: JWTTest.java

@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"));
}
 
源代码13 项目: java-jwt   文件: JWTDecoderTest.java

@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)));
}
 
源代码15 项目: bookmark   文件: JwtUtil.java

/**
 * 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();
}
 
源代码16 项目: java-jwt   文件: JWTVerifierTest.java

@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()));
}
 
源代码17 项目: airsonic   文件: ExternalPlayerController.java

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;
}
 
源代码18 项目: java-jwt   文件: JWTTest.java

@Test
public void shouldDecodeAStringToken() throws Exception {
    String token = "eyJhbGciOiJIUzI1NiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.mZ0m_N1J4PgeqWmi903JuUoDRZDBPB7HwkS4nVyWH1M";
    DecodedJWT jwt = JWT.decode(token);

    assertThat(jwt, is(notNullValue()));
}
 
源代码19 项目: ProjectStudy   文件: JwtUtil.java

/**
 * 校验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;
}
 
源代码20 项目: java-jwt   文件: JWTVerifierTest.java

@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");
}
 
源代码22 项目: java-jwt   文件: JWTTest.java

@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"));
}
 
源代码23 项目: mycore   文件: MCRJWTResource.java

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());
}
 
源代码25 项目: curiostack   文件: JwtVerifier.java

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);
          });
}
 
源代码26 项目: java-jwt   文件: JWTDecoderTest.java

@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));
}
 
源代码27 项目: keeper   文件: SimpleJwtToken.java

@Override
public String getUsername(String token) {
    if (StringUtil.isEmpty(token)) {
        return null;
    }
    return this.parseToken(token)
            .map(DecodedJWT::getSubject)
            .orElse(null);
}
 
源代码28 项目: springbootexamples   文件: JWTService.java

/**
 * 获取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;
}
 
源代码29 项目: JWT4B   文件: TestAlgorithmLinker.java

@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();
}
 
源代码30 项目: keeper   文件: SimpleJwtToken.java

private Optional<DecodedJWT> parseToken(String token) {
    try {
        return Optional.of(JWT.decode(token));
    } catch (Exception e) {
        return Optional.empty();
    }
}