org.jose4j.jwt.MalformedClaimException Java Examples

The following examples show how to use org.jose4j.jwt.MalformedClaimException. 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: JwtBuilder.java    From microshed-testing with Apache License 2.0 6 votes vote down vote up
public static String buildJwt(String subject, String issuer, String[] claims) throws JoseException, MalformedClaimException {
    JwtBuilder builder = new JwtBuilder();
    init();
    builder.claims = new JwtClaims();
    builder.jws = new JsonWebSignature();

    builder.jws.setKeyIdHeaderValue(rsajwk.getKeyId());
    builder.jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    // The JWT is signed using the private key, get the key we'll use every time.
    builder.jws.setKey(rsajwk.getPrivateKey());
    if (subject != null) {
        builder.claims.setClaim("sub", subject);
        builder.claims.setClaim("upn", subject);
    }
    builder.claims.setIssuer(issuer == null ? JwtConfig.DEFAULT_ISSUER : issuer);
    builder.claims.setExpirationTimeMinutesInTheFuture(60);
    setClaims(builder, claims);
    if (builder.claims.getIssuedAt() == null) {
        builder.claims.setIssuedAtToNow();
    }
    builder.jws.setPayload(builder.claims.toJson());
    return builder.jws.getCompactSerialization();
}
 
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: 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 #5
Source File: IssValidator.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Override
public String validate(JwtContext jwtContext) throws MalformedClaimException
{
    String issuer = jwtContext.getJwtClaims().getIssuer();

    if (issuer == null)
    {
        return requireIssuer ? "No Issuer (iss) claim present but was expecting " + expectedIssuer: null;
    }

    if (expectedIssuer != null && !issuer.equals(expectedIssuer))
    {
        return "Issuer (iss) claim value (" + issuer + ") doesn't match expected value of " + expectedIssuer;
    }

    return null;
}
 
Example #6
Source File: JwtAuthApplication.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<MyUser> authenticate(JwtContext context) {
    // Provide your own implementation to lookup users based on the principal attribute in the
    // JWT Token. E.g.: lookup users from a database etc.
    // This method will be called once the token's signature has been verified

    // In case you want to verify different parts of the token you can do that here.
    // E.g.: Verifying that the provided token has not expired.

    // All JsonWebTokenExceptions will result in a 401 Unauthorized response.

    try {
        final String subject = context.getJwtClaims().getSubject();
        if ("good-guy".equals(subject)) {
            return Optional.of(new MyUser(ONE, "good-guy"));
        }
        return Optional.empty();
    }
    catch (MalformedClaimException e) { return Optional.empty(); }
}
 
Example #7
Source File: AuthUtil.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
public static Authenticator<JwtContext, Principal> getJWTAuthenticator(final List<String> validUsers) {
    return context -> {
        try {
            final String subject = context.getJwtClaims().getSubject();

            if (validUsers.contains(subject)) {
                return Optional.of(new PrincipalImpl(subject));
            }

            if ("bad-guy".equals(subject)) {
                throw new AuthenticationException("CRAP");
            }

            return Optional.empty();
        } catch (MalformedClaimException e) {
            return Optional.empty();
        }
    };
}
 
Example #8
Source File: JwtBuilder.java    From boost with Eclipse Public License 1.0 6 votes vote down vote up
public static String buildJwt(String subject, String issuer, String[] claims)
        throws JoseException, MalformedClaimException {
    me = new JwtBuilder();
    init();
    me.claims = new JwtClaims();
    me.jws = new JsonWebSignature();

    me.jws.setKeyIdHeaderValue(rsajwk.getKeyId());
    me.jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    // The JWT is signed using the private key, get the key we'll use every time.
    me.jws.setKey(rsajwk.getPrivateKey());
    if (subject != null) {
        me.claims.setClaim("sub", subject);
        me.claims.setClaim("upn", subject);
    }
    me.claims.setIssuer(issuer);
    me.claims.setExpirationTimeMinutesInTheFuture(60);
    setClaims(claims);
    if (me.claims.getIssuedAt() == null) {
        me.claims.setIssuedAtToNow();
    }
    me.jws.setPayload(me.claims.toJson());
    return me.jws.getCompactSerialization();
}
 
