Search in sources :

Example 1 with JwtClaims

use of org.jose4j.jwt.JwtClaims in project blueocean-plugin by jenkinsci.

the class JwtImplTest method anonymousUserToken.

@Test
public void anonymousUserToken() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    JenkinsRule.WebClient webClient = j.createWebClient();
    Page page = webClient.goTo("jwt-auth/token/", null);
    String token = page.getWebResponse().getResponseHeaderValue("X-BLUEOCEAN-JWT");
    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 = 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().setAllowedClockSkewInSeconds(// allow some leeway in validating time based claims to account for clock skew
    30).setRequireSubject().setVerificationKey(// verify the sign with the public key
    rsaJsonWebKey.getKey()).build();
    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"));
}
Also used : JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) Page(com.gargoylesoftware.htmlunit.Page) JenkinsRule(org.jvnet.hudson.test.JenkinsRule) JsonWebSignature(org.jose4j.jws.JsonWebSignature) JSONObject(net.sf.json.JSONObject) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JSONObject(net.sf.json.JSONObject) RsaJsonWebKey(org.jose4j.jwk.RsaJsonWebKey) Map(java.util.Map) JsonWebStructure(org.jose4j.jwx.JsonWebStructure) Test(org.junit.Test)

Example 2 with JwtClaims

use of org.jose4j.jwt.JwtClaims in project blueocean-plugin by jenkinsci.

the class JwtAuthenticationToken method validate.

private static JwtClaims validate(StaplerRequest request) {
    String authHeader = request.getHeader("Authorization");
    if (authHeader == null || !authHeader.startsWith("Bearer ")) {
        throw new ServiceException.UnauthorizedException("JWT token not found");
    }
    String token = authHeader.substring("Bearer ".length());
    try {
        JsonWebStructure jws = JsonWebStructure.fromCompactSerialization(token);
        String alg = jws.getAlgorithmHeaderValue();
        if (alg == null || !alg.equals(RSA_USING_SHA256)) {
            logger.error(String.format("Invalid JWT token: unsupported algorithm in header, found %s, expected %s", alg, RSA_USING_SHA256));
            throw new ServiceException.UnauthorizedException("Invalid JWT token");
        }
        String kid = jws.getKeyIdHeaderValue();
        if (kid == null) {
            logger.error("Invalid JWT token: missing kid");
            throw new ServiceException.UnauthorizedException("Invalid JWT token");
        }
        JwtToken.JwtRsaDigitalSignatureKey key = new JwtToken.JwtRsaDigitalSignatureKey(kid);
        try {
            if (!key.exists()) {
                throw new ServiceException.NotFoundException(String.format("kid %s not found", kid));
            }
        } catch (IOException e) {
            logger.error(String.format("Error reading RSA key for id %s: %s", kid, e.getMessage()), e);
            throw new ServiceException.UnexpectedErrorException("Unexpected error: " + e.getMessage(), e);
        }
        JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setRequireJwtId().setAllowedClockSkewInSeconds(// allow some leeway in validating time based claims to account for clock skew
        30).setRequireSubject().setVerificationKey(// verify the sign with the public key
        key.getPublicKey()).build();
        try {
            JwtContext context = jwtConsumer.process(token);
            JwtClaims claims = context.getJwtClaims();
            //check if token expired
            NumericDate expirationTime = claims.getExpirationTime();
            if (expirationTime.isBefore(NumericDate.now())) {
                throw new ServiceException.UnauthorizedException("Invalid JWT token: expired");
            }
            return claims;
        } catch (InvalidJwtException e) {
            logger.error("Invalid JWT token: " + e.getMessage(), e);
            throw new ServiceException.UnauthorizedException("Invalid JWT token");
        } catch (MalformedClaimException e) {
            logger.error(String.format("Error reading sub header for token %s", jws.getPayload()), e);
            throw new ServiceException.UnauthorizedException("Invalid JWT token: malformed claim");
        }
    } catch (JoseException e) {
        logger.error("Error parsing JWT token: " + e.getMessage(), e);
        throw new ServiceException.UnauthorizedException("Invalid JWT Token: " + e.getMessage());
    }
}
Also used : InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) NumericDate(org.jose4j.jwt.NumericDate) JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JoseException(org.jose4j.lang.JoseException) JwtContext(org.jose4j.jwt.consumer.JwtContext) IOException(java.io.IOException) JwtToken(io.jenkins.blueocean.auth.jwt.JwtToken) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) ServiceException(io.jenkins.blueocean.commons.ServiceException) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JsonWebStructure(org.jose4j.jwx.JsonWebStructure)

Example 3 with JwtClaims

use of org.jose4j.jwt.JwtClaims in project cas by apereo.

the class OidcIdTokenGeneratorService method produceIdTokenClaims.

