Search in sources :

Example 11 with JoseException

use of org.jose4j.lang.JoseException in project stdlib by petergeneric.

the class JwtCreationRestServiceImpl method getResult.

@Override
public String getResult(String token, final String secret, final String payload, final String op) {
    final TemplateCall template = templater.template(PREFIX + "jwt_generated.html");
    final Long expireTime;
    if (token == null) {
        try {
            JwtClaims claims = JwtClaims.parse(payload);
            if (claims.getExpirationTime() != null)
                expireTime = claims.getExpirationTime().getValueInMillis();
            else
                expireTime = null;
            token = createJWT(secret, payload);
        } catch (InvalidJwtException | MalformedClaimException | JoseException e) {
            throw new RuntimeException(e);
        }
    } else {
        // User has provided a JWT. We should simply parse it and extract the expiry time (for the cookie)
        try {
            JwtConsumer jwtConsumer = new JwtConsumerBuilder().setSkipAllValidators().setDisableRequireSignature().setSkipSignatureVerification().build();
            final JwtClaims claims = jwtConsumer.processToClaims(token);
            if (claims.getExpirationTime() != null)
                expireTime = claims.getExpirationTime().getValueInMillis();
            else
                expireTime = null;
        } catch (InvalidJwtException | MalformedClaimException e) {
            throw new RuntimeException(e);
        }
    }
    final boolean save = StringUtils.equalsIgnoreCase("save", op);
    // Optionally save as a cookie
    if (save) {
        Cookie cookie = new Cookie(cookieName, token);
        // Set the cookie path based on the webapp endpoint path
        cookie.setPath(webappEndpoint.getPath());
        // If the webapp has an https endpoint (or if we were accessed by HTTPS) then set the cookie as a secure cookie
        cookie.setSecure(HttpCallContext.get().getRequest().isSecure() || StringUtils.equalsIgnoreCase("https", webappEndpoint.getScheme()));
        // Expire the cookie 1 minute before the token expires
        if (expireTime != null)
            cookie.setMaxAge(expireTime.intValue() - 60);
        // Kill the current session (just in case it's associated with a job manager login)
        final HttpSession session = HttpCallContext.get().getRequest().getSession(false);
        if (session != null) {
            session.invalidate();
        }
        // Now add the JWT cookie
        HttpCallContext.get().getResponse().addCookie(cookie);
    }
    template.set("saved", save);
    template.set("token", token);
    return template.process();
}
Also used : InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) Cookie(javax.servlet.http.Cookie) JwtClaims(org.jose4j.jwt.JwtClaims) JoseException(org.jose4j.lang.JoseException) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) HttpSession(javax.servlet.http.HttpSession) TemplateCall(com.peterphi.std.guice.web.rest.templating.TemplateCall) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer)

Example 12 with JoseException

use of org.jose4j.lang.JoseException in project kylo by Teradata.

the class JwtRememberMeServices method encodeCookie.

/**
 * Encodes the specified tokens into a JWT cookie.
 *
 * <p>The first element of {@code tokens} should be the user's principal. The remaining elements are the groups assigned to the user.</p>
 *
 * @param tokens an array with the username and group names
 * @return a JWT cookie
 * @throws IllegalStateException if the secret key is invalid
 */
