Search in sources :

Example 61 with JWT

use of com.auth0.android.jwt.JWT in project commons by mosip.

the class TokenHandlerUtil method isValidBearerToken.

/**
 * Validates the token offline based on the Oauth2 standards.
 *
 * @param accessToken
 *            - Bearer token
 * @param issuerUrl
 *            - issuer URL to be read from the properties,
 * @param clientId
 *            - client Id to be read from the properties
 * @return Boolean
 */
public static boolean isValidBearerToken(String accessToken, String issuerUrl, String clientId) {
    try {
        DecodedJWT decodedJWT = decodedTokens.get(accessToken);
        if (decodedJWT == null) {
            decodedJWT = JWT.decode(accessToken);
            decodedTokens.put(accessToken, decodedJWT);
        }
        Map<String, Claim> claims = decodedJWT.getClaims();
        LocalDateTime expiryTime = DateUtils.convertUTCToLocalDateTime(DateUtils.getUTCTimeFromDate(decodedJWT.getExpiresAt()));
        if (!decodedJWT.getIssuer().equals(issuerUrl)) {
            return false;
        } else if (!DateUtils.before(DateUtils.getUTCCurrentDateTime(), expiryTime)) {
            return false;
        } else if (!claims.get("clientId").asString().equals(clientId)) {
            return false;
        } else {
            return true;
        }
    } catch (JWTDecodeException e) {
        LOGGER.error("JWT DECODE EXCEPTION ::".concat(e.getMessage()).concat(ExceptionUtils.getStackTrace(e)));
        return false;
    } catch (Exception e) {
        LOGGER.error(e.getMessage().concat(ExceptionUtils.getStackTrace(e)));
        return false;
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) JWTDecodeException(com.auth0.jwt.exceptions.JWTDecodeException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Claim(com.auth0.jwt.interfaces.Claim) JWTDecodeException(com.auth0.jwt.exceptions.JWTDecodeException)

Example 62 with JWT

use of com.auth0.android.jwt.JWT in project edge-cloud-sampleapps by mobiledgex.

the class RegisterClientTest method registerClientTest.

@Test
public void registerClientTest() {
    Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
    MatchingEngine me = new MatchingEngine(context);
    me.setUseWifiOnly(useWifiOnly);
    me.setMatchingEngineLocationAllowed(true);
    me.setAllowSwitchIfNoSubscriberInfo(true);
    AppClient.RegisterClientReply reply = null;
    String appName = applicationName;
    try {
        Location location = getTestLocation(47.6062, 122.3321);
        AppClient.RegisterClientRequest request = me.createDefaultRegisterClientRequest(context, organizationName).setAppName(applicationName).setAppVers(appVersion).setCellId(getCellId(context, me)).build();
        if (useHostOverride) {
            reply = me.registerClient(request, hostOverride, portOverride, GRPC_TIMEOUT_MS);
        } else {
            reply = me.registerClient(request, me.generateDmeHostAddress(), me.getPort(), GRPC_TIMEOUT_MS);
        }
        JWT jwt = null;
        try {
            jwt = new JWT(reply.getSessionCookie());
        } catch (DecodeException e) {
            Log.e(TAG, Log.getStackTraceString(e));
            assertFalse("registerClientTest: DecodeException!", true);
        }
        // Validate JWT
        // 10 seconds leeway
        boolean isExpired = jwt.isExpired(10);
        assertTrue(!isExpired);
        Log.i(TAG, "Claims count: " + jwt.getClaims().keySet().size());
        for (String key : jwt.getClaims().keySet()) {
            Claim claim = jwt.getClaims().get(key);
            Log.i(TAG, "key: " + key + " Claim: " + claim.asString());
        }
        Claim c = jwt.getClaim("key");
        JsonObject claimJson = c.asObject(JsonObject.class);
        String orgName = claimJson.get("orgname").getAsString();
        assertEquals("orgname doesn't match!", "MobiledgeX", orgName);
        Log.i(TAG, "registerReply.getSessionCookie()=" + reply.getSessionCookie());
        assertTrue(reply != null);
        assertTrue(reply.getStatus() == AppClient.ReplyStatus.RS_SUCCESS);
        assertTrue(!reply.getUniqueId().isEmpty());
        assertTrue(reply.getSessionCookie().length() > 0);
    } catch (PackageManager.NameNotFoundException nnfe) {
        Log.e(TAG, Log.getStackTraceString(nnfe));
        assertFalse("ExecutionException registering using PackageManager.", true);
    } catch (DmeDnsException dde) {
        Log.e(TAG, Log.getStackTraceString(dde));
        assertFalse("registerClientTest: DmeDnsException!", true);
    } catch (ExecutionException ee) {
        Log.e(TAG, Log.getStackTraceString(ee));
        assertFalse("registerClientTest: ExecutionException!", true);
    } catch (StatusRuntimeException sre) {
        Log.e(TAG, Log.getStackTraceString(sre));
        assertFalse("registerClientTest: StatusRuntimeException!", true);
    } catch (InterruptedException ie) {
        Log.e(TAG, Log.getStackTraceString(ie));
        assertFalse("registerClientTest: InterruptedException!", true);
    }
    Log.i(TAG, "registerClientTest reply: " + reply.toString());
    assertEquals(0, reply.getVer());
    assertEquals(AppClient.ReplyStatus.RS_SUCCESS, reply.getStatus());
}
Also used : Context(android.content.Context) JWT(com.auth0.android.jwt.JWT) JsonObject(com.google.gson.JsonObject) MatchingEngine(com.mobiledgex.matchingengine.MatchingEngine) DecodeException(com.auth0.android.jwt.DecodeException) PackageManager(android.content.pm.PackageManager) StatusRuntimeException(io.grpc.StatusRuntimeException) AppClient(distributed_match_engine.AppClient) ExecutionException(java.util.concurrent.ExecutionException) Claim(com.auth0.android.jwt.Claim) Location(android.location.Location) DmeDnsException(com.mobiledgex.matchingengine.DmeDnsException) Test(org.junit.Test)

Example 63 with JWT

use of com.auth0.android.jwt.JWT in project simple-jwt by vorbote.

the class AccessKeyUtil method Info.

/**
 * Decode the token, and you can easily get some info from
 * this token.
 *
 * @param token The token.
 * @return The decoded jwt token.
 * @throws com.auth0.jwt.exceptions.AlgorithmMismatchException     If the algorithm stated in the token's
 *                                                                 header it's not equal to the one
 *                                                                 defined in the JWTVerifier.
 * @throws com.auth0.jwt.exceptions.SignatureVerificationException If the signature is invalid.
 * @throws com.auth0.jwt.exceptions.TokenExpiredException          If the token has expired.
 * @throws com.auth0.jwt.exceptions.InvalidClaimException          If a claim contained a different value
 *                                                                 than the expected one.
 * @throws com.auth0.jwt.exceptions.JWTVerificationException       If any of the verification steps fail
 * @see JWTVerifier#verify(String)
 */
public DecodedJWT Info(String token) {
    JWTVerifier verifier;
    switch(algorithm) {
        case HS256:
            verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            break;
        case HS384:
            verifier = JWT.require(Algorithm.HMAC384(secret)).build();
            break;
        case HS512:
            verifier = JWT.require(Algorithm.HMAC512(secret)).build();
            break;
        default:
            // 这里理论上应该抛出异常的,但是实在是懒得做了,就先这样吧。
            // 至于其他的算法,后续再考虑加上。
            verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            log.error("This algorithm is not supported yet, will use HMAC256 by default.");
    }
    return verifier.verify(token);
}
Also used : JWTVerifier(com.auth0.jwt.JWTVerifier)

Example 64 with JWT

use of com.auth0.android.jwt.JWT in project avni-server by avniproject.

the class AuthenticationFilter method getCookieMaxAge.

private int getCookieMaxAge(String authToken) {
    DecodedJWT jwt = JWT.decode(authToken);
    int expiryDuration = (int) ((jwt.getExpiresAt().getTime() - new Date().getTime()) / 1000) - 60;
    return expiryDuration < 0 ? 0 : expiryDuration;
}
Also used : DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Date(java.util.Date)

Example 65 with JWT

use of com.auth0.android.jwt.JWT in project cf-java-logging-support by SAP.

the class TokenDecoder method validateAndDecodeToken.

/**
 * This method validates if a token has a valid signature as well as a valid
 * timestamp and returns the decoded token
 *
 * @throws DynamicLogLevelException
 */
public DecodedJWT validateAndDecodeToken(String token) throws DynamicLogLevelException {
    try {
        DecodedJWT jwt = verifier.verify(token);
        Date exp = jwt.getExpiresAt();
        Date iat = jwt.getIssuedAt();
        Date now = new Date();
        if (exp != null && iat != null && now.after(iat) && now.before(exp)) {
            return jwt;
        } else {
            throw new DynamicLogLevelException("Token provided to dynamically change the log-level on thread-level is outdated");
        }
    } catch (JWTVerificationException e) {
        // Exception is not attached to avoid logging of JWT token
        throw new DynamicLogLevelException("Token could not be verified");
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Date(java.util.Date)

Aggregations

DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)305 Test (org.junit.Test)217 Algorithm (com.auth0.jwt.algorithms.Algorithm)110 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)82 JWTVerifier (com.auth0.jwt.JWTVerifier)79 IOException (java.io.IOException)60 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)54 ECDSAAlgorithmTest (com.auth0.jwt.algorithms.ECDSAAlgorithmTest)53 Date (java.util.Date)50 Claim (com.auth0.jwt.interfaces.Claim)36 RSAPublicKey (java.security.interfaces.RSAPublicKey)34 ECPublicKey (java.security.interfaces.ECPublicKey)27 ECDSAKeyProvider (com.auth0.jwt.interfaces.ECDSAKeyProvider)26 HashMap (java.util.HashMap)25 JWTDecodeException (com.auth0.jwt.exceptions.JWTDecodeException)20 Instant (java.time.Instant)20 JsonObject (com.google.gson.JsonObject)19 ServletException (javax.servlet.ServletException)19 JWT (com.auth0.jwt.JWT)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)18