Search in sources :

Example 76 with JwtClaims

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

the class OidcIdTokenGeneratorService method generate.

/**
 * Generate string.
 *
 * @param request           the request
 * @param response          the response
 * @param accessTokenId     the access token id
 * @param timeout           the timeout
 * @param responseType      the response type
 * @param registeredService the registered service
 * @return the string
 * @throws Exception the exception
 */
public String generate(final HttpServletRequest request, final HttpServletResponse response, final AccessToken accessTokenId, final long timeout, final OAuth20ResponseTypes responseType, final OAuthRegisteredService registeredService) throws Exception {
    if (!(registeredService instanceof OidcRegisteredService)) {
        throw new IllegalArgumentException("Registered service instance is not an OIDC service");
    }
    final OidcRegisteredService oidcRegisteredService = (OidcRegisteredService) registeredService;
    final J2EContext context = Pac4jUtils.getPac4jJ2EContext(request, response);
    final ProfileManager manager = Pac4jUtils.getPac4jProfileManager(request, response);
    final Optional<UserProfile> profile = manager.get(true);
    LOGGER.debug("Attempting to produce claims for the id token [{}]", accessTokenId);
    final JwtClaims claims = produceIdTokenClaims(request, accessTokenId, timeout, oidcRegisteredService, profile.get(), context, responseType);
    LOGGER.debug("Produce claims for the id token [{}] as [{}]", accessTokenId, claims);
    return this.signingService.encode(oidcRegisteredService, claims);
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager) UserProfile(org.pac4j.core.profile.UserProfile) JwtClaims(org.jose4j.jwt.JwtClaims) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) J2EContext(org.pac4j.core.context.J2EContext)

Example 77 with JwtClaims

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

the class BasePasswordManagementService method createToken.

@Override
public String createToken(final String to) {
    try {
        final String token = UUID.randomUUID().toString();
        final JwtClaims claims = new JwtClaims();
        claims.setJwtId(token);
        claims.setIssuer(issuer);
        claims.setAudience(issuer);
        claims.setExpirationTimeMinutesInTheFuture(properties.getReset().getExpirationMinutes());
        claims.setIssuedAtToNow();
        final ClientInfo holder = ClientInfoHolder.getClientInfo();
        claims.setStringClaim("origin", holder.getServerIpAddress());
        claims.setStringClaim("client", holder.getClientIpAddress());
        claims.setSubject(to);
        final String json = claims.toJson();
        return this.cipherExecutor.encode(json);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}
Also used : JwtClaims(org.jose4j.jwt.JwtClaims) ClientInfo(org.apereo.inspektr.common.web.ClientInfo)

Example 78 with JwtClaims

use of org.jose4j.jwt.JwtClaims 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 79 with JwtClaims

use of org.jose4j.jwt.JwtClaims 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 80 with JwtClaims

use of org.jose4j.jwt.JwtClaims in project blockchain-java-api-client by astarlabs.

the class Token method sign.

public static String sign(String key) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    String decoded = new String(Hex.decode(key));
    String replaced = decoded.replaceAll("-----BEGIN RSA PRIVATE KEY-----", "").replaceAll("-----END RSA PRIVATE KEY-----", "").replaceAll("\\s", "");
    byte[] encodedPrivateKey = Base64.getDecoder().decode(replaced);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
    PrivateKey privKey = kf.generatePrivate(keySpec);
    JwtClaims claims = new JwtClaims();
    claims.setExpirationTimeMinutesInTheFuture(10);
    claims.setGeneratedJwtId();
    claims.setIssuedAtToNow();
    claims.setNotBeforeMinutesInThePast(2);
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(privKey);
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    String innerJwt = jws.getCompactSerialization();
    return innerJwt;
}
Also used : PrivateKey(java.security.PrivateKey) JsonWebSignature(org.jose4j.jws.JsonWebSignature) JwtClaims(org.jose4j.jwt.JwtClaims) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) KeyFactory(java.security.KeyFactory)

Aggregations

JwtClaims (org.jose4j.jwt.JwtClaims)130 Test (org.junit.Test)47 JwtConsumer (org.jose4j.jwt.consumer.JwtConsumer)23 JwtConsumerBuilder (org.jose4j.jwt.consumer.JwtConsumerBuilder)23 InvalidJwtException (org.jose4j.jwt.consumer.InvalidJwtException)21 MalformedClaimException (org.jose4j.jwt.MalformedClaimException)19 JoseException (org.jose4j.lang.JoseException)17 lombok.val (lombok.val)15 JsonWebSignature (org.jose4j.jws.JsonWebSignature)15 Map (java.util.Map)14 JwtContext (org.jose4j.jwt.consumer.JwtContext)11 NumericDate (org.jose4j.jwt.NumericDate)9 JsonWebStructure (org.jose4j.jwx.JsonWebStructure)9 HashMap (java.util.HashMap)7 KeyStoreException (java.security.KeyStoreException)6 ArrayList (java.util.ArrayList)5 OidcRegisteredService (org.apereo.cas.services.OidcRegisteredService)5 ExpiredTokenException (com.networknt.exception.ExpiredTokenException)4 JwksVerificationKeyResolver (org.jose4j.keys.resolvers.JwksVerificationKeyResolver)4 Test (org.junit.jupiter.api.Test)4