/**
 * Produce id token claims jwt claims.
 *
 * @param request       the request
 * @param accessTokenId the access token id
 * @param timeout       the timeout
 * @param service       the service
 * @param profile       the user profile
 * @param context       the context
 * @param responseType  the response type
 * @return the jwt claims
 */
protected JwtClaims produceIdTokenClaims(final HttpServletRequest request, final AccessToken accessTokenId, final long timeout, final OidcRegisteredService service, final UserProfile profile, final J2EContext context, final OAuth20ResponseTypes responseType) {
    final Authentication authentication = accessTokenId.getAuthentication();
    final Principal principal = authentication.getPrincipal();
    final OidcProperties oidc = casProperties.getAuthn().getOidc();
    final JwtClaims claims = new JwtClaims();
    claims.setJwtId(getOAuthServiceTicket(accessTokenId.getTicketGrantingTicket()).getKey());
    claims.setIssuer(oidc.getIssuer());
    claims.setAudience(service.getClientId());
    final NumericDate expirationDate = NumericDate.now();
    expirationDate.addSeconds(timeout);
    claims.setExpirationTime(expirationDate);
    claims.setIssuedAtToNow();
    claims.setNotBeforeMinutesInThePast(oidc.getSkew());
    claims.setSubject(principal.getId());
    final MultifactorAuthenticationProperties mfa = casProperties.getAuthn().getMfa();
    final Map<String, Object> attributes = authentication.getAttributes();
    if (attributes.containsKey(mfa.getAuthenticationContextAttribute())) {
        final Collection<Object> val = CollectionUtils.toCollection(attributes.get(mfa.getAuthenticationContextAttribute()));
        claims.setStringClaim(OidcConstants.ACR, val.iterator().next().toString());
    }
    if (attributes.containsKey(AuthenticationHandler.SUCCESSFUL_AUTHENTICATION_HANDLERS)) {
        final Collection<Object> val = CollectionUtils.toCollection(attributes.get(AuthenticationHandler.SUCCESSFUL_AUTHENTICATION_HANDLERS));
        claims.setStringListClaim(OidcConstants.AMR, val.toArray(new String[] {}));
    }
    claims.setClaim(OAuth20Constants.STATE, attributes.get(OAuth20Constants.STATE));
    claims.setClaim(OAuth20Constants.NONCE, attributes.get(OAuth20Constants.NONCE));
    claims.setClaim(OidcConstants.CLAIM_AT_HASH, generateAccessTokenHash(accessTokenId, service));
    principal.getAttributes().entrySet().stream().filter(entry -> oidc.getClaims().contains(entry.getKey())).forEach(entry -> claims.setClaim(entry.getKey(), entry.getValue()));
    if (!claims.hasClaim(OidcConstants.CLAIM_PREFERRED_USERNAME)) {
        claims.setClaim(OidcConstants.CLAIM_PREFERRED_USERNAME, profile.getId());
    }
    return claims;
}
Also used : CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) Arrays(java.util.Arrays) AlgorithmIdentifiers(org.jose4j.jws.AlgorithmIdentifiers) DigestUtils(org.apereo.cas.util.DigestUtils) HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationHandler(org.apereo.cas.authentication.AuthenticationHandler) MultifactorAuthenticationProperties(org.apereo.cas.configuration.model.support.mfa.MultifactorAuthenticationProperties) Authentication(org.apereo.cas.authentication.Authentication) OidcProperties(org.apereo.cas.configuration.model.support.oidc.OidcProperties) Map(java.util.Map) CollectionUtils(org.apereo.cas.util.CollectionUtils) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) ServicesManager(org.apereo.cas.services.ServicesManager) OAuth20Constants(org.apereo.cas.support.oauth.OAuth20Constants) OAuth20ResponseTypes(org.apereo.cas.support.oauth.OAuth20ResponseTypes) OidcConstants(org.apereo.cas.oidc.OidcConstants) Collection(java.util.Collection) HttpServletResponse(javax.servlet.http.HttpServletResponse) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) ProfileManager(org.pac4j.core.profile.ProfileManager) StandardCharsets(java.nio.charset.StandardCharsets) Pac4jUtils(org.apereo.cas.util.Pac4jUtils) Slf4j(lombok.extern.slf4j.Slf4j) MessageDigestAlgorithms(org.apache.commons.codec.digest.MessageDigestAlgorithms) NumericDate(org.jose4j.jwt.NumericDate) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) Stream(java.util.stream.Stream) JwtClaims(org.jose4j.jwt.JwtClaims) Service(org.apereo.cas.authentication.principal.Service) Entry(java.util.Map.Entry) J2EContext(org.pac4j.core.context.J2EContext) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) Principal(org.apereo.cas.authentication.principal.Principal) EncodingUtils(org.apereo.cas.util.EncodingUtils) UserProfile(org.pac4j.core.profile.UserProfile) NumericDate(org.jose4j.jwt.NumericDate) JwtClaims(org.jose4j.jwt.JwtClaims) Authentication(org.apereo.cas.authentication.Authentication) OidcProperties(org.apereo.cas.configuration.model.support.oidc.OidcProperties) MultifactorAuthenticationProperties(org.apereo.cas.configuration.model.support.mfa.MultifactorAuthenticationProperties) Principal(org.apereo.cas.authentication.principal.Principal)

