Search in sources :

Example 31 with Claim

use of com.auth0.android.jwt.Claim 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 32 with Claim

use of com.auth0.android.jwt.Claim 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 33 with Claim

use of com.auth0.android.jwt.Claim 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 34 with Claim

use of com.auth0.android.jwt.Claim in project jpsonic by tesshucom.

the class JWTAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication auth) {
    JWTAuthenticationToken authentication = (JWTAuthenticationToken) auth;
    if (!(authentication.getCredentials() instanceof String)) {
        LOG.error("Credentials not present");
        return null;
    }
    String rawToken = (String) auth.getCredentials();
    DecodedJWT token = JWTSecurityService.verify(jwtKey, rawToken);
    Claim path = token.getClaim(JWTSecurityService.CLAIM_PATH);
    authentication.setAuthenticated(true);
    // TODO:AD This is super unfortunate, but not sure there is a better way when using JSP
    if (StringUtils.contains(authentication.getRequestedPath(), "/WEB-INF/jsp/")) {
        LOG.warn("BYPASSING AUTH FOR WEB-INF page");
    } else if (!roughlyEqual(path.asString(), authentication.getRequestedPath())) {
        throw new InsufficientAuthenticationException("Credentials not valid for path " + authentication.getRequestedPath() + ". They are valid for " + path.asString());
    }
    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("IS_AUTHENTICATED_FULLY"));
    authorities.add(new SimpleGrantedAuthority("ROLE_TEMP"));
    return new JWTAuthenticationToken(authorities, rawToken, authentication.getRequestedPath());
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Claim(com.auth0.jwt.interfaces.Claim)

Example 35 with Claim

use of com.auth0.android.jwt.Claim in project jpsonic by tesshucom.

the class JWTSecurityServiceTest method testAddJWTToken.

// false positive
@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert")
@Test
void testAddJWTToken() {
    // Originally Parameterized was used. If possible, it is better to rewrite to the new
    // spring-method.
    Arrays.asList(new Object[][] { { "http://localhost:8080/jpsonic/stream?id=4", "/jpsonic/stream?id=4" }, { "/jpsonic/stream?id=4", "/jpsonic/stream?id=4" } }).forEach(o -> {
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(o[0].toString());
        String actualUri = jwtSecurityService.addJWTToken(builder).build().toUriString();
        String jwtToken = UriComponentsBuilder.fromUriString(actualUri).build().getQueryParams().getFirst(JWTSecurityService.JWT_PARAM_NAME);
        Algorithm algorithm = JWTSecurityService.getAlgorithm(settingsService.getJWTKey());
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT verify = verifier.verify(jwtToken);
        Claim claim = verify.getClaim(JWTSecurityService.CLAIM_PATH);
        assertEquals(o[1], claim.asString());
    });
}
Also used : UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Claim(com.auth0.jwt.interfaces.Claim) Test(org.junit.jupiter.api.Test)

Aggregations

Claim (com.auth0.jwt.interfaces.Claim)110 Test (org.junit.Test)67 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)62 JsonNode (com.fasterxml.jackson.databind.JsonNode)42 Algorithm (com.auth0.jwt.algorithms.Algorithm)24 Date (java.util.Date)24 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)21 RSAPublicKey (java.security.interfaces.RSAPublicKey)21 Test (org.junit.jupiter.api.Test)18 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)17 JWTVerifier (com.auth0.jwt.JWTVerifier)15 JwksTestKeySource (org.sdase.commons.server.auth.service.testsources.JwksTestKeySource)14 JsonObject (com.google.gson.JsonObject)10 HashMap (java.util.HashMap)9 UserPojo (com.auth0.jwt.UserPojo)8 IOException (java.io.IOException)8 Map (java.util.Map)8 TestingProcessManager (io.supertokens.test.TestingProcessManager)7 NullClaim (com.auth0.jwt.impl.NullClaim)5 JWT (com.auth0.jwt.JWT)4