Java Code Examples for org.jose4j.jwt.consumer.JwtConsumer#processToClaims()
The following examples show how to use
org.jose4j.jwt.consumer.JwtConsumer#processToClaims() .
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: OauthHelperTest.java From light-4j with Apache License 2.0 | 6 votes |
private static boolean isTokenExpired(String authorization) { boolean expired = false; String jwt = getJwtFromAuthorization(authorization); if(jwt != null) { JwtConsumer consumer = new JwtConsumerBuilder() .setDisableRequireSignature() .setSkipSignatureVerification() .build(); try { consumer.processToClaims(jwt); } catch (InvalidJwtException e) { if(e.hasExpired()) expired = true; } } return expired; }
Example 2
Source File: JWTokenFactory.java From eplmp with Eclipse Public License 1.0 | 6 votes |
public static String validateSharedResourceToken(Key key, String jwt) { JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setVerificationKey(key) .setRelaxVerificationKeyValidation() .build(); try { JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt); String subject = jwtClaims.getSubject(); try (JsonReader reader = Json.createReader(new StringReader(subject))) { JsonObject subjectObject = reader.readObject(); // JsonParsingException return subjectObject.getString(SHARED_ENTITY_UUID); // Npe } } catch (InvalidJwtException | MalformedClaimException | JsonParsingException | NullPointerException e) { LOGGER.log(Level.FINE, "Cannot validate jwt token", e); } return null; }
Example 3
Source File: JWTokenFactory.java From eplmp with Eclipse Public License 1.0 | 6 votes |
public static String validateEntityToken(Key key, String jwt) { JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setVerificationKey(key) .setRelaxVerificationKeyValidation() .build(); try { JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt); String subject = jwtClaims.getSubject(); try (JsonReader reader = Json.createReader(new StringReader(subject))) { JsonObject subjectObject = reader.readObject(); // JsonParsingException return subjectObject.getString(ENTITY_KEY); // Npe } } catch (InvalidJwtException | MalformedClaimException | JsonParsingException | NullPointerException e) { LOGGER.log(Level.FINE, "Cannot validate jwt token", e); } return null; }
Example 4
Source File: JwtHelper.java From openhab-core with Eclipse Public License 2.0 | 6 votes |
/** * Performs verifications on a JWT token, then parses it into a {@link AuthenticationException} instance * * @param jwt the base64-encoded JWT token from the request * @return the {@link Authentication} derived from the information in the token * @throws AuthenticationException */ public Authentication verifyAndParseJwtAccessToken(String jwt) throws AuthenticationException { JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(30) .setRequireSubject().setExpectedIssuer(ISSUER_NAME).setExpectedAudience(AUDIENCE) .setVerificationKey(jwtWebKey.getKey()) .setJwsAlgorithmConstraints(ConstraintType.WHITELIST, AlgorithmIdentifiers.RSA_USING_SHA256).build(); try { JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt); String username = jwtClaims.getSubject(); List<String> roles = jwtClaims.getStringListClaimValue("role"); Authentication auth = new Authentication(username, roles.toArray(new String[roles.size()])); return auth; } catch (Exception e) { logger.error("Error while processing JWT token", e); throw new AuthenticationException(e.getMessage()); } }
Example 5
Source File: BoxDeveloperEditionAPIConnectionTest.java From box-java-sdk with Apache License 2.0 | 6 votes |
private JwtClaims getClaimsFromRequest(Request request) throws Exception { // Get the JWT out of the request body String body = request.getBodyAsString(); String[] tokens = body.split("&"); String jwt = null; for (String s : tokens) { String[] parts = s.split("="); if (parts[0] != null && parts[0].equals("assertion") && parts[1] != null) { jwt = parts[1]; } } if (jwt == null) { throw new Exception("No jwt assertion found in request body"); } // Parse out the JWT to verify the claims JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setSkipSignatureVerification() .setSkipAllValidators() .build(); return jwtConsumer.processToClaims(jwt); }
Example 6
Source File: Token.java From server_face_recognition with GNU General Public License v3.0 | 5 votes |
public static Token decypherToken(String token) { JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setRequireExpirationTime() .setAllowedClockSkewInSeconds(30) .setRequireSubject() .setExpectedIssuer("Sanstorik") .setExpectedAudience("User") .setVerificationKey(key.getKey()) .setJwsAlgorithmConstraints( new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, AlgorithmIdentifiers.RSA_USING_SHA256)) .build(); Token decypheredToken = null; try { JwtClaims jwtClaims = jwtConsumer.processToClaims(token); decypheredToken = new Token(token, jwtClaims.getClaimValue(USERNAME_KEY).toString(), jwtClaims.getClaimValue(PASSWORD_KEY).toString(), Integer.valueOf(jwtClaims.getClaimValue(USERID_KEY).toString()) ); } catch (InvalidJwtException e) { e.printStackTrace(); } return decypheredToken; }
Example 7
Source File: JWTokenFactory.java From eplmp with Eclipse Public License 1.0 | 5 votes |
public static JWTokenUserGroupMapping validateAuthToken(Key key, String jwt) { JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setVerificationKey(key) .setRelaxVerificationKeyValidation() .build(); try { JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt); String subject = jwtClaims.getSubject(); try (JsonReader reader = Json.createReader(new StringReader(subject))) { JsonObject subjectObject = reader.readObject(); // JsonParsingException String login = subjectObject.getString(SUBJECT_LOGIN); // Npe String groupName = subjectObject.getString(SUBJECT_GROUP_NAME); // Npe if (login != null && !login.isEmpty() && groupName != null && !groupName.isEmpty()) { return new JWTokenUserGroupMapping(jwtClaims, new UserGroupMapping(login, groupName)); } } } catch (InvalidJwtException | MalformedClaimException | JsonParsingException | NullPointerException e) { LOGGER.log(Level.FINE, "Cannot validate jwt token", e); } return null; }
Example 8
Source File: JwtUtil.java From light with Apache License 2.0 | 5 votes |
public static Map<String, Object> verifyJwt(String jwt) throws InvalidJwtException, MalformedClaimException { Map<String, Object> user = null; X509VerificationKeyResolver x509VerificationKeyResolver = new X509VerificationKeyResolver(certificate); x509VerificationKeyResolver.setTryAllOnNoThumbHeader(true); JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setRequireExpirationTime() // the JWT must have an expiration time .setAllowedClockSkewInSeconds((Integer) config.get(CLOCK_SKEW_IN_MINUTE)*60) // allow some leeway in validating time based claims to account for clock skew .setRequireSubject() // the JWT must have a subject claim .setExpectedIssuer(issuer) .setExpectedAudience(audience) .setVerificationKeyResolver(x509VerificationKeyResolver) // verify the signature with the certificates .build(); // create the JwtConsumer instance // Validate the JWT and process it to the Claims JwtClaims claims = jwtConsumer.processToClaims(jwt); if(claims != null) { user = new HashMap<String, Object>(); user.put("userId", claims.getClaimValue("userId")); user.put("clientId", claims.getClaimValue("clientId")); List roles = claims.getStringListClaimValue("roles"); user.put("roles", roles); Object host = claims.getClaimValue("host"); if(host != null) user.put("host", host); } return user; }
Example 9
Source File: JwtAuthenticationServiceImplTest.java From blueocean-plugin with MIT License | 4 votes |
@Test public void anonymousUserToken() throws Exception{ j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); JenkinsRule.WebClient webClient = j.createWebClient(); String token = getToken(webClient); Assert.assertNotNull(token); JsonWebStructure jsonWebStructure = JsonWebStructure.fromCompactSerialization(token); Assert.assertTrue(jsonWebStructure instanceof JsonWebSignature); JsonWebSignature jsw = (JsonWebSignature) jsonWebStructure; String kid = jsw.getHeader("kid"); Assert.assertNotNull(kid); Page page = webClient.goTo("jwt-auth/jwks/"+kid+"/", "application/json"); // for(NameValuePair valuePair: page.getWebResponse().getResponseHeaders()){ // System.out.println(valuePair); // } JSONObject jsonObject = JSONObject.fromObject(page.getWebResponse().getContentAsString()); RsaJsonWebKey rsaJsonWebKey = new RsaJsonWebKey(jsonObject,null); JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setRequireExpirationTime() // the JWT must have an expiration time .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew .setRequireSubject() // the JWT must have a subject claim .setVerificationKey(rsaJsonWebKey.getKey()) // verify the sign with the public key .build(); // create the JwtConsumer instance JwtClaims claims = jwtConsumer.processToClaims(token); Assert.assertEquals("anonymous",claims.getSubject()); Map<String,Object> claimMap = claims.getClaimsMap(); Map<String,Object> context = (Map<String, Object>) claimMap.get("context"); Map<String,String> userContext = (Map<String, String>) context.get("user"); Assert.assertEquals("anonymous", userContext.get("id")); }
Example 10
Source File: JWT_Encrypted_Validator_Callout.java From iloveapis2015-jwt-jwe-jws with Apache License 2.0 | 4 votes |
public ExecutionResult execute (MessageContext msgCtxt, ExecutionContext exeCtxt) { String varName; try { String encryptedJwt = getJwt(msgCtxt); // dot-separated JWT // diagnostic purposes varName = getVarname("jwt"); msgCtxt.setVariable(varName, encryptedJwt); RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(msgCtxt); BASE64Encoder b64 = new BASE64Encoder(); varName = getVarname("PrivateKey"); msgCtxt.setVariable(varName, b64.encode(privateKey.getEncoded())); /***************************RECEIVER'S END ***********************************/ JwtConsumer consumer = new JwtConsumerBuilder() //.setExpectedAudience("Admins") //.setExpectedIssuer("CA") //.setRequireSubject() //.setRequireExpirationTime() .setDecryptionKey(privateKey) .setDisableRequireSignature() .build(); JwtClaims receivedClaims = consumer.processToClaims(encryptedJwt); //System.out.println("SUCESS :: JWT Validation :: " + receivedClaims); String receivedClaimsJSON = receivedClaims.getRawJson(); varName = getVarname("receivedClaims"); msgCtxt.setVariable(varName, receivedClaimsJSON); } catch (Exception e) { //e.printStackTrace(); varName = getVarname("error"); msgCtxt.setVariable(varName, "Exception (A): " + e.toString()); varName = getVarname("stacktrace"); msgCtxt.setVariable(varName, "Stack (A): " + ExceptionUtils.getStackTrace(e)); } return ExecutionResult.SUCCESS; }
Example 11
Source File: JwtAuthenticationServiceImplTest.java From blueocean-plugin with MIT License | 2 votes |
@Test public void getToken() throws Exception { j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); User user = User.get("alice"); user.setFullName("Alice Cooper"); user.addProperty(new Mailer.UserProperty("[email protected]")); JenkinsRule.WebClient webClient = j.createWebClient(); webClient.login("alice"); String token = getToken(webClient); Assert.assertNotNull(token); JsonWebStructure jsonWebStructure = JsonWebStructure.fromCompactSerialization(token); Assert.assertTrue(jsonWebStructure instanceof JsonWebSignature); JsonWebSignature jsw = (JsonWebSignature) jsonWebStructure; System.out.println(token); System.out.println(jsw.toString()); String kid = jsw.getHeader("kid"); Assert.assertNotNull(kid); Page page = webClient.goTo("jwt-auth/jwks/"+kid+"/", "application/json"); // for(NameValuePair valuePair: page.getWebResponse().getResponseHeaders()){ // System.out.println(valuePair); // } JSONObject jsonObject = JSONObject.fromObject(page.getWebResponse().getContentAsString()); System.out.println(jsonObject.toString()); RsaJsonWebKey rsaJsonWebKey = new RsaJsonWebKey(jsonObject,null); JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setRequireExpirationTime() // the JWT must have an expiration time .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew .setRequireSubject() // the JWT must have a subject claim .setVerificationKey(rsaJsonWebKey.getKey()) // verify the sign with the public key .build(); // create the JwtConsumer instance JwtClaims claims = jwtConsumer.processToClaims(token); Assert.assertEquals("alice",claims.getSubject()); Map<String,Object> claimMap = claims.getClaimsMap(); Map<String,Object> context = (Map<String, Object>) claimMap.get("context"); Map<String,String> userContext = (Map<String, String>) context.get("user"); Assert.assertEquals("alice", userContext.get("id")); Assert.assertEquals("Alice Cooper", userContext.get("fullName")); Assert.assertEquals("[email protected]", userContext.get("email")); }