use of org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer in project syncope by apache.
the class JWTITCase method notBefore.
@Test
public void notBefore() throws ParseException {
// Get an initial token
SyncopeClient localClient = clientFactory.create(ADMIN_UNAME, ADMIN_PWD);
AccessTokenService accessTokenService = localClient.getService(AccessTokenService.class);
Response response = accessTokenService.login();
String token = response.getHeaderString(RESTHeaders.TOKEN);
assertNotNull(token);
JwsJwtCompactConsumer consumer = new JwsJwtCompactConsumer(token);
String tokenId = consumer.getJwtClaims().getTokenId();
// Create a new token using the Id of the first token
Date now = new Date();
long currentTime = now.getTime() / 1000L;
Calendar expiry = Calendar.getInstance();
expiry.setTime(now);
expiry.add(Calendar.MINUTE, 5);
JwtClaims jwtClaims = new JwtClaims();
jwtClaims.setTokenId(tokenId);
jwtClaims.setSubject(ADMIN_UNAME);
jwtClaims.setIssuedAt(currentTime);
jwtClaims.setIssuer(JWT_ISSUER);
jwtClaims.setExpiryTime(expiry.getTime().getTime() / 1000L);
jwtClaims.setNotBefore(currentTime + 60L);
JwsHeaders jwsHeaders = new JwsHeaders(JoseType.JWT, SignatureAlgorithm.HS512);
JwtToken jwtToken = new JwtToken(jwsHeaders, jwtClaims);
JwsJwtCompactProducer producer = new JwsJwtCompactProducer(jwtToken);
JwsSignatureProvider jwsSignatureProvider = new HmacJwsSignatureProvider(JWS_KEY.getBytes(), SignatureAlgorithm.HS512);
String signed = producer.signWith(jwsSignatureProvider);
SyncopeClient jwtClient = clientFactory.create(signed);
UserSelfService jwtUserSelfService = jwtClient.getService(UserSelfService.class);
try {
jwtUserSelfService.read();
fail("Failure expected on a token that is not valid yet");
} catch (AccessControlException ex) {
// expected
}
}
use of org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer in project syncope by apache.
the class SAML2SPLogic method createLogoutRequest.
@PreAuthorize("isAuthenticated() and not(hasRole('" + StandardEntitlement.ANONYMOUS + "'))")
public SAML2RequestTO createLogoutRequest(final String accessToken, final String spEntityID) {
check();
// 1. fetch the current JWT used for Syncope authentication
JwsJwtCompactConsumer consumer = new JwsJwtCompactConsumer(accessToken);
if (!consumer.verifySignatureWith(jwsSignatureVerifier)) {
throw new IllegalArgumentException("Invalid signature found in Access Token");
}
// 2. look for IdP
String idpEntityID = (String) consumer.getJwtClaims().getClaim(JWT_CLAIM_IDP_ENTITYID);
if (idpEntityID == null) {
throw new NotFoundException("No SAML 2.0 IdP information found in the access token");
}
SAML2IdPEntity idp = cache.get(idpEntityID);
if (idp == null) {
throw new NotFoundException("SAML 2.0 IdP '" + idpEntityID + "'");
}
if (idp.getSLOLocation(idp.getBindingType()) == null) {
throw new IllegalArgumentException("No SingleLogoutService available for " + idp.getId());
}
// 3. create LogoutRequest
LogoutRequest logoutRequest = new LogoutRequestBuilder().buildObject();
logoutRequest.setID("_" + UUID_GENERATOR.generate().toString());
logoutRequest.setDestination(idp.getSLOLocation(idp.getBindingType()).getLocation());
DateTime now = new DateTime();
logoutRequest.setIssueInstant(now);
logoutRequest.setNotOnOrAfter(now.plusMinutes(5));
Issuer issuer = new IssuerBuilder().buildObject();
issuer.setValue(spEntityID);
logoutRequest.setIssuer(issuer);
NameID nameID = new NameIDBuilder().buildObject();
nameID.setFormat((String) consumer.getJwtClaims().getClaim(JWT_CLAIM_NAMEID_FORMAT));
nameID.setValue((String) consumer.getJwtClaims().getClaim(JWT_CLAIM_NAMEID_VALUE));
logoutRequest.setNameID(nameID);
SessionIndex sessionIndex = new SessionIndexBuilder().buildObject();
sessionIndex.setSessionIndex((String) consumer.getJwtClaims().getClaim(JWT_CLAIM_SESSIONINDEX));
logoutRequest.getSessionIndexes().add(sessionIndex);
SAML2RequestTO requestTO = new SAML2RequestTO();
requestTO.setIdpServiceAddress(logoutRequest.getDestination());
requestTO.setBindingType(idp.getBindingType());
try {
// 3. generate relay state as JWT
Map<String, Object> claims = new HashMap<>();
claims.put(JWT_CLAIM_IDP_DEFLATE, idp.getBindingType() == SAML2BindingType.REDIRECT ? true : idp.isUseDeflateEncoding());
Triple<String, String, Date> relayState = accessTokenDataBinder.generateJWT(logoutRequest.getID(), JWT_RELAY_STATE_DURATION, claims);
requestTO.setRelayState(relayState.getMiddle());
// 4. sign and encode AuthnRequest
switch(idp.getBindingType()) {
case REDIRECT:
requestTO.setContent(saml2rw.encode(logoutRequest, true));
requestTO.setSignAlg(saml2rw.getSigAlgo());
requestTO.setSignature(saml2rw.sign(requestTO.getContent(), requestTO.getRelayState()));
break;
case POST:
default:
saml2rw.sign(logoutRequest);
requestTO.setContent(saml2rw.encode(logoutRequest, idp.isUseDeflateEncoding()));
}
} catch (Exception e) {
LOG.error("While generating LogoutRequest", e);
SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
sce.getElements().add(e.getMessage());
throw sce;
}
return requestTO;
}
use of org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer in project syncope by apache.
the class AccessTokenDataBinderImpl method update.
@Override
public Pair<String, Date> update(final AccessToken accessToken, final byte[] authorities) {
JwsJwtCompactConsumer consumer = new JwsJwtCompactConsumer(accessToken.getBody());
credentialChecker.checkIsDefaultJWSKeyInUse();
long duration = confDAO.find("jwt.lifetime.minutes", 120L);
long currentTime = new Date().getTime() / 1000L;
long expiry = currentTime + 60L * duration;
consumer.getJwtClaims().setExpiryTime(expiry);
Date expiryDate = new Date(expiry * 1000L);
JwsHeaders jwsHeaders = new JwsHeaders(JoseType.JWT, jwsSignatureProvider.getAlgorithm());
JwtToken token = new JwtToken(jwsHeaders, consumer.getJwtClaims());
JwsJwtCompactProducer producer = new JwsJwtCompactProducer(token);
String body = producer.signWith(jwsSignatureProvider);
accessToken.setBody(body);
// AccessToken stores expiry time in milliseconds, as opposed to seconds for the JWT tokens.
accessToken.setExpiryTime(expiryDate);
if (!adminUser.equals(accessToken.getOwner())) {
accessToken.setAuthorities(authorities);
}
accessTokenDAO.save(accessToken);
return Pair.of(body, expiryDate);
}
use of org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer in project testcases by coheigea.
the class JWTJAXRSAuthenticationTest method testJWTKerberosAccessToken.
@org.junit.Test
public void testJWTKerberosAccessToken() throws Exception {
URL busFile = JWTJAXRSAuthenticationTest.class.getResource("cxf-client.xml");
// 1. Get a JWT Token from the STS via the REST interface for "alice"
String jwtToken = getJWTTokenFromSTS(busFile);
JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(jwtToken);
JwtToken jwt = jwtConsumer.getJwtToken();
Assert.assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
Assert.assertTrue(((List<?>) jwt.getClaim(ROLE)).contains("boss"));
// 2. Now call on the service using a custom HttpAuthSupplier
String address = "https://localhost:" + PORT + "/doubleit/services";
WebClient client = WebClient.create(address, busFile.toString()).type("application/xml");
Map<String, Object> requestContext = WebClient.getConfig(client).getRequestContext();
requestContext.put("auth.spnego.useKerberosOid", "true");
KerbyHttpAuthSupplier authSupplier = new KerbyHttpAuthSupplier();
authSupplier.setServicePrincipalName("bob/service.ws.apache.org@service.ws.apache.org");
authSupplier.setServiceNameType(GSSName.NT_HOSTBASED_SERVICE);
authSupplier.setJwtToken(jwtToken);
WebClient.getConfig(client).getHttpConduit().setAuthSupplier(authSupplier);
Number numberToDouble = new Number();
numberToDouble.setDescription("This is the number to double");
numberToDouble.setNumber(25);
Response response = client.post(numberToDouble);
Assert.assertEquals(response.getStatus(), 200);
Assert.assertEquals(response.readEntity(Number.class).getNumber(), 50);
}
use of org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer in project testcases by coheigea.
the class AuthorizationCodeFlowTest method validateIdToken.
private void validateIdToken(String idToken, String nonce) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
JwtToken jwt = jwtConsumer.getJwtToken();
// Validate claims
Assert.assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
Assert.assertEquals("OIDC IdP", jwt.getClaim(JwtConstants.CLAIM_ISSUER));
Assert.assertEquals("consumer-id", jwt.getClaim(JwtConstants.CLAIM_AUDIENCE));
Assert.assertNotNull(jwt.getClaim(JwtConstants.CLAIM_EXPIRY));
Assert.assertNotNull(jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT));
if (nonce != null) {
Assert.assertEquals(nonce, jwt.getClaim(IdToken.NONCE_CLAIM));
}
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(Loader.getResource("servicestore.jks").openStream(), "sspass".toCharArray());
Certificate cert = keystore.getCertificate("myservicekey");
Assert.assertNotNull(cert);
Assert.assertTrue(jwtConsumer.verifySignatureWith((X509Certificate) cert, SignatureAlgorithm.RS256));
}
Aggregations