@Nonnull
@Override
protected String encodeCookie(@Nonnull final String[] tokens) {
    // Determine expiration time
    final NumericDate expireTime = NumericDate.fromMilliseconds(DateTimeUtils.currentTimeMillis());
    expireTime.addSeconds(getExpirationTimeSeconds());
    // Build the JSON Web Token
    final JwtClaims claims = new JwtClaims();
    claims.setExpirationTime(expireTime);
    claims.setSubject(tokens[0]);
    claims.setStringListClaim(PRINCIPALS, Arrays.asList(tokens).subList(1, tokens.length));
    // Generate a signature
    final JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(algorithmIdentifier);
    jws.setKey(getSecretKey());
    jws.setKeyIdHeaderValue(getSecretKey().getAlgorithm());
    jws.setPayload(claims.toJson());
    // Serialize the cookie
    try {
        return jws.getCompactSerialization();
    } catch (final JoseException e) {
        log.error("Unable to encode cookie: ", e);
        throw new IllegalStateException("Unable to encode cookie: ", e);
    }
}
Also used : NumericDate(org.jose4j.jwt.NumericDate) JsonWebSignature(org.jose4j.jws.JsonWebSignature) JwtClaims(org.jose4j.jwt.JwtClaims) JoseException(org.jose4j.lang.JoseException) Nonnull(javax.annotation.Nonnull)

Example 13 with JoseException

use of org.jose4j.lang.JoseException in project light-portal by networknt.

the class JwtToken method handle.

@Override
public ByteBuffer handle(HttpServerExchange exchange, Object input) {
    JwtClaims claims = JwtIssuer.getDefaultJwtClaims();
    ((Map<String, Object>) input).forEach((k, v) -> claims.setClaim(k, v));
    String jwt = "";
    try {
        jwt = JwtIssuer.getJwt(claims);
    } catch (JoseException e) {
        logger.error("JoseException:", e);
    }
    return NioUtils.toByteBuffer(jwt);
}
Also used : JwtClaims(org.jose4j.jwt.JwtClaims) JoseException(org.jose4j.lang.JoseException) Map(java.util.Map)

Example 14 with JoseException

use of org.jose4j.lang.JoseException in project kafka by apache.

the class RefreshingHttpsJwks method init.

@Override
public void init() throws IOException {
    try {
        log.debug("init started");
        List<JsonWebKey> localJWKs;
        try {
            localJWKs = httpsJwks.getJsonWebKeys();
        } catch (JoseException e) {
            throw new IOException("Could not refresh JWKS", e);
        }
        try {
            refreshLock.writeLock().lock();
            jsonWebKeys = Collections.unmodifiableList(localJWKs);
        } finally {
            refreshLock.writeLock().unlock();
        }
        // Since we just grabbed the keys (which will have invoked a HttpsJwks.refresh()
        // internally), we can delay our first invocation by refreshMs.
        // 
        // Note: we refer to this as a _scheduled_ refresh.
        executorService.scheduleAtFixedRate(this::refresh, refreshMs, refreshMs, TimeUnit.MILLISECONDS);
        log.info("JWKS validation key refresh thread started with a refresh interval of {} ms", refreshMs);
    } finally {
        isInitialized = true;
        log.debug("init completed");
    }
}
Also used : JoseException(org.jose4j.lang.JoseException) JsonWebKey(org.jose4j.jwk.JsonWebKey) IOException(java.io.IOException)

Example 15 with JoseException

use of org.jose4j.lang.JoseException in project digilib by robcast.

the class OpenIdAuthnOps method init.

/* (non-Javadoc)
     * @see digilib.auth.AuthnOps#init(digilib.conf.DigilibConfiguration)
     */