Example #9
Source File: JWTCallerPrincipal.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public Set<String> getAudience() {
    final Set<String> audSet = new HashSet<>();
    try {
        final List<String> audList = claimsSet.getStringListClaimValue("aud");
        if (audList != null) {
            audSet.addAll(audList);
        }

    } catch (final MalformedClaimException e) {
        try {
            final String aud = claimsSet.getStringClaimValue("aud");
            audSet.add(aud);
        } catch (final MalformedClaimException e1) {
            logger.log(Level.FINEST, "Can't retrieve malformed 'aud' claim.", e);
        }
    }
    return audSet.isEmpty() ? null : audSet;
}
 
Example #10
Source File: JwtUtil.java    From light with Apache License 2.0 5 votes vote down vote up
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 #11
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;
  }
}
 
Example #12
Source File: JsonWebToken.java    From datamill with ISC License 5 votes vote down vote up
public String getSubject() {
    try {
        return claims.getSubject();
    } catch (MalformedClaimException e) {
        throw new SecurityException(e);
    }
}
 
Example #13
Source File: JsonWebToken.java    From datamill with ISC License 5 votes vote down vote up
public String getClaim(String claimName) {
    try {
        return claims.getStringClaimValue(claimName);
    } catch (MalformedClaimException e) {
        throw new SecurityException(e);
    }
}
 
Example #14
Source File: JWTCallerPrincipal.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public Set<String> getGroups() {
    final HashSet<String> groups = new HashSet<>();
    try {
        final List<String> globalGroups = claimsSet.getStringListClaimValue("groups");
        if (globalGroups != null) {
            groups.addAll(globalGroups);
        }

    } catch (final MalformedClaimException e) {
        logger.log(Level.FINEST, "Can't retrieve malformed 'groups' claim.", e);
    }
    return groups;
}
 
Example #15
Source File: JWTCallerPrincipal.java    From tomee with Apache License 2.0 5 votes vote down vote up
/**
 * Replace the jose4j Map<String,Object> with a JsonObject
 *
 * @param name - claim name
 */
private void replaceMap(final String name) {
    try {
        final Map<String, Object> map = claimsSet.getClaimValue(name, Map.class);
        final JsonObject jsonObject = replaceMap(map);
        claimsSet.setClaim(name, jsonObject);

    } catch (final MalformedClaimException e) {
        logger.log(Level.WARNING, "replaceMap failure for: " + name, e);
    }
}
 
Example #16
Source File: JWTCallerPrincipal.java    From tomee with Apache License 2.0 5 votes vote down vote up
/**
 * Replace the jose4j List<?> with a JsonArray
 *
 * @param name - claim name
 */
private void replaceList(final String name) {
    try {
        final List list = claimsSet.getClaimValue(name, List.class);
        final JsonArray array = (JsonArray) wrapValue(list);
        claimsSet.setClaim(name, array);

    } catch (final MalformedClaimException e) {
        logger.log(Level.WARNING, "replaceList failure for: " + name, e);
    }
}
 
Example #17
Source File: JWTCallerPrincipal.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void replaceNumber(final String name) {
    try {
        final Number number = claimsSet.getClaimValue(name, Number.class);
        final JsonNumber jsonNumber = (JsonNumber) wrapValue(number);
        claimsSet.setClaim(name, jsonNumber);

    } catch (final MalformedClaimException e) {
        logger.log(Level.WARNING, "replaceNumber failure for: " + name, e);
    }
}
 
Example #18
Source File: JwtBuilder.java    From microshed-testing with Apache License 2.0 5 votes vote down vote up
private static void setClaims(JwtBuilder builder, String[] claims) throws MalformedClaimException {
    for (String claim : claims) {
        if (!claim.contains("="))
            throw new MalformedClaimException("Claim did not contain an equals sign (=). Each claim must be of the form 'key=value'");
        int loc = claim.indexOf('=');
        String claimName = claim.substring(0, loc);
        Object claimValue = claim.substring(loc + 1);
        claimValue = handleArrays((String) claimValue);
        builder.claims.setClaim(claimName, claimValue);
    }
}
 
