com.auth0.jwt.interfaces.DecodedJWT Java Examples

The following examples show how to use com.auth0.jwt.interfaces.DecodedJWT. 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: RetestAuthentication.java    From recheck with GNU Affero General Public License v3.0 7 votes vote down vote up
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();
}
 
Example #2
Source File: IdTokenVerifierTest.java    From auth0-java with MIT License 6 votes vote down vote up
@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");
}
 
Example #3
Source File: JWTSsoService.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@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);
	}
}
 
Example #4
Source File: ECDSAAlgorithm.java    From java-jwt with MIT License 6 votes vote down vote up
@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);
    }
}
 
Example #5
Source File: SonosLinkSecurityInterceptor.java    From airsonic-advanced with GNU General Public License v3.0 6 votes vote down vote up
@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");
    }
}
 
Example #6
Source File: JWTFilter.java    From spring-jwt-gateway with Apache License 2.0 6 votes vote down vote up
@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());
        }
    };
}
 
Example #7
Source File: RSAAlgorithm.java    From java-jwt with MIT License 6 votes vote down vote up
@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);
    }
}
 
Example #8
Source File: JWTAuthenticationFilter.java    From waltz with Apache License 2.0 6 votes vote down vote up
@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());
    }
}
 
Example #9
Source File: JWTTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldGetStringAudience() throws Exception {
    String token = "eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJKYWNrIFJleWVzIn0.a4I9BBhPt1OB1GW67g2P1bEHgi6zgOjGUL4LvhE9Dgc";
    DecodedJWT jwt = JWT.require(Algorithm.HMAC256("secret"))
            .build()
            .verify(token);

    assertThat(jwt, is(notNullValue()));
    assertThat(jwt.getAudience(), is(IsCollectionWithSize.hasSize(1)));
    assertThat(jwt.getAudience(), is(IsCollectionContaining.hasItems("Jack Reyes")));
}
 
Example #10
Source File: JWTDecoderTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldGetCustomClaimOfTypeInteger() throws Exception {
    String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoxMjN9.XZAudnA7h3_Al5kJydzLjw6RzZC3Q6OvnLEYlhNW7HA";
    DecodedJWT jwt = JWT.decode(token);
    Assert.assertThat(jwt, is(notNullValue()));
    Assert.assertThat(jwt.getClaim("name").asInt(), is(123));
}
 
Example #11
Source File: JWTDecoderTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldGetIssuedAt() throws Exception {
    DecodedJWT jwt = JWT.decode("eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE0NzY3MjcwODZ9.KPjGoW665E8V5_27Jugab8qSTxLk2cgquhPCBfAP0_w");
    assertThat(jwt, is(notNullValue()));
    assertThat(jwt.getIssuedAt(), is(instanceOf(Date.class)));
    long ms = 1476727086L * 1000;
    Date expectedDate = new Date(ms);
    assertThat(jwt.getIssuedAt(), is(notNullValue()));
    assertThat(jwt.getIssuedAt(), is(equalTo(expectedDate)));
}
 
Example #12
Source File: JWTVerifierTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldValidateNotBeforeIfPresent() 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()));
}
 
Example #13
Source File: JWTSsoService.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String jwtToken2userId(String jwtToken) throws JWTVerificationException {
	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!!!");
	String userId = userIdClaim.asString();
	LogMF.debug(logger, "User id is [{0}]", userId);
	return userId;
}
 
Example #14
Source File: AuthController.java    From tutorials with MIT License 5 votes vote down vote up
@GetMapping(value="/callback")
public void callback(HttpServletRequest request, HttpServletResponse response) throws IOException, IdentityVerificationException {
    Tokens tokens = authenticationController.handle(request, response);

    DecodedJWT jwt = JWT.decode(tokens.getIdToken());
    TestingAuthenticationToken authToken2 = new TestingAuthenticationToken(jwt.getSubject(), jwt.getToken());
    authToken2.setAuthenticated(true);

    SecurityContextHolder.getContext().setAuthentication(authToken2);
    response.sendRedirect(config.getContextPath(request) + "/"); 
}
 
