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");
}
}
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"));
}
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);
}
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;
}
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);
}
}
Aggregations