use of org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier in project cxf by apache.
the class JoseConsumer method getData.
public String getData(String data) {
super.checkProcessRequirements();
if (isJweRequired()) {
JweCompactConsumer jweConsumer = new JweCompactConsumer(data);
JweDecryptionProvider theDecryptor = getInitializedDecryptionProvider(jweConsumer.getJweHeaders());
if (theDecryptor == null) {
throw new JwtException("Unable to decrypt JWT");
}
if (!isJwsRequired()) {
return jweConsumer.getDecryptedContentText(theDecryptor);
}
JweDecryptionOutput decOutput = theDecryptor.decrypt(data);
data = decOutput.getContentText();
}
JwsCompactConsumer jwsConsumer = new JwsCompactConsumer(data);
if (isJwsRequired()) {
JwsSignatureVerifier theSigVerifier = getInitializedSignatureVerifier(jwsConsumer.getJwsHeaders());
if (theSigVerifier == null) {
throw new JwtException("Unable to validate JWT");
}
if (!jwsConsumer.verifySignatureWith(theSigVerifier)) {
throw new JwtException("Invalid Signature");
}
}
return jwsConsumer.getDecodedJwsPayload();
}
use of org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier in project cxf by apache.
the class JWTTokenValidator method validateToken.
/**
* Validate a Token using the given TokenValidatorParameters.
*/
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
LOG.fine("Validating JWT Token");
STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
TokenValidatorResponse response = new TokenValidatorResponse();
ReceivedToken validateTarget = tokenParameters.getToken();
validateTarget.setState(STATE.INVALID);
response.setToken(validateTarget);
String token = ((Element) validateTarget.getToken()).getTextContent();
if (token == null || "".equals(token)) {
return response;
}
if (token.split("\\.").length != 3) {
LOG.log(Level.WARNING, "JWT Token appears not to be signed. Validation has failed");
return response;
}
JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
JwtToken jwt = jwtConsumer.getJwtToken();
// Verify the signature
Properties verificationProperties = new Properties();
Crypto signatureCrypto = stsProperties.getSignatureCrypto();
String alias = stsProperties.getSignatureUsername();
if (alias != null) {
verificationProperties.put(JoseConstants.RSSEC_KEY_STORE_ALIAS, alias);
}
if (!(signatureCrypto instanceof Merlin)) {
throw new STSException("Can't get the keystore", STSException.REQUEST_FAILED);
}
KeyStore keystore = ((Merlin) signatureCrypto).getKeyStore();
verificationProperties.put(JoseConstants.RSSEC_KEY_STORE, keystore);
JwsSignatureVerifier signatureVerifier = JwsUtils.loadSignatureVerifier(verificationProperties, jwt.getJwsHeaders());
if (!jwtConsumer.verifySignatureWith(signatureVerifier)) {
return response;
}
try {
validateToken(jwt);
} catch (RuntimeException ex) {
LOG.log(Level.WARNING, "JWT token validation failed", ex);
return response;
}
// Get the realm of the JWT Token
if (realmCodec != null) {
String tokenRealm = realmCodec.getRealmFromToken(jwt);
response.setTokenRealm(tokenRealm);
}
if (isVerifiedWithAPublicKey(jwt)) {
Principal principal = new SimplePrincipal(jwt.getClaims().getSubject());
response.setPrincipal(principal);
// Parse roles from the validated token
if (roleParser != null) {
Set<Principal> roles = roleParser.parseRolesFromToken(principal, null, jwt);
response.setRoles(roles);
}
}
validateTarget.setState(STATE.VALID);
LOG.fine("JWT Token successfully validated");
return response;
}
use of org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier in project cxf by apache.
the class OAuth2JwtFiltersTest method doTestServiceWithJwtTokenAndScope.
private void doTestServiceWithJwtTokenAndScope(String oauthService, String rsAddress) throws Exception {
URL busFile = OAuth2JwtFiltersTest.class.getResource("client.xml");
// Get Authorization Code
WebClient oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(), "alice", "security", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(oauthClient).getRequestContext().put(org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
String code = OAuth2TestUtils.getAuthorizationCode(oauthClient, "create_book");
assertNotNull(code);
// Now get the access token
oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(), "consumer-id", "this-is-a-secret", busFile.toString());
// Save the Cookie for the second request...
WebClient.getConfig(oauthClient).getRequestContext().put(org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
ClientAccessToken accessToken = OAuth2TestUtils.getAccessTokenWithAuthorizationCode(oauthClient, code);
assertNotNull(accessToken.getTokenKey());
JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(accessToken.getTokenKey());
JwsSignatureVerifier verifier = JwsUtils.loadSignatureVerifier("org/apache/cxf/systest/jaxrs/security/alice.rs.properties", null);
assertTrue(jwtConsumer.verifySignatureWith(verifier));
JwtClaims claims = jwtConsumer.getJwtClaims();
assertEquals("consumer-id", claims.getStringProperty(OAuthConstants.CLIENT_ID));
assertEquals("alice", claims.getStringProperty("username"));
// Now invoke on the service with the access token
WebClient client = WebClient.create(rsAddress, OAuth2TestUtils.setupProviders(), busFile.toString());
client.header("Authorization", "Bearer " + accessToken.getTokenKey());
Response response = client.type("application/xml").post(new Book("book", 123L));
assertEquals(200, response.getStatus());
Book returnedBook = response.readEntity(Book.class);
assertEquals(returnedBook.getName(), "book");
assertEquals(returnedBook.getId(), 123L);
}
use of org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier in project cxf by apache.
the class JwsMultipartSignatureInFilter method filter.
@Override
public void filter(List<Attachment> atts) {
if (atts.size() < 2) {
throw ExceptionUtils.toBadRequestException(null, null);
}
Attachment sigPart = atts.remove(atts.size() - 1);
String jwsSequence = null;
try {
jwsSequence = IOUtils.readStringFromStream(sigPart.getDataHandler().getInputStream());
} catch (IOException ex) {
throw ExceptionUtils.toBadRequestException(null, null);
}
String base64UrlEncodedHeaders = null;
String base64UrlEncodedSignature = null;
if (!useJwsJsonSignatureFormat) {
String[] parts = JoseUtils.getCompactParts(jwsSequence);
if (parts.length != 3 || parts[1].length() > 0) {
throw ExceptionUtils.toBadRequestException(null, null);
}
base64UrlEncodedHeaders = parts[0];
base64UrlEncodedSignature = parts[2];
} else {
Map<String, Object> parts = reader.fromJson(jwsSequence);
if (parts.size() != 2 || !parts.containsKey("protected") || !parts.containsKey("signature")) {
throw ExceptionUtils.toBadRequestException(null, null);
}
base64UrlEncodedHeaders = (String) parts.get("protected");
base64UrlEncodedSignature = (String) parts.get("signature");
}
JwsHeaders headers = new JwsHeaders(new JsonMapObjectReaderWriter().fromJson(JoseUtils.decodeToString(base64UrlEncodedHeaders)));
JoseUtils.traceHeaders(headers);
if (Boolean.FALSE != headers.getPayloadEncodingStatus()) {
throw ExceptionUtils.toBadRequestException(null, null);
}
JwsSignatureVerifier theVerifier = null;
if (verifier == null) {
Properties props = KeyManagementUtils.loadStoreProperties(message, true, JoseConstants.RSSEC_SIGNATURE_IN_PROPS, JoseConstants.RSSEC_SIGNATURE_PROPS);
theVerifier = JwsUtils.loadSignatureVerifier(message, props, headers);
} else {
theVerifier = verifier;
}
JwsVerificationSignature sig = theVerifier.createJwsVerificationSignature(headers);
if (sig == null) {
throw ExceptionUtils.toBadRequestException(null, null);
}
byte[] signatureBytes = JoseUtils.decode(base64UrlEncodedSignature);
byte[] headerBytesWithDot = StringUtils.toBytesASCII(base64UrlEncodedHeaders + ".");
sig.update(headerBytesWithDot, 0, headerBytesWithDot.length);
int attSize = atts.size();
for (int i = 0; i < attSize; i++) {
Attachment dataPart = atts.remove(i);
InputStream dataPartStream = null;
try {
dataPartStream = dataPart.getDataHandler().getDataSource().getInputStream();
} catch (IOException ex) {
throw ExceptionUtils.toBadRequestException(ex, null);
}
boolean verifyOnLastRead = i == attSize - 1 ? true : false;
JwsInputStream jwsStream = new JwsInputStream(dataPartStream, sig, signatureBytes, verifyOnLastRead);
InputStream newStream = null;
if (bufferPayload) {
CachedOutputStream cos = new CachedOutputStream();
try {
IOUtils.copy(jwsStream, cos);
newStream = cos.getInputStream();
} catch (Exception ex) {
throw ExceptionUtils.toBadRequestException(ex, null);
}
} else {
newStream = jwsStream;
}
Attachment newDataPart = new Attachment(newStream, dataPart.getHeaders());
atts.add(i, newDataPart);
}
}
use of org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier in project cxf by apache.
the class JwsClientResponseFilter method filter.
@Override
public void filter(ClientRequestContext req, ClientResponseContext res) throws IOException {
if (isMethodWithNoContent(req.getMethod()) || isCheckEmptyStream() && !res.hasEntity()) {
return;
}
JwsCompactConsumer p = new JwsCompactConsumer(IOUtils.readStringFromStream(res.getEntityStream()));
JwsSignatureVerifier theSigVerifier = getInitializedSigVerifier(p.getJwsHeaders());
if (!p.verifySignatureWith(theSigVerifier)) {
throw new JwsException(JwsException.Error.INVALID_SIGNATURE);
}
byte[] bytes = p.getDecodedJwsPayloadBytes();
res.setEntityStream(new ByteArrayInputStream(bytes));
res.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length));
String ct = JoseUtils.checkContentType(p.getJwsHeaders().getContentType(), getDefaultMediaType());
if (ct != null) {
res.getHeaders().putSingle("Content-Type", ct);
}
if (super.isValidateHttpHeaders()) {
super.validateHttpHeadersIfNeeded(res.getHeaders(), p.getJwsHeaders());
}
}
Aggregations