Example #15
Source File: JWTVerifierTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test(expected = InvalidClaimException.class)
public void shouldThrowOnFutureIssuedAt() throws Exception {
    Clock clock = mock(Clock.class);
    when(clock.getToday()).thenReturn(new Date(DATE_TOKEN_MS_VALUE - 1000));

    String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE0Nzc1OTJ9.CWq-6pUXl1bFg81vqOUZbZrheO2kUBd2Xr3FUZmvudE";
    JWTVerifier.BaseVerification verification = (JWTVerifier.BaseVerification) JWTVerifier.init(Algorithm.HMAC256("secret"));

    DecodedJWT jwt = verification.build(clock).verify(token);
    assertThat(jwt, is(notNullValue()));
}
 
Example #16
Source File: IdTokenVerifierTest.java    From auth0-java with MIT License 5 votes vote down vote up
private IdTokenVerifier.Builder configureVerifier(String token) {
    DecodedJWT decodedJWT = JWT.decode(token);
    SignatureVerifier verifier = mock(SignatureVerifier.class);
    when(verifier.verifySignature(token)).thenReturn(decodedJWT);

    return IdTokenVerifier.init("https://" + DOMAIN + "/", AUDIENCE, verifier)
            .withClock(DEFAULT_CLOCK);
}
 
Example #17
Source File: JWTVerifierTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldSkipClaimValidationsIfNoClaimsRequired() throws Exception {
    String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M";
    DecodedJWT jwt = JWTVerifier.init(Algorithm.HMAC256("secret"))
            .build()
            .verify(token);

    assertThat(jwt, is(notNullValue()));
}
 
Example #18
Source File: AuthenticationJsonWebTokenTest.java    From auth0-spring-security-api with MIT License 5 votes vote down vote up
@Test
public void shouldGetJWTAsDetails() throws Exception {
    String token = JWT.create()
            .withIssuer("auth0")
            .sign(hmacAlgorithm);

    AuthenticationJsonWebToken auth = new AuthenticationJsonWebToken(token, verifier);
    assertThat(auth, is(notNullValue()));
    assertThat(auth.getDetails(), is(notNullValue()));
    assertThat(auth.getDetails(), is(instanceOf(DecodedJWT.class)));
}
 
Example #19
Source File: AthenzAccessToken.java    From vespa with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #20
Source File: JwtUtil.java    From spring-boot-plus with Apache License 2.0 5 votes vote down vote up
/**
 * 获取创建时间
 *
 * @param token
 * @return
 */
public static Date getIssuedAt(String token) {
    DecodedJWT decodedJwt = getJwtInfo(token);
    if (decodedJwt == null) {
        return null;
    }
    return decodedJwt.getIssuedAt();
}
 
Example #21
Source File: JWTDecoderTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldNotGetNullClaimIfClaimIsEmptyObject() throws Exception {
    DecodedJWT jwt = JWT.decode("eyJhbGciOiJIUzI1NiJ9.eyJvYmplY3QiOnt9fQ.d3nUeeL_69QsrHL0ZWij612LHEQxD8EZg1rNoY3a4aI");
    assertThat(jwt, is(notNullValue()));
    assertThat(jwt.getClaim("object"), is(notNullValue()));
    assertThat(jwt.getClaim("object").isNull(), is(false));
}
 
Example #22
Source File: JWTVerifierTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldValidateCustomClaimOfTypeDate() throws Exception {
    String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoxNDc4ODkxNTIxfQ.mhioumeok8fghQEhTKF3QtQAksSvZ_9wIhJmgZLhJ6c";
    Date date = new Date(1478891521000L);
    DecodedJWT jwt = JWTVerifier.init(Algorithm.HMAC256("secret"))
            .withClaim("name", date)
            .build()
            .verify(token);

    assertThat(jwt, is(notNullValue()));
}
 
Example #23
Source File: SignatureVerifierTest.java    From auth0-java-mvc-common with MIT License 5 votes vote down vote up
@Test
public void succeedsSkippingSignatureCheckOnHS256Token() {
    SignatureVerifier verifier = new AlgorithmNameVerifier();
    DecodedJWT decodedJWT1 = verifier.verifySignature(HS_JWT);
    DecodedJWT decodedJWT2 = verifier.verifySignature(HS_JWT_INVALID_SIGNATURE);

    assertThat(decodedJWT1, notNullValue());
    assertThat(decodedJWT2, notNullValue());
}
 
