Java Code Examples for org.jose4j.jwt.JwtClaims#getSubject()

The following examples show how to use org.jose4j.jwt.JwtClaims#getSubject() . 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: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
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 2
Source File: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
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 3
Source File: SubValidator.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Override
public String validate(JwtContext jwtContext) throws MalformedClaimException
{
    JwtClaims jwtClaims = jwtContext.getJwtClaims();
    String subject = jwtClaims.getSubject();
    if (subject == null && requireSubject)
    {
        return "No Subject (sub) claim is present.";
    }
    else if (expectedSubject != null && !expectedSubject.equals(subject))
    {
        return "Subject (sub) claim value (" + subject + ") doesn't match expected value of " + expectedSubject;
    }

    return null;
}
 
Example 4
Source File: JwtHelper.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
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 6
Source File: JWTCredential.java    From thorntail with Apache License 2.0 5 votes vote down vote up
/**
 * This just parses the token without validation to extract one of the following in order to obtain
 * the name to be used for the principal:
 * upn
 * preferred_username
 * subject
 *
 * If there is an exception it sets the name to INVALID_TOKEN_NAME and saves the exception for access
 * via {@link #getJwtException()}
 *
 * @return the name to use for the principal
 */
public String getName() {
    if (name == null) {
        name = "INVALID_TOKEN_NAME";
        try {
            // Build a JwtConsumer that doesn't check signatures or do any validation.
            JwtConsumer firstPassJwtConsumer = new JwtConsumerBuilder()
                    .setSkipAllValidators()
                    .setDisableRequireSignature()
                    .setSkipSignatureVerification()
                    .build();

            //The first JwtConsumer is basically just used to parse the JWT into a JwtContext object.
            JwtContext jwtContext = firstPassJwtConsumer.process(bearerToken);
            JwtClaims claimsSet = jwtContext.getJwtClaims();
            // We have to determine the unique name to use as the principal name. It comes from upn, preferred_username, sub in that order
            name = claimsSet.getClaimValue("upn", String.class);
            if (name == null) {
                name = claimsSet.getClaimValue("preferred_username", String.class);
                if (name == null) {
                    name = claimsSet.getSubject();
                }
            }
        } catch (Exception e) {
            jwtException = e;
        }
    }
    return name;
}
 
Example 7
Source File: TokenHelper.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@Nullable
public static User parseToken(@NotNull JsonWebEncryption jwe, @NotNull String token, int tokenEnsureTime) {
  try {
    jwe.setCompactSerialization(token);
    final JwtClaims claims = JwtClaims.parse(jwe.getPayload());
    final NumericDate now = NumericDate.now();
    final NumericDate expire = NumericDate.fromMilliseconds(now.getValueInMillis());
    if (tokenEnsureTime > 0) {
      expire.addSeconds(tokenEnsureTime);
    }
    if (claims.getExpirationTime() == null || claims.getExpirationTime().isBefore(expire)) {
      return null;
    }
    if (claims.getNotBefore() == null || claims.getNotBefore().isAfter(now)) {
      return null;
    }
    if (claims.getSubject() == null) {
      return User.getAnonymous();
    }
    return User.create(
        claims.getSubject(),
        claims.getClaimValue("name", String.class),
        claims.getClaimValue("email", String.class),
        claims.getClaimValue("external", String.class),
        UserType.valueOf(claims.getClaimValue("type", String.class)),
        null
    );
  } catch (JoseException | MalformedClaimException | InvalidJwtException e) {
    log.warn("Token parsing error: " + e.getMessage());
    return null;
  }
}