Example 4 with JwtClaims

use of org.jose4j.jwt.JwtClaims in project kylo by Teradata.

the class JwtRememberMeServices method decodeCookie.

/**
 * Decodes the specified JWT cookie into tokens.
 *
 * <p>The first element of the return value with be the JWT subject. The remaining element (should be 1) is the principals JSON token.</p>
 *
 * @param cookie the JWT cookie
 * @return an array with the username and group names
 * @throws IllegalStateException  if the secret key is invalid
 * @throws InvalidCookieException if the cookie cannot be decoded
 */
@Nonnull
@Override
protected String[] decodeCookie(@Nonnull final String cookie) throws InvalidCookieException {
    // Build the JWT parser
    final JwtConsumer consumer = new JwtConsumerBuilder().setEvaluationTime(NumericDate.fromMilliseconds(DateTimeUtils.currentTimeMillis())).setVerificationKey(getSecretKey()).build();
    // Parse the cookie
    final String user;
    final List<String> principalsClaim;
    try {
        final JwtClaims claims = consumer.processToClaims(cookie);
        user = claims.getSubject();
        principalsClaim = claims.getStringListClaimValue(PRINCIPALS);
    } catch (final InvalidJwtException e) {
        log.debug("JWT cookie is invalid: ", e);
        throw new InvalidCookieException("JWT cookie is invalid: " + e);
    } catch (final MalformedClaimException e) {
        log.debug("JWT cookie is malformed: ", e);
        throw new InvalidCookieException("JWT cookie is malformed: " + cookie);
    }
    if (StringUtils.isBlank(user)) {
        throw new InvalidCookieException("Missing user in JWT cookie: " + cookie);
    }
    // Build the token array
    final Stream<String> userStream = Stream.of(user);
    final Stream<String> groupStream = principalsClaim.stream();
    return Stream.concat(userStream, groupStream).toArray(String[]::new);
}
Also used : InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) InvalidCookieException(org.springframework.security.web.authentication.rememberme.InvalidCookieException) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) Nonnull(javax.annotation.Nonnull)

Example 5 with JwtClaims

use of org.jose4j.jwt.JwtClaims in project light-4j by networknt.

the class Http2ClientIT method isTokenExpired.

private static boolean isTokenExpired(String authorization) {
    boolean expired = false;
    String jwt = getJwtFromAuthorization(authorization);
    if (jwt != null) {
        try {
            JwtConsumer consumer = new JwtConsumerBuilder().setSkipAllValidators().setDisableRequireSignature().setSkipSignatureVerification().build();
            JwtContext jwtContext = consumer.process(jwt);
            JwtClaims jwtClaims = jwtContext.getJwtClaims();
            try {
                if ((NumericDate.now().getValue() - 60) >= jwtClaims.getExpirationTime().getValue()) {
                    expired = true;
                }
            } catch (MalformedClaimException e) {
                logger.error("MalformedClaimException:", e);
            }
        } catch (InvalidJwtException e) {
            e.printStackTrace();
        }
    }
    return expired;
}
Also used : InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) JwtContext(org.jose4j.jwt.consumer.JwtContext)

Aggregations

JwtClaims (org.jose4j.jwt.JwtClaims)68 Test (org.junit.Test)19 lombok.val (lombok.val)15 JwtConsumer (org.jose4j.jwt.consumer.JwtConsumer)15 JwtConsumerBuilder (org.jose4j.jwt.consumer.JwtConsumerBuilder)14 MalformedClaimException (org.jose4j.jwt.MalformedClaimException)13 InvalidJwtException (org.jose4j.jwt.consumer.InvalidJwtException)12 Map (java.util.Map)11 NumericDate (org.jose4j.jwt.NumericDate)8 JsonWebSignature (org.jose4j.jws.JsonWebSignature)7 JwtContext (org.jose4j.jwt.consumer.JwtContext)7 HashMap (java.util.HashMap)5 OidcRegisteredService (org.apereo.cas.services.OidcRegisteredService)5 JsonWebStructure (org.jose4j.jwx.JsonWebStructure)5 JoseException (org.jose4j.lang.JoseException)5 ArrayList (java.util.ArrayList)4 Optional (java.util.Optional)4 Test (org.junit.jupiter.api.Test)4 UserProfile (org.pac4j.core.profile.UserProfile)4 Objects (java.util.Objects)3