Example #24
Source File: JwtToken.java    From spring-boot-plus with Apache License 2.0 5 votes vote down vote up
public static JwtToken build(String token, String username, String salt, long expireSecond) {
    DecodedJWT decodedJwt = JwtUtil.getJwtInfo(token);
    Date createDate = decodedJwt.getIssuedAt();
    Date expireDate = decodedJwt.getExpiresAt();
    return new JwtToken()
            .setUsername(username)
            .setToken(token)
            .setHost(IpUtil.getRequestIp())
            .setSalt(salt)
            .setCreateDate(createDate)
            .setExpireSecond(expireSecond)
            .setExpireDate(expireDate);

}
 
Example #25
Source File: JWTDecoderTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldGetCustomClaimOfTypeBoolean() throws Exception {
    String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjp0cnVlfQ.FwQ8VfsZNRqBa9PXMinSIQplfLU4-rkCLfIlTLg_MV0";
    DecodedJWT jwt = JWT.decode(token);
    Assert.assertThat(jwt, is(notNullValue()));
    Assert.assertThat(jwt.getClaim("name").asBoolean(), is(true));
}
 
Example #26
Source File: TokenCheck.java    From JWT4B with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isValidJWT(String jwt) {
	 
	if (StringUtils.countMatches(jwt, ".") != 2) {
		return false;
	}
	
	jwt=jwt.trim();
	if(StringUtils.contains(jwt," ")){
		return false;
	}

	String[] sArray=StringUtils.split(jwt,".");
	if(sArray.length < 3){
		return false;
	}
	for(String value:sArray){
		if(!value.matches("[A-Za-z0-9+/=_-]+")){
			return false;
		}
	}

	try {
		DecodedJWT decoded = JWT.decode(jwt);
		decoded.getAlgorithm();
		return true;
	} catch (Exception exception) {}
	
	return false;
}
 
Example #27
Source File: RetestAuthentication.java    From recheck with GNU Affero General Public License v3.0 5 votes vote down vote up
private void refreshTokens() {
	final Optional<DecodedJWT> refreshedToken = refreshAccessToken();
	if ( refreshedToken.isPresent() ) {
		accessToken = refreshedToken.get();
	} else {
		login();
	}
}
 
Example #28
Source File: JWTVerifierTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldValidateCustomClaimOfTypeString() throws Exception {
    String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoidmFsdWUifQ.Jki8pvw6KGbxpMinufrgo6RDL1cu7AtNMJYVh6t-_cE";
    DecodedJWT jwt = JWTVerifier.init(Algorithm.HMAC256("secret"))
            .withClaim("name", "value")
            .build()
            .verify(token);

    assertThat(jwt, is(notNullValue()));
}
 
Example #29
Source File: JwtUtil.java    From wetech-admin with MIT License 5 votes vote down vote up
/**
 * 获得Token中的信息无需secret解密也能获得
 *
 * @param token
 * @param claim
 * @return
 */
public static String getClaim(String token, String claim) {
    try {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim(claim).asString();
    } catch (JWTDecodeException e) {
        return null;
    }
}
 
Example #30
Source File: Token.java    From mdw with Apache License 2.0 5 votes vote down vote up
private void verify() throws IOException {
    Props props = new Props(this);

    String mdwAppId = appId;
    if (mdwAppId == null)
        mdwAppId = props.get(Props.APP_ID);
    if (mdwAppId == null)
        throw new IOException("--app-id param or mdw.app.id prop required");

    if (userToken == null)
        throw new IOException("--user-token required for verification");

    String mdwAppToken = appToken;
    if (mdwAppToken == null)
        mdwAppToken = System.getenv("MDW_APP_TOKEN");
    if (mdwAppToken == null)
        throw new IOException("--app-token param or MDW_APP_TOKEN environment variable required");

    JWTVerifier verifier = JWT.require(Algorithm.HMAC256(mdwAppToken))
            .withIssuer("mdwAuth")
            .withAudience(mdwAppId)
            .build();

    DecodedJWT jwt = verifier.verify(userToken);
    String subject = jwt.getSubject();
    getOut().println("Token verified for app " + mdwAppId + " and user " + subject);
}