http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpFacebookProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpFacebookProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpFacebookProtocolHandler.java
index 83444e5..bde582b 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpFacebookProtocolHandler.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpFacebookProtocolHandler.java
@@ -60,19 +60,19 @@ import org.springframework.webflow.execution.RequestContext;
*/
@Component
public class TrustedIdpFacebookProtocolHandler extends AbstractTrustedIdpOAuth2ProtocolHandler {
-
+
/**
* The facebook API endpoint for querying claims (such as email address). If not specified
* it defaults to "https://graph.facebook.com/v2.6".
*/
public static final String API_ENDPOINT = "api.endpoint";
-
+
/**
- * The Claim to use for the subject username to insert into the SAML Token. It defaults to
+ * The Claim to use for the subject username to insert into the SAML Token. It defaults to
* "email".
*/
public static final String SUBJECT_CLAIM = "subject.claim";
-
+
public static final String PROTOCOL = "facebook-connect";
private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpFacebookProtocolHandler.class);
@@ -88,24 +88,24 @@ public class TrustedIdpFacebookProtocolHandler extends AbstractTrustedIdpOAuth2P
String code = (String) WebUtils.getAttributeFromFlowScope(context,
OAuthConstants.CODE_RESPONSE_TYPE);
if (code != null && !code.isEmpty()) {
-
+
String tokenEndpoint = getProperty(trustedIdp, TOKEN_ENDPOINT);
if (tokenEndpoint == null || tokenEndpoint.isEmpty()) {
tokenEndpoint = "https://graph.facebook.com/v2.6/oauth/access_token";
}
-
+
String apiEndpoint = getProperty(trustedIdp, API_ENDPOINT);
if (apiEndpoint == null || apiEndpoint.isEmpty()) {
apiEndpoint = "https://graph.facebook.com/v2.6";
}
-
+
String clientId = getProperty(trustedIdp, CLIENT_ID);
String clientSecret = getProperty(trustedIdp, CLIENT_SECRET);
if (clientSecret == null || clientSecret.isEmpty()) {
LOG.warn("A CLIENT_SECRET must be configured to use the TrustedIdpFacebookProtocolHandler");
throw new IllegalStateException("No CLIENT_SECRET specified");
}
-
+
// Here we need to get the AccessToken using the authorization code
ClientAccessToken accessToken = getAccessTokenUsingCode(tokenEndpoint, code, clientId,
clientSecret, idp.getIdpUrl().toString());
@@ -113,8 +113,8 @@ public class TrustedIdpFacebookProtocolHandler extends AbstractTrustedIdpOAuth2P
LOG.warn("No Access Token received from the Facebook IdP");
return null;
}
-
- // Now we need to invoke on the API endpoint using the access token to get the
+
+ // Now we need to invoke on the API endpoint using the access token to get the
// user's claims
String subjectName = getSubjectName(apiEndpoint, accessToken.getTokenKey(), trustedIdp);
try {
@@ -123,25 +123,25 @@ public class TrustedIdpFacebookProtocolHandler extends AbstractTrustedIdpOAuth2P
LOG.warn("Home realm is null");
throw new IllegalStateException("Home realm is null");
}
-
+
// Convert into a SAML Token
Date expires = new Date();
expires.setTime(expires.getTime() + (accessToken.getExpiresIn() * 1000L));
SecurityToken idpToken = new SecurityToken(IDGenerator.generateID(null), null, expires);
- SamlAssertionWrapper assertion =
+ SamlAssertionWrapper assertion =
createSamlAssertion(idp, trustedIdp, subjectName, null, expires);
Document doc = DOMUtils.createDocument();
Element token = assertion.toDOM(doc);
-
- // Create new Security token with new id.
+
+ // Create new Security token with new id.
// Parameters for freshness computation are copied from original IDP_TOKEN
idpToken.setToken(token);
-
+
LOG.info("[IDP_TOKEN={}] for user '{}' issued by home realm [{}]",
- assertion.getId(), assertion.getSaml2().getSubject().getNameID().getValue(),
+ assertion.getId(), assertion.getSaml2().getSubject().getNameID().getValue(),
whr);
LOG.debug("Expired date={}", expires);
-
+
return idpToken;
} catch (IllegalStateException ex) {
throw ex;
@@ -152,23 +152,23 @@ public class TrustedIdpFacebookProtocolHandler extends AbstractTrustedIdpOAuth2P
}
return null;
}
-
+
private ClientAccessToken getAccessTokenUsingCode(String tokenEndpoint, String code, String clientId,
String clientSecret, String redirectURI) {
// Here we need to get the AccessToken using the authorization code
List<Object> providers = new ArrayList<>();
providers.add(new OAuthJSONProvider());
-
- WebClient client =
+
+ WebClient client =
WebClient.create(tokenEndpoint, providers, "cxf-tls.xml");
-
+
ClientConfiguration config = WebClient.getConfig(client);
if (LOG.isDebugEnabled()) {
config.getOutInterceptors().add(new LoggingOutInterceptor());
config.getInInterceptors().add(new LoggingInInterceptor());
}
-
+
client.type("application/x-www-form-urlencoded");
client.accept("application/json");
@@ -182,10 +182,10 @@ public class TrustedIdpFacebookProtocolHandler extends AbstractTrustedIdpOAuth2P
return response.readEntity(ClientAccessToken.class);
}
-
+
private String getSubjectName(String apiEndpoint, String accessToken, TrustedIdp trustedIdp) {
- WebClient client = WebClient.create(apiEndpoint,
- Collections.singletonList(new JsonMapObjectProvider()),
+ WebClient client = WebClient.create(apiEndpoint,
+ Collections.singletonList(new JsonMapObjectProvider()),
"cxf-tls.xml");
client.path("/me");
ClientConfiguration config = WebClient.getConfig(client);
@@ -197,27 +197,27 @@ public class TrustedIdpFacebookProtocolHandler extends AbstractTrustedIdpOAuth2P
client.accept("application/json");
client.query("access_token", accessToken);
-
+
String subjectName = getProperty(trustedIdp, SUBJECT_CLAIM);
if (subjectName == null || subjectName.isEmpty()) {
subjectName = "email";
}
client.query("fields", subjectName);
JsonMapObject mapObject = client.get(JsonMapObject.class);
-
+
String parsedSubjectName = (String)mapObject.getProperty(subjectName);
if (subjectName.contains("email")) {
parsedSubjectName = parsedSubjectName.replace("\\u0040", "@");
}
return parsedSubjectName;
}
-
+
protected String getScope(TrustedIdp trustedIdp) {
String scope = getProperty(trustedIdp, SCOPE);
if (scope != null) {
scope = scope.trim();
}
-
+
if (scope == null || scope.isEmpty()) {
scope = "email";
}
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java
index 47a318d..96d56e6 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java
@@ -72,29 +72,29 @@ import org.springframework.webflow.execution.RequestContext;
*/
@Component
public class TrustedIdpOIDCProtocolHandler extends AbstractTrustedIdpOAuth2ProtocolHandler {
-
+
/**
* The signature algorithm to use in verifying the IdToken. The default is "RS256".
*/
public static final String SIGNATURE_ALGORITHM = "signature.algorithm";
-
+
/**
- * The Claim in which to extract the Subject username to insert into the generated SAML token.
+ * The Claim in which to extract the Subject username to insert into the generated SAML token.
* It defaults to "preferred_username", otherwise it falls back to the "sub" claim.
*/
public static final String SUBJECT_CLAIM = "subject.claim";
-
+
/**
* Additional (space-separated) parameters to be sent in the "scope" to the authorization endpoint.
- * Fediz will automatically use "openid" for this value.
+ * Fediz will automatically use "openid" for this value.
*/
public static final String SCOPE = "scope";
-
+
/**
* The URI from which to retrieve the JSON Web Keys to validate the signed IdToken.
*/
public static final String JWKS_URI = "jwks.uri";
-
+
public static final String PROTOCOL = "openid-connect-1.0";
private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpOIDCProtocolHandler.class);
@@ -110,34 +110,34 @@ public class TrustedIdpOIDCProtocolHandler extends AbstractTrustedIdpOAuth2Proto
String code = (String) WebUtils.getAttributeFromFlowScope(context,
OAuthConstants.CODE_RESPONSE_TYPE);
if (code != null && !code.isEmpty()) {
-
+
String tokenEndpoint = getProperty(trustedIdp, TOKEN_ENDPOINT);
if (tokenEndpoint == null || tokenEndpoint.isEmpty()) {
LOG.warn("A TOKEN_ENDPOINT must be configured to use the OIDCProtocolHandler");
throw new IllegalStateException("No TOKEN_ENDPOINT specified");
}
-
+
String clientId = getProperty(trustedIdp, CLIENT_ID);
String clientSecret = getProperty(trustedIdp, CLIENT_SECRET);
if (clientSecret == null || clientSecret.isEmpty()) {
LOG.warn("A CLIENT_SECRET must be configured to use the OIDCProtocolHandler");
throw new IllegalStateException("No CLIENT_SECRET specified");
}
-
+
// Here we need to get the IdToken using the authorization code
List<Object> providers = new ArrayList<>();
providers.add(new OAuthJSONProvider());
-
- WebClient client =
+
+ WebClient client =
WebClient.create(tokenEndpoint, providers, clientId, clientSecret, "cxf-tls.xml");
-
+
ClientConfiguration config = WebClient.getConfig(client);
if (LOG.isDebugEnabled()) {
config.getOutInterceptors().add(new LoggingOutInterceptor());
config.getInInterceptors().add(new LoggingInInterceptor());
}
-
+
client.type("application/x-www-form-urlencoded").accept("application/json");
Form form = new Form();
@@ -153,50 +153,50 @@ public class TrustedIdpOIDCProtocolHandler extends AbstractTrustedIdpOAuth2Proto
LOG.warn("No IdToken received from the OIDC IdP");
return null;
}
-
+
client.close();
-
+
try {
String whr = (String) WebUtils.getAttributeFromFlowScope(context, IdpConstants.HOME_REALM);
if (whr == null) {
LOG.warn("Home realm is null");
throw new IllegalStateException("Home realm is null");
}
-
+
// Parse the received Token
JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
JwtToken jwt = jwtConsumer.getJwtToken();
-
+
if (jwt != null && jwt.getClaims() != null && LOG.isDebugEnabled()) {
LOG.debug("Received Claims:");
for (Map.Entry<String, Object> claim : jwt.getClaims().asMap().entrySet()) {
LOG.debug(claim.getKey() + ": " + claim.getValue());
}
}
-
+
if (jwt != null && jwt.getJwsHeaders() != null && LOG.isDebugEnabled()) {
LOG.debug("Received JWS Headers:");
for (Map.Entry<String, Object> header : jwt.getJwsHeaders().asMap().entrySet()) {
LOG.debug(header.getKey() + ": " + header.getValue());
}
}
-
+
if (!validateSignature(trustedIdp, jwtConsumer)) {
LOG.warn("Signature does not validate");
return null;
}
-
+
// Make sure the received token is valid according to the spec
validateToken(jwt, clientId);
-
+
Date created = new Date((long)jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT) * 1000L);
Date notBefore = null;
if (jwt.getClaim(JwtConstants.CLAIM_NOT_BEFORE) != null) {
notBefore = new Date((long)jwt.getClaim(JwtConstants.CLAIM_NOT_BEFORE) * 1000L);
- }
-
+ }
+
Date expires = new Date((long)jwt.getClaim(JwtConstants.CLAIM_EXPIRY) * 1000L);
-
+
// Subject
String subjectName = getProperty(trustedIdp, SUBJECT_CLAIM);
LOG.debug("Trying to extract subject name using the claim name {}", subjectName);
@@ -210,24 +210,24 @@ public class TrustedIdpOIDCProtocolHandler extends AbstractTrustedIdpOAuth2Proto
+ "Falling back to use {}", subjectName);
}
}
-
+
// Convert into a SAML Token
- SamlAssertionWrapper assertion =
+ SamlAssertionWrapper assertion =
createSamlAssertion(idp, trustedIdp, (String)jwt.getClaim(subjectName), notBefore, expires);
Document doc = DOMUtils.createDocument();
Element token = assertion.toDOM(doc);
-
- // Create new Security token with new id.
+
+ // Create new Security token with new id.
// Parameters for freshness computation are copied from original IDP_TOKEN
SecurityToken idpToken = new SecurityToken(assertion.getId(), created, expires);
idpToken.setToken(token);
-
+
LOG.info("[IDP_TOKEN={}] for user '{}' created from [RP_TOKEN={}] issued by home realm [{}/{}]",
- assertion.getId(), assertion.getSaml2().getSubject().getNameID().getValue(),
+ assertion.getId(), assertion.getSaml2().getSubject().getNameID().getValue(),
jwt.getClaim(JwtConstants.CLAIM_JWT_ID), whr, jwt.getClaim(JwtConstants.CLAIM_ISSUER));
LOG.debug("Created date={}", created);
LOG.debug("Expired date={}", expires);
-
+
return idpToken;
} catch (IllegalStateException ex) {
throw ex;
@@ -238,7 +238,7 @@ public class TrustedIdpOIDCProtocolHandler extends AbstractTrustedIdpOAuth2Proto
}
return null;
}
-
+
protected void validateToken(JwtToken jwt, String clientId) {
// We must have the following claims
if (jwt.getClaim(JwtConstants.CLAIM_ISSUER) == null
@@ -249,7 +249,7 @@ public class TrustedIdpOIDCProtocolHandler extends AbstractTrustedIdpOAuth2Proto
LOG.warn("The IdToken is missing a required claim");
throw new IllegalStateException("The IdToken is missing a required claim");
}
-
+
// The audience must match the client_id of this client
boolean match = false;
for (String audience : jwt.getClaims().getAudiences()) {
@@ -262,61 +262,61 @@ public class TrustedIdpOIDCProtocolHandler extends AbstractTrustedIdpOAuth2Proto
LOG.warn("The audience of the token does not match this client");
throw new IllegalStateException("The audience of the token does not match this client");
}
-
+
JwtUtils.validateTokenClaims(jwt.getClaims(), 300, 0, false);
}
-
- private boolean validateSignature(TrustedIdp trustedIdp, JwsJwtCompactConsumer jwtConsumer)
- throws CertificateException, WSSecurityException, Base64DecodingException,
+
+ private boolean validateSignature(TrustedIdp trustedIdp, JwsJwtCompactConsumer jwtConsumer)
+ throws CertificateException, WSSecurityException, Base64DecodingException,
ProcessingException, IOException {
-
+
// Validate the Signature
String sigAlgo = getProperty(trustedIdp, SIGNATURE_ALGORITHM);
if (sigAlgo == null || sigAlgo.isEmpty()) {
sigAlgo = "RS256";
}
-
+
JwtToken jwt = jwtConsumer.getJwtToken();
String jwksUri = getProperty(trustedIdp, JWKS_URI);
JsonWebKey verifyingKey = null;
-
- if (jwksUri != null && jwt.getJwsHeaders() != null
+
+ if (jwksUri != null && jwt.getJwsHeaders() != null
&& jwt.getJwsHeaders().containsHeader(JoseConstants.HEADER_KEY_ID)) {
String kid = (String)jwt.getJwsHeaders().getHeader(JoseConstants.HEADER_KEY_ID);
LOG.debug("Attemping to retrieve key id {} from uri {}", kid, jwksUri);
List<Object> jsonKeyProviders = new ArrayList<>();
jsonKeyProviders.add(new JsonWebKeysProvider());
-
- WebClient client =
+
+ WebClient client =
WebClient.create(jwksUri, jsonKeyProviders, "cxf-tls.xml");
client.accept("application/json");
-
+
ClientConfiguration config = WebClient.getConfig(client);
if (LOG.isDebugEnabled()) {
config.getOutInterceptors().add(new LoggingOutInterceptor());
config.getInInterceptors().add(new LoggingInInterceptor());
}
-
+
Response response = client.get();
JsonWebKeys jsonWebKeys = response.readEntity(JsonWebKeys.class);
if (jsonWebKeys != null) {
verifyingKey = jsonWebKeys.getKey(kid);
}
}
-
+
if (verifyingKey != null) {
return jwtConsumer.verifySignatureWith(verifyingKey, SignatureAlgorithm.getAlgorithm(sigAlgo));
}
-
+
X509Certificate validatingCert = CertsUtils.parseX509Certificate(trustedIdp.getCertificate());
if (validatingCert != null) {
return jwtConsumer.verifySignatureWith(validatingCert, SignatureAlgorithm.getAlgorithm(sigAlgo));
}
-
+
LOG.warn("No key supplied to verify the signature of the IdToken");
return false;
}
-
+
protected String getScope(TrustedIdp trustedIdp) {
String scope = getProperty(trustedIdp, SCOPE);
if (scope != null) {
@@ -325,7 +325,7 @@ public class TrustedIdpOIDCProtocolHandler extends AbstractTrustedIdpOAuth2Proto
scope = "openid " + scope;
}
}
-
+
if (scope == null || scope.isEmpty()) {
scope = "openid";
}
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpProtocolControllerImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpProtocolControllerImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpProtocolControllerImpl.java
index 31bc572..1d7c050 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpProtocolControllerImpl.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpProtocolControllerImpl.java
@@ -33,10 +33,10 @@ import org.springframework.stereotype.Component;
public class TrustedIdpProtocolControllerImpl implements ProtocolController<TrustedIdpProtocolHandler> {
private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpProtocolControllerImpl.class);
-
+
@Autowired
private List<TrustedIdpProtocolHandler> protocolHandlers;
-
+
@Override
public TrustedIdpProtocolHandler getProtocolHandler(String protocol) {
for (TrustedIdpProtocolHandler protocolHandler : protocolHandlers) {
@@ -47,7 +47,7 @@ public class TrustedIdpProtocolControllerImpl implements ProtocolController<Trus
LOG.warn("No protocol handler found for {}", protocol);
return null;
}
-
+
@Override
public List<String> getProtocols() {
List<String> protocols = new ArrayList<>();
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpSAMLProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpSAMLProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpSAMLProtocolHandler.java
index 7b8c3eb..b256c3e 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpSAMLProtocolHandler.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpSAMLProtocolHandler.java
@@ -80,28 +80,28 @@ public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHan
* Whether to sign the request or not. The default is "true".
*/
public static final String SIGN_REQUEST = "sign.request";
-
+
/**
* Whether to require a KeyInfo or not when processing a (signed) Response. The default is "true".
*/
public static final String REQUIRE_KEYINFO = "require.keyinfo";
-
+
/**
* Whether the assertions contained in the Response must be signed or not (if the response itself
* is not signed). The default is "true".
*/
public static final String REQUIRE_SIGNED_ASSERTIONS = "require.signed.assertions";
-
+
/**
* Whether we have to "know" the issuer of the SAML Response or not. The default is "true".
*/
public static final String REQUIRE_KNOWN_ISSUER = "require.known.issuer";
-
+
/**
* Whether we BASE-64 decode the response or not. The default is "true".
*/
public static final String SUPPORT_BASE64_ENCODING = "support.base64.encoding";
-
+
/**
* Whether we support Deflate encoding or not. The default is "false".
*/
@@ -131,11 +131,11 @@ public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHan
Document doc = DOMUtils.createDocument();
doc.appendChild(doc.createElement("root"));
// Create the AuthnRequest
- AuthnRequest authnRequest =
+ AuthnRequest authnRequest =
authnRequestBuilder.createAuthnRequest(
null, idp.getRealm(), idp.getIdpUrl().toString()
);
-
+
boolean signRequest = isBooleanPropertyConfigured(trustedIdp, SIGN_REQUEST, true);
if (signRequest) {
authnRequest.setDestination(trustedIdp.getUrl());
@@ -148,13 +148,13 @@ public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHan
UriBuilder ub = UriBuilder.fromUri(trustedIdp.getUrl());
ub.queryParam(SSOConstants.SAML_REQUEST, urlEncodedRequest);
-
+
String wctx = context.getFlowScope().getString(IdpConstants.TRUSTED_IDP_CONTEXT);
ub.queryParam(SSOConstants.RELAY_STATE, wctx);
if (signRequest) {
signRequest(urlEncodedRequest, wctx, idp, ub);
}
-
+
// Store the Request ID
String authnRequestId = authnRequest.getID();
WebUtils.putAttributeInExternalContext(context, SAML_SSO_REQUEST_ID, authnRequestId);
@@ -180,23 +180,23 @@ public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHan
public SecurityToken mapSignInResponse(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
try {
- String encodedSAMLResponse = (String) WebUtils.getAttributeFromFlowScope(context,
+ String encodedSAMLResponse = (String) WebUtils.getAttributeFromFlowScope(context,
SSOConstants.SAML_RESPONSE);
-
+
// Read the response + convert to an OpenSAML Response Object
- org.opensaml.saml.saml2.core.Response samlResponse =
+ org.opensaml.saml.saml2.core.Response samlResponse =
readSAMLResponse(encodedSAMLResponse, trustedIdp);
-
+
Crypto crypto = CertsUtils.getCryptoFromCertificate(trustedIdp.getCertificate());
validateSamlResponseProtocol(samlResponse, crypto, trustedIdp);
// Validate the Response
- SSOValidatorResponse validatorResponse =
+ SSOValidatorResponse validatorResponse =
validateSamlSSOResponse(samlResponse, idp, trustedIdp, context);
- // Create new Security token with new id.
+ // Create new Security token with new id.
// Parameters for freshness computation are copied from original IDP_TOKEN
String id = IDGenerator.generateID("_");
- SecurityToken idpToken =
+ SecurityToken idpToken =
new SecurityToken(id, validatorResponse.getCreated(), validatorResponse.getSessionNotOnOrAfter());
idpToken.setToken(validatorResponse.getAssertionElement());
@@ -217,10 +217,10 @@ public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHan
throw new IllegalStateException("Unexpected exception occured: " + ex.getMessage());
}
}
-
+
private String encodeAuthnRequest(Element authnRequest) throws IOException {
String requestMessage = DOM2Writer.nodeToString(authnRequest);
-
+
if (LOG.isDebugEnabled()) {
LOG.debug(requestMessage);
}
@@ -230,7 +230,7 @@ public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHan
return Base64Utility.encode(deflatedBytes);
}
-
+
/**
* Sign a request according to the redirect binding spec for Web SSO
*/
@@ -245,7 +245,7 @@ public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHan
LOG.error("No crypto instance of properties file configured for signature");
throw new IllegalStateException("Invalid IdP configuration");
}
-
+
String alias = crypto.getDefaultX509Identifier();
X509Certificate cert = CertsUtils.getX509CertificateFromCrypto(crypto, alias);
if (cert == null) {
@@ -262,29 +262,29 @@ public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHan
jceSigAlgo = "SHA1withDSA";
}
LOG.debug("Using Signature algorithm " + sigAlgo);
-
+
ub.queryParam(SSOConstants.SIG_ALG, URLEncoder.encode(sigAlgo, "UTF-8"));
-
+
// Get the password
String password = config.getCertificatePassword();
-
+
// Get the private key
PrivateKey privateKey = crypto.getPrivateKey(alias, password);
-
+
// Sign the request
Signature signature = Signature.getInstance(jceSigAlgo);
signature.initSign(privateKey);
-
- String requestToSign =
+
+ String requestToSign =
SSOConstants.SAML_REQUEST + "=" + authnRequest + "&"
+ SSOConstants.RELAY_STATE + "=" + relayState + "&"
+ SSOConstants.SIG_ALG + "=" + URLEncoder.encode(sigAlgo, "UTF-8");
signature.update(requestToSign.getBytes("UTF-8"));
byte[] signBytes = signature.sign();
-
+
String encodedSignature = Base64.encode(signBytes);
-
+
ub.queryParam(SSOConstants.SIGNATURE, URLEncoder.encode(encodedSignature, "UTF-8"));
}
@@ -294,14 +294,14 @@ public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHan
}
String samlResponseDecoded = samlResponse;
-
+
InputStream tokenStream = null;
if (isBooleanPropertyConfigured(trustedIdp, SUPPORT_BASE64_ENCODING, true)) {
try {
byte[] deflatedToken = Base64Utility.decode(samlResponseDecoded);
tokenStream = isBooleanPropertyConfigured(trustedIdp, SUPPORT_DEFLATE_ENCODING, false)
? new DeflateEncoderDecoder().inflateToken(deflatedToken)
- : new ByteArrayInputStream(deflatedToken);
+ : new ByteArrayInputStream(deflatedToken);
} catch (Base64Exception ex) {
throw ExceptionUtils.toBadRequestException(ex, null);
} catch (DataFormatException ex) {
@@ -321,9 +321,9 @@ public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHan
} catch (Exception ex) {
throw new WebApplicationException(400);
}
-
+
LOG.debug("Received response: " + DOM2Writer.nodeToString(responseDoc.getDocumentElement()));
-
+
XMLObject responseObject = null;
try {
responseObject = OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
@@ -336,7 +336,7 @@ public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHan
return (org.opensaml.saml.saml2.core.Response)responseObject;
}
-
+
/**
* Validate the received SAML Response as per the protocol
*/
@@ -353,13 +353,13 @@ public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHan
throw ExceptionUtils.toBadRequestException(null, null);
}
}
-
+
/**
* Validate the received SAML Response as per the Web SSO profile
*/
private SSOValidatorResponse validateSamlSSOResponse(
org.opensaml.saml.saml2.core.Response samlResponse,
- Idp idp,
+ Idp idp,
TrustedIdp trustedIdp,
RequestContext requestContext
) {
@@ -378,9 +378,9 @@ public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHan
}
LOG.debug("Using {} for issuer validation", issuer);
ssoResponseValidator.setIssuerIDP(issuer);
-
+
// Get the stored request ID
- String requestId =
+ String requestId =
(String)WebUtils.getAttributeFromExternalContext(requestContext, SAML_SSO_REQUEST_ID);
ssoResponseValidator.setRequestId(requestId);
ssoResponseValidator.setSpIdentifier(idp.getRealm());
@@ -388,7 +388,7 @@ public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHan
isBooleanPropertyConfigured(trustedIdp, REQUIRE_SIGNED_ASSERTIONS, true));
ssoResponseValidator.setEnforceKnownIssuer(
isBooleanPropertyConfigured(trustedIdp, REQUIRE_KNOWN_ISSUER, true));
-
+
HttpServletRequest httpServletRequest = WebUtils.getHttpServletRequest(requestContext);
boolean post = "POST".equals(httpServletRequest.getMethod());
if (post) {
@@ -401,11 +401,11 @@ public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHan
throw ExceptionUtils.toBadRequestException(ex, null);
}
}
-
+
public void setReplayCache(TokenReplayCache<String> replayCache) {
this.replayCache = replayCache;
}
-
+
public TokenReplayCache<String> getReplayCache() {
if (replayCache == null) {
replayCache = new EHCacheTokenReplayCache();
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpWSFedProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpWSFedProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpWSFedProtocolHandler.java
index ea8feb4..a3f5615 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpWSFedProtocolHandler.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpWSFedProtocolHandler.java
@@ -59,12 +59,12 @@ import org.springframework.webflow.execution.RequestContext;
@Component
public class TrustedIdpWSFedProtocolHandler extends AbstractTrustedIdpProtocolHandler {
-
+
/**
* Whether to add the home realm parameter to the URL for redirection or not. The default is "true".
*/
public static final String HOME_REALM_PROPAGATION = "home.realm.propagation";
-
+
public static final String PROTOCOL = "http://docs.oasis-open.org/wsfed/federation/200706";
private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpWSFedProtocolHandler.class);
@@ -73,10 +73,10 @@ public class TrustedIdpWSFedProtocolHandler extends AbstractTrustedIdpProtocolHa
public String getProtocol() {
return PROTOCOL;
}
-
+
@Override
public URL mapSignInRequest(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
-
+
try {
StringBuilder sb = new StringBuilder();
sb.append(trustedIdp.getUrl());
@@ -86,12 +86,12 @@ public class TrustedIdpWSFedProtocolHandler extends AbstractTrustedIdpProtocolHa
sb.append(URLEncoder.encode(idp.getRealm(), "UTF-8"));
sb.append("&").append(FederationConstants.PARAM_REPLY).append('=');
sb.append(URLEncoder.encode(idp.getIdpUrl().toString(), "UTF-8"));
-
+
if (isBooleanPropertyConfigured(trustedIdp, HOME_REALM_PROPAGATION, true)) {
sb.append("&").append(FederationConstants.PARAM_HOME_REALM).append('=');
sb.append(trustedIdp.getRealm());
}
-
+
String wfresh = context.getFlowScope().getString(FederationConstants.PARAM_FRESHNESS);
if (wfresh != null) {
sb.append("&").append(FederationConstants.PARAM_FRESHNESS).append('=');
@@ -100,7 +100,7 @@ public class TrustedIdpWSFedProtocolHandler extends AbstractTrustedIdpProtocolHa
String wctx = context.getFlowScope().getString(IdpConstants.TRUSTED_IDP_CONTEXT);
sb.append("&").append(FederationConstants.PARAM_CONTEXT).append('=');
sb.append(wctx);
-
+
return new URL(sb.toString());
} catch (MalformedURLException ex) {
LOG.error("Invalid Redirect URL for Trusted Idp", ex);
@@ -110,45 +110,45 @@ public class TrustedIdpWSFedProtocolHandler extends AbstractTrustedIdpProtocolHa
throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
}
}
-
+
@Override
public SecurityToken mapSignInResponse(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
try {
String whr = (String) WebUtils.getAttributeFromFlowScope(context, IdpConstants.HOME_REALM);
-
+
if (whr == null) {
LOG.warn("Home realm is null");
throw new IllegalStateException("Home realm is null");
}
-
+
String wresult = (String) WebUtils.getAttributeFromFlowScope(context,
FederationConstants.PARAM_RESULT);
-
+
if (wresult == null) {
LOG.warn("Parameter wresult not found");
throw new IllegalStateException("No security token issued");
}
-
+
FedizContext fedContext = getFedizContext(idp, trustedIdp);
-
+
FedizRequest wfReq = new FedizRequest();
wfReq.setAction(FederationConstants.ACTION_SIGNIN);
wfReq.setResponseToken(wresult);
-
+
FedizProcessor wfProc = new FederationProcessorImpl();
FedizResponse wfResp = wfProc.processRequest(wfReq, fedContext);
-
+
fedContext.close();
-
+
Element e = wfResp.getToken();
-
- // Create new Security token with new id.
+
+ // Create new Security token with new id.
// Parameters for freshness computation are copied from original IDP_TOKEN
String id = IDGenerator.generateID("_");
SecurityToken idpToken = new SecurityToken(id,
wfResp.getTokenCreated(), wfResp.getTokenExpires());
-
+
idpToken.setToken(e);
LOG.info("[IDP_TOKEN={}] for user '{}' created from [RP_TOKEN={}] issued by home realm [{}/{}]",
id, wfResp.getUsername(), wfResp.getUniqueTokenId(), whr, wfResp.getIssuer());
@@ -166,8 +166,8 @@ public class TrustedIdpWSFedProtocolHandler extends AbstractTrustedIdpProtocolHa
throw new IllegalStateException("Unexpected exception occured: " + ex.getMessage());
}
}
-
-
+
+
private FedizContext getFedizContext(Idp idpConfig,
TrustedIdp trustedIdpConfig) throws ProcessingException {
@@ -190,7 +190,7 @@ public class TrustedIdpWSFedProtocolHandler extends AbstractTrustedIdpProtocolHa
certStores.getTrustManager().add(tm0);
config.setCertificateStores(certStores);
}
-
+
// Configure trusted IDP
TrustedIssuers trustedIssuers = new TrustedIssuers();
TrustedIssuerType ti0 = new TrustedIssuerType();
@@ -210,7 +210,7 @@ public class TrustedIdpWSFedProtocolHandler extends AbstractTrustedIdpProtocolHa
FedizContext fedContext = new FedizContext(config);
if (!isCertificateLocation) {
CertificateStore cs = null;
-
+
X509Certificate cert;
try {
cert = CertsUtils.parseX509Certificate(trustedIdpConfig.getCertificate());
@@ -219,13 +219,13 @@ public class TrustedIdpWSFedProtocolHandler extends AbstractTrustedIdpProtocolHa
throw new ProcessingException("Failed to parse trusted certificate");
}
cs = new CertificateStore(Collections.singletonList(cert).toArray(new X509Certificate[0]));
-
+
TrustManager tm = new TrustManager(cs);
fedContext.getCertificateStores().add(tm);
}
-
+
fedContext.init();
return fedContext;
}
-
+
}
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationService.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationService.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationService.java
index 2034dca..cb1365f 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationService.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationService.java
@@ -63,22 +63,22 @@ public interface ApplicationService {
@POST
@PreAuthorize("hasRole('APPLICATION_CREATE')")
Response addApplication(@Context UriInfo ui, Application service);
-
+
@PUT
@Path("{realm}")
@PreAuthorize("hasRole('APPLICATION_UPDATE')")
Response updateApplication(@Context UriInfo ui, @PathParam("realm") String realm, Application application);
-
+
@DELETE
@Path("{realm}")
@PreAuthorize("hasRole('APPLICATION_DELETE')")
Response deleteApplication(@PathParam("realm") String realm);
-
+
@POST
@Path("{realm}/claims")
@PreAuthorize("hasRole('APPLICATION_UPDATE')")
Response addClaimToApplication(@Context UriInfo ui, @PathParam("realm") String realm, RequestClaim claim);
-
+
@DELETE
@Path("{realm}/claims/{claimType}")
@PreAuthorize("hasRole('APPLICATION_UPDATE')")
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationServiceImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationServiceImpl.java
index 1b2f6ff..8861744 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationServiceImpl.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationServiceImpl.java
@@ -48,24 +48,24 @@ public class ApplicationServiceImpl implements ApplicationService {
@Autowired
private ApplicationDAO applicationDAO;
-
+
@Autowired
private ClaimDAO claimDAO;
-
+
@Override
public Applications getApplications(int start, int size, List<String> expand, UriInfo uriInfo) {
List<Application> applications = applicationDAO.getApplications(start, size, expand);
-
+
for (Application a : applications) {
URI self = uriInfo.getAbsolutePathBuilder().path(a.getRealm()).build();
a.setHref(self);
}
-
+
Applications list = new Applications();
list.setApplications(applications);
return list;
}
-
+
@Override
public Application getApplication(String realm, List<String> expand) {
Application application = applicationDAO.getApplication(realm, expand);
@@ -75,7 +75,7 @@ public class ApplicationServiceImpl implements ApplicationService {
return application;
}
}
-
+
@Override
public Response addApplication(UriInfo ui, Application application) {
LOG.info("add Service config");
@@ -84,13 +84,13 @@ public class ApplicationServiceImpl implements ApplicationService {
throw new WebApplicationException(Status.BAD_REQUEST);
}
Application createdApplication = applicationDAO.addApplication(application);
-
+
UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
uriBuilder.path("{index}");
URI location = uriBuilder.build(createdApplication.getRealm());
return Response.created(location).entity(application).build();
}
-
+
@Override
public Response updateApplication(UriInfo ui, String realm, Application application) {
if (!realm.equals(application.getRealm().toString())) {
@@ -101,17 +101,17 @@ public class ApplicationServiceImpl implements ApplicationService {
throw new WebApplicationException(Status.BAD_REQUEST);
}
applicationDAO.updateApplication(realm, application);
-
+
return Response.noContent().build();
}
-
+
@Override
public Response deleteApplication(String realm) {
applicationDAO.deleteApplication(realm);
-
+
return Response.noContent().build();
}
-
+
@Override
public Response addClaimToApplication(UriInfo ui, String realm, RequestClaim claim) {
Application application = applicationDAO.getApplication(realm, null);
@@ -124,15 +124,15 @@ public class ApplicationServiceImpl implements ApplicationService {
RequestClaim rc = new RequestClaim(foundClaim);
application.getRequestedClaims().add(rc);
applicationDAO.addClaimToApplication(application, claim);
-
+
return Response.noContent().build();
}
-
+
@Override
public Response removeClaimFromApplication(UriInfo ui, String realm, String claimType) {
Application application = applicationDAO.getApplication(realm, null);
-
- RequestClaim foundItem = null;
+
+ RequestClaim foundItem = null;
for (RequestClaim item : application.getRequestedClaims()) {
if (item.getClaimType().toString().equals(claimType)) {
foundItem = item;
@@ -145,7 +145,7 @@ public class ApplicationServiceImpl implements ApplicationService {
}
application.getRequestedClaims().remove(foundItem);
applicationDAO.removeClaimFromApplication(application, foundItem);
-
+
return Response.noContent().build();
}
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimService.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimService.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimService.java
index 47dac60..ce0d1a9 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimService.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimService.java
@@ -49,7 +49,7 @@ public interface ClaimService {
Response getClaims(@QueryParam("start") int start,
@QueryParam("size") @DefaultValue("2") int size,
@Context UriInfo uriInfo);
-
+
@GET
@Path("{claimType}")
@PreAuthorize("hasRole('CLAIM_READ')")
@@ -58,12 +58,12 @@ public interface ClaimService {
@POST
@PreAuthorize("hasRole('CLAIM_CREATE')")
Response addClaim(@Context UriInfo ui, Claim claim);
-
+
@PUT
@Path("{claimType}")
@PreAuthorize("hasRole('CLAIM_UPDATE')")
Response updateClaim(@Context UriInfo ui, @PathParam("claimType") String claimType, Claim claim);
-
+
@DELETE
@Path("{claimType}")
@PreAuthorize("hasRole('CLAIM_DELETE')")
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimServiceImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimServiceImpl.java
index 141bfab..965485b 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimServiceImpl.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimServiceImpl.java
@@ -47,32 +47,32 @@ public class ClaimServiceImpl implements ClaimService {
@Override
public Response getClaims(int start, int size, UriInfo uriInfo) {
List<Claim> claims = claimDAO.getClaims(start, size);
-
+
for (Claim c : claims) {
URI self = uriInfo.getAbsolutePathBuilder().path(c.getClaimType().toString()).build();
c.setHref(self);
}
-
+
Claims list = new Claims();
list.setClaims(claims);
-
-
+
+
//return Response.ok(list).type(MediaType.APPLICATION_JSON_TYPE).build();
return Response.ok(list).build();
}
-
+
@Override
public Response addClaim(UriInfo ui, Claim claim) {
LOG.info("add Claim config");
-
+
Claim createdClaim = claimDAO.addClaim(claim);
-
+
UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
uriBuilder.path("{index}");
URI location = uriBuilder.build(createdClaim.getClaimType().toString());
return Response.created(location).entity(claim).build();
}
-
+
@Override
public Claim getClaim(String claimType) {
Claim claim = claimDAO.getClaim(claimType);
@@ -89,18 +89,18 @@ public class ClaimServiceImpl implements ClaimService {
throw new BadRequestException();
}
claimDAO.updateClaim(claimType, claim);
-
+
return Response.noContent().build();
}
@Override
public Response deleteClaim(String claimType) {
claimDAO.deleteClaim(claimType);
-
+
return Response.noContent().build();
}
-
-
+
+
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementService.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementService.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementService.java
index 4bc392c..951f332 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementService.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementService.java
@@ -58,16 +58,16 @@ public interface EntitlementService {
@POST
@PreAuthorize("hasRole('ENTITLEMENT_CREATE')")
Response addEntitlement(@Context UriInfo ui, Entitlement entitlement);
-
+
@PUT
@Path("{name}")
@PreAuthorize("hasRole('ENTITLEMENT_UPDATE')")
Response updateEntitlement(@Context UriInfo ui, @PathParam("name") String name, Entitlement entitlement);
-
+
@DELETE
@Path("{name}")
@PreAuthorize("hasRole('ENTITLEMENT_DELETE')")
Response deleteEntitlement(@PathParam("name") String name);
-
+
}
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementServiceImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementServiceImpl.java
index 9c89c04..b71672b 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementServiceImpl.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementServiceImpl.java
@@ -47,25 +47,25 @@ public class EntitlementServiceImpl implements EntitlementService {
@Override
public Entitlements getEntitlements(int start, int size, UriInfo uriInfo) {
List<Entitlement> entitlements = entitlementDAO.getEntitlements(start, size);
-
+
Entitlements list = new Entitlements();
list.setEntitlements(entitlements);
-
+
return list;
}
-
+
@Override
public Response addEntitlement(UriInfo ui, Entitlement entitlement) {
Entitlement createdEntitlement = entitlementDAO.addEntitlement(entitlement);
-
+
UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
uriBuilder.path("{index}");
URI location = uriBuilder.build(createdEntitlement.getName());
-
+
LOG.debug("Entitlement '" + createdEntitlement.getName() + "' added");
return Response.created(location).entity(entitlement).build();
}
-
+
@Override
public Entitlement getEntitlement(String name) {
Entitlement entitlement = entitlementDAO.getEntitlement(name);
@@ -82,7 +82,7 @@ public class EntitlementServiceImpl implements EntitlementService {
throw new BadRequestException();
}
entitlementDAO.updateEntitlement(name, entitlement);
-
+
LOG.debug("Entitlement '" + entitlement.getName() + "' updated");
return Response.noContent().build();
}
@@ -90,7 +90,7 @@ public class EntitlementServiceImpl implements EntitlementService {
@Override
public Response deleteEntitlement(String name) {
entitlementDAO.deleteEntitlement(name);
-
+
LOG.debug("Entitlement '" + name + "' deleted");
return Response.noContent().build();
}
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpService.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpService.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpService.java
index b4692e8..c51fb5c 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpService.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpService.java
@@ -64,51 +64,51 @@ public interface IdpService {
@POST
@PreAuthorize("hasRole('IDP_CREATE')")
Response addIdp(@Context UriInfo ui, Idp idp);
-
+
@PUT
@Path("{realm}")
@PreAuthorize("hasRole('IDP_UPDATE')")
Response updateIdp(@Context UriInfo ui, @PathParam("realm") String realm, Idp idp);
-
+
@DELETE
@Path("{realm}")
@PreAuthorize("hasRole('IDP_DELETE')")
Response deleteIdp(@PathParam("realm") String realm);
-
+
@POST
@Path("{realm}/applications")
@PreAuthorize("hasRole('IDP_UPDATE')")
Response addApplicationToIdp(@Context UriInfo ui, @PathParam("realm") String realm,
Application application);
-
+
@DELETE
@Path("{realm}/applications/{realmApplication}")
@PreAuthorize("hasRole('IDP_UPDATE')")
Response removeApplicationFromIdp(@Context UriInfo ui, @PathParam("realm") String realm,
@PathParam("realmApplication") String applicationRealm);
-
+
@POST
@Path("{realm}/trusted-idps")
@PreAuthorize("hasRole('IDP_UPDATE')")
Response addTrustedIdpToIdp(@Context UriInfo ui, @PathParam("realm") String realm,
TrustedIdp trustedIdp);
-
+
@DELETE
@Path("{realm}/trusted-idps/{realmTrustedIdp}")
@PreAuthorize("hasRole('IDP_UPDATE')")
Response removeTrustedIdpFromIdp(@Context UriInfo ui, @PathParam("realm") String realm,
@PathParam("realmTrustedIdp") String trustedIdpRealm);
-
+
@POST
@Path("{realm}/claims")
@PreAuthorize("hasRole('IDP_UPDATE')")
Response addClaimToIdp(@Context UriInfo ui, @PathParam("realm") String realm,
Claim claim);
-
+
@DELETE
@Path("{realm}/claims/{claimType}")
@PreAuthorize("hasRole('IDP_UPDATE')")
Response removeClaimFromIdp(@Context UriInfo ui, @PathParam("realm") String realm,
- @PathParam("claimType") String claimType);
+ @PathParam("claimType") String claimType);
}
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpServiceImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpServiceImpl.java
index d4b5c40..61dac14 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpServiceImpl.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpServiceImpl.java
@@ -52,25 +52,25 @@ public class IdpServiceImpl implements IdpService {
@Autowired
private IdpDAO idpDAO;
-
+
@Autowired
private ApplicationDAO applicationDAO;
-
+
@Autowired
private TrustedIdpDAO trustedIdpDAO;
-
+
@Autowired
private ClaimDAO claimDAO;
-
+
@Override
public Idps getIdps(int start, int size, List<String> expand, UriInfo uriInfo) {
List<Idp> idps = idpDAO.getIdps(start, size, expand);
-
+
Idps list = new Idps();
list.setIdps(idps);
return list;
}
-
+
@Override
public Idp getIdp(String realm, List<String> expand) {
Idp idp = idpDAO.getIdp(realm, expand);
@@ -81,7 +81,7 @@ public class IdpServiceImpl implements IdpService {
return idp;
}
}
-
+
@Override
public Response addIdp(UriInfo ui, Idp idp) {
LOG.info("add IDP config");
@@ -94,13 +94,13 @@ public class IdpServiceImpl implements IdpService {
throw new WebApplicationException(Status.BAD_REQUEST);
}
Idp createdIdp = idpDAO.addIdp(idp);
-
+
UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
uriBuilder.path("{index}");
URI location = uriBuilder.build(createdIdp.getRealm());
return Response.created(location).entity(idp).build();
}
-
+
@Override
public Response updateIdp(UriInfo ui, String realm, Idp idp) {
if (!realm.equals(idp.getRealm().toString())) {
@@ -115,14 +115,14 @@ public class IdpServiceImpl implements IdpService {
throw new WebApplicationException(Status.BAD_REQUEST);
}
idpDAO.updateIdp(realm, idp);
-
+
return Response.noContent().build();
}
@Override
public Response deleteIdp(String realm) {
idpDAO.deleteIdp(realm);
-
+
return Response.noContent().build();
}
@@ -137,15 +137,15 @@ public class IdpServiceImpl implements IdpService {
}
Application application2 = applicationDAO.getApplication(application.getRealm(), null);
idpDAO.addApplicationToIdp(idp, application2);
-
+
return Response.noContent().build();
}
-
+
@Override
public Response removeApplicationFromIdp(UriInfo ui, String realm, String applicationRealm) {
Idp idp = idpDAO.getIdp(realm, Arrays.asList("all"));
-
- Application foundItem = null;
+
+ Application foundItem = null;
for (Application item : idp.getApplications()) {
if (item.getRealm().equals(applicationRealm)) {
foundItem = item;
@@ -157,13 +157,13 @@ public class IdpServiceImpl implements IdpService {
throw new WebApplicationException(Status.NOT_FOUND);
}
idpDAO.removeApplicationFromIdp(idp, foundItem);
-
+
return Response.noContent().build();
}
-
-
-
-
+
+
+
+
@Override
public Response addTrustedIdpToIdp(UriInfo ui, String realm, TrustedIdp trustedIdp) {
Idp idp = idpDAO.getIdp(realm, Arrays.asList("all"));
@@ -174,17 +174,17 @@ public class IdpServiceImpl implements IdpService {
}
}
TrustedIdp trustedIpd2 = trustedIdpDAO.getTrustedIDP(trustedIdp.getRealm());
-
+
idpDAO.addTrustedIdpToIdp(idp, trustedIpd2);
-
+
return Response.noContent().build();
}
-
+
@Override
public Response removeTrustedIdpFromIdp(UriInfo ui, String realm, String trustedIdpRealm) {
Idp idp = idpDAO.getIdp(realm, Arrays.asList("all"));
-
- TrustedIdp foundItem = null;
+
+ TrustedIdp foundItem = null;
for (TrustedIdp item : idp.getTrustedIdps()) {
if (item.getRealm().equals(trustedIdpRealm)) {
foundItem = item;
@@ -196,15 +196,15 @@ public class IdpServiceImpl implements IdpService {
throw new WebApplicationException(Status.NOT_FOUND);
}
idpDAO.removeTrustedIdpFromIdp(idp, foundItem);
-
+
return Response.noContent().build();
- }
-
+ }
+
@Override
public Response addClaimToIdp(UriInfo ui, String realm, Claim claim) {
Idp idp = idpDAO.getIdp(realm, Arrays.asList("all"));
for (Claim idpClaim : idp.getClaimTypesOffered()) {
- if (idpClaim.getClaimType() != null
+ if (idpClaim.getClaimType() != null
&& idpClaim.getClaimType().toString().equals(claim.getClaimType().toString())) {
LOG.warn("Claim '" + claim.getClaimType() + "' already added");
throw new WebApplicationException(Status.CONFLICT);
@@ -212,15 +212,15 @@ public class IdpServiceImpl implements IdpService {
}
Claim claim2 = claimDAO.getClaim(claim.getClaimType().toString());
idpDAO.addClaimToIdp(idp, claim2);
-
+
return Response.noContent().build();
}
-
+
@Override
public Response removeClaimFromIdp(UriInfo ui, String realm, String claimType) {
Idp idp = idpDAO.getIdp(realm, Arrays.asList("all"));
-
- Claim foundItem = null;
+
+ Claim foundItem = null;
for (Claim item : idp.getClaimTypesOffered()) {
if (item.getClaimType().toString().equals(claimType)) {
foundItem = item;
@@ -232,7 +232,7 @@ public class IdpServiceImpl implements IdpService {
throw new WebApplicationException(Status.NOT_FOUND);
}
idpDAO.removeClaimFromIdp(idp, foundItem);
-
+
return Response.noContent().build();
}
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/QueryResourceInfoComparator.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/QueryResourceInfoComparator.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/QueryResourceInfoComparator.java
index 1e87bfc..b9bd2cf 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/QueryResourceInfoComparator.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/QueryResourceInfoComparator.java
@@ -1,114 +1,114 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cxf.fediz.service.idp.rest;
-
-import java.util.List;
-import java.util.Map;
-
-import org.apache.cxf.jaxrs.ext.ResourceComparator;
-import org.apache.cxf.jaxrs.model.ClassResourceInfo;
-import org.apache.cxf.jaxrs.model.OperationResourceInfo;
-import org.apache.cxf.jaxrs.model.OperationResourceInfoComparator;
-import org.apache.cxf.jaxrs.model.Parameter;
-import org.apache.cxf.jaxrs.utils.JAXRSUtils;
-import org.apache.cxf.message.Message;
-
-public class QueryResourceInfoComparator extends OperationResourceInfoComparator implements ResourceComparator {
-
- public QueryResourceInfoComparator() {
- super(null, null);
- }
-
- @Override
- public int compare(final ClassResourceInfo cri1, final ClassResourceInfo cri2, final Message message) {
- // Leave Class selection to CXF
- return 0;
- }
-
- @Override
- public int compare(final OperationResourceInfo oper1, final OperationResourceInfo oper2, final Message message) {
- // Check if CXF can make a decision
- int cxfResult = super.compare(oper1, oper2);
- if (cxfResult != 0) {
- return cxfResult;
- }
-
- int op1Counter = getMatchingRate(oper1, message);
- int op2Counter = getMatchingRate(oper2, message);
-
- return op1Counter == op2Counter
- ? 0
- : op1Counter < op2Counter
- ? 1
- : -1;
- }
-
- /**
- * This method calculates a number indicating a good or bad match between values provided within the request and
- * expected method parameters. A higher number means a better match.
- *
- * @param operation The operation to be rated, based on contained parameterInfo values.
- * @param message A message containing query and header values from user request
- * @return A positive or negative number, indicating a good match between query and method
- */
- protected int getMatchingRate(final OperationResourceInfo operation, final Message message) {
- List<Parameter> params = operation.getParameters();
- if (params == null || params.isEmpty()) {
- return 0;
- }
-
- // Get Request QueryParams
- String query = (String) message.get(Message.QUERY_STRING);
- String path = (String) message.get(Message.REQUEST_URI);
- Map<String, List<String>> qParams = JAXRSUtils.getStructuredParams(query, "&", true, false);
- Map<String, List<String>> mParams = JAXRSUtils.getMatrixParams(path, true);
- // Get Request Headers
- Map<?, ?> qHeader = (java.util.Map<?, ?>) message.get(Message.PROTOCOL_HEADERS);
-
- int rate = 0;
- for (Parameter p : params) {
- switch (p.getType()) {
- case QUERY:
- if (qParams.containsKey(p.getName())) {
- rate += 2;
- } else if (p.getDefaultValue() == null) {
- rate -= 1;
- }
- break;
- case MATRIX:
- if (mParams.containsKey(p.getName())) {
- rate += 2;
- } else if (p.getDefaultValue() == null) {
- rate -= 1;
- }
- break;
- case HEADER:
- if (qHeader.containsKey(p.getName())) {
- rate += 2;
- } else if (p.getDefaultValue() == null) {
- rate -= 1;
- }
- break;
- default:
- break;
- }
- }
- return rate;
- }
-}
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cxf.fediz.service.idp.rest;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.cxf.jaxrs.ext.ResourceComparator;
+import org.apache.cxf.jaxrs.model.ClassResourceInfo;
+import org.apache.cxf.jaxrs.model.OperationResourceInfo;
+import org.apache.cxf.jaxrs.model.OperationResourceInfoComparator;
+import org.apache.cxf.jaxrs.model.Parameter;
+import org.apache.cxf.jaxrs.utils.JAXRSUtils;
+import org.apache.cxf.message.Message;
+
+public class QueryResourceInfoComparator extends OperationResourceInfoComparator implements ResourceComparator {
+
+ public QueryResourceInfoComparator() {
+ super(null, null);
+ }
+
+ @Override
+ public int compare(final ClassResourceInfo cri1, final ClassResourceInfo cri2, final Message message) {
+ // Leave Class selection to CXF
+ return 0;
+ }
+
+ @Override
+ public int compare(final OperationResourceInfo oper1, final OperationResourceInfo oper2, final Message message) {
+ // Check if CXF can make a decision
+ int cxfResult = super.compare(oper1, oper2);
+ if (cxfResult != 0) {
+ return cxfResult;
+ }
+
+ int op1Counter = getMatchingRate(oper1, message);
+ int op2Counter = getMatchingRate(oper2, message);
+
+ return op1Counter == op2Counter
+ ? 0
+ : op1Counter < op2Counter
+ ? 1
+ : -1;
+ }
+
+ /**
+ * This method calculates a number indicating a good or bad match between values provided within the request and
+ * expected method parameters. A higher number means a better match.
+ *
+ * @param operation The operation to be rated, based on contained parameterInfo values.
+ * @param message A message containing query and header values from user request
+ * @return A positive or negative number, indicating a good match between query and method
+ */
+ protected int getMatchingRate(final OperationResourceInfo operation, final Message message) {
+ List<Parameter> params = operation.getParameters();
+ if (params == null || params.isEmpty()) {
+ return 0;
+ }
+
+ // Get Request QueryParams
+ String query = (String) message.get(Message.QUERY_STRING);
+ String path = (String) message.get(Message.REQUEST_URI);
+ Map<String, List<String>> qParams = JAXRSUtils.getStructuredParams(query, "&", true, false);
+ Map<String, List<String>> mParams = JAXRSUtils.getMatrixParams(path, true);
+ // Get Request Headers
+ Map<?, ?> qHeader = (java.util.Map<?, ?>) message.get(Message.PROTOCOL_HEADERS);
+
+ int rate = 0;
+ for (Parameter p : params) {
+ switch (p.getType()) {
+ case QUERY:
+ if (qParams.containsKey(p.getName())) {
+ rate += 2;
+ } else if (p.getDefaultValue() == null) {
+ rate -= 1;
+ }
+ break;
+ case MATRIX:
+ if (mParams.containsKey(p.getName())) {
+ rate += 2;
+ } else if (p.getDefaultValue() == null) {
+ rate -= 1;
+ }
+ break;
+ case HEADER:
+ if (qHeader.containsKey(p.getName())) {
+ rate += 2;
+ } else if (p.getDefaultValue() == null) {
+ rate -= 1;
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ return rate;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RestServiceExceptionMapper.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RestServiceExceptionMapper.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RestServiceExceptionMapper.java
index c7a1e1e..b305e0f 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RestServiceExceptionMapper.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RestServiceExceptionMapper.java
@@ -1,83 +1,83 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cxf.fediz.service.idp.rest;
-
-import javax.validation.ConstraintViolationException;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
-import javax.ws.rs.core.Response.Status;
-import javax.ws.rs.ext.ExceptionMapper;
-import javax.ws.rs.ext.Provider;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.dao.DataIntegrityViolationException;
-import org.springframework.dao.DataRetrievalFailureException;
-import org.springframework.dao.EmptyResultDataAccessException;
-import org.springframework.security.access.AccessDeniedException;
-
-@Provider
-public class RestServiceExceptionMapper implements ExceptionMapper<Exception> {
-
- public static final String APPLICATION_ERROR_CODE = "X-Application-Error-Code";
-
- public static final String APPLICATION_ERROR_INFO = "X-Application-Error-Info";
-
- private static final String BASIC_REALM_UNAUTHORIZED = "Basic realm=\"Apache Fediz authentication\"";
-
- private static final Logger LOG = LoggerFactory.getLogger(RestServiceExceptionMapper.class);
-
- @Override
- public Response toResponse(final Exception ex) {
- LOG.warn("Exception occured processing REST request: " + ex.getMessage(), ex);
-
- if (ex instanceof AccessDeniedException) {
- return Response.status(Response.Status.UNAUTHORIZED).
- header(HttpHeaders.WWW_AUTHENTICATE, BASIC_REALM_UNAUTHORIZED).
- build();
- }
- if (ex instanceof ConstraintViolationException) {
- ConstraintViolationException cve = (ConstraintViolationException)ex;
- LOG.debug("{}\n{}", ex.getMessage(), cve.getConstraintViolations().toString());
- return buildResponse(Response.Status.BAD_REQUEST, ex);
- }
- if (ex instanceof DataIntegrityViolationException) {
- return buildResponse(Response.Status.CONFLICT, ex);
- }
-
- if (ex instanceof EmptyResultDataAccessException) {
- return buildResponse(Response.Status.NOT_FOUND, ex);
- }
-
- if (ex instanceof DataRetrievalFailureException) {
- return buildResponse(Response.Status.NOT_FOUND, ex);
- }
-
- // Rest is interpreted as InternalServerError
- return buildResponse(Response.Status.INTERNAL_SERVER_ERROR, ex);
- }
-
- Response buildResponse(final Status status, final Exception ex) {
- ResponseBuilder responseBuilder = Response.status(status);
- return responseBuilder.header(APPLICATION_ERROR_CODE, ex.getClass().getName())
- .header(APPLICATION_ERROR_INFO, ex.getMessage())
- .status(status).build();
- }
-
-}
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cxf.fediz.service.idp.rest;
+
+import javax.validation.ConstraintViolationException;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.ResponseBuilder;
+import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.dao.DataRetrievalFailureException;
+import org.springframework.dao.EmptyResultDataAccessException;
+import org.springframework.security.access.AccessDeniedException;
+
+@Provider
+public class RestServiceExceptionMapper implements ExceptionMapper<Exception> {
+
+ public static final String APPLICATION_ERROR_CODE = "X-Application-Error-Code";
+
+ public static final String APPLICATION_ERROR_INFO = "X-Application-Error-Info";
+
+ private static final String BASIC_REALM_UNAUTHORIZED = "Basic realm=\"Apache Fediz authentication\"";
+
+ private static final Logger LOG = LoggerFactory.getLogger(RestServiceExceptionMapper.class);
+
+ @Override
+ public Response toResponse(final Exception ex) {
+ LOG.warn("Exception occured processing REST request: " + ex.getMessage(), ex);
+
+ if (ex instanceof AccessDeniedException) {
+ return Response.status(Response.Status.UNAUTHORIZED).
+ header(HttpHeaders.WWW_AUTHENTICATE, BASIC_REALM_UNAUTHORIZED).
+ build();
+ }
+ if (ex instanceof ConstraintViolationException) {
+ ConstraintViolationException cve = (ConstraintViolationException)ex;
+ LOG.debug("{}\n{}", ex.getMessage(), cve.getConstraintViolations().toString());
+ return buildResponse(Response.Status.BAD_REQUEST, ex);
+ }
+ if (ex instanceof DataIntegrityViolationException) {
+ return buildResponse(Response.Status.CONFLICT, ex);
+ }
+
+ if (ex instanceof EmptyResultDataAccessException) {
+ return buildResponse(Response.Status.NOT_FOUND, ex);
+ }
+
+ if (ex instanceof DataRetrievalFailureException) {
+ return buildResponse(Response.Status.NOT_FOUND, ex);
+ }
+
+ // Rest is interpreted as InternalServerError
+ return buildResponse(Response.Status.INTERNAL_SERVER_ERROR, ex);
+ }
+
+ Response buildResponse(final Status status, final Exception ex) {
+ ResponseBuilder responseBuilder = Response.status(status);
+ return responseBuilder.header(APPLICATION_ERROR_CODE, ex.getClass().getName())
+ .header(APPLICATION_ERROR_INFO, ex.getMessage())
+ .status(status).build();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleService.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleService.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleService.java
index 27d498c..f5d1313 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleService.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleService.java
@@ -63,22 +63,22 @@ public interface RoleService {
@POST
@PreAuthorize("hasRole('ROLE_CREATE')")
Response addRole(@Context UriInfo ui, Role role);
-
+
@PUT
@Path("{name}")
@PreAuthorize("hasRole('ROLE_UPDATE')")
Response updateRole(@Context UriInfo ui, @PathParam("name") String name, Role role);
-
+
@DELETE
@Path("{name}")
@PreAuthorize("hasRole('ROLE_DELETE')")
Response deleteRole(@PathParam("name") String name);
-
+
@POST
@Path("{name}/entitlements")
@PreAuthorize("hasRole('ROLE_UPDATE')")
Response addEntitlementToRole(@Context UriInfo ui, @PathParam("name") String name, Entitlement entitlement);
-
+
@DELETE
@Path("{name}/entitlements/{entitlementName}")
@PreAuthorize("hasRole('ROLE_UPDATE')")
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleServiceImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleServiceImpl.java
index 24ff339..58df748 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleServiceImpl.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleServiceImpl.java
@@ -47,19 +47,19 @@ public class RoleServiceImpl implements RoleService {
@Autowired
private RoleDAO roleDAO;
-
+
@Autowired
private EntitlementDAO entitlementDAO;
-
+
@Override
public Roles getRoles(int start, int size, List<String> expand, UriInfo uriInfo) {
List<Role> roles = roleDAO.getRoles(start, size, expand);
-
+
Roles list = new Roles();
list.setRoles(roles);
return list;
}
-
+
@Override
public Role getRole(String name, List<String> expand) {
Role role = roleDAO.getRole(name, expand);
@@ -69,7 +69,7 @@ public class RoleServiceImpl implements RoleService {
return role;
}
}
-
+
@Override
public Response addRole(UriInfo ui, Role role) {
if (role.getEntitlements() != null && role.getEntitlements().size() > 0) {
@@ -77,15 +77,15 @@ public class RoleServiceImpl implements RoleService {
throw new WebApplicationException(Status.BAD_REQUEST);
}
Role createdRole = roleDAO.addRole(role);
-
+
UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
uriBuilder.path("{index}");
URI location = uriBuilder.build(createdRole.getName());
-
+
LOG.debug("Role '" + role.getName() + "' added");
return Response.created(location).entity(role).build();
}
-
+
@Override
public Response updateRole(UriInfo ui, String name, Role role) {
if (!name.equals(role.getName().toString())) {
@@ -96,37 +96,37 @@ public class RoleServiceImpl implements RoleService {
throw new WebApplicationException(Status.BAD_REQUEST);
}
roleDAO.updateRole(name, role);
-
+
LOG.debug("Role '" + role.getName() + "' updated");
return Response.noContent().build();
}
-
+
@Override
public Response deleteRole(String name) {
roleDAO.deleteRole(name);
-
+
LOG.debug("Role '" + name + "' deleted");
return Response.noContent().build();
}
-
+
@Override
public Response addEntitlementToRole(UriInfo ui, String name, Entitlement entitlement) {
Role role = roleDAO.getRole(name, null);
-
+
Entitlement foundEntitlement = entitlementDAO.getEntitlement(entitlement.getName());
roleDAO.addEntitlementToRole(role, foundEntitlement);
-
+
LOG.debug("Entitlement '" + entitlement.getName() + "' added to Role '" + name + "'");
return Response.noContent().build();
}
-
+
@Override
public Response removeEntitlementFromRole(UriInfo ui, String name, String entitlementName) {
Role role = roleDAO.getRole(name, null);
Entitlement entitlement = entitlementDAO.getEntitlement(entitlementName);
-
+
roleDAO.removeEntitlementFromRole(role, entitlement);
-
+
LOG.debug("Entitlement '" + entitlementName + "' removed from Role '" + name + "'");
return Response.noContent().build();
}
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootServiceImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootServiceImpl.java
index 03eb6da..bed3e9a 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootServiceImpl.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootServiceImpl.java
@@ -30,7 +30,7 @@ public class RootServiceImpl implements RootService {
public RootServiceImpl() {
}
-
+
public Response head(UriInfo uriInfo) {
UriBuilder absolute = uriInfo.getBaseUriBuilder();
URI claimUrl = absolute.clone().path("claims").build();
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/2ca31863/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpService.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpService.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpService.java
index b76d91d..01578a2 100644
--- a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpService.java
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpService.java
@@ -57,12 +57,12 @@ public interface TrustedIdpService {
@POST
@PreAuthorize("hasRole('TRUSTEDIDP_CREATE')")
Response addTrustedIDP(@Context UriInfo ui, TrustedIdp trustedIdp);
-
+
@PUT
@Path("{realm}")
@PreAuthorize("hasRole('TRUSTEDIDP_UPDATE')")
Response updateTrustedIDP(@Context UriInfo ui, @PathParam("realm") String realm, TrustedIdp trustedIdp);
-
+
@DELETE
@Path("{realm}")
@PreAuthorize("hasRole('TRUSTEDIDP_DELETE')")
|