Example #19
Source File: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isJWTValidBefore(Key key, int seconds, String authorizationString) {
    JWTokenUserGroupMapping jwTokenUserGroupMapping = validateAuthToken(key, authorizationString);
    if (jwTokenUserGroupMapping != null) {
        try {
            NumericDate issuedAt = jwTokenUserGroupMapping.getClaims().getIssuedAt();
            issuedAt.addSeconds(seconds);
            return NumericDate.now().isBefore(issuedAt);
        } catch (MalformedClaimException e) {
            return false;
        }
    }
    return false;
}
 
Example #20
Source File: DefaultJWTCallerPrincipal.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@Override
public Set<String> getAudience() {
    Set<String> audSet = null;
    if (claimsSet.hasAudience()) {
        try {
            // Use LinkedHashSet to preserve iteration order
            audSet = new LinkedHashSet<>(claimsSet.getAudience());
        } catch (MalformedClaimException e) {
            PrincipalLogging.log.getAudienceFailure(e);
        }
    }
    return audSet;
}
 
Example #21
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 #22
Source File: DefaultJWTCallerPrincipal.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@Override
public Set<String> getGroups() {
    HashSet<String> groups = new HashSet<>();
    try {
        List<String> globalGroups = claimsSet.getStringListClaimValue(Claims.groups.name());
        if (globalGroups != null) {
            groups.addAll(globalGroups);
        }
    } catch (MalformedClaimException e) {
        PrincipalLogging.log.getGroupsFailure(e);
    }
    return groups;
}
 
Example #23
Source File: DefaultJWTCallerPrincipal.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@Override
protected Object getClaimValue(String claimName) {
    Claims claimType = getClaimType(claimName);
    Object claim = null;

    // Handle the jose4j NumericDate types and
    switch (claimType) {
        case exp:
        case iat:
        case auth_time:
        case nbf:
        case updated_at:
            try {
                claim = claimsSet.getClaimValue(claimType.name(), Long.class);
                if (claim == null) {
                    claim = 0L;
                }
            } catch (MalformedClaimException e) {
                PrincipalLogging.log.getGroupsFailure(claimName, e);
            }
            break;
        case groups:
            claim = getGroups();
            break;
        case aud:
            claim = getAudience();
            break;
        case UNKNOWN:
            claim = claimsSet.getClaimValue(claimName);
            break;
        default:
            claim = claimsSet.getClaimValue(claimType.name());
    }
    return claim;
}
 
Example #24
Source File: DefaultJWTCallerPrincipal.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
protected void replaceClaimValueWithJsonValue(String name) {
    try {
        final Object object = claimsSet.getClaimValue(name, Object.class);
        if (!(object instanceof String)) {
            claimsSet.setClaim(name, JsonUtils.wrapValue(object));
        }
    } catch (MalformedClaimException e) {
        PrincipalLogging.log.replaceClaimValueWithJsonFailure(name, e);
    }
}
 
Example #25
Source File: DownloadController.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validate a given token for a given channel.
 *
 * @param token the token to validate
 * @param channel the channel
 * @param filename the filename
 */
private static void validateToken(String token, String channel, String filename) {
    AccessTokenFactory.lookupByToken(token).ifPresent(obj -> {
        if (!obj.getValid()) {
            halt(HttpStatus.SC_FORBIDDEN, "This token is not valid");
        }
    });
    try {
        JwtClaims claims = JWT_CONSUMER.processToClaims(token);

        // enforce channel claim
        Optional<List<String>> channelClaim = Optional.ofNullable(claims.getStringListClaimValue("onlyChannels"))
                // new versions of getStringListClaimValue() return an empty list instead of null
                .filter(l -> !l.isEmpty());
        if (Opt.fold(channelClaim, () -> false, channels -> !channels.contains(channel))) {
            halt(HttpStatus.SC_FORBIDDEN, "Token does not provide access to channel " + channel);
        }

        // enforce org claim
        Optional<Long> orgClaim = Optional.ofNullable(claims.getClaimValue("org", Long.class));
        Opt.consume(orgClaim, () -> {
            halt(HttpStatus.SC_BAD_REQUEST, "Token does not specify the organization");
        }, orgId -> {
            if (!ChannelFactory.isAccessibleBy(channel, orgId)) {
                halt(HttpStatus.SC_FORBIDDEN, "Token does not provide access to channel %s" + channel);
            }
        });
    }
    catch (InvalidJwtException | MalformedClaimException e) {
        halt(HttpStatus.SC_FORBIDDEN,
             String.format("Token is not valid to access %s in %s: %s", filename, channel, e.getMessage()));
    }
}
 