@Override
public void init(DigilibConfiguration dlConfig) throws AuthOpException {
    configFile = dlConfig.getAsFile("auth-file");
    logger.debug("openidauthnops.init (" + configFile + ")");
    List<Map<String, String>> idpList;
    try {
        // load identity providers
        XMLMapListLoader idpLoader = new XMLMapListLoader("digilib-oauth", "openid");
        idpList = idpLoader.loadUri(configFile.toURI());
    } catch (Exception e) {
        throw new AuthOpException("ERROR loading auth config file: " + e);
    }
    if (idpList == null) {
        throw new AuthOpException("ERROR unable to load auth config file!");
    }
    // create Map of roles by issuer
    idpRoles = new HashMap<String, List<String>>();
    // build a first pass JwtConsumer that doesn't check signatures or do any validation.
    firstPassJwtConsumer = new JwtConsumerBuilder().setSkipAllValidators().setDisableRequireSignature().setSkipSignatureVerification().build();
    // create Map of configured JwtConsumers by issuer
    idpJwtConsumers = new HashMap<String, JwtConsumer>();
    for (Map<String, String> idpDesc : idpList) {
        String issuer = idpDesc.get("issuer");
        if (issuer == null) {
            logger.error("Missing issuer in openid tag!");
            continue;
        }
        String clientid = idpDesc.get("clientid");
        if (clientid == null) {
            logger.error("Missing clientid in openid tag! (issuer: " + issuer + ")");
            continue;
        }
        String rolestr = idpDesc.get("roles");
        if (rolestr == null) {
            logger.error("Missing roles in openid tag! (issuer: " + issuer + ")");
            continue;
        }
        // split roles string into list
        List<String> roles = Arrays.asList(rolestr.split(","));
        String keytype = idpDesc.get("keytype");
        if (keytype == null || !keytype.equals("jwk")) {
            logger.error("Missing or invalid keytype in openid tag! (issuer: " + issuer + ")");
            continue;
        }
        String keyData = idpDesc.get("_text");
        if (keyData == null || keyData.length() == 0) {
            logger.error("Missing key data in openid tag! (issuer: " + issuer + ")");
            continue;
        }
        try {
            // create key from JWK data
            JsonWebKey jwk = JsonWebKey.Factory.newJwk(keyData);
            // create second pass consumer for validation
            JwtConsumer secondPassJwtConsumer = new JwtConsumerBuilder().setExpectedIssuer(issuer).setVerificationKey(jwk.getKey()).setRequireExpirationTime().setAllowedClockSkewInSeconds(300).setRequireSubject().setExpectedAudience(clientid).build();
            // save consumer and roles
            idpJwtConsumers.put(issuer, secondPassJwtConsumer);
            idpRoles.put(issuer, roles);
            logger.debug("Registered id provider '" + issuer + "'");
        } catch (JoseException e) {
            logger.error("Invalid key data in openid tag! (issuer: " + issuer + ")");
            continue;
        }
    }
    // set token cookie name
    tokenCookieName = dlConfig.getAsString("authn-token-cookie");
}
Also used : XMLMapListLoader(digilib.util.XMLMapListLoader) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JoseException(org.jose4j.lang.JoseException) JsonWebKey(org.jose4j.jwk.JsonWebKey) InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) JoseException(org.jose4j.lang.JoseException) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

JoseException (org.jose4j.lang.JoseException)17 JwtClaims (org.jose4j.jwt.JwtClaims)7 IOException (java.io.IOException)6 JsonWebKey (org.jose4j.jwk.JsonWebKey)6 MalformedClaimException (org.jose4j.jwt.MalformedClaimException)5 InvalidJwtException (org.jose4j.jwt.consumer.InvalidJwtException)5 JsonWebSignature (org.jose4j.jws.JsonWebSignature)4 JwtConsumer (org.jose4j.jwt.consumer.JwtConsumer)4 JwtConsumerBuilder (org.jose4j.jwt.consumer.JwtConsumerBuilder)4 ServiceException (io.jenkins.blueocean.commons.ServiceException)3 NumericDate (org.jose4j.jwt.NumericDate)3 StringReader (java.io.StringReader)2 Map (java.util.Map)2 DeploymentException (javax.enterprise.inject.spi.DeploymentException)2 JsonObject (javax.json.JsonObject)2 JsonParsingException (javax.json.stream.JsonParsingException)2 JsonWebKeySet (org.jose4j.jwk.JsonWebKeySet)2 JwtContext (org.jose4j.jwt.consumer.JwtContext)2 JsonWebStructure (org.jose4j.jwx.JsonWebStructure)2 TemplateCall (com.peterphi.std.guice.web.rest.templating.TemplateCall)1