Search in sources :

Example 61 with JwtClaims

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

the class JwtAuthenticationToken method create.

public static Authentication create(StaplerRequest request) {
    JwtClaims claims = validate(request);
    String subject = null;
    try {
        subject = claims.getSubject();
        if (subject.equals("anonymous")) {
            //if anonymous, we don't look in user db
            return Jenkins.getInstance().ANONYMOUS;
        } else {
            return new JwtAuthenticationToken(subject);
        }
    } catch (MalformedClaimException e) {
        logger.error(String.format("Error reading sub header for token %s", claims.getRawJson()), e);
        throw new ServiceException.UnauthorizedException("Invalid JWT token: malformed claim");
    }
}
Also used : MalformedClaimException(org.jose4j.jwt.MalformedClaimException) ServiceException(io.jenkins.blueocean.commons.ServiceException) JwtClaims(org.jose4j.jwt.JwtClaims)

Example 62 with JwtClaims

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

the class JwtImplTest method getToken.

@Test
public void getToken() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    User user = j.jenkins.getUser("alice");
    user.setFullName("Alice Cooper");
    user.addProperty(new Mailer.UserProperty("alice@jenkins-ci.org"));
    JenkinsRule.WebClient webClient = j.createWebClient();
    webClient.login("alice");
    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;
    System.out.println(token);
    System.out.println(jsw.toString());
    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());
    System.out.println(jsonObject.toString());
    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("alice", 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("alice", userContext.get("id"));
    Assert.assertEquals("Alice Cooper", userContext.get("fullName"));
    Assert.assertEquals("alice@jenkins-ci.org", userContext.get("email"));
}
Also used : User(hudson.model.User) JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) Mailer(hudson.tasks.Mailer) 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 63 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 64 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 65 with JwtClaims

use of org.jose4j.jwt.JwtClaims in project habot by ghys.

the class PushService method send.

/**
 * Send a notification and wait for the response.
 *
 * @param notification
 * @return
 * @throws GeneralSecurityException
 * @throws IOException
 * @throws JoseException
 * @throws ExecutionException
 * @throws InterruptedException
 */
public Future<Response> send(Notification notification) throws GeneralSecurityException, IOException, JoseException, ExecutionException, InterruptedException {
    assert (verifyKeyPair());
    BaseEncoding base64url = BaseEncoding.base64Url();
    Encrypted encrypted = encrypt(notification.getPayload(), notification.getUserPublicKey(), notification.getUserAuth(), notification.getPadSize());
    byte[] dh = Utils.savePublicKey((ECPublicKey) encrypted.getPublicKey());
    byte[] salt = encrypted.getSalt();
    Invocation.Builder invocationBuilder = ClientBuilder.newClient().target(notification.getEndpoint()).request();
    MultivaluedMap<String, Object> headers = new MultivaluedHashMap<String, Object>();
    headers.add("TTL", String.valueOf(notification.getTTL()));
    if (notification.hasPayload()) {
        headers.add("Content-Type", "application/octet-stream");
        headers.add("Content-Encoding", "aesgcm");
        headers.add("Encryption", "keyid=p256dh;salt=" + base64url.omitPadding().encode(salt));
        headers.add("Crypto-Key", "keyid=p256dh;dh=" + base64url.encode(dh));
    }
    if (notification.isGcm()) {
        if (gcmApiKey == null) {
            throw new IllegalStateException("An GCM API key is needed to send a push notification to a GCM endpoint.");
        }
        headers.add("Authorization", "key=" + gcmApiKey);
    }
    if (vapidEnabled() && !notification.isGcm()) {
        JwtClaims claims = new JwtClaims();
        claims.setAudience(notification.getOrigin());
        claims.setExpirationTimeMinutesInTheFuture(12 * 60);
        claims.setSubject(subject);
        JsonWebSignature jws = new JsonWebSignature();
        jws.setHeader("typ", "JWT");
        jws.setHeader("alg", "ES256");
        jws.setPayload(claims.toJson());
        jws.setKey(privateKey);
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256);
        headers.add("Authorization", "WebPush " + jws.getCompactSerialization());
        byte[] pk = Utils.savePublicKey((ECPublicKey) publicKey);
        if (headers.containsKey("Crypto-Key")) {
            headers.add("Crypto-Key", headers.get("Crypto-Key") + ";p256ecdsa=" + base64url.omitPadding().encode(pk));
        } else {
            headers.add("Crypto-Key", "p256ecdsa=" + base64url.encode(pk));
        }
    }
    invocationBuilder.headers(headers);
    if (notification.hasPayload()) {
        return invocationBuilder.async().post(Entity.entity(encrypted.getCiphertext(), new Variant(MediaType.APPLICATION_OCTET_STREAM_TYPE, (String) null, "aesgcm")));
    } else {
        return invocationBuilder.async().post(null);
    }
}
Also used : Invocation(javax.ws.rs.client.Invocation) JwtClaims(org.jose4j.jwt.JwtClaims) BaseEncoding(com.google.common.io.BaseEncoding) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Variant(javax.ws.rs.core.Variant) JsonWebSignature(org.jose4j.jws.JsonWebSignature)

Aggregations

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