Example #26
Source File: JwtBuilder.java    From boost with Eclipse Public License 1.0 5 votes vote down vote up
private static void setClaims(String[] claims) throws MalformedClaimException {
    for (String claim : claims) {
        if (!claim.contains("="))
            throw new MalformedClaimException(
                    "Claim did not contain an equals sign (=). Each claim must be of the form 'key=value'");
        int loc = claim.indexOf('=');
        String claimName = claim.substring(0, loc);
        Object claimValue = claim.substring(loc + 1);
        claimValue = handleArrays((String) claimValue);
        setClaim(claimName, claimValue);
    }
}
 
Example #27
Source File: OpenIDConnectAuthenticator.java    From java with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isExpired(Map<String, Object> config) {
  String idToken = (String) config.get(OIDC_ID_TOKEN);

  if (idToken == null) {
    return true;
  } else {
    JsonWebSignature jws = new JsonWebSignature();
    try {
      jws.setCompactSerialization(idToken);
      // we don't care if its valid or not cryptographicly as the only way to verify is to query
      // the remote identity provider's configuration url which is the same chanel as the token
      // request.  If there is a malicious proxy there's no way for the client to know.  Also,
      // the client doesn't need to trust the, token, only bear it to the server which will verify
      // it.

      String jwt = jws.getUnverifiedPayload();
      JwtClaims claims = JwtClaims.parse(jwt);

      // expired now is >= expiration AND exp is present
      return claims.getExpirationTime() == null
          || NumericDate.now().isOnOrAfter(claims.getExpirationTime());
    } catch (JoseException | InvalidJwtException | MalformedClaimException e) {
      throw new RuntimeException(e);
    }
  }
}
 
Example #28
Source File: JwtBuilder.java    From microprofile-sandbox with Apache License 2.0 5 votes vote down vote up
public static String buildJwt(String subject, String issuer, String[] claims) {
	me = new JwtBuilder();
	init();
	me.claims = new JwtClaims();
	me.jws = new JsonWebSignature();

	me.jws.setKeyIdHeaderValue(rsajwk.getKeyId());
	me.jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
	// The JWT is signed using the private key, get the key we'll use every time.
	me.jws.setKey(rsajwk.getPrivateKey());
	if (subject != null) {
		me.claims.setClaim("sub", subject);
		me.claims.setClaim("upn", subject);
	}
	me.claims.setIssuer(DEFAULT_ISSUER);
	me.claims.setExpirationTimeMinutesInTheFuture(60);
	if (issuer != null) {
		me.claims.setIssuer(issuer);
	}
	setClaims(claims);
	try {
		if (me.claims.getIssuedAt() == null) {
			me.claims.setIssuedAtToNow();
		}
	} catch (MalformedClaimException e1) {
		e1.printStackTrace(System.out);
	}
	me.jws.setPayload(me.claims.toJson());
	try {
		return me.jws.getCompactSerialization();
	} catch (JoseException e) {
		e.printStackTrace(System.out);
		return null;
	}

}
 
Example #29
Source File: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
public static void refreshTokenIfNeeded(Key key, HttpServletResponse response, JWTokenUserGroupMapping jwTokenUserGroupMapping) {

        try {
            NumericDate expirationTime = jwTokenUserGroupMapping.getClaims().getExpirationTime();

            if (NumericDate.now().getValue() + JWT_TOKEN_REFRESH_BEFORE >= expirationTime.getValue()) {
                UserGroupMapping userGroupMapping = jwTokenUserGroupMapping.getUserGroupMapping();
                response.addHeader("jwt", createAuthToken(key, userGroupMapping));
            }

        } catch (MalformedClaimException e) {
            LOGGER.log(Level.FINE, "Cannot get expiration time from claims", e);
        }

    }
 
Example #30
Source File: TokenGenerator.java    From rufus with MIT License 5 votes vote down vote up
public static boolean isExpired(JwtContext context) {
    try {
        return context.getJwtClaims().getExpirationTime().isBefore(NumericDate.now());
    } catch (MalformedClaimException e) {
        logger.debug("failed to validate token {}", e);
        return false;
    }
}