From 3546cafb4942247edf298996186fcdfa32eb9954 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 17 Dec 2013 08:33:18 +0100 Subject: First version for testing -> Exthex OAuth implementation --- .../auth/builder/StartAuthenticationBuilder.java | 7 +- .../moa/id/auth/data/AuthenticationSession.java | 649 ++++++++++----------- .../gv/egovernment/moa/id/config/OAParameter.java | 123 ++-- .../id/config/auth/AuthConfigurationProvider.java | 19 +- .../moa/id/entrypoints/DispatcherServlet.java | 2 +- .../gv/egovernment/moa/id/moduls/ModulStorage.java | 3 +- .../id/protocols/oauth20/OAuth20AuthAction.java | 92 +++ .../id/protocols/oauth20/OAuth20Configuration.java | 51 ++ .../moa/id/protocols/oauth20/OAuth20Constants.java | 45 ++ .../moa/id/protocols/oauth20/OAuth20Protocol.java | 166 ++++++ .../id/protocols/oauth20/OAuth20SessionObject.java | 39 ++ .../id/protocols/oauth20/OAuth20TokenAction.java | 346 +++++++++++ .../moa/id/protocols/oauth20/OAuth20Util.java | 134 +++++ .../exceptions/OAuth20AccessDeniedException.java | 12 + .../OAuth20CertificateErrorException.java | 12 + .../oauth20/exceptions/OAuth20Exception.java | 49 ++ .../exceptions/OAuth20InvalidClientException.java | 12 + .../exceptions/OAuth20InvalidGrantException.java | 12 + .../exceptions/OAuth20InvalidRequestException.java | 13 + .../exceptions/OAuth20ResponseTypeException.java | 12 + .../exceptions/OAuth20ServerErrorException.java | 12 + .../OAuth20UnauthorizedClientException.java | 12 + .../exceptions/OAuth20WrongParameterException.java | 12 + .../oauth20/requests/OAuth20AuthRequest.java | 134 +++++ .../oauth20/requests/OAuth20BaseRequest.java | 118 ++++ .../oauth20/requests/OAuth20TokenRequest.java | 118 ++++ 26 files changed, 1803 insertions(+), 401 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20AuthAction.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Configuration.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Constants.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Protocol.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20TokenAction.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Util.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20AccessDeniedException.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20CertificateErrorException.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20Exception.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidClientException.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidGrantException.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidRequestException.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ResponseTypeException.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ServerErrorException.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20UnauthorizedClientException.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20WrongParameterException.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20AuthRequest.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20BaseRequest.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20TokenRequest.java (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java index 3bc152ec8..e4bf37417 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java @@ -36,7 +36,8 @@ public class StartAuthenticationBuilder { Logger.info("Starting authentication for a citizen of country: " + (StringUtils.isEmpty(moasession.getCcc()) ? "AT" : moasession.getCcc())); // STORK or normal authentication - if (storkConfig.isSTORKAuthentication(moasession.getCcc())) { + //TODO: commented because npe was thrown + /*if (storkConfig.isSTORKAuthentication(moasession.getCcc())) { //STORK authentication Logger.trace("Found C-PEPS configuration for citizen of country: " + moasession.getCcc()); Logger.debug("Starting STORK authentication"); @@ -44,13 +45,13 @@ public class StartAuthenticationBuilder { AuthenticationServer.startSTORKAuthentication(req, resp, moasession); return ""; - } else { + } else {*/ //normal MOA-ID authentication Logger.debug("Starting normal MOA-ID authentication"); String getIdentityLinkForm = AuthenticationServer.getInstance().startAuthentication(moasession, req); return getIdentityLinkForm; - } + //} } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java index 9eaa13f04..1061a2802 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java @@ -1,24 +1,15 @@ /* - * Copyright 2003 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * Copyright 2003 Federal Chancellery Austria MOA-ID has been developed in a cooperation between + * BRZ, the Federal Chancellery Austria - ICT staff unit, and Graz University of Technology. + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: http://www.osor.eu/eupl/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. This product combines work with different licenses. See the "NOTICE" text file for + * details on the various modules and licenses. The "NOTICE" text file is part of the distribution. + * Any derivative works that you distribute must include a readable copy of the "NOTICE" text file. */ package at.gv.egovernment.moa.id.auth.data; @@ -37,6 +28,7 @@ import org.w3c.dom.Element; import at.gv.egovernment.moa.id.auth.validator.InfoboxValidator; import at.gv.egovernment.moa.id.auth.validator.parep.ParepUtils; +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20SessionObject; import at.gv.egovernment.moa.id.util.client.mis.simple.MISMandate; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; @@ -44,43 +36,40 @@ import at.gv.egovernment.moa.util.DOMUtils; import eu.stork.mw.messages.saml.STORKAuthnRequest; /** - * Session data to be stored between AuthenticationServer API - * calls. + * Session data to be stored between AuthenticationServer API calls. * * @author Paul Ivancsics * @version $Id$ */ public class AuthenticationSession implements Serializable { - + /** * */ private static final long serialVersionUID = 1L; public static final String TARGET_PREFIX_ = Constants.URN_PREFIX_CDID + "+"; - public static final String REGISTERANDORDNR_PREFIX_ = Constants.URN_PREFIX_WBPK - + "+"; - + public static final String REGISTERANDORDNR_PREFIX_ = Constants.URN_PREFIX_WBPK + "+"; + /** * session ID */ private String sessionID; /** - * "Geschäftsbereich" the online application belongs to; maybe - * null if the online application is a business application + * "Geschäftsbereich" the online application belongs to; maybe null if the + * online application is a business application */ private String target; /** - * Friendly name for the target, if target is configured via MOA-ID - * configuration + * Friendly name for the target, if target is configured via MOA-ID configuration */ private String targetFriendlyName; - + /** * SourceID */ private String sourceID; - + /** * public online application URL requested */ @@ -97,28 +86,25 @@ public class AuthenticationSession implements Serializable { * HTML template URL */ private String templateURL; - + /** * URL of the BKU */ private String bkuURL; - + /** - * Indicates whether the corresponding online application is a business - * service or not + * Indicates whether the corresponding online application is a business service or not */ private boolean businessService; - //Store Mandate + // Store Mandate /** * Use mandate */ private boolean useMandate; - private boolean isOW = false; - /** * STORK */ @@ -126,33 +112,32 @@ public class AuthenticationSession implements Serializable { /** * - * Mandate element + * Mandate element */ private MISMandate mandate; /** - * Reference value for mandate - * bussiness service for the assertion + * Reference value for mandate bussiness service for the assertion */ private String mandateReferenceValue; - + /** * SessionID for MIS */ private String misSessionID; - //store Identitylink + // store Identitylink /** * identity link read from smartcard */ private IdentityLink identityLink; - -// /** -// * timestamp logging when identity link has been received -// */ -// private Date timestampIdentityLink; - //store Authblock + // /** + // * timestamp logging when identity link has been received + // */ + // private Date timestampIdentityLink; + + // store Authblock /** * authentication block to be signed by the user */ @@ -164,61 +149,56 @@ public class AuthenticationSession implements Serializable { * The issuing time of the AUTH-Block SAML assertion. */ private String issueInstant; - - //Signer certificate + + // Signer certificate /** * Signer certificate of the foreign citizen or for mandate mode */ - //private X509Certificate signerCertificate; + // private X509Certificate signerCertificate; private byte[] signerCertificate; - /** - * SAML attributes from an extended infobox validation to be appended to the - * SAML assertion delivered to the final online application. + * SAML attributes from an extended infobox validation to be appended to the SAML assertion + * delivered to the final online application. */ private List extendedSAMLAttributesOA; - + /** - * The boolean value for either a target or a wbPK is provided as SAML - * Attribute in the SAML Assertion or not. + * The boolean value for either a target or a wbPK is provided as SAML Attribute in the SAML + * Assertion or not. */ private boolean samlAttributeGebeORwbpk; - + /** - * SAML attributes from an extended infobox validation to be appended to the - * SAML assertion of the AUTHBlock. + * SAML attributes from an extended infobox validation to be appended to the SAML assertion of + * the AUTHBlock. */ private List extendedSAMLAttributesAUTH; - + /** - * If infobox validators are needed after signing, they can be stored in - * this list. + * If infobox validators are needed after signing, they can be stored in this list. */ private List infoboxValidators; - + /** - * The register and number in the register parameter in case of a business - * service application. + * The register and number in the register parameter in case of a business service application. */ private String domainIdentifier; - + /** - * This string contains all identifiers of infoboxes, the online application - * is configured to accept. The infobox identifiers are comma separated. + * This string contains all identifiers of infoboxes, the online application is configured to + * accept. The infobox identifiers are comma separated. */ private String pushInfobox; - + /** * The STORK AuthRequest to be sent to the C-PEPS */ private STORKAuthnRequest storkAuthnRequest; + // private AuthenticationData authData; - - //private AuthenticationData authData; - - //protocol selection + // protocol selection private String action; private String modul; @@ -227,82 +207,83 @@ public class AuthenticationSession implements Serializable { private boolean ssoRequested = false; -// /** -// * Indicates if target from configuration is used or not -// */ -// private boolean useTargetFromConfig; - -// /** -// * Authentication data for the assertion -// */ -// private AuthenticationData assertionAuthData; -// -// /** -// * Persondata for the assertion -// */ -// private String assertionPrPerson; -// -// /** -// * Authblock for the assertion -// */ -// private String assertionAuthBlock; -// -// /** -// * Identitylink assertion for the (MOA) assertion -// */ -// private String assertionIlAssertion; -// -// /** -// * Signer certificate (base64 encoded) for the assertion -// */ -// private String assertionSignerCertificateBase64; -// -// /** -// * bussiness service for the assertion -// */ -// boolean assertionBusinessService; -// -// /** -// * timestamp logging when authentication session has been created -// */ -// private Date timestampStart; -// private CreateXMLSignatureResponse XMLCreateSignatureResponse; + private OAuth20SessionObject oAuth20SessionObject; + + // /** + // * Indicates if target from configuration is used or not + // */ + // private boolean useTargetFromConfig; + + // /** + // * Authentication data for the assertion + // */ + // private AuthenticationData assertionAuthData; + // + // /** + // * Persondata for the assertion + // */ + // private String assertionPrPerson; + // + // /** + // * Authblock for the assertion + // */ + // private String assertionAuthBlock; + // + // /** + // * Identitylink assertion for the (MOA) assertion + // */ + // private String assertionIlAssertion; + // + // /** + // * Signer certificate (base64 encoded) for the assertion + // */ + // private String assertionSignerCertificateBase64; + // + // /** + // * bussiness service for the assertion + // */ + // boolean assertionBusinessService; + // + // /** + // * timestamp logging when authentication session has been created + // */ + // private Date timestampStart; + // private CreateXMLSignatureResponse XMLCreateSignatureResponse; private VerifyXMLSignatureResponse XMLVerifySignatureResponse; private boolean isForeigner; -// private String requestedProtocolURL = null; - + // private String requestedProtocolURL = null; + public String getModul() { return modul; } - + public void setModul(String modul) { this.modul = modul; } - + public String getAction() { return action; } - + public void setAction(String action) { this.action = action; } - -// public AuthenticationData getAuthData() { -// return authData; -// } -// -// public void setAuthData(AuthenticationData authData) { -// this.authData = authData; -// } - - + + // public AuthenticationData getAuthData() { + // return authData; + // } + // + // public void setAuthData(AuthenticationData authData) { + // this.authData = authData; + // } + public boolean isAuthenticatedUsed() { return authenticatedUsed; } - + public void setAuthenticatedUsed(boolean authenticatedUsed) { this.authenticatedUsed = authenticatedUsed; } @@ -314,16 +295,15 @@ public class AuthenticationSession implements Serializable { public void setAuthenticated(boolean authenticated) { this.authenticated = authenticated; } - - -// public String getRequestedProtocolURL() { -// return requestedProtocolURL; -// } -// -// public void setRequestedProtocolURL(String requestedProtocolURL) { -// this.requestedProtocolURL = requestedProtocolURL; -// } - + + // public String getRequestedProtocolURL() { + // return requestedProtocolURL; + // } + // + // public void setRequestedProtocolURL(String requestedProtocolURL) { + // this.requestedProtocolURL = requestedProtocolURL; + // } + /** * Constructor for AuthenticationSession. * @@ -332,14 +312,15 @@ public class AuthenticationSession implements Serializable { */ public AuthenticationSession(String id) { sessionID = id; -// setTimestampStart(); + // setTimestampStart(); infoboxValidators = new ArrayList(); } - - public X509Certificate getSignerCertificate(){ + + public X509Certificate getSignerCertificate() { try { return new X509Certificate(signerCertificate); - } catch (CertificateException e) { + } + catch (CertificateException e) { Logger.warn("Signer certificate can not be loaded from session database!", e); return null; } @@ -348,15 +329,16 @@ public class AuthenticationSession implements Serializable { public byte[] getEncodedSignerCertificate() { return this.signerCertificate; } - + public void setSignerCertificate(X509Certificate signerCertificate) { try { this.signerCertificate = signerCertificate.getEncoded(); - } catch (CertificateEncodingException e) { + } + catch (CertificateEncodingException e) { Logger.warn("Signer certificate can not be stored to session database!", e); } } - + /** * Returns the identityLink. * @@ -365,7 +347,7 @@ public class AuthenticationSession implements Serializable { public IdentityLink getIdentityLink() { return identityLink; } - + /** * Returns the sessionID. * @@ -374,7 +356,7 @@ public class AuthenticationSession implements Serializable { public String getSessionID() { return sessionID; } - + /** * Sets the identityLink. * @@ -384,7 +366,7 @@ public class AuthenticationSession implements Serializable { public void setIdentityLink(IdentityLink identityLink) { this.identityLink = identityLink; } - + /** * Sets the sessionID. * @@ -394,7 +376,7 @@ public class AuthenticationSession implements Serializable { public void setSessionID(String sessionId) { this.sessionID = sessionId; } - + /** * Returns the oaURLRequested. * @@ -403,7 +385,7 @@ public class AuthenticationSession implements Serializable { public String getOAURLRequested() { return oaURLRequested; } - + /** * Returns the oaURLRequested. * @@ -412,7 +394,7 @@ public class AuthenticationSession implements Serializable { public String getPublicOAURLPrefix() { return oaPublicURLPrefix; } - + /** * Returns the BKU URL. * @@ -421,7 +403,7 @@ public class AuthenticationSession implements Serializable { public String getBkuURL() { return bkuURL; } - + /** * Returns the target. * @@ -430,7 +412,7 @@ public class AuthenticationSession implements Serializable { public String getTarget() { return target; } - + /** * Returns the sourceID. * @@ -439,7 +421,7 @@ public class AuthenticationSession implements Serializable { public String getSourceID() { return sourceID; } - + /** * Returns the target friendly name. * @@ -448,7 +430,7 @@ public class AuthenticationSession implements Serializable { public String getTargetFriendlyName() { return targetFriendlyName; } - + /** * Sets the oaURLRequested. * @@ -458,7 +440,7 @@ public class AuthenticationSession implements Serializable { public void setOAURLRequested(String oaURLRequested) { this.oaURLRequested = oaURLRequested; } - + /** * Sets the oaPublicURLPrefix * @@ -468,7 +450,7 @@ public class AuthenticationSession implements Serializable { public void setPublicOAURLPrefix(String oaPublicURLPrefix) { this.oaPublicURLPrefix = oaPublicURLPrefix; } - + /** * Sets the bkuURL * @@ -478,10 +460,9 @@ public class AuthenticationSession implements Serializable { public void setBkuURL(String bkuURL) { this.bkuURL = bkuURL; } - + /** - * Sets the target. If the target includes the target prefix, the prefix - * will be stripped off. + * Sets the target. If the target includes the target prefix, the prefix will be stripped off. * * @param target * The target to set @@ -491,13 +472,12 @@ public class AuthenticationSession implements Serializable { // If target starts with prefix "urn:publicid:gv.at:cdid+"; remove // prefix this.target = target.substring(TARGET_PREFIX_.length()); - Logger.debug("Target prefix stripped off; resulting target: " - + this.target); + Logger.debug("Target prefix stripped off; resulting target: " + this.target); } else { this.target = target; } } - + /** * Sets the sourceID * @@ -507,10 +487,9 @@ public class AuthenticationSession implements Serializable { public void setSourceID(String sourceID) { this.sourceID = sourceID; } - + /** - * Sets the target. If the target includes the target prefix, the prefix - * will be stripped off. + * Sets the target. If the target includes the target prefix, the prefix will be stripped off. * * @param target * The target to set @@ -518,7 +497,7 @@ public class AuthenticationSession implements Serializable { public void setTargetFriendlyName(String targetFriendlyName) { this.targetFriendlyName = targetFriendlyName; } - + /** * Returns the authURL. * @@ -527,7 +506,7 @@ public class AuthenticationSession implements Serializable { public String getAuthURL() { return authURL; } - + /** * Sets the authURL. * @@ -537,7 +516,7 @@ public class AuthenticationSession implements Serializable { public void setAuthURL(String authURL) { this.authURL = authURL; } - + /** * Returns the authBlock. * @@ -546,7 +525,7 @@ public class AuthenticationSession implements Serializable { public String getAuthBlock() { return authBlock; } - + /** * Sets the authBlock. * @@ -556,17 +535,17 @@ public class AuthenticationSession implements Serializable { public void setAuthBlock(String authBlock) { this.authBlock = authBlock; } - + /** * Returns the businessService. * - * @return true if the corresponding online application is a - * business application, otherwise false + * @return true if the corresponding online application is a business application, + * otherwise false */ public boolean getBusinessService() { return businessService; } - + /** * Sets the businessService variable. * @@ -576,15 +555,14 @@ public class AuthenticationSession implements Serializable { public void setBusinessService(boolean businessService) { this.businessService = businessService; } - - + /** * @return template URL */ public String getTemplateURL() { return templateURL; } - + /** * @param string * the template URL @@ -592,21 +570,18 @@ public class AuthenticationSession implements Serializable { public void setTemplateURL(String string) { templateURL = string; } - + /** - * Returns the SAML Attributes to be appended to the AUTHBlock. Maybe - * null. + * Returns the SAML Attributes to be appended to the AUTHBlock. Maybe null. * - * @return The SAML Attributes to be appended to the AUTHBlock. Maybe - * null. + * @return The SAML Attributes to be appended to the AUTHBlock. Maybe null. */ public List getExtendedSAMLAttributesAUTH() { - if (extendedSAMLAttributesAUTH == null) - extendedSAMLAttributesAUTH = new ArrayList(); + if (extendedSAMLAttributesAUTH == null) extendedSAMLAttributesAUTH = new ArrayList(); return extendedSAMLAttributesAUTH; } - + /** * Sets the SAML Attributes to be appended to the AUTHBlock. * @@ -616,53 +591,53 @@ public class AuthenticationSession implements Serializable { public void setExtendedSAMLAttributesAUTH(List extendedSAMLAttributesAUTH) { this.extendedSAMLAttributesAUTH = extendedSAMLAttributesAUTH; } - + /** - * Returns the SAML Attributes to be appended to the SAML assertion - * delivered to the online application. Maybe null. + * Returns the SAML Attributes to be appended to the SAML assertion delivered to the online + * application. Maybe null. * - * @return The SAML Attributes to be appended to the SAML assertion - * delivered to the online application + * @return The SAML Attributes to be appended to the SAML assertion delivered to the online + * application */ public List getExtendedSAMLAttributesOA() { return extendedSAMLAttributesOA; } - + /** - * Sets the SAML Attributes to be appended to the SAML assertion delivered - * to the online application. + * Sets the SAML Attributes to be appended to the SAML assertion delivered to the online + * application. * * @param extendedSAMLAttributesOA - * The SAML Attributes to be appended to the SAML assertion - * delivered to the online application. + * The SAML Attributes to be appended to the SAML assertion delivered to the online + * application. */ public void setExtendedSAMLAttributesOA(List extendedSAMLAttributesOA) { this.extendedSAMLAttributesOA = extendedSAMLAttributesOA; } - + /** - * Returns the boolean value for either a target or a wbPK is provided as - * SAML Attribute in the SAML Assertion or not. + * Returns the boolean value for either a target or a wbPK is provided as SAML Attribute in the + * SAML Assertion or not. * - * @return true either a target or a wbPK is provided as SAML Attribute in - * the SAML Assertion or false if not. + * @return true either a target or a wbPK is provided as SAML Attribute in the SAML Assertion or + * false if not. */ public boolean getSAMLAttributeGebeORwbpk() { return this.samlAttributeGebeORwbpk; } - + /** - * Sets the boolean value for either a target or a wbPK is provided as SAML - * Attribute in the SAML Assertion or not. + * Sets the boolean value for either a target or a wbPK is provided as SAML Attribute in the + * SAML Assertion or not. * * @param samlAttributeGebeORwbpk - * The boolean for value either a target or wbPK is provided as - * SAML Attribute in the SAML Assertion or not. + * The boolean for value either a target or wbPK is provided as SAML Attribute in the + * SAML Assertion or not. */ public void setSAMLAttributeGebeORwbpk(boolean samlAttributeGebeORwbpk) { this.samlAttributeGebeORwbpk = samlAttributeGebeORwbpk; } - + /** * Returns the issuing time of the AUTH-Block SAML assertion. * @@ -671,7 +646,7 @@ public class AuthenticationSession implements Serializable { public String getIssueInstant() { return issueInstant; } - + /** * Sets the issuing time of the AUTH-Block SAML assertion. * @@ -681,40 +656,39 @@ public class AuthenticationSession implements Serializable { public void setIssueInstant(String issueInstant) { this.issueInstant = issueInstant; } - + /** * Returns the iterator to the stored infobox validators. * * @return Iterator */ public Iterator getInfoboxValidatorIterator() { - if (infoboxValidators == null) - return null; + if (infoboxValidators == null) return null; return infoboxValidators.iterator(); } - -// /** -// * Adds an infobox validator class to the stored infobox validators. -// * -// * @param infoboxIdentifier -// * the identifier of the infobox the validator belongs to -// * @param infoboxFriendlyName -// * the friendly name of the infobox -// * @param infoboxValidator -// * the infobox validator to add -// */ -// public Iterator addInfoboxValidator(String infoboxIdentifier, -// String infoboxFriendlyName, InfoboxValidator infoboxValidator) { -// if (infoboxValidators == null) -// infoboxValidators = new ArrayList(); -// Vector v = new Vector(3); -// v.add(infoboxIdentifier); -// v.add(infoboxFriendlyName); -// v.add(infoboxValidator); -// infoboxValidators.add(v); -// return infoboxValidators.iterator(); -// } - + + // /** + // * Adds an infobox validator class to the stored infobox validators. + // * + // * @param infoboxIdentifier + // * the identifier of the infobox the validator belongs to + // * @param infoboxFriendlyName + // * the friendly name of the infobox + // * @param infoboxValidator + // * the infobox validator to add + // */ + // public Iterator addInfoboxValidator(String infoboxIdentifier, + // String infoboxFriendlyName, InfoboxValidator infoboxValidator) { + // if (infoboxValidators == null) + // infoboxValidators = new ArrayList(); + // Vector v = new Vector(3); + // v.add(infoboxIdentifier); + // v.add(infoboxFriendlyName); + // v.add(infoboxValidator); + // infoboxValidators.add(v); + // return infoboxValidators.iterator(); + // } + /** * Tests for pending input events of the infobox validators. * @@ -726,100 +700,94 @@ public class AuthenticationSession implements Serializable { if (iter != null) { while (!result && iter.hasNext()) { Vector infoboxValidatorVector = (Vector) iter.next(); - InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector - .get(2); - if (!ParepUtils.isEmpty(infoboxvalidator.getForm())) - result = true; + InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector.get(2); + if (!ParepUtils.isEmpty(infoboxvalidator.getForm())) result = true; } } return result; } - -// /** -// * Returns the first pending infobox validator. -// * -// * @return the infobox validator class -// */ -// public InfoboxValidator getFirstPendingValidator() { -// Iterator iter = getInfoboxValidatorIterator(); -// if (iter != null) { -// while (iter.hasNext()) { -// Vector infoboxValidatorVector = (Vector) iter.next(); -// InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector -// .get(2); -// String form = infoboxvalidator.getForm(); -// if (!ParepUtils.isEmpty(form)) -// return infoboxvalidator; -// } -// } -// return null; -// } - -// /** -// * Returns the input form of the first pending infobox validator input -// * processor. -// * -// * @return the form to show -// */ -// public String getFirstValidatorInputForm() { -// Iterator iter = getInfoboxValidatorIterator(); -// if (iter != null) { -// while (iter.hasNext()) { -// Vector infoboxValidatorVector = (Vector) iter.next(); -// InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector -// .get(2); -// String form = infoboxvalidator.getForm(); -// if (!ParepUtils.isEmpty(form)) -// return form; -// } -// } -// return null; -// } - - /** - * Returns domain identifier (the register and number in the register - * parameter). null in the case of not a business service. + + // /** + // * Returns the first pending infobox validator. + // * + // * @return the infobox validator class + // */ + // public InfoboxValidator getFirstPendingValidator() { + // Iterator iter = getInfoboxValidatorIterator(); + // if (iter != null) { + // while (iter.hasNext()) { + // Vector infoboxValidatorVector = (Vector) iter.next(); + // InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector + // .get(2); + // String form = infoboxvalidator.getForm(); + // if (!ParepUtils.isEmpty(form)) + // return infoboxvalidator; + // } + // } + // return null; + // } + + // /** + // * Returns the input form of the first pending infobox validator input + // * processor. + // * + // * @return the form to show + // */ + // public String getFirstValidatorInputForm() { + // Iterator iter = getInfoboxValidatorIterator(); + // if (iter != null) { + // while (iter.hasNext()) { + // Vector infoboxValidatorVector = (Vector) iter.next(); + // InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector + // .get(2); + // String form = infoboxvalidator.getForm(); + // if (!ParepUtils.isEmpty(form)) + // return form; + // } + // } + // return null; + // } + + /** + * Returns domain identifier (the register and number in the register parameter). + * null in the case of not a business service. * * @return the domainIdentifier */ public String getDomainIdentifier() { return domainIdentifier; } - + /** - * Sets the register and number in the register parameter if the application - * is a business service. If the domain identifier includes the - * registerAndOrdNr prefix, the prefix will be stripped off. + * Sets the register and number in the register parameter if the application is a business + * service. If the domain identifier includes the registerAndOrdNr prefix, the prefix will be + * stripped off. * * @param domainIdentifier * the domain identifier to set */ public void setDomainIdentifier(String domainIdentifier) { - if (domainIdentifier != null - && domainIdentifier.startsWith(REGISTERANDORDNR_PREFIX_)) { + if (domainIdentifier != null && domainIdentifier.startsWith(REGISTERANDORDNR_PREFIX_)) { // If domainIdentifier starts with prefix // "urn:publicid:gv.at:wbpk+"; remove this prefix - this.domainIdentifier = domainIdentifier - .substring(REGISTERANDORDNR_PREFIX_.length()); - Logger.debug("Register and ordernumber prefix stripped off; resulting register string: " - + this.domainIdentifier); + this.domainIdentifier = domainIdentifier.substring(REGISTERANDORDNR_PREFIX_.length()); + Logger.debug("Register and ordernumber prefix stripped off; resulting register string: " + this.domainIdentifier); } else { this.domainIdentifier = domainIdentifier; } } - + /** - * Gets all identifiers of infoboxes, the online application is configured - * to accept. The infobox identifiers are comma separated. + * Gets all identifiers of infoboxes, the online application is configured to accept. The + * infobox identifiers are comma separated. * * @return the string containing infobox identifiers */ public String getPushInfobox() { - if (pushInfobox == null) - return ""; + if (pushInfobox == null) return ""; return pushInfobox; } - + /** * @param pushInfobox * the infobox identifiers to set (comma separated) @@ -827,7 +795,7 @@ public class AuthenticationSession implements Serializable { public void setPushInfobox(String pushInfobox) { this.pushInfobox = pushInfobox; } - + /** * * @param useMandate @@ -838,9 +806,9 @@ public class AuthenticationSession implements Serializable { this.useMandate = true; else this.useMandate = false; - + } - + /** * Returns if mandate is used or not * @@ -849,7 +817,7 @@ public class AuthenticationSession implements Serializable { public boolean getUseMandate() { return this.useMandate; } - + /** * * @param misSessionID @@ -858,7 +826,7 @@ public class AuthenticationSession implements Serializable { public void setMISSessionID(String misSessionID) { this.misSessionID = misSessionID; } - + /** * Returns the MIS session ID * @@ -867,14 +835,14 @@ public class AuthenticationSession implements Serializable { public String getMISSessionID() { return this.misSessionID; } - + /** * @return the mandateReferenceValue */ public String getMandateReferenceValue() { return mandateReferenceValue; } - + /** * @param mandateReferenceValue * the mandateReferenceValue to set @@ -882,7 +850,7 @@ public class AuthenticationSession implements Serializable { public void setMandateReferenceValue(String mandateReferenceValue) { this.mandateReferenceValue = mandateReferenceValue; } - + /** * Gets the STORK SAML AuthnRequest * @@ -891,7 +859,7 @@ public class AuthenticationSession implements Serializable { public STORKAuthnRequest getStorkAuthnRequest() { return storkAuthnRequest; } - + /** * Sets the STORK SAML AuthnRequest * @@ -901,11 +869,11 @@ public class AuthenticationSession implements Serializable { public void setStorkAuthnRequest(STORKAuthnRequest storkAuthnRequest) { this.storkAuthnRequest = storkAuthnRequest; } - + public String getCcc() { return ccc; } - + public void setCcc(String ccc) { this.ccc = ccc; } @@ -913,23 +881,23 @@ public class AuthenticationSession implements Serializable { public boolean isForeigner() { return isForeigner; } - + public void setForeigner(boolean isForeigner) { this.isForeigner = isForeigner; } - + public VerifyXMLSignatureResponse getXMLVerifySignatureResponse() { return XMLVerifySignatureResponse; } - + public void setXMLVerifySignatureResponse(VerifyXMLSignatureResponse xMLVerifySignatureResponse) { XMLVerifySignatureResponse = xMLVerifySignatureResponse; } - + public MISMandate getMISMandate() { return mandate; } - + public void setMISMandate(MISMandate mandate) { this.mandate = mandate; } @@ -938,60 +906,75 @@ public class AuthenticationSession implements Serializable { try { byte[] byteMandate = mandate.getMandate(); String stringMandate = new String(byteMandate); - return DOMUtils.parseDocument(stringMandate, false, - null, null).getDocumentElement(); + return DOMUtils.parseDocument(stringMandate, false, null, null).getDocumentElement(); - }catch (Throwable e) { + } + catch (Throwable e) { Logger.warn("Mandate content could not be generated from MISMandate."); return null; - } + } } - + /** * @return the ssoRequested */ - //TODO: SSO only allowed without mandates, actually!!!!!! + // TODO: SSO only allowed without mandates, actually!!!!!! public boolean isSsoRequested() { return ssoRequested && !useMandate; } - + /** - * @param ssoRequested the ssoRequested to set + * @param ssoRequested + * the ssoRequested to set */ public void setSsoRequested(boolean ssoRequested) { this.ssoRequested = ssoRequested; } - + /** * @return the isOW */ public boolean isOW() { return isOW; } - + /** - * @param isOW the isOW to set + * @param isOW + * the isOW to set */ public void setOW(boolean isOW) { this.isOW = isOW; } - + /** * @return the authBlockTokken */ public String getAuthBlockTokken() { return authBlockTokken; } - + /** - * @param authBlockTokken the authBlockTokken to set + * @param authBlockTokken + * the authBlockTokken to set */ public void setAuthBlockTokken(String authBlockTokken) { this.authBlockTokken = authBlockTokken; } + /** + * @return the oAuth20SessionObject + */ + public OAuth20SessionObject getoAuth20SessionObject() { + return oAuth20SessionObject; + } - + /** + * @param oAuth20SessionObject + * the oAuth20SessionObject to set + */ + public void setoAuth20SessionObject(OAuth20SessionObject oAuth20SessionObject) { + this.oAuth20SessionObject = oAuth20SessionObject; + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/OAParameter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/OAParameter.java index 7d76ce9d5..e5cf14d50 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/OAParameter.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/OAParameter.java @@ -1,40 +1,30 @@ /* - * Copyright 2003 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * Copyright 2003 Federal Chancellery Austria MOA-ID has been developed in a cooperation between + * BRZ, the Federal Chancellery Austria - ICT staff unit, and Graz University of Technology. + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: http://www.osor.eu/eupl/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. This product combines work with different licenses. See the "NOTICE" text file for + * details on the various modules and licenses. The "NOTICE" text file is part of the distribution. + * Any derivative works that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.id.config; +import at.gv.egovernment.moa.id.commons.db.dao.config.OAOAUTH20; import at.gv.egovernment.moa.id.commons.db.dao.config.OnlineApplication; /** - * Configuration parameters belonging to an online application, - * to be used within both, the MOA ID Auth and the - * MOA ID PROXY component. + * Configuration parameters belonging to an online application, to be used within both, the MOA ID + * Auth and the MOA ID PROXY component. * * @author Harald Bratko */ public class OAParameter { - + public OAParameter(OnlineApplication oa) { this.oaType = oa.getType(); @@ -54,55 +44,68 @@ public class OAParameter { this.removePBKFromAuthblock = oa.isRemoveBPKFromAuthBlock(); + this.oAuth20Config = oa.getAuthComponentOA().getOAOAUTH20(); + + } - /** - * type of the online application (maybe "PublicService" or "BusinessService") - */ - private String oaType; - - /** - * specifies whether the online application is a business application or not - * (true if value of {@link #oaType} is "businessService" - */ - private boolean businessService; - - /** - * public URL prefix of the online application - */ - private String publicURLPrefix; - - /** - * specifies a human readable name of the Online Application - */ - private String friendlyName; - - /** - * specified a specific target for the Online Application (overwrites the target in der request) - */ - private String target; - /** - * specifies a friendly name for the target - */ - private String targetFriendlyName; - - private boolean removePBKFromAuthblock; - + /** + * type of the online application (maybe "PublicService" or "BusinessService") + */ + private String oaType; + + /** + * specifies whether the online application is a business application or not (true + * if value of {@link #oaType} is "businessService" + */ + private boolean businessService; + + /** + * public URL prefix of the online application + */ + private String publicURLPrefix; + + /** + * specifies a human readable name of the Online Application + */ + private String friendlyName; + + /** + * specified a specific target for the Online Application (overwrites the target in der request) + */ + private String target; + /** + * specifies a friendly name for the target + */ + private String targetFriendlyName; + + private boolean removePBKFromAuthblock; + + /** + * Contains the oAuth 2.0 configuration (client id, secret and redirect uri) + */ + private OAOAUTH20 oAuth20Config; + public String getOaType() { return oaType; } + public boolean getBusinessService() { return businessService; } + public String getPublicURLPrefix() { return publicURLPrefix; } + public String getFriendlyName() { return friendlyName; } + public String getTarget() { return target; } + public String getTargetFriendlyName() { return targetFriendlyName; } @@ -110,5 +113,9 @@ public class OAParameter { public boolean isRemovePBKFromAuthBlock() { return removePBKFromAuthblock; } - + + public OAOAUTH20 getoAuth20Config() { + return oAuth20Config; + } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java index 304771edf..29f567324 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java @@ -76,7 +76,6 @@ import at.gv.egovernment.moa.id.commons.db.dao.session.ExceptionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.OldSSOSessionIDStore; import at.gv.egovernment.moa.id.commons.db.dao.statistic.StatisticLog; -import at.gv.egovernment.moa.id.config.legacy.BuildFromLegacyConfig; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.ConfigurationProvider; import at.gv.egovernment.moa.id.config.ConfigurationUtils; @@ -84,6 +83,7 @@ import at.gv.egovernment.moa.id.config.ConnectionParameter; import at.gv.egovernment.moa.id.config.ConnectionParameterForeign; import at.gv.egovernment.moa.id.config.ConnectionParameterMOASP; import at.gv.egovernment.moa.id.config.ConnectionParameterMandate; +import at.gv.egovernment.moa.id.config.legacy.BuildFromLegacyConfig; import at.gv.egovernment.moa.id.config.stork.STORKConfig; import at.gv.egovernment.moa.id.data.IssuerAndSerial; import at.gv.egovernment.moa.logging.Logger; @@ -432,8 +432,10 @@ public class AuthConfigurationProvider extends ConfigurationProvider { if (foreign == null ) { Logger.warn("Error in MOA-ID Configuration. No STORK configuration found."); - } else - storkconfig = new STORKConfig(foreign.getSTORK(), props, rootConfigFileDir); + } + //TODO: commented because npe was thrown + //else + //storkconfig = new STORKConfig(foreign.getSTORK(), props, rootConfigFileDir); //load Chaining modes @@ -687,10 +689,9 @@ public class AuthConfigurationProvider extends ConfigurationProvider { } - public Properties getGeneralPVP2ProperiesConfig() { + private Properties getGeneralProperiesConfig(final String propPrefix) { Properties configProp = new Properties(); for (Object key : props.keySet()) { - String propPrefix = "protocols.pvp2."; if (key.toString().startsWith(propPrefix)) { String propertyName = key.toString().substring(propPrefix.length()); configProp.put(propertyName, props.get(key.toString())); @@ -699,6 +700,14 @@ public class AuthConfigurationProvider extends ConfigurationProvider { return configProp; } + public Properties getGeneralPVP2ProperiesConfig() { + return this.getGeneralProperiesConfig("protocols.pvp2."); + } + + public Properties getGeneralOAuth20ProperiesConfig() { + return this.getGeneralProperiesConfig("protocols.oauth20."); + } + public PVP2 getGeneralPVP2DBConfig() { return pvp2general; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java index 234641b4a..7130089ae 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java @@ -69,7 +69,6 @@ public class DispatcherServlet extends AuthServlet{ protected void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - boolean isValidSSOSession = false; boolean useSSOOA = false; String protocolRequestID = null; @@ -350,6 +349,7 @@ public class DispatcherServlet extends AuthServlet{ isValidSSOSession = ssomanager.isValidSSOSession(ssoId, req); useSSOOA = oaParam.useSSO(); + //if a legacy request is used SSO should not be allowed, actually boolean isUseMandateRequested = LegacyHelper.isUseMandateRequested(req); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.java index 2a92f3ce5..31bf1ff58 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.java @@ -10,7 +10,8 @@ public class ModulStorage { private static final String[] modulClasses = new String[]{ "at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol", - "at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol" + "at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol", + "at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Protocol" }; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20AuthAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20AuthAction.java new file mode 100644 index 000000000..949b06bb2 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20AuthAction.java @@ -0,0 +1,92 @@ +package at.gv.egovernment.moa.id.protocols.oauth20; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.moduls.IAction; +import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ResponseTypeException; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ServerErrorException; +import at.gv.egovernment.moa.id.protocols.oauth20.requests.OAuth20AuthRequest; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.logging.Logger; + +public class OAuth20AuthAction implements IAction { + + public String processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, + AuthenticationSession moasession) throws MOAIDException { + + OAuth20AuthRequest oAuthRequest = (OAuth20AuthRequest) req; + + // OAAuthParameter oaParam = + // AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(oAuthRequest.getOAURL()); + // AuthenticationData authData = + // AuthenticationServer.buildAuthenticationData(moasession, oaParam, + // oAuthRequest.getTarget()); + + String responseType = oAuthRequest.getResponseType(); + + String code = AuthenticationSessionStoreage.changeSessionID(moasession); + Logger.debug("Stored session with id: " + code); + if (responseType.equals(OAuth20Constants.RESPONSE_CODE)) { + OAuth20SessionObject o = new OAuth20SessionObject(); + o.setScope(oAuthRequest.getScope()); + o.setCode(code); + moasession.setoAuth20SessionObject(o); + try { + AuthenticationSessionStoreage.storeSession(moasession); + } + catch (MOADatabaseException e) { + throw new OAuth20ServerErrorException(); + } + + Logger.debug("Saved OAuth20SessionObject in session with id: " + moasession.getSessionID()); + } else if (responseType.equals(OAuth20Constants.RESPONSE_TOKEN)) { + throw new OAuth20ResponseTypeException(); + } + + // add code and state to redirect url + httpResp.setStatus(HttpServletResponse.SC_FOUND); + String redirectURI = oAuthRequest.getRedirectUri(); + String state = oAuthRequest.getState(); + + redirectURI = this.addURLParameter(redirectURI, OAuth20Constants.RESPONSE_CODE, code); + redirectURI = this.addURLParameter(redirectURI, OAuth20Constants.PARAM_STATE, state); + + String finalUrl = redirectURI; + httpResp.addHeader("Location", finalUrl); + Logger.debug("REDIRECT TO: " + finalUrl.toString()); + return null; + } + + /* + * (non-Javadoc) + * @see + * at.gv.egovernment.moa.id.moduls.IAction#needAuthentication(at.gv.egovernment.moa.id.moduls + * .IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) { + return true; + } + + private String addURLParameter(String url, String name, String value) { + String param = name + "=" + value; + if (url.indexOf("?") < 0) { + return url + "?" + param; + } else { + return url + "&" + param; + } + } + + /* + * (non-Javadoc) + * @see at.gv.egovernment.moa.id.moduls.IAction#getDefaultActionName() + */ + public String getDefaultActionName() { + return OAuth20Protocol.AUTH_ACTION; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Configuration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Configuration.java new file mode 100644 index 000000000..54c285b96 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Configuration.java @@ -0,0 +1,51 @@ +package at.gv.egovernment.moa.id.protocols.oauth20; + +import java.util.Properties; + +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; + +public class OAuth20Configuration { + + private static OAuth20Configuration instance; + + public static OAuth20Configuration getInstance() { + if (instance == null) { + instance = new OAuth20Configuration(); + } + return instance; + } + + public static final String JWT_KEYSTORE = "jwt.ks.file"; + public static final String JWT_KEYSTORE_PASSWORD = "jwt.ks.password"; + public static final String JWT_KEY_NAME = "jwt.ks.key.name"; + public static final String JWT_KEY_PASSWORD = "jwt.ks.key.password"; + + private Properties props; + + private OAuth20Configuration() { + try { + props = AuthConfigurationProvider.getInstance().getGeneralOAuth20ProperiesConfig(); + } + catch (ConfigurationException e) { + e.printStackTrace(); + } + } + + public String getJWTKeyStore() { + return props.getProperty(JWT_KEYSTORE); + } + + public String getJWTKeyStorePassword() { + return props.getProperty(JWT_KEYSTORE_PASSWORD); + } + + public String getJWTKeyName() { + return props.getProperty(JWT_KEY_NAME); + } + + public String getJWTKeyPassword() { + return props.getProperty(JWT_KEY_PASSWORD); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Constants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Constants.java new file mode 100644 index 000000000..8189aa01b --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Constants.java @@ -0,0 +1,45 @@ +package at.gv.egovernment.moa.id.protocols.oauth20; + +public class OAuth20Constants { + + private OAuth20Constants() { + + } + + // error parameters and error codes + public static final String PARAM_ERROR = "error"; + public static final String PARAM_ERROR_DESCRIPTION = "error_description"; + public static final String PARAM_ERROR_URI = "error_uri"; + + public static final String ERROR_INVALID_REQUEST = "invalid_request"; + public static final String ERROR_UNSUPPORTED_RESPONSE_TYPE = "unsupported_response_type"; + public static final String ERROR_INVALID_CLIENT = "invalid_client"; + public static final String ERROR_ACCESS_DENIED = "access_denied"; + public static final String ERROR_SERVER_ERROR = "server_error"; + public static final String ERROR_INVALID_GRANT = "invalid_grant"; + public static final String ERROR_UNAUTHORIZED_CLIENT = "unauthorized_client"; + + // request parameters + //public static final String PARAM_OA_URL = "oaURL"; + public static final String PARAM_RESPONSE_TYPE = "response_type"; + public static final String PARAM_REDIRECT_URI = "redirect_uri"; + public static final String PARAM_STATE = "state"; + public static final String PARAM_GRANT_TYPE = "grant_type"; + public static final String PARAM_GRANT_TYPE_VALUE_AUTHORIZATION_CODE = "authorization_code"; + public static final String PARAM_CLIENT_ID = "client_id"; + public static final String PARAM_CLIENT_SECRET = "client_secret"; + public static final String PARAM_SCOPE = "scope"; + public static final String PARAM_MOA_MOD = "mod"; + public static final String PARAM_MOA_ACTION = "action"; + + + // reponse parameters + public static final String RESPONSE_CODE = "code"; + public static final String RESPONSE_TOKEN = "token"; + public static final String RESPONSE_ACCESS_TOKEN = "access_token"; + public static final String RESPONSE_ID_TOKEN = "id_token"; + public static final String RESPONSE_EXPIRES_IN = "expires_in"; + public static final String RESPONSE_TOKEN_TYPE = "token_type"; + public static final String RESPONSE_TOKEN_TYPE_VALUE_BEARER = "Bearer"; + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Protocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Protocol.java new file mode 100644 index 000000000..2c8aa8a73 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Protocol.java @@ -0,0 +1,166 @@ +package at.gv.egovernment.moa.id.protocols.oauth20; + +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; + +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.moduls.IAction; +import at.gv.egovernment.moa.id.moduls.IModulInfo; +import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; +import at.gv.egovernment.moa.id.protocols.oauth20.requests.OAuth20BaseRequest; +import at.gv.egovernment.moa.logging.Logger; + +import com.google.gson.JsonObject; + +public class OAuth20Protocol implements IModulInfo { + + public static final String NAME = OAuth20Protocol.class.getName(); + public static final String PATH = "id_oauth20"; + + public static final String AUTH_ACTION = "AUTH"; + public static final String TOKEN_ACTION = "TOKEN"; + + private static HashMap actions = new HashMap(); + + static { + actions.put(AUTH_ACTION, new OAuth20AuthAction()); + actions.put(TOKEN_ACTION, new OAuth20TokenAction()); + } + + public String getName() { + return NAME; + } + + public String getPath() { + return PATH; + } + + public IAction getAction(String action) { + return actions.get(action); + } + + /* + * (non-Javadoc) + * @see + * at.gv.egovernment.moa.id.moduls.IModulInfo#preProcess(javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse, java.lang.String) + */ + public IRequest preProcess(HttpServletRequest request, HttpServletResponse resp, String action) throws MOAIDException { + // validation is done inside creation + OAuth20BaseRequest res = OAuth20BaseRequest.newInstance(action, request); + Logger.debug("Created: " + res); + return res; + } + + /* + * (non-Javadoc) + * @see + * at.gv.egovernment.moa.id.moduls.IModulInfo#canHandleRequest(javax.servlet.http.HttpServletRequest + * , javax.servlet.http.HttpServletResponse) + */ + public IAction canHandleRequest(HttpServletRequest request, HttpServletResponse response) { + if (request.getParameter("action").equals(AUTH_ACTION)) { + return getAction(AUTH_ACTION); + } else if (request.getParameter("action").equals(TOKEN_ACTION)) { + return getAction(TOKEN_ACTION); + } + + return null;// getAction(AUTH_ACTION); + } + + /* + * (non-Javadoc) + * @see at.gv.egovernment.moa.id.moduls.IModulInfo#generateErrorMessage(java.lang.Throwable, + * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, + * at.gv.egovernment.moa.id.moduls.IRequest) + */ + public boolean generateErrorMessage(Throwable e, HttpServletRequest request, HttpServletResponse response, IRequest protocolRequest) + throws Throwable { + + StringBuilder url = new StringBuilder(); + + String paramRedirect = request.getParameter(OAuth20Constants.PARAM_REDIRECT_URI); + + if (e instanceof OAuth20Exception) { + + String action = request.getParameter("action"); + + Logger.debug("Going to throw O OAuth20Exception for action: " + action); + OAuth20Exception oAuth20Exception = ((OAuth20Exception) e); + + String errorCode = oAuth20Exception.getErrorCode(); + String errorDescription = oAuth20Exception.getMessage(); + // String errorUri = "http://tools.ietf.org/html/draft-ietf-oauth-v2-11"; + + if (action.equals(AUTH_ACTION)) { + + // check if given redirect url is ok + if (StringUtils.isNotEmpty(paramRedirect) && OAuth20Util.isUrl(paramRedirect)) { + url.append(paramRedirect); + + // otherwise throw an + } else { + throw new MOAIDException("oauth20.01", new Object[] {}); + } + + String state = request.getParameter(OAuth20Constants.PARAM_STATE); + + OAuth20Util.addParameterToURL(url, OAuth20Constants.PARAM_ERROR, errorCode); + OAuth20Util.addParameterToURL(url, OAuth20Constants.PARAM_ERROR_DESCRIPTION, + URLEncoder.encode(oAuth20Exception.getMessageId() + ": " + errorDescription, "UTF-8")); + // OAuth20Util.addParameterToURL(url, OAuth20Constants.PARAM_ERROR_URI, errorUri); + OAuth20Util.addParameterToURL(url, OAuth20Constants.PARAM_STATE, state); + + response.setContentType("text/html"); + response.setStatus(HttpServletResponse.SC_FOUND); + response.addHeader("Location", url.toString()); + Logger.debug("REDIRECT TO: " + url.toString()); + return true; + + } else if (action.equals(TOKEN_ACTION)) { + Map params = new HashMap(); + params.put(OAuth20Constants.PARAM_ERROR, errorCode); + params.put(OAuth20Constants.PARAM_ERROR_DESCRIPTION, + URLEncoder.encode(oAuth20Exception.getMessageId() + ": " + errorDescription, "UTF-8")); + // params.put(OAuth20Constants.PARAM_ERROR_URI, errorUri); + + // create response + JsonObject jsonObject = new JsonObject(); + OAuth20Util.addProperytiesToJsonObject(jsonObject, params); + String jsonResponse = jsonObject.toString(); + Logger.debug("JSON Response: " + jsonResponse); + + // write respone to http response + response.setContentType("application/json"); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.getOutputStream().print(jsonResponse); + response.getOutputStream().close(); + + return true; + } + + } + + return false; + + } + + /* + * (non-Javadoc) + * @see + * at.gv.egovernment.moa.id.moduls.IModulInfo#validate(javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.moduls.IRequest) + */ + public boolean validate(HttpServletRequest request, HttpServletResponse response, IRequest pending) { + // we validate in the preProcess + return true; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java new file mode 100644 index 000000000..91c099d2c --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java @@ -0,0 +1,39 @@ +package at.gv.egovernment.moa.id.protocols.oauth20; + +import java.io.Serializable; + +public class OAuth20SessionObject implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 1L; + + private String scope; + + private String code; + + public String getScope() { + return scope; + } + + public void setScope(String scope) { + this.scope = scope; + } + + /** + * @return the code + */ + public String getCode() { + return code; + } + + /** + * @param code + * the code to set + */ + public void setCode(String code) { + this.code = code; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20TokenAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20TokenAction.java new file mode 100644 index 000000000..70f425148 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20TokenAction.java @@ -0,0 +1,346 @@ +package at.gv.egovernment.moa.id.protocols.oauth20; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import net.oauth.jsontoken.JsonToken; +import net.oauth.jsontoken.crypto.Signer; + +import org.w3c.dom.Element; + +import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; +import at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBodyType; +import at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType; +import at.gv.e_government.reference.namespace.persondata._20020228_.PersonNameType.FamilyName; +import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.builder.BPKBuilder; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.BuildException; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.moduls.IAction; +import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ServerErrorException; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20UnauthorizedClientException; +import at.gv.egovernment.moa.id.protocols.oauth20.requests.OAuth20TokenRequest; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AttributeExtractor; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.IdentityLinkReSigner; +import at.gv.egovernment.moa.id.util.MandateBuilder; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.Base64Utils; +import at.gv.egovernment.moa.util.Constants; +import at.gv.egovernment.moa.util.DOMUtils; + +import com.google.gson.JsonObject; + +public class OAuth20TokenAction implements IAction { + + private int expirationTime = 5 * 60; // in seconds + + public class Pair { + private T1 first; + private T2 second; + + public Pair(T1 newFirst, T2 newSecond) { + first = newFirst; + second = newSecond; + } + + public T1 getFirst() { + return first; + } + + public T2 getSecond() { + return second; + } + } + + public String processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, + AuthenticationSession moasession) throws MOAIDException { + + AuthenticationSession session = null; + try { + OAuth20TokenRequest oAuthRequest = (OAuth20TokenRequest) req; + + session = AuthenticationSessionStoreage.getSession(oAuthRequest.getCode()); + if (session == null) { + throw new OAuth20UnauthorizedClientException(); + } + + OAuth20SessionObject auth20SessionObject = session.getoAuth20SessionObject(); + Logger.debug("Loaded OAuth20SessionObject from session: " + auth20SessionObject); + + // do checking for different grant types and code + if (!auth20SessionObject.getCode().equals(oAuthRequest.getCode())) { + throw new OAuth20UnauthorizedClientException(); + + } + + final String accessToken = UUID.randomUUID().toString(); + + // create response + Map params = new HashMap(); + params.put(OAuth20Constants.RESPONSE_ACCESS_TOKEN, accessToken); + params.put(OAuth20Constants.RESPONSE_TOKEN_TYPE, OAuth20Constants.RESPONSE_TOKEN_TYPE_VALUE_BEARER); + params.put(OAuth20Constants.RESPONSE_EXPIRES_IN, this.expirationTime); + + // build id token and scope + Pair pair = buildIdToken(auth20SessionObject.getScope(), oAuthRequest, session); + Logger.debug("RESPONSE ID_TOKEN: " + pair.getFirst()); + params.put(OAuth20Constants.RESPONSE_ID_TOKEN, pair.getFirst()); + Logger.debug("RESPONSE SCOPE: " + pair.getSecond()); + params.put(OAuth20Constants.PARAM_SCOPE, pair.getSecond()); + + // create response + JsonObject jsonObject = new JsonObject(); + OAuth20Util.addProperytiesToJsonObject(jsonObject, params); + String jsonResponse = jsonObject.toString(); + Logger.debug("JSON Response: " + jsonResponse); + + // write respone to http response + httpResp.setContentType("application/json"); + httpResp.setStatus(HttpServletResponse.SC_OK); + httpResp.getOutputStream().print(jsonResponse); + httpResp.getOutputStream().close(); + + return null; + } + catch (Exception e) { + throw new OAuth20ServerErrorException(); + } + finally { + if (session != null) { + // destroy session for clean up + try { + Logger.debug("Going to destroy session: " + session.getSessionID()); + AuthenticationSessionStoreage.destroySession(session.getSessionID()); + } + catch (MOADatabaseException e) { + } + } + } + } + + /* + * (non-Javadoc) + * @see + * at.gv.egovernment.moa.id.moduls.IAction#needAuthentication(at.gv.egovernment.moa.id.moduls + * .IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) { + return false; + } + + /* + * (non-Javadoc) + * @see at.gv.egovernment.moa.id.moduls.IAction#getDefaultActionName() + */ + public String getDefaultActionName() { + return OAuth20Protocol.TOKEN_ACTION; + } + + private Pair buildIdToken(String scope, OAuth20TokenRequest oAuthRequest, AuthenticationSession session) + throws Exception { + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(oAuthRequest.getOAURL()); + AuthenticationData authData = AuthenticationServer.buildAuthenticationData(session, oaParam, oAuthRequest.getTarget()); + + Map params = new HashMap(); + StringBuilder resultScopes = new StringBuilder(); + // always fill with open id + this.fillScopeOpenId(params, authData); + resultScopes.append("openId"); + + for (String s : scope.split(" ")) { + + try { + if (s.equalsIgnoreCase("profile")) { + this.fillScopeProfile(params, authData); + resultScopes.append(" profile"); + } else if (s.equalsIgnoreCase("eID")) { + this.fillScopeEID(params, authData, session); + resultScopes.append(" eID"); + } else if (s.equalsIgnoreCase("eID_gov") && oaParam.getBusinessService()) { + this.fillScopeEID_GOV(params, authData, session); + resultScopes.append(" eID_gov"); + } else if (s.equalsIgnoreCase("mandate") && session.getUseMandate() && oaParam.getBusinessService()) { + this.fillScopeMandate(params, oaParam, authData, session); + resultScopes.append(" mandate"); + } + } + catch (Exception e) { + Logger.warn(e.getMessage(), e); + } + // TODO parser STORK + } + + // add properties and sign + // HmacSHA256Signer signer = new HmacSHA256Signer("testSigner", "key_id", + // "super_secure_pwd".getBytes()); + // Signer signer = OAuth20Util.loadSigner(authData.getIssuer(), oaParam.getoAuth20Config()); + Signer signer = OAuth20Util.loadSigner(authData.getIssuer()); + JsonToken token = new JsonToken(signer); + OAuth20Util.addProperytiesToJsonObject(token.getPayloadAsJsonObject(), params); + return new Pair(token.serializeAndSign(), resultScopes.toString()); + } + + private void fillScopeProfile(Map params, AuthenticationData authData) { + params.put("given_name", authData.getGivenName()); + params.put("family_name", authData.getFamilyName()); + params.put("birthdate", authData.getDateOfBirth()); + } + + private void fillScopeOpenId(Map params, AuthenticationData authData) { + params.put("iss", authData.getIssuer()); + params.put("sub", authData.getBPK()); + // params.put("aud", ""); // not used + params.put("exp", (long) (new Date().getTime() / 1000 + this.expirationTime)); + params.put("iat", (long) (new Date().getTime() / 1000)); + params.put("auth_time", (long) (authData.getTimestamp().getTime() / 1000)); + // params.put("acr", ""); //? + } + + private void fillScopeEID(Map params, AuthenticationData authData, AuthenticationSession session) throws Exception { + params.put(PVPConstants.EID_CCS_URL_FRIENDLY_NAME, authData.getBkuURL()); + // params.put("ENC-BPK-LIST", ); // not used + // params.put("MAIL", ); //not used + // params.put("TEL", ); //not used + + params.put(PVPConstants.EID_CITIZEN_QAA_LEVEL_FRIENDLY_NAME, 4); + params.put(PVPConstants.EID_ISSUING_NATION_FRIENDLY_NAME, "AT"); + params.put(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME, authData.getBPKType()); + params.put(PVPConstants.EID_AUTH_BLOCK_FRIENDLY_NAME, Base64Utils.encode(session.getAuthBlock().getBytes())); + params.put(PVPConstants.EID_SIGNER_CERTIFICATE_FRIENDLY_NAME, Base64Utils.encode(session.getEncodedSignerCertificate())); + // params.put(PVPConstants.EID_STORK_TOKEN_FRIENDLY_NAME, ); //not used + + // bpk + String bpk = authData.getBPK(); + String type = authData.getBPKType(); + if (type.startsWith(Constants.URN_PREFIX_WBPK)) + type = type.substring((Constants.URN_PREFIX_WBPK + "+").length()); + else if (type.startsWith(Constants.URN_PREFIX_CDID)) type = type.substring((Constants.URN_PREFIX_CDID + "+").length()); + if (bpk.length() > PVPConstants.BPK_MAX_LENGTH) { + bpk = bpk.substring(0, PVPConstants.BPK_MAX_LENGTH); + } + params.put(PVPConstants.BPK_FRIENDLY_NAME, type + ":" + bpk); + } + + private void fillScopeEID_GOV(Map params, AuthenticationData authData, AuthenticationSession session) + throws Exception { + params.put(PVPConstants.EID_SOURCE_PIN_FRIENDLY_NAME, authData.getIdentificationValue()); + params.put(PVPConstants.EID_SOURCE_PIN_TYPE_FRIENDLY_NAME, authData.getIdentificationType()); + + IdentityLinkReSigner identitylinkresigner = IdentityLinkReSigner.getInstance(); + Element resignedilAssertion = identitylinkresigner.resignIdentityLink(authData.getIdentityLink().getSamlAssertion()); + params.put(PVPConstants.EID_IDENTITY_LINK_FRIENDLY_NAME, + Base64Utils.encode(DOMUtils.serializeNode(resignedilAssertion).getBytes())); + } + + private void fillScopeMandate(Map params, OAAuthParameter oaParam, AuthenticationData authData, + AuthenticationSession session) { + Element mandate = session.getMandate(); + + if (mandate == null) { + throw new OAuth20ServerErrorException(); + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if (mandateObject == null) { + throw new OAuth20ServerErrorException(); + } + + params.put(PVPConstants.MANDATE_TYPE_FRIENDLY_NAME, mandateObject.getAnnotation()); + params.put(PVPConstants.MANDATE_REFERENCE_VALUE_FRIENDLY_NAME, mandateObject.getMandateID()); + + // natural person + PhysicalPersonType physicalPerson = mandateObject.getMandator().getPhysicalPerson(); + if (physicalPerson != null && physicalPerson.getIdentification().size() != 0) { + IdentificationType id = physicalPerson.getIdentification().get(0); + params.put(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_FRIENDLY_NAME, id.getValue().getValue()); + params.put(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, id.getType()); + + try { + String bpk; + if (id.getType().equals(Constants.URN_PREFIX_BASEID)) { + if (session.getBusinessService()) { + bpk = new BPKBuilder().buildWBPK(id.getValue().getValue(), oaParam.getIdentityLinkDomainIdentifier()); + } else { + bpk = new BPKBuilder().buildBPK(id.getValue().getValue(), oaParam.getTarget()); + } + } else { + bpk = id.getValue().getValue(); + } + params.put(PVPConstants.MANDATE_NAT_PER_BPK_FRIENDLY_NAME, bpk); + } + catch (BuildException e) { + // ignore + } + + // params.put(PVPConstants.MANDATE_NAT_PER_ENC_BPK_LIST_FRIENDLY_NAME, ); //not used + + StringBuilder sb = new StringBuilder(); + Iterator fNamesit = physicalPerson.getName().getFamilyName().iterator(); + + while (fNamesit.hasNext()) { + sb.append(" " + fNamesit.next().getValue()); + } + params.put(PVPConstants.MANDATE_NAT_PER_FAMILY_NAME_FRIENDLY_NAME, sb.toString()); + + sb = new StringBuilder(); + Iterator gNamesit = physicalPerson.getName().getGivenName().iterator(); + + while (gNamesit.hasNext()) { + sb.append(" " + gNamesit.next()); + } + params.put(PVPConstants.MANDATE_NAT_PER_GIVEN_NAME_FRIENDLY_NAME, sb.toString()); + + try { + DateFormat mandateFormat = new SimpleDateFormat(MandateBuilder.MANDATE_DATE_OF_BIRTH_FORMAT); + Date date = mandateFormat.parse(physicalPerson.getDateOfBirth()); + DateFormat pvpDateFormat = new SimpleDateFormat(PVPConstants.MANDATE_NAT_PER_BIRTHDATE_FORMAT_PATTERN); + String dateString = pvpDateFormat.format(date); + params.put(PVPConstants.MANDATE_NAT_PER_BIRTHDATE_FRIENDLY_NAME, dateString); + } + catch (ParseException e) { + // ignore + } + + } + + // legal person + CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); + if (corporation != null && corporation.getIdentification().size() != 0) { + IdentificationType id = corporation.getIdentification().get(0); + params.put(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_FRIENDLY_NAME, id.getValue().getValue()); + params.put(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, id.getType()); + params.put(PVPConstants.MANDATE_LEG_PER_FULL_NAME_FRIENDLY_NAME, corporation.getFullName()); + } + + String oid = AttributeExtractor.extractSAMLAttributeOA(EXT_SAML_MANDATE_OID, session); + if (oid != null) { + params.put(PVPConstants.MANDATE_PROF_REP_OID_FRIENDLY_NAME, oid); + } + + String text = AttributeExtractor.extractSAMLAttributeOA(EXT_SAML_MANDATE_OIDTEXTUALDESCRIPTION, session); + + if (text != null) { + params.put(PVPConstants.MANDATE_PROF_REP_DESC_FRIENDLY_NAME, oid); + } + + // params.put("MANDATE-FULL-MANDATE-LIST", ); // not used + + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Util.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Util.java new file mode 100644 index 000000000..4d3030a0f --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Util.java @@ -0,0 +1,134 @@ +package at.gv.egovernment.moa.id.protocols.oauth20; + +import java.io.UnsupportedEncodingException; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.X509Certificate; +import java.security.interfaces.RSAPrivateKey; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import net.oauth.jsontoken.crypto.RsaSHA256Signer; +import net.oauth.jsontoken.crypto.Signer; + +import org.opensaml.xml.security.x509.BasicX509Credential; + +import at.gv.egovernment.moa.id.commons.db.dao.config.OAOAUTH20; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20CertificateErrorException; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.KeyStoreUtils; +import at.gv.egovernment.moa.util.StringUtils; + +import com.google.gson.JsonObject; + +public class OAuth20Util { + + public static final String REGEX_HTTPS = "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; + public static final String REGEX_FILE = "^(file):/.[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; + + /** + * Simple helper function to add parameter to a url + * + * @param url + * @param name + * @param value + * @throws UnsupportedEncodingException + */ + public static void addParameterToURL(final StringBuilder url, final String name, final String value) + throws UnsupportedEncodingException { + if (url.indexOf("?") < 0) { + url.append("?"); + } else { + url.append("&"); + } + // URLEncoder.encode(value, "UTF-8") + url.append(name).append("=").append(value); + } + + public static boolean isUrl(final String url) { + Pattern urlPattern; + if (url.startsWith("file")) { + urlPattern = Pattern.compile(REGEX_FILE, Pattern.CASE_INSENSITIVE); + } else { + urlPattern = Pattern.compile(REGEX_HTTPS, Pattern.CASE_INSENSITIVE); + } + + Matcher matcher = urlPattern.matcher(url); + return matcher.find(); + } + + public static void addProperytiesToJsonObject(JsonObject jsonObject, Map params) { + for (Map.Entry param : params.entrySet()) { + if (param.getKey() != null && !"".equals(param.getKey()) && param.getValue() != null && !"".equals(param.getValue())) { + + // check for integer + try { + int i = Integer.parseInt(String.valueOf(param.getValue())); + jsonObject.addProperty(param.getKey(), i); + continue; + } + catch (NumberFormatException e) { + } + + // check for long + try { + long l = Long.parseLong(String.valueOf(param.getValue())); + jsonObject.addProperty(param.getKey(), l); + continue; + } + catch (NumberFormatException e) { + } + + // string + if (param.getValue() instanceof String) { + jsonObject.addProperty(param.getKey(), String.valueOf(param.getValue())); + } + } + } + } + + public static Signer loadSigner(String issuer) throws OAuth20Exception { + OAuth20Configuration globalConfig = OAuth20Configuration.getInstance(); + + if (StringUtils.isEmpty(globalConfig.getJWTKeyStore())) { + throw new OAuth20CertificateErrorException("keystore"); + } + + if (StringUtils.isEmpty(globalConfig.getJWTKeyName())) { + throw new OAuth20CertificateErrorException("key name"); + } + + try { + KeyStore ks = KeyStoreUtils.loadKeyStore(globalConfig.getJWTKeyStore(), globalConfig.getJWTKeyStorePassword()); + + X509Certificate certificate = (X509Certificate) ks.getCertificate(globalConfig.getJWTKeyName()); + + PrivateKey privateKey = (PrivateKey) ks.getKey(globalConfig.getJWTKeyName(), globalConfig.getJWTKeyPassword() + .toCharArray()); + BasicX509Credential credential = new BasicX509Credential(); + credential.setEntityCertificate(certificate); + credential.setPrivateKey(privateKey); + + //Logger.debug("Going to use X509Certificate:"); + Logger.debug(certificate); + //Logger.debug("Going to use private key:"); + Logger.debug(privateKey); + + return new RsaSHA256Signer(issuer, globalConfig.getJWTKeyName(), (RSAPrivateKey) credential.getPrivateKey()); + + } + catch (Exception e) { + throw new OAuth20CertificateErrorException("keystore"); + } + + } + + public static boolean isValidStateValue(String state) { + Pattern urlPattern = Pattern.compile("javascript|<|>|&|;", Pattern.CASE_INSENSITIVE); + Matcher matcher = urlPattern.matcher(state); + return !matcher.find(); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20AccessDeniedException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20AccessDeniedException.java new file mode 100644 index 000000000..e4abd5bd1 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20AccessDeniedException.java @@ -0,0 +1,12 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.exceptions; + +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; + +public class OAuth20AccessDeniedException extends OAuth20Exception { + private static final long serialVersionUID = 1L; + + public OAuth20AccessDeniedException() { + super(OAuth20Constants.ERROR_ACCESS_DENIED, "oauth20.05", new Object[] {}); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20CertificateErrorException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20CertificateErrorException.java new file mode 100644 index 000000000..6f5a41ca5 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20CertificateErrorException.java @@ -0,0 +1,12 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.exceptions; + +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; + +public class OAuth20CertificateErrorException extends OAuth20Exception { + private static final long serialVersionUID = 1L; + + public OAuth20CertificateErrorException(final String name) { + super(OAuth20Constants.ERROR_SERVER_ERROR, "oauth20.09", new Object[] { name }); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20Exception.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20Exception.java new file mode 100644 index 000000000..1c4cb20ac --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20Exception.java @@ -0,0 +1,49 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.exceptions; + +import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; + +public class OAuth20Exception extends RuntimeException { + + private static final long serialVersionUID = 1L; + + private String messageId; + + private String errorCode; + + public OAuth20Exception(final String errorCode, final String messageId, final Object[] parameters) { + super(MOAIDMessageProvider.getInstance().getMessage(messageId, parameters)); + this.errorCode = errorCode; + this.messageId = messageId; + } + + /** + * @return the messageId + */ + public String getMessageId() { + return messageId; + } + + /** + * @param messageId + * the messageId to set + */ + public void setMessageId(String messageId) { + this.messageId = messageId; + } + + /** + * @return the errorCode + */ + public String getErrorCode() { + return errorCode; + } + + /** + * @param errorCode + * the errorCode to set + */ + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidClientException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidClientException.java new file mode 100644 index 000000000..2a2ec4498 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidClientException.java @@ -0,0 +1,12 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.exceptions; + +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; + +public class OAuth20InvalidClientException extends OAuth20Exception { + private static final long serialVersionUID = 1L; + + public OAuth20InvalidClientException() { + super(OAuth20Constants.ERROR_INVALID_CLIENT, "oauth20.05", new Object[] {}); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidGrantException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidGrantException.java new file mode 100644 index 000000000..288667104 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidGrantException.java @@ -0,0 +1,12 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.exceptions; + +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; + +public class OAuth20InvalidGrantException extends OAuth20Exception { + private static final long serialVersionUID = 1L; + + public OAuth20InvalidGrantException() { + super(OAuth20Constants.ERROR_INVALID_GRANT, "oauth20.07", new Object[] {}); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidRequestException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidRequestException.java new file mode 100644 index 000000000..30c1cb1cc --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidRequestException.java @@ -0,0 +1,13 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.exceptions; + +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; + +public class OAuth20InvalidRequestException extends OAuth20Exception { + private static final long serialVersionUID = 1L; + + public OAuth20InvalidRequestException() { + super(OAuth20Constants.ERROR_INVALID_REQUEST, "oauth20.04", new Object[] {}); + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ResponseTypeException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ResponseTypeException.java new file mode 100644 index 000000000..5dd0a13c3 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ResponseTypeException.java @@ -0,0 +1,12 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.exceptions; + +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; + +public class OAuth20ResponseTypeException extends OAuth20Exception { + private static final long serialVersionUID = 1L; + + public OAuth20ResponseTypeException() { + super(OAuth20Constants.ERROR_UNSUPPORTED_RESPONSE_TYPE, "oauth20.03", new Object[] {}); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ServerErrorException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ServerErrorException.java new file mode 100644 index 000000000..59855d511 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ServerErrorException.java @@ -0,0 +1,12 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.exceptions; + +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; + +public class OAuth20ServerErrorException extends OAuth20Exception { + private static final long serialVersionUID = 1L; + + public OAuth20ServerErrorException() { + super(OAuth20Constants.ERROR_SERVER_ERROR, "oauth20.06", new Object[] {}); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20UnauthorizedClientException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20UnauthorizedClientException.java new file mode 100644 index 000000000..28cc44968 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20UnauthorizedClientException.java @@ -0,0 +1,12 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.exceptions; + +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; + +public class OAuth20UnauthorizedClientException extends OAuth20Exception { + private static final long serialVersionUID = 1L; + + public OAuth20UnauthorizedClientException() { + super(OAuth20Constants.ERROR_UNAUTHORIZED_CLIENT, "oauth20.08", new Object[] {}); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20WrongParameterException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20WrongParameterException.java new file mode 100644 index 000000000..24d151869 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20WrongParameterException.java @@ -0,0 +1,12 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.exceptions; + +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; + +public class OAuth20WrongParameterException extends OAuth20Exception { + private static final long serialVersionUID = 1L; + + public OAuth20WrongParameterException(final String name) { + super(OAuth20Constants.ERROR_INVALID_REQUEST, "oauth20.02", new Object[] { name }); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20AuthRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20AuthRequest.java new file mode 100644 index 000000000..8aac75413 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20AuthRequest.java @@ -0,0 +1,134 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.requests; + +import javax.servlet.http.HttpServletRequest; + +import at.gv.egovernment.moa.id.commons.db.dao.config.OAOAUTH20; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Util; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20AccessDeniedException; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ResponseTypeException; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20WrongParameterException; + +public class OAuth20AuthRequest extends OAuth20BaseRequest { + + private static final long serialVersionUID = 1L; + + private String responseType; + private String state; + private String redirectUri; + private String scope; + private String clientID; + + /** + * @return the responseType + */ + public String getResponseType() { + return responseType; + } + + /** + * @param responseType + * the responseType to set + */ + public void setResponseType(String responseType) { + this.responseType = responseType; + } + + /** + * @return the state + */ + public String getState() { + return state; + } + + /** + * @param state + * the state to set + */ + public void setState(String state) { + this.state = state; + } + + /** + * @return the redirectUri + */ + public String getRedirectUri() { + return redirectUri; + } + + /** + * @param redirectUri + * the redirectUri to set + */ + public void setRedirectUri(String redirectUri) { + this.redirectUri = redirectUri; + } + + /** + * @return the scope + */ + public String getScope() { + return scope; + } + + /** + * @param scope + * the scope to set + */ + public void setScope(String scope) { + this.scope = scope; + } + + /** + * @return the clientID + */ + public String getClientID() { + return clientID; + } + + /** + * @param clientID + * the clientID to set + */ + public void setClientID(String clientID) { + this.clientID = clientID; + } + + @Override + protected void populateSpecialParameters(HttpServletRequest request) throws OAuth20Exception { + this.setResponseType(this.getParam(request, OAuth20Constants.PARAM_RESPONSE_TYPE, true)); + this.setState(this.getParam(request, OAuth20Constants.PARAM_STATE, true)); + this.setRedirectUri(this.getParam(request, OAuth20Constants.PARAM_REDIRECT_URI, true)); + this.setClientID(this.getParam(request, OAuth20Constants.PARAM_CLIENT_ID, true)); + this.setScope(this.getParam(request, OAuth20Constants.PARAM_SCOPE, false)); + + // check for response type + if (!this.responseType.equals(OAuth20Constants.RESPONSE_CODE)) { + throw new OAuth20ResponseTypeException(); + } + + // check state for invalid characters (like < > & ; ... javascript ... to prevent xss) + if (!OAuth20Util.isValidStateValue(this.getState())) { + throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_STATE); + } + + // check if client id and redirect uri are ok + try { + // OAOAUTH20 cannot be null at this point. check was done in base request + OAOAUTH20 oAuthConfig = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(this.getOAURL()) + .getoAuth20Config(); + + if (!this.getClientID().equals(oAuthConfig.getOAuthClientId()) + || !this.getRedirectUri().equals(oAuthConfig.getOAuthRedirectUri())) { + throw new OAuth20AccessDeniedException(); + } + } + catch (ConfigurationException e) { + throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID); + } + + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20BaseRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20BaseRequest.java new file mode 100644 index 000000000..05362c977 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20BaseRequest.java @@ -0,0 +1,118 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.requests; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang.StringUtils; + +import at.gv.egovernment.moa.id.commons.db.dao.config.OAOAUTH20; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.moduls.RequestImpl; +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Protocol; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20InvalidRequestException; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ServerErrorException; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20WrongParameterException; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.logging.Logger; + +public abstract class OAuth20BaseRequest extends RequestImpl { + + private static final long serialVersionUID = 1L; + + protected Set allowedParameters = new HashSet(); + + protected String getParam(final HttpServletRequest request, final String name, final boolean isNeeded) throws OAuth20Exception { + String param = request.getParameter(name); + Logger.debug("Reading param " + name + " from HttpServletRequest with value " + param); + + if (isNeeded && StringUtils.isEmpty(param)) { + throw new OAuth20WrongParameterException(name); + } + + this.allowedParameters.add(name); + + return param; + } + + protected void populateParameters(final HttpServletRequest request) throws OAuth20Exception { + + // moa id - load oa with client id! + try { + String oaURL = StringEscapeUtils.escapeHtml(this.getParam(request, OAuth20Constants.PARAM_CLIENT_ID, true)); + if (!ParamValidatorUtils.isValidOA(oaURL)) { + throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID); + } + this.setOAURL(oaURL); + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(oaURL); + + if (oaParam == null) { + throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID); + } + this.setTarget(oaParam.getTarget()); + + OAOAUTH20 config = oaParam.getoAuth20Config(); + if (config == null) { + throw new OAuth20InvalidRequestException(); + } + if (StringUtils.isEmpty(config.getOAuthClientSecret()) || StringUtils.isEmpty(config.getOAuthClientId()) + || StringUtils.isEmpty(config.getOAuthRedirectUri())) { + throw new OAuth20ServerErrorException(); + } + } + catch (ConfigurationException e) { + throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID); + } + + // oAuth + this.populateSpecialParameters(request); + + // cleanup parameters + this.checkAllowedParameters(request); + } + + private void checkAllowedParameters(final HttpServletRequest request) { + Logger.debug("Going to check for allowed parameters"); + this.allowedParameters.add(OAuth20Constants.PARAM_MOA_ACTION); + this.allowedParameters.add(OAuth20Constants.PARAM_MOA_MOD); + + @SuppressWarnings("rawtypes") + Iterator iter = request.getParameterMap().keySet().iterator(); + while (iter.hasNext()) { + String name = (String) iter.next(); + if (!this.allowedParameters.contains(name)) { + + Logger.debug("Found wrong parameter: " + name); + throw new OAuth20WrongParameterException(name); + } + } + + } + + protected abstract void populateSpecialParameters(final HttpServletRequest request) throws OAuth20Exception; + + public static OAuth20BaseRequest newInstance(final String action, final HttpServletRequest request) throws OAuth20Exception { + OAuth20BaseRequest res; + + if (action.equals(OAuth20Protocol.AUTH_ACTION)) { + res = new OAuth20AuthRequest(); + } else if (action.equals(OAuth20Protocol.TOKEN_ACTION)) { + res = new OAuth20TokenRequest(); + } else { + throw new OAuth20InvalidRequestException(); + } + + res.setAction(action); + res.setModule(OAuth20Protocol.NAME); + + res.populateParameters(request); + return res; + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20TokenRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20TokenRequest.java new file mode 100644 index 000000000..6d69f8238 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20TokenRequest.java @@ -0,0 +1,118 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.requests; + +import javax.servlet.http.HttpServletRequest; + +import at.gv.egovernment.moa.id.commons.db.dao.config.OAOAUTH20; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20AccessDeniedException; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20InvalidGrantException; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20WrongParameterException; + +public class OAuth20TokenRequest extends OAuth20BaseRequest { + + private static final long serialVersionUID = 1L; + + private String code; + private String grantType; + private String clientID; + private String clientSecret; + + /** + * @return the code + */ + public String getCode() { + return code; + } + + /** + * @param code + * the code to set + */ + public void setCode(String code) { + this.code = code; + } + + /** + * @return the grantType + */ + public String getGrantType() { + return grantType; + } + + /** + * @param grantType + * the grantType to set + */ + public void setGrantType(String grantType) { + this.grantType = grantType; + } + + /** + * @return the clientID + */ + public String getClientID() { + return clientID; + } + + /** + * @param clientID + * the clientID to set + */ + public void setClientID(String clientID) { + this.clientID = clientID; + } + + /** + * @return the clientSecret + */ + public String getClientSecret() { + return clientSecret; + } + + /** + * @param clientSecret + * the clientSecret to set + */ + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } + + @Override + protected void populateSpecialParameters(HttpServletRequest request) throws OAuth20Exception { + this.setCode(this.getParam(request, OAuth20Constants.RESPONSE_CODE, true)); + this.setGrantType(this.getParam(request, OAuth20Constants.PARAM_GRANT_TYPE, true)); + this.setClientID(this.getParam(request, OAuth20Constants.PARAM_CLIENT_ID, true)); + this.setClientSecret(this.getParam(request, OAuth20Constants.PARAM_CLIENT_SECRET, true)); + + // check for grant type + if (!this.getGrantType().equals(OAuth20Constants.PARAM_GRANT_TYPE_VALUE_AUTHORIZATION_CODE)) { + throw new OAuth20InvalidGrantException(); + } + + // check if client id and secret are ok + try { + // OAOAUTH20 cannot be null at this point. check was done in base request + OAOAUTH20 oAuthConfig = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(this.getOAURL()) + .getoAuth20Config(); + + if (!this.getClientID().equals(oAuthConfig.getOAuthClientId())) { + throw new OAuth20AccessDeniedException(); + } + + if (!this.getClientSecret().equals(oAuthConfig.getOAuthClientSecret())) { + throw new OAuth20AccessDeniedException(); + } + + } + catch (ConfigurationException e) { + throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID); + } + + //add valid parameters + this.allowedParameters.add(OAuth20Constants.PARAM_SCOPE); + this.allowedParameters.add(OAuth20Constants.PARAM_REDIRECT_URI); + } +} -- cgit v1.2.3 From d7404bc44ae84df98031a87052ff2d71ac960bd1 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 7 Jan 2014 11:03:11 +0100 Subject: short Bugfixes, but not complete --- .../auth/builder/StartAuthenticationBuilder.java | 4 ++-- .../id/protocols/oauth20/OAuth20TokenAction.java | 25 ++++++++++++---------- .../id/storage/AuthenticationSessionStoreage.java | 1 + 3 files changed, 17 insertions(+), 13 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java index c616d94b3..91040dde2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java @@ -44,13 +44,13 @@ public class StartAuthenticationBuilder { AuthenticationServer.startSTORKAuthentication(req, resp, moasession); return ""; - } else {*/ + } else { //normal MOA-ID authentication Logger.debug("Starting normal MOA-ID authentication"); String getIdentityLinkForm = AuthenticationServer.getInstance().startAuthentication(moasession, req); return getIdentityLinkForm; - //} + } } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20TokenAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20TokenAction.java index 70f425148..d66f9cb2a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20TokenAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20TokenAction.java @@ -27,6 +27,7 @@ import at.gv.egovernment.moa.id.auth.builder.BPKBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.BuildException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; @@ -111,7 +112,7 @@ public class OAuth20TokenAction implements IAction { OAuth20Util.addProperytiesToJsonObject(jsonObject, params); String jsonResponse = jsonObject.toString(); Logger.debug("JSON Response: " + jsonResponse); - + // write respone to http response httpResp.setContentType("application/json"); httpResp.setStatus(HttpServletResponse.SC_OK); @@ -124,18 +125,20 @@ public class OAuth20TokenAction implements IAction { throw new OAuth20ServerErrorException(); } finally { - if (session != null) { - // destroy session for clean up - try { - Logger.debug("Going to destroy session: " + session.getSessionID()); - AuthenticationSessionStoreage.destroySession(session.getSessionID()); - } - catch (MOADatabaseException e) { - } - } + ConfigurationDBUtils.closeSession(); + +// if (session != null) { +// // destroy session for clean up +// try { +// Logger.debug("Going to destroy session: " + session.getSessionID()); +// AuthenticationSessionStoreage.destroySession(session.getSessionID()); +// } +// catch (MOADatabaseException e) { +// } +// } } } - + /* * (non-Javadoc) * @see diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java index e40d11128..d0c28538c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java @@ -209,6 +209,7 @@ public class AuthenticationSessionStoreage { //Assertion requires an unique artifact if (result.size() != 1) { Logger.trace("No entries found."); + tx.commit(); throw new MOADatabaseException("No session found with this sessionID"); } -- cgit v1.2.3 From 8b4b3a97cdbdfc4158781982f6e9fc2900871198 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 17 Jan 2014 11:56:10 +0100 Subject: Exthex Version 0.2 --- .../moa/id/auth/AuthenticationServer.java | 58 ++++----- .../AuthenticationBlockAssertionBuilder.java | 17 +-- .../moa/id/auth/builder/PersonDataBuilder.java | 12 +- .../auth/builder/StartAuthenticationBuilder.java | 7 +- .../servlet/GenerateIFrameTemplateServlet.java | 18 +-- .../moa/id/auth/servlet/GetForeignIDServlet.java | 6 - .../moa/id/auth/servlet/LogOutServlet.java | 16 +-- .../moa/id/auth/stork/STORKResponseProcessor.java | 6 - .../id/config/auth/AuthConfigurationProvider.java | 16 +-- .../moa/id/entrypoints/DispatcherServlet.java | 5 +- .../gv/egovernment/moa/id/moduls/ModulStorage.java | 2 +- .../gv/egovernment/moa/id/moduls/SSOManager.java | 140 +++++++++++---------- .../moa/id/protocols/oauth20/OAuth20Constants.java | 4 +- .../id/protocols/oauth20/OAuth20SessionObject.java | 12 ++ .../moa/id/protocols/oauth20/OAuth20Util.java | 73 +++-------- .../pvp2x/builder/PVPAttributeBuilder.java | 45 +++++-- .../builder/assertion/PVP2AssertionBuilder.java | 21 +--- .../builder/attributes/BPKAttributeBuilder.java | 31 +++-- .../attributes/BirthdateAttributeBuilder.java | 40 +++--- .../pvp2x/builder/attributes/EIDAuthBlock.java | 36 +++--- .../pvp2x/builder/attributes/EIDCcsURL.java | 21 ++-- .../EIDCitizenQAALevelAttributeBuilder.java | 15 ++- .../builder/attributes/EIDIdentityLinkBuilder.java | 22 ++-- .../EIDIssuingNationAttributeBuilder.java | 15 ++- .../attributes/EIDSectorForIDAttributeBuilder.java | 15 ++- .../builder/attributes/EIDSignerCertificate.java | 21 ++-- .../pvp2x/builder/attributes/EIDSourcePIN.java | 21 ++-- .../pvp2x/builder/attributes/EIDSourcePINType.java | 23 ++-- .../attributes/GivenNameAttributeBuilder.java | 15 ++- .../builder/attributes/IAttributeBuilder.java | 12 +- .../MandateFullMandateAttributeBuilder.java | 17 ++- ...MandateLegalPersonFullNameAttributeBuilder.java | 40 +++--- ...andateLegalPersonSourcePinAttributeBuilder.java | 27 ++-- ...teLegalPersonSourcePinTypeAttributeBuilder.java | 59 ++++----- .../MandateNaturalPersonBPKAttributeBuilder.java | 70 +++++------ ...dateNaturalPersonBirthDateAttributeBuilder.java | 58 ++++----- ...ateNaturalPersonFamilyNameAttributeBuilder.java | 23 ++-- ...dateNaturalPersonGivenNameAttributeBuilder.java | 41 +++--- ...dateNaturalPersonSourcePinAttributeBuilder.java | 27 ++-- ...NaturalPersonSourcePinTypeAttributeBuilder.java | 27 ++-- .../MandateProfRepDescAttributeBuilder.java | 19 ++- .../MandateProfRepOIDAttributeBuilder.java | 36 +++--- .../MandateReferenceValueAttributeBuilder.java | 34 +++-- .../attributes/MandateTypeAttributeBuilder.java | 32 ++--- .../attributes/PVPVersionAttributeBuilder.java | 21 ++-- .../attributes/PrincipalNameAttributeBuilder.java | 23 ++-- .../pvp2x/requestHandler/AuthnRequestHandler.java | 14 +-- .../verification/MetadataSignatureFilter.java | 6 +- .../id/storage/AuthenticationSessionStoreage.java | 1 - 49 files changed, 591 insertions(+), 729 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java index 014a9ec03..af23d4c78 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java @@ -1155,14 +1155,7 @@ public class AuthenticationServer implements MOAIDAuthConstants { CreateXMLSignatureResponse csresp = new CreateXMLSignatureResponseParser( xmlCreateXMLSignatureReadResponse).parseResponse(); - - Element signature = csresp.getDsigSignature(); - - try { - String test = DOMUtils.serializeNode(signature); - - String serializedAssertion = DOMUtils.serializeNode(csresp .getSamlAssertion()); session.setAuthBlock(serializedAssertion); @@ -1695,36 +1688,37 @@ public class AuthenticationServer implements MOAIDAuthConstants { * @param signature XMLDSIG signature * @return Identity link assertion * @throws SZRGWClientException - * @throws ConfigurationException */ - public CreateIdentityLinkResponse getIdentityLink(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, Element signature) throws SZRGWClientException, ConfigurationException { + public CreateIdentityLinkResponse getIdentityLink(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, Element signature) throws SZRGWClientException { SZRGWClient client = new SZRGWClient(); - AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); - ConnectionParameter connectionParameters = authConf.getForeignIDConnectionParameter(); - - client.setAddress(connectionParameters.getUrl()); - if (connectionParameters.getUrl().toLowerCase().startsWith("https:")) { - Logger.debug("Initialisiere SSL Verbindung"); - try { - client.setSSLSocketFactory(SSLUtils.getSSLSocketFactory(AuthConfigurationProvider.getInstance(), connectionParameters)); - - } catch (IOException e) { - Logger.error("Could not initialize SSL Factory", e); - throw new SZRGWClientException("Could not initialize SSL Factory"); - - } catch (GeneralSecurityException e) { - Logger.error("Could not initialize SSL Factory", e); - throw new SZRGWClientException("Could not initialize SSL Factory"); - - } catch (PKIException e) { - Logger.error("Could not initialize SSL Factory", e); - throw new SZRGWClientException("Could not initialize SSL Factory"); - } - } - + try { + AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); + ConnectionParameter connectionParameters = authConf.getForeignIDConnectionParameter(); + + client.setAddress(connectionParameters.getUrl()); + if (connectionParameters.getUrl().toLowerCase().startsWith("https:")) { + Logger.debug("Initialisiere SSL Verbindung"); + try { + client.setSSLSocketFactory(SSLUtils.getSSLSocketFactory(AuthConfigurationProvider.getInstance(), connectionParameters)); + } catch (IOException e) { + Logger.error("Could not initialize SSL Factory", e); + throw new SZRGWClientException("Could not initialize SSL Factory"); + } catch (GeneralSecurityException e) { + Logger.error("Could not initialize SSL Factory", e); + throw new SZRGWClientException("Could not initialize SSL Factory"); + } catch (PKIException e) { + Logger.error("Could not initialize SSL Factory", e); + throw new SZRGWClientException("Could not initialize SSL Factory"); + } + } Logger.info("Starte Kommunikation mit dem Stammzahlenregister Gateway(" + connectionParameters.getUrl() + ")..."); + } + catch (ConfigurationException e) { + Logger.warn(e); + Logger.warn(MOAIDMessageProvider.getInstance().getMessage("config.12", null )); + } // create request CreateIdentityLinkResponse response = null; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java index 3a308f6da..f5d603480 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java @@ -190,22 +190,9 @@ public class AuthenticationBlockAssertionBuilder extends AuthenticationAssertion gebeORwbpk = MessageFormat.format(WBPK_ATTRIBUTE, new Object[] { identityLinkValue, identityLinkType }); wbpkNSDeclaration = " xmlns:pr=\"" + PD_NS_URI + "\""; - //adding type of wbPK domain identifier - - String idtype = oaParam.getIdentityLinkDomainIdentifierType(); - if (MiscUtil.isEmpty(idtype)) { - if (identityLinkType.contains("FN")) - idtype = "Firmenbuchnummer"; - else if (identityLinkType.contains("ZVR")) - idtype = "Vereinsnummer"; - else if (identityLinkType.contains("ERSB")) - idtype = "ERJPZahl"; - else - idtype = "Bereichskennung"; - } - + //adding type of wbPK domain identifier ExtendedSAMLAttribute idLinkDomainIdentifierTypeAttribute = - new ExtendedSAMLAttributeImpl("IdentityLinkDomainIdentifierType", idtype, Constants.MOA_NS_URI, ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY); + new ExtendedSAMLAttributeImpl("IdentityLinkDomainIdentifierType", oaParam.getIdentityLinkDomainIdentifierType(), Constants.MOA_NS_URI, ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY); extendedSAMLAttributes.add(idLinkDomainIdentifierTypeAttribute); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/PersonDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/PersonDataBuilder.java index 5d94d2f16..fd5ff6744 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/PersonDataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/PersonDataBuilder.java @@ -27,11 +27,8 @@ package at.gv.egovernment.moa.id.auth.builder; import org.w3c.dom.Element; import org.w3c.dom.Node; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.IdentityLink; import at.gv.egovernment.moa.id.auth.exception.BuildException; -import at.gv.egovernment.moa.id.commons.db.dao.config.MOAIDConfiguration; -import at.gv.egovernment.moa.util.Constants; import at.gv.egovernment.moa.util.DOMUtils; import at.gv.egovernment.moa.util.XPathUtils; @@ -68,12 +65,9 @@ public class PersonDataBuilder { try { Element prPerson = (Element)identityLink.getPrPerson().cloneNode(true); - - Node prType = XPathUtils.selectSingleNode(prPerson, "pr:Identification/pr:Type"); - - if (! provideStammzahl && - Constants.URN_PREFIX_BASEID.equals(prType.getFirstChild().getNodeValue())) { - Node prIdentification = XPathUtils.selectSingleNode(prPerson, "pr:Identification/pr:Value"); + if (! provideStammzahl) { + Node prIdentification = XPathUtils.selectSingleNode(prPerson, "pr:Identification/pr:Value"); + //remove IdentificationValue prIdentification.getFirstChild().setNodeValue(""); } String xmlString = DOMUtils.serializeNode(prPerson); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java index 91040dde2..e4bf37417 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java @@ -36,7 +36,8 @@ public class StartAuthenticationBuilder { Logger.info("Starting authentication for a citizen of country: " + (StringUtils.isEmpty(moasession.getCcc()) ? "AT" : moasession.getCcc())); // STORK or normal authentication - if (storkConfig != null && storkConfig.isSTORKAuthentication(moasession.getCcc())) { + //TODO: commented because npe was thrown + /*if (storkConfig.isSTORKAuthentication(moasession.getCcc())) { //STORK authentication Logger.trace("Found C-PEPS configuration for citizen of country: " + moasession.getCcc()); Logger.debug("Starting STORK authentication"); @@ -44,13 +45,13 @@ public class StartAuthenticationBuilder { AuthenticationServer.startSTORKAuthentication(req, resp, moasession); return ""; - } else { + } else {*/ //normal MOA-ID authentication Logger.debug("Starting normal MOA-ID authentication"); String getIdentityLinkForm = AuthenticationServer.getInstance().startAuthentication(moasession, req); return getIdentityLinkForm; - } + //} } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java index eaa6ac1ae..98ef78d53 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java @@ -32,16 +32,16 @@ public class GenerateIFrameTemplateServlet extends AuthServlet { private static final long serialVersionUID = 1L; public void init(ServletConfig servletConfig) throws ServletException { -// try { + try { super.init(servletConfig); -// MOAIDAuthInitializer.initialize(); -// Logger.debug("default platform file.encoding: " + System.getProperty("file.encoding")); -// Logger.info(MOAIDMessageProvider.getInstance().getMessage("init.00", null)); -// } -// catch (Exception ex) { -// Logger.fatal(MOAIDMessageProvider.getInstance().getMessage("init.02", null), ex); -// throw new ServletException(ex); -// } + MOAIDAuthInitializer.initialize(); + Logger.debug("default platform file.encoding: " + System.getProperty("file.encoding")); + Logger.info(MOAIDMessageProvider.getInstance().getMessage("init.00", null)); + } + catch (Exception ex) { + Logger.fatal(MOAIDMessageProvider.getInstance().getMessage("init.02", null), ex); + throw new ServletException(ex); + } } protected void doGet(HttpServletRequest req, HttpServletResponse resp) diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java index 07d006bc2..222faec37 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java @@ -156,15 +156,9 @@ public class GetForeignIDServlet extends AuthServlet { try { session.setSignerCertificate(AuthenticationServer.getCertificateFromXML(signature)); - - //String test = DOMUtils.serializeNode(signature); - } catch (CertificateException e) { Logger.error("Could not extract certificate from CreateXMLSignatureResponse"); throw new MOAIDException("auth.14", null); -// } catch (TransformerException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); } // make SZR request to the identity link diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/LogOutServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/LogOutServlet.java index ff8265ac3..9c72cfff2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/LogOutServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/LogOutServlet.java @@ -101,15 +101,15 @@ public class LogOutServlet extends AuthServlet { * @see javax.servlet.Servlet#init(ServletConfig) */ public void init(ServletConfig servletConfig) throws ServletException { -// try { + try { super.init(servletConfig); -// MOAIDAuthInitializer.initialize(); -// Logger.info(MOAIDMessageProvider.getInstance().getMessage("init.00", null)); -// } -// catch (Exception ex) { -// Logger.fatal(MOAIDMessageProvider.getInstance().getMessage("init.02", null), ex); -// throw new ServletException(ex); -// } + MOAIDAuthInitializer.initialize(); + Logger.info(MOAIDMessageProvider.getInstance().getMessage("init.00", null)); + } + catch (Exception ex) { + Logger.fatal(MOAIDMessageProvider.getInstance().getMessage("init.02", null), ex); + throw new ServletException(ex); + } } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java index c0626e84a..a87e9a8c0 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java @@ -35,7 +35,6 @@ import at.gv.egovernment.moa.id.auth.exception.ParseException; import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.CreateIdentityLinkResponse; import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClientException; -import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; import at.gv.egovernment.moa.util.DateTimeUtils; @@ -349,14 +348,9 @@ public class STORKResponseProcessor { } catch (SZRGWClientException e) { Logger.error("Error connecting SZR-Gateway: ", e); throw new STORKException("Error connecting SZR-Gateway: ", e); - } catch (ParseException e) { Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e); throw new STORKException("Error parsing IdentityLink received from SZR-Gateway: ", e); - - } catch (ConfigurationException e) { - Logger.error("Error connecting SZR-Gateway: ", e); - throw new STORKException("Error connecting SZR-Gateway: ", e); } return identityLink; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java index 4507cd236..29f567324 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java @@ -417,25 +417,24 @@ public class AuthConfigurationProvider extends ConfigurationProvider { public synchronized void reloadDataBaseConfig() throws ConfigurationException { - Logger.info("Read MOA-ID 2.x configuration from database."); + Logger.info("Read MOA-ID 2.0 configuration from database."); moaidconfig = ConfigurationDBRead.getMOAIDConfiguration(); + Logger.info("MOA-ID 2.0 is loaded."); if (moaidconfig == null) { Logger.warn("NO MOA-ID configuration found."); throw new ConfigurationException("config.18", null); } - - Logger.debug("MOA-ID 2.x configuration is loaded from database."); - Logger.info("MOA-ID 2.x starts initialization process ..."); - + //build STORK Config AuthComponentGeneral auth = getAuthComponentGeneral(); - ForeignIdentities foreign = auth.getForeignIdentities(); if (foreign == null ) { Logger.warn("Error in MOA-ID Configuration. No STORK configuration found."); - } //else + } + //TODO: commented because npe was thrown + //else //storkconfig = new STORKConfig(foreign.getSTORK(), props, rootConfigFileDir); @@ -787,9 +786,6 @@ public class AuthConfigurationProvider extends ConfigurationProvider { * @throws ConfigurationException */ public ConnectionParameter getForeignIDConnectionParameter() throws ConfigurationException { - if (ForeignIDConnectionParameter == null) - throw new ConfigurationException("config.20", null); - return ForeignIDConnectionParameter; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java index c8f14585a..7130089ae 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java @@ -262,7 +262,7 @@ public class DispatcherServlet extends AuthServlet{ for (String el : mapkeys) { IRequest value = protocolRequests.get(el); - if (value.getOAURL() != null && value.getOAURL().equals(protocolRequest.getOAURL())) { + if (value.getOAURL().equals(protocolRequest.getOAURL())) { if(!AuthenticationSessionStoreage.deleteSessionWithPendingRequestID(el)) { Logger.warn(DispatcherServlet.class.getName()+": NO MOASession with PendingRequestID " + el + " found. Delete all user sessions!"); @@ -423,6 +423,9 @@ public class DispatcherServlet extends AuthServlet{ moasession = AuthenticationSessionStoreage.getSession(moasessionID); moasessionID = AuthenticationSessionStoreage.changeSessionID(moasession); } + + + } String assertionID = moduleAction.processRequest(protocolRequest, req, resp, moasession); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.java index 31bf1ff58..d030b8844 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.java @@ -11,7 +11,7 @@ public class ModulStorage { private static final String[] modulClasses = new String[]{ "at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol", "at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol", - "at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Protocol" + "at.gv.egovernment.moa.id.protocols.oauth20.protocol.OAuth20Protocol" }; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java index 7008239ab..0693aef8c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java @@ -23,41 +23,41 @@ public class SSOManager { private static final String SSOCOOKIE = "MOA_ID_SSO"; - private static final int DEFAULTSSOTIMEOUT = 15*60; //sec + private static final int DEFAULTSSOTIMEOUT = 15 * 60; // sec private static SSOManager instance = null; private static int sso_timeout; - public static SSOManager getInstance() { if (instance == null) { instance = new SSOManager(); try { sso_timeout = (int) AuthConfigurationProvider.getInstance().getTimeOuts().getMOASessionUpdated().longValue(); - - } catch (ConfigurationException e) { + + } + catch (ConfigurationException e) { Logger.info("SSO Timeout can not be loaded from MOA-ID configuration. Use default Timeout with " + DEFAULTSSOTIMEOUT); sso_timeout = DEFAULTSSOTIMEOUT; } - + } return instance; } public boolean isValidSSOSession(String ssoSessionID, HttpServletRequest httpReq) { - - //search SSO Session + + // search SSO Session if (ssoSessionID == null) { Logger.info("No SSO Session cookie found."); - return false; + return false; } -// String moaSessionId =HTTPSessionUtils.getHTTPSessionString(httpReq.getSession(), -// AuthenticationManager.MOA_SESSION, null); + // String moaSessionId =HTTPSessionUtils.getHTTPSessionString(httpReq.getSession(), + // AuthenticationManager.MOA_SESSION, null); - return AuthenticationSessionStoreage.isValidSessionWithSSOID(ssoSessionID, null); + return AuthenticationSessionStoreage.isValidSessionWithSSOID(ssoSessionID, null); } @@ -67,51 +67,65 @@ public class SSOManager { public String existsOldSSOSession(String ssoId) { - Logger.trace("Check that the SSOID has already been used"); - Session session = MOASessionDBUtils.getCurrentSession(); - - List result; - - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getSSOSessionWithOldSessionID"); - query.setString("sessionid", ssoId); - result = query.list(); - - //send transaction - - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() == 0) { - session.getTransaction().commit(); - return null; - } - - OldSSOSessionIDStore oldSSOSession = result.get(0); - - AuthenticatedSessionStore correspondingMoaSession = oldSSOSession.getMoasession(); - - if (correspondingMoaSession == null) { - Logger.info("Get request with old SSO SessionID but no corresponding SSO Session is found."); - return null; - } - - - String moasessionid = correspondingMoaSession.getSessionid(); - - session.getTransaction().commit(); + Logger.trace("Check that the SSOID has already been used"); + Session session = MOASessionDBUtils.getCurrentSession(); + + List result; + + synchronized (session) { - return moasessionid; - +// try { +// session.getTransaction().rollback(); +// } +// catch (Exception e) { +// e.printStackTrace(); +// } +// try { +// session.getSessionFactory().openSession(); +// } +// catch (Exception e) { +// e.printStackTrace(); +// } + // session.getTransaction().begin(); + + session.beginTransaction(); + Query query = session.getNamedQuery("getSSOSessionWithOldSessionID"); + query.setString("sessionid", ssoId); + result = query.list(); + + // send transaction + + } + + Logger.trace("Found entries: " + result.size()); + + // Assertion requires an unique artifact + if (result.size() == 0) { + session.getTransaction().commit(); + return null; + } + + OldSSOSessionIDStore oldSSOSession = result.get(0); + + AuthenticatedSessionStore correspondingMoaSession = oldSSOSession.getMoasession(); + + if (correspondingMoaSession == null) { + Logger.info("Get request with old SSO SessionID but no corresponding SSO Session is found."); + return null; + } + + String moasessionid = correspondingMoaSession.getSessionid(); + + session.getTransaction().commit(); + + return moasessionid; + } public String createSSOSessionInformations(String moaSessionID, String OAUrl) { String newSSOId = Random.nextRandom(); - + System.out.println("generate new SSO Tokken (" + newSSOId + ")"); if (MiscUtil.isEmpty(moaSessionID) || MiscUtil.isEmpty(OAUrl)) { @@ -123,32 +137,30 @@ public class SSOManager { } - public void setSSOSessionID(HttpServletRequest httpReq, HttpServletResponse httpResp, String ssoId) { Cookie[] cookies = httpReq.getCookies(); if (cookies != null) { - deleteSSOSessionID(httpReq, httpResp); + deleteSSOSessionID(httpReq, httpResp); } Cookie cookie = new Cookie(SSOCOOKIE, ssoId); cookie.setMaxAge(sso_timeout); cookie.setSecure(true); - cookie.setPath(httpReq.getContextPath()); - httpResp.addCookie(cookie); + cookie.setPath(httpReq.getContextPath()); + httpResp.addCookie(cookie); } - - public String getSSOSessionID(HttpServletRequest httpReq) { - Cookie[] cookies = httpReq.getCookies(); + Cookie[] cookies = httpReq.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { - //funktioniert nicht, da Cookie seltsamerweise immer unsecure übertragen wird (firefox) - //if (cookie.getName().equals(SSOCOOKIE) && cookie.getSecure()) { - + // funktioniert nicht, da Cookie seltsamerweise immer unsecure übertragen wird + // (firefox) + // if (cookie.getName().equals(SSOCOOKIE) && cookie.getSecure()) { + if (cookie.getName().equals(SSOCOOKIE)) { return cookie.getValue(); } @@ -158,14 +170,12 @@ public class SSOManager { } public void deleteSSOSessionID(HttpServletRequest httpReq, HttpServletResponse httpResp) { - Cookie[] cookies = httpReq.getCookies(); - + Cookie[] cookies = httpReq.getCookies(); + if (cookies != null) { for (Cookie cookie : cookies) { - if (!cookie.getName().equals(SSOCOOKIE)) - httpResp.addCookie(cookie); + if (!cookie.getName().equals(SSOCOOKIE)) httpResp.addCookie(cookie); } } } } - diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Constants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Constants.java index 8189aa01b..9466c9faf 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Constants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Constants.java @@ -1,9 +1,9 @@ package at.gv.egovernment.moa.id.protocols.oauth20; -public class OAuth20Constants { +public final class OAuth20Constants { private OAuth20Constants() { - + throw new InstantiationError(); } // error parameters and error codes diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java index 91c099d2c..20711373e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java @@ -2,6 +2,8 @@ package at.gv.egovernment.moa.id.protocols.oauth20; import java.io.Serializable; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; + public class OAuth20SessionObject implements Serializable { /** @@ -13,6 +15,8 @@ public class OAuth20SessionObject implements Serializable { private String code; + private AuthenticationSession authDataSession; + public String getScope() { return scope; } @@ -36,4 +40,12 @@ public class OAuth20SessionObject implements Serializable { this.code = code; } + public AuthenticationSession getAuthDataSession() { + return authDataSession; + } + + public void setAuthDataSession(AuthenticationSession authDataSession) { + this.authDataSession = authDataSession; + } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Util.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Util.java index 4d3030a0f..11b798d00 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Util.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Util.java @@ -1,33 +1,23 @@ package at.gv.egovernment.moa.id.protocols.oauth20; import java.io.UnsupportedEncodingException; -import java.security.KeyStore; -import java.security.PrivateKey; -import java.security.cert.X509Certificate; -import java.security.interfaces.RSAPrivateKey; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; -import net.oauth.jsontoken.crypto.RsaSHA256Signer; -import net.oauth.jsontoken.crypto.Signer; - -import org.opensaml.xml.security.x509.BasicX509Credential; - -import at.gv.egovernment.moa.id.commons.db.dao.config.OAOAUTH20; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20CertificateErrorException; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.KeyStoreUtils; -import at.gv.egovernment.moa.util.StringUtils; +import org.apache.commons.lang.StringUtils; import com.google.gson.JsonObject; -public class OAuth20Util { +public final class OAuth20Util { public static final String REGEX_HTTPS = "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; public static final String REGEX_FILE = "^(file):/.[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; + private OAuth20Util() { + throw new InstantiationError(); + } + /** * Simple helper function to add parameter to a url * @@ -59,9 +49,16 @@ public class OAuth20Util { return matcher.find(); } + public static boolean isValidStateValue(String state) { + Pattern urlPattern = Pattern.compile("javascript|<|>|&|;", Pattern.CASE_INSENSITIVE); + Matcher matcher = urlPattern.matcher(state); + return !matcher.find(); + } + public static void addProperytiesToJsonObject(JsonObject jsonObject, Map params) { for (Map.Entry param : params.entrySet()) { - if (param.getKey() != null && !"".equals(param.getKey()) && param.getValue() != null && !"".equals(param.getValue())) { + + if (!StringUtils.isEmpty(param.getKey()) && param.getValue() != null) { // check for integer try { @@ -89,46 +86,4 @@ public class OAuth20Util { } } - public static Signer loadSigner(String issuer) throws OAuth20Exception { - OAuth20Configuration globalConfig = OAuth20Configuration.getInstance(); - - if (StringUtils.isEmpty(globalConfig.getJWTKeyStore())) { - throw new OAuth20CertificateErrorException("keystore"); - } - - if (StringUtils.isEmpty(globalConfig.getJWTKeyName())) { - throw new OAuth20CertificateErrorException("key name"); - } - - try { - KeyStore ks = KeyStoreUtils.loadKeyStore(globalConfig.getJWTKeyStore(), globalConfig.getJWTKeyStorePassword()); - - X509Certificate certificate = (X509Certificate) ks.getCertificate(globalConfig.getJWTKeyName()); - - PrivateKey privateKey = (PrivateKey) ks.getKey(globalConfig.getJWTKeyName(), globalConfig.getJWTKeyPassword() - .toCharArray()); - BasicX509Credential credential = new BasicX509Credential(); - credential.setEntityCertificate(certificate); - credential.setPrivateKey(privateKey); - - //Logger.debug("Going to use X509Certificate:"); - Logger.debug(certificate); - //Logger.debug("Going to use private key:"); - Logger.debug(privateKey); - - return new RsaSHA256Signer(issuer, globalConfig.getJWTKeyName(), (RSAPrivateKey) credential.getPrivateKey()); - - } - catch (Exception e) { - throw new OAuth20CertificateErrorException("keystore"); - } - - } - - public static boolean isValidStateValue(String state) { - Pattern urlPattern = Pattern.compile("javascript|<|>|&|;", Pattern.CASE_INSENSITIVE); - Matcher matcher = urlPattern.matcher(state); - return !matcher.find(); - } - } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java index 9403cb205..054f87e18 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java @@ -23,6 +23,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDSourcePIN; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDSourcePINType; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.GivenNameAttributeBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeGenerator; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateFullMandateAttributeBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateLegalPersonFullNameAttributeBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateLegalPersonSourcePinAttributeBuilder; @@ -39,16 +40,26 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateRefere import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateTypeAttributeBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.PVPVersionAttributeBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.PrincipalNameAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.SamlAttributeGenerator; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.InvalidDateFormatAttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.InvalidDateFormatException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.UnprovideableAttributeException; public class PVPAttributeBuilder { - + + private static IAttributeGenerator generator = new SamlAttributeGenerator(); + private static HashMap builders; - + private static void addBuilder(IAttributeBuilder builder) { builders.put(builder.getName(), builder); } - + static { builders = new HashMap(); // Citizen Token normal @@ -84,27 +95,39 @@ public class PVPAttributeBuilder { addBuilder(new MandateReferenceValueAttributeBuilder()); addBuilder(new MandateFullMandateAttributeBuilder()); } - - public static Attribute buildAttribute(String name, - AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) throws PVP2Exception { + + public static Attribute buildAttribute(String name, AuthenticationSession authSession, OAAuthParameter oaParam, + AuthenticationData authData) throws PVP2Exception { if (builders.containsKey(name)) { - return builders.get(name).build(authSession, oaParam, authData); + try { + return builders.get(name).build(authSession, oaParam, authData, generator); + } + catch (AttributeException e) { + if (e instanceof UnavailableAttributeException) { + throw new UnprovideableAttributeException(((UnavailableAttributeException) e).getAttributeName()); + } else if (e instanceof InvalidDateFormatAttributeException) { + throw new InvalidDateFormatException(); + } else if (e instanceof NoMandateDataAttributeException) { + throw new NoMandateDataAvailableException(); + } else { + throw new UnprovideableAttributeException(name); + } + } } return null; } - + public static List buildSupportedEmptyAttributes() { List attributes = new ArrayList(); Iterator builderIt = builders.values().iterator(); while (builderIt.hasNext()) { IAttributeBuilder builder = builderIt.next(); - Attribute emptyAttribute = builder.buildEmpty(); + Attribute emptyAttribute = builder.buildEmpty(generator); if (emptyAttribute != null) { attributes.add(emptyAttribute); } } return attributes; } - + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java index f21567245..5e8206739 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java @@ -21,7 +21,6 @@ import org.opensaml.saml2.core.RequestedAuthnContext; import org.opensaml.saml2.core.Subject; import org.opensaml.saml2.core.SubjectConfirmation; import org.opensaml.saml2.core.SubjectConfirmationData; -import org.opensaml.saml2.metadata.AssertionConsumerService; import org.opensaml.saml2.metadata.AttributeConsumingService; import org.opensaml.saml2.metadata.EntityDescriptor; import org.opensaml.saml2.metadata.NameIDFormat; @@ -43,7 +42,6 @@ import at.gv.egovernment.moa.id.data.AuthenticationData; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.InvalidAssertionConsumerServiceException; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NameIDFormatNotSupportedException; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoAuthContextException; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; @@ -295,16 +293,7 @@ public class PVP2AssertionBuilder implements PVPConstants { .createSAMLObject(SubjectConfirmationData.class); subjectConfirmationData.setInResponseTo(authnRequest.getID()); subjectConfirmationData.setNotOnOrAfter(new DateTime().plusMinutes(20)); - - //TL: change from entityID to destination URL - AssertionConsumerService consumerService = spSSODescriptor - .getAssertionConsumerServices().get(idx); - - if (consumerService == null) { - throw new InvalidAssertionConsumerServiceException(idx); - } - - subjectConfirmationData.setRecipient(consumerService.getLocation()); + subjectConfirmationData.setRecipient(peerEntity.getEntityID()); subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData); @@ -314,7 +303,7 @@ public class PVP2AssertionBuilder implements PVPConstants { AudienceRestriction audienceRestriction = SAML2Utils .createSAMLObject(AudienceRestriction.class); Audience audience = SAML2Utils.createSAMLObject(Audience.class); - + audience.setAudienceURI(peerEntity.getEntityID()); audienceRestriction.getAudiences().add(audience); conditions.setNotBefore(new DateTime()); @@ -327,12 +316,8 @@ public class PVP2AssertionBuilder implements PVPConstants { assertion.setConditions(conditions); Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); - - //TODO: check! - //change to entity value from entity name to IDP EntityID (URL) - issuer.setValue(PVPConfiguration.getInstance().getIDPPublicPath()); + issuer.setValue(PVPConfiguration.getInstance().getIDPIssuerName()); issuer.setFormat(NameID.ENTITY); - assertion.setIssuer(issuer); assertion.setSubject(subject); assertion.setID(SAML2Utils.getSecureIdentifier()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BPKAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BPKAttributeBuilder.java index bb568cd90..f5f84a322 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BPKAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BPKAttributeBuilder.java @@ -1,41 +1,38 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; - import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; -public class BPKAttributeBuilder extends BaseAttributeBuilder { - +public class BPKAttributeBuilder implements IPVPAttributeBuilder { + public String getName() { return BPK_NAME; } - - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) { + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { String bpk = authData.getBPK(); String type = authData.getBPKType(); if (type.startsWith(Constants.URN_PREFIX_WBPK)) - type = type.substring((Constants.URN_PREFIX_WBPK+"+").length()); - else if (type.startsWith(Constants.URN_PREFIX_CDID)) - type = type.substring((Constants.URN_PREFIX_CDID+"+").length()); - - if(bpk.length() > BPK_MAX_LENGTH) { + type = type.substring((Constants.URN_PREFIX_WBPK + "+").length()); + else if (type.startsWith(Constants.URN_PREFIX_CDID)) type = type.substring((Constants.URN_PREFIX_CDID + "+").length()); + + if (bpk.length() > BPK_MAX_LENGTH) { bpk = bpk.substring(0, BPK_MAX_LENGTH); } Logger.trace("Authenticate user with bPK/wbPK " + bpk + " and Type=" + type); - return buildStringAttribute(BPK_FRIENDLY_NAME, BPK_NAME, type + ":" + bpk); + return g.buildStringAttribute(BPK_FRIENDLY_NAME, BPK_NAME, type + ":" + bpk); } - - public Attribute buildEmpty() { - return buildemptyAttribute(BPK_FRIENDLY_NAME, BPK_NAME); + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(BPK_FRIENDLY_NAME, BPK_NAME); } - + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BirthdateAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BirthdateAttributeBuilder.java index fa42fc54f..ef594b91c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BirthdateAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BirthdateAttributeBuilder.java @@ -5,41 +5,39 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; -import org.opensaml.saml2.core.Attribute; - import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -public class BirthdateAttributeBuilder extends BaseAttributeBuilder { - +public class BirthdateAttributeBuilder implements IPVPAttributeBuilder { + public static final String IDENTITY_LINK_DATE_FORMAT = "yyyy-MM-dd"; - + public String getName() { return BIRTHDATE_NAME; } - - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) { + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { try { - DateFormat identityLinkFormat = new SimpleDateFormat( - IDENTITY_LINK_DATE_FORMAT); - Date date = identityLinkFormat.parse(authSession.getIdentityLink() - .getDateOfBirth()); - DateFormat pvpDateFormat = new SimpleDateFormat( - BIRTHDATE_FORMAT_PATTERN); + DateFormat identityLinkFormat = new SimpleDateFormat(IDENTITY_LINK_DATE_FORMAT); + Date date = identityLinkFormat.parse(authSession.getIdentityLink().getDateOfBirth()); + DateFormat pvpDateFormat = new SimpleDateFormat(BIRTHDATE_FORMAT_PATTERN); String dateString = pvpDateFormat.format(date); - return buildStringAttribute(BIRTHDATE_FRIENDLY_NAME, - BIRTHDATE_NAME, dateString); - } catch (ParseException e) { + + return g.buildStringAttribute(BIRTHDATE_FRIENDLY_NAME, BIRTHDATE_NAME, dateString); + + //return buildStringAttribute(BIRTHDATE_FRIENDLY_NAME, BIRTHDATE_NAME, dateString); + } + catch (ParseException e) { e.printStackTrace(); return null; } } - public Attribute buildEmpty() { - return buildemptyAttribute(BIRTHDATE_FRIENDLY_NAME, - BIRTHDATE_NAME); + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(BIRTHDATE_FRIENDLY_NAME, BIRTHDATE_NAME); } - + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDAuthBlock.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDAuthBlock.java index 16d05842a..d2532fc28 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDAuthBlock.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDAuthBlock.java @@ -4,42 +4,40 @@ import iaik.util.logging.Log; import java.io.IOException; -import org.opensaml.saml2.core.Attribute; - import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.UnprovideableAttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.MiscUtil; -public class EIDAuthBlock extends BaseAttributeBuilder { - +public class EIDAuthBlock implements IPVPAttributeBuilder { + public String getName() { return EID_AUTH_BLOCK_NAME; } - - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) - throws PVP2Exception { + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { try { String authblock = authSession.getAuthBlock(); if (MiscUtil.isNotEmpty(authblock)) { - return buildStringAttribute(EID_AUTH_BLOCK_FRIENDLY_NAME, - EID_AUTH_BLOCK_NAME, Base64Utils.encode(authblock.getBytes())); + return g.buildStringAttribute(EID_AUTH_BLOCK_FRIENDLY_NAME, EID_AUTH_BLOCK_NAME, + Base64Utils.encode(authblock.getBytes())); } - } catch (IOException e) { + } + catch (IOException e) { Log.info("Encode AuthBlock BASE64 failed."); } - throw new UnprovideableAttributeException(EID_AUTH_BLOCK_NAME); - + throw new UnavailableAttributeException(EID_AUTH_BLOCK_NAME); + } - - public Attribute buildEmpty() { - return buildemptyAttribute(EID_AUTH_BLOCK_FRIENDLY_NAME, EID_AUTH_BLOCK_NAME); + + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(EID_AUTH_BLOCK_FRIENDLY_NAME, EID_AUTH_BLOCK_NAME); } - + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDCcsURL.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDCcsURL.java index 0d96d4817..470dc11fa 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDCcsURL.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDCcsURL.java @@ -1,33 +1,30 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; - import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.UnprovideableAttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; import at.gv.egovernment.moa.util.MiscUtil; -public class EIDCcsURL extends BaseAttributeBuilder{ +public class EIDCcsURL implements IPVPAttributeBuilder { public String getName() { return EID_CCS_URL_NAME; } - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) - throws PVP2Exception { + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { String bkuurl = authSession.getBkuURL(); if (MiscUtil.isNotEmpty(bkuurl)) - return buildStringAttribute(EID_CCS_URL_FRIENDLY_NAME, EID_CCS_URL_NAME, bkuurl); + return g.buildStringAttribute(EID_CCS_URL_FRIENDLY_NAME, EID_CCS_URL_NAME, bkuurl); else - throw new UnprovideableAttributeException(EID_CCS_URL_NAME); + throw new UnavailableAttributeException(EID_CCS_URL_NAME); } - public Attribute buildEmpty() { - return buildemptyAttribute(EID_CCS_URL_FRIENDLY_NAME, EID_CCS_URL_NAME); + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(EID_CCS_URL_FRIENDLY_NAME, EID_CCS_URL_NAME); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDCitizenQAALevelAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDCitizenQAALevelAttributeBuilder.java index 5ddd87c7b..770609e7a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDCitizenQAALevelAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDCitizenQAALevelAttributeBuilder.java @@ -1,26 +1,25 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; - import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -public class EIDCitizenQAALevelAttributeBuilder extends BaseAttributeBuilder { +public class EIDCitizenQAALevelAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return EID_CITIZEN_QAA_LEVEL_NAME; } - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) { - return buildIntegerAttribute(EID_CITIZEN_QAA_LEVEL_FRIENDLY_NAME, + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { + return g.buildIntegerAttribute(EID_CITIZEN_QAA_LEVEL_FRIENDLY_NAME, EID_CITIZEN_QAA_LEVEL_NAME, 4); } - public Attribute buildEmpty() { - return buildemptyAttribute(EID_CITIZEN_QAA_LEVEL_FRIENDLY_NAME, + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(EID_CITIZEN_QAA_LEVEL_FRIENDLY_NAME, EID_CITIZEN_QAA_LEVEL_NAME); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDIdentityLinkBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDIdentityLinkBuilder.java index d8be65f53..ea1ed0470 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDIdentityLinkBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDIdentityLinkBuilder.java @@ -4,28 +4,26 @@ import java.io.IOException; import javax.xml.transform.TransformerException; -import org.opensaml.saml2.core.Attribute; import org.w3c.dom.Element; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.id.util.IdentityLinkReSigner; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.DOMUtils; -public class EIDIdentityLinkBuilder extends BaseAttributeBuilder { +public class EIDIdentityLinkBuilder implements IPVPAttributeBuilder { public String getName() { return EID_IDENTITY_LINK_NAME; } - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) - throws PVP2Exception { + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { try { String ilAssertion = null; if (oaParam.getBusinessService()) { @@ -43,27 +41,27 @@ public class EIDIdentityLinkBuilder extends BaseAttributeBuilder { ilAssertion = authData.getIdentityLink().getSerializedSamlAssertion(); - return buildStringAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, + return g.buildStringAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, EID_IDENTITY_LINK_NAME, Base64Utils.encode(ilAssertion.getBytes())); } catch (MOAIDException e) { Logger.warn("IdentityLink serialization error.", e); - return buildemptyAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, + return g.buildEmptyAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, EID_IDENTITY_LINK_NAME); } catch (TransformerException e) { Logger.warn("IdentityLink serialization error.", e); - return buildemptyAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, + return g.buildEmptyAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, EID_IDENTITY_LINK_NAME); } catch (IOException e) { Logger.warn("IdentityLink serialization error.", e); - return buildemptyAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, + return g.buildEmptyAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, EID_IDENTITY_LINK_NAME); } } - public Attribute buildEmpty() { - return buildemptyAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, EID_IDENTITY_LINK_NAME); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDIssuingNationAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDIssuingNationAttributeBuilder.java index 08e4e67b3..7d6173ee2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDIssuingNationAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDIssuingNationAttributeBuilder.java @@ -5,21 +5,20 @@ import iaik.x509.X509Certificate; import javax.naming.ldap.LdapName; import javax.naming.ldap.Rdn; -import org.opensaml.saml2.core.Attribute; - import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.logging.Logger; -public class EIDIssuingNationAttributeBuilder extends BaseAttributeBuilder { +public class EIDIssuingNationAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return EID_ISSUING_NATION_NAME; } - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) { + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { String countryCode = "AT"; @@ -48,12 +47,12 @@ public class EIDIssuingNationAttributeBuilder extends BaseAttributeBuilder { } } - return buildStringAttribute(EID_ISSUING_NATION_FRIENDLY_NAME, + return g.buildStringAttribute(EID_ISSUING_NATION_FRIENDLY_NAME, EID_ISSUING_NATION_NAME, countryCode); } - public Attribute buildEmpty() { - return buildemptyAttribute(EID_ISSUING_NATION_FRIENDLY_NAME, + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(EID_ISSUING_NATION_FRIENDLY_NAME, EID_ISSUING_NATION_NAME); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSectorForIDAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSectorForIDAttributeBuilder.java index 8cb2b5be6..43e052644 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSectorForIDAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSectorForIDAttributeBuilder.java @@ -1,26 +1,25 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; - import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -public class EIDSectorForIDAttributeBuilder extends BaseAttributeBuilder { +public class EIDSectorForIDAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return EID_SECTOR_FOR_IDENTIFIER_NAME; } - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) { + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { String bpktype = authData.getBPKType(); - return buildStringAttribute(EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME, + return g.buildStringAttribute(EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME, EID_SECTOR_FOR_IDENTIFIER_NAME, bpktype); } - public Attribute buildEmpty() { - return buildemptyAttribute(EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME, + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME, EID_SECTOR_FOR_IDENTIFIER_NAME); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSignerCertificate.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSignerCertificate.java index f5cb51228..93ddd3506 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSignerCertificate.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSignerCertificate.java @@ -4,29 +4,26 @@ import iaik.util.logging.Log; import java.io.IOException; -import org.opensaml.saml2.core.Attribute; - import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.UnprovideableAttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; import at.gv.egovernment.moa.util.Base64Utils; -public class EIDSignerCertificate extends BaseAttributeBuilder { +public class EIDSignerCertificate implements IPVPAttributeBuilder { public String getName() { return EID_SIGNER_CERTIFICATE_NAME; } - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) - throws PVP2Exception { + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { try { byte[] signerCertificate = authSession.getEncodedSignerCertificate(); if (signerCertificate != null) { - return buildStringAttribute(EID_SIGNER_CERTIFICATE_FRIENDLY_NAME, EID_SIGNER_CERTIFICATE_NAME, Base64Utils + return g.buildStringAttribute(EID_SIGNER_CERTIFICATE_FRIENDLY_NAME, EID_SIGNER_CERTIFICATE_NAME, Base64Utils .encode(signerCertificate)); } @@ -34,12 +31,12 @@ public class EIDSignerCertificate extends BaseAttributeBuilder { Log.info("Signer certificate BASE64 encoding error"); } - throw new UnprovideableAttributeException(EID_SIGNER_CERTIFICATE_NAME); + throw new UnavailableAttributeException(EID_SIGNER_CERTIFICATE_NAME); } - public Attribute buildEmpty() { - return buildemptyAttribute(EID_SIGNER_CERTIFICATE_FRIENDLY_NAME, EID_SIGNER_CERTIFICATE_NAME); + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(EID_SIGNER_CERTIFICATE_FRIENDLY_NAME, EID_SIGNER_CERTIFICATE_NAME); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSourcePIN.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSourcePIN.java index d21d264f6..a8ec0bfb4 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSourcePIN.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSourcePIN.java @@ -1,33 +1,30 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; - import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.UnprovideableAttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; -public class EIDSourcePIN extends BaseAttributeBuilder { +public class EIDSourcePIN implements IPVPAttributeBuilder { public String getName() { return EID_SOURCE_PIN_NAME; } - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) - throws PVP2Exception { + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { if (oaParam.getBusinessService()) - throw new UnprovideableAttributeException(EID_SOURCE_PIN_NAME); + throw new UnavailableAttributeException(EID_SOURCE_PIN_NAME); else { - return buildStringAttribute(EID_SOURCE_PIN_FRIENDLY_NAME, EID_SOURCE_PIN_NAME, authData.getIdentificationValue()); + return g.buildStringAttribute(EID_SOURCE_PIN_FRIENDLY_NAME, EID_SOURCE_PIN_NAME, authData.getIdentificationValue()); } } - public Attribute buildEmpty() { - return buildemptyAttribute(EID_SOURCE_PIN_FRIENDLY_NAME, EID_SOURCE_PIN_NAME); + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(EID_SOURCE_PIN_FRIENDLY_NAME, EID_SOURCE_PIN_NAME); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSourcePINType.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSourcePINType.java index 9bc9716cf..858a53bed 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSourcePINType.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSourcePINType.java @@ -1,33 +1,30 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; - import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.UnprovideableAttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; -public class EIDSourcePINType extends BaseAttributeBuilder { +public class EIDSourcePINType implements IPVPAttributeBuilder { public String getName() { return EID_SOURCE_PIN_TYPE_NAME; } - - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) - throws PVP2Exception { + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { if (oaParam.getBusinessService()) - throw new UnprovideableAttributeException(EID_SOURCE_PIN_TYPE_NAME); + throw new UnavailableAttributeException(EID_SOURCE_PIN_TYPE_NAME); else { - return buildStringAttribute(EID_SOURCE_PIN_TYPE_FRIENDLY_NAME, EID_SOURCE_PIN_TYPE_NAME, authData.getIdentificationType()); + return g.buildStringAttribute(EID_SOURCE_PIN_TYPE_FRIENDLY_NAME, EID_SOURCE_PIN_TYPE_NAME, authData.getIdentificationType()); } } - public Attribute buildEmpty() { - return buildemptyAttribute(EID_SOURCE_PIN_TYPE_FRIENDLY_NAME, EID_SOURCE_PIN_TYPE_NAME); + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(EID_SOURCE_PIN_TYPE_FRIENDLY_NAME, EID_SOURCE_PIN_TYPE_NAME); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/GivenNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/GivenNameAttributeBuilder.java index 5c8151c01..648ea6d25 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/GivenNameAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/GivenNameAttributeBuilder.java @@ -1,24 +1,23 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; - import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -public class GivenNameAttributeBuilder extends BaseAttributeBuilder { +public class GivenNameAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return GIVEN_NAME_NAME; } - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) { - return buildStringAttribute(GIVEN_NAME_FRIENDLY_NAME, GIVEN_NAME_NAME, authSession.getIdentityLink().getGivenName()); + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { + return g.buildStringAttribute(GIVEN_NAME_FRIENDLY_NAME, GIVEN_NAME_NAME, authSession.getIdentityLink().getGivenName()); } - public Attribute buildEmpty() { - return buildemptyAttribute(GIVEN_NAME_FRIENDLY_NAME, GIVEN_NAME_NAME); + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(GIVEN_NAME_FRIENDLY_NAME, GIVEN_NAME_NAME); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IAttributeBuilder.java index 173fbd52f..29f612961 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IAttributeBuilder.java @@ -1,15 +1,15 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; - import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; public interface IAttributeBuilder { public String getName(); - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) throws PVP2Exception; - public Attribute buildEmpty(); + + public ATT build(final AuthenticationSession authSession, final OAAuthParameter oaParam, final AuthenticationData authData, + final IAttributeGenerator g) throws AttributeException; + + public ATT buildEmpty(final IAttributeGenerator g); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateFullMandateAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateFullMandateAttributeBuilder.java index 0afd71bc1..7d5f1d998 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateFullMandateAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateFullMandateAttributeBuilder.java @@ -4,32 +4,29 @@ import java.io.IOException; import javax.xml.transform.TransformerException; -import org.opensaml.saml2.core.Attribute; - import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.DOMUtils; -public class MandateFullMandateAttributeBuilder extends BaseAttributeBuilder { +public class MandateFullMandateAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_FULL_MANDATE_NAME; } - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) - throws PVP2Exception { + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { if (authSession.getUseMandate()) { if (authSession.getMandate() != null) { String fullMandate; try { fullMandate = DOMUtils.serializeNode(authSession .getMandate()); - return buildStringAttribute(MANDATE_FULL_MANDATE_FRIENDLY_NAME, + return g.buildStringAttribute(MANDATE_FULL_MANDATE_FRIENDLY_NAME, MANDATE_FULL_MANDATE_NAME, Base64Utils.encode(fullMandate.getBytes())); } catch (TransformerException e) { Logger.error("Failed to generate Full Mandate", e); @@ -42,8 +39,8 @@ public class MandateFullMandateAttributeBuilder extends BaseAttributeBuilder { } - public Attribute buildEmpty() { - return buildemptyAttribute(MANDATE_FULL_MANDATE_FRIENDLY_NAME, + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(MANDATE_FULL_MANDATE_FRIENDLY_NAME, MANDATE_FULL_MANDATE_NAME); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonFullNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonFullNameAttributeBuilder.java index 15059c036..c49f72315 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonFullNameAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonFullNameAttributeBuilder.java @@ -1,6 +1,5 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; @@ -8,44 +7,43 @@ import at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBod import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; -public class MandateLegalPersonFullNameAttributeBuilder extends BaseAttributeBuilder { - +public class MandateLegalPersonFullNameAttributeBuilder implements IPVPAttributeBuilder { + public String getName() { return MANDATE_LEG_PER_FULL_NAME_NAME; } - - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) throws PVP2Exception { - if(authSession.getUseMandate()) { + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { + if (authSession.getUseMandate()) { Element mandate = authSession.getMandate(); - if(mandate == null) { - throw new NoMandateDataAvailableException(); + if (mandate == null) { + throw new NoMandateDataAttributeException(); } Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if(mandateObject == null) { - throw new NoMandateDataAvailableException(); + if (mandateObject == null) { + throw new NoMandateDataAttributeException(); } CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); - if(corporation == null) { + if (corporation == null) { Logger.error("No corporation mandate"); - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } - return buildStringAttribute(MANDATE_LEG_PER_FULL_NAME_FRIENDLY_NAME, - MANDATE_LEG_PER_FULL_NAME_NAME, corporation.getFullName()); + return g.buildStringAttribute(MANDATE_LEG_PER_FULL_NAME_FRIENDLY_NAME, MANDATE_LEG_PER_FULL_NAME_NAME, + corporation.getFullName()); } return null; } - public Attribute buildEmpty() { - return buildemptyAttribute(MANDATE_LEG_PER_FULL_NAME_FRIENDLY_NAME, - MANDATE_LEG_PER_FULL_NAME_NAME); + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(MANDATE_LEG_PER_FULL_NAME_FRIENDLY_NAME, MANDATE_LEG_PER_FULL_NAME_NAME); } - + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonSourcePinAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonSourcePinAttributeBuilder.java index 820efb209..9b1ed0520 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonSourcePinAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonSourcePinAttributeBuilder.java @@ -1,6 +1,5 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; @@ -9,37 +8,37 @@ import at.gv.e_government.reference.namespace.persondata._20020228_.Identificati import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; -public class MandateLegalPersonSourcePinAttributeBuilder extends BaseAttributeBuilder { +public class MandateLegalPersonSourcePinAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_LEG_PER_SOURCE_PIN_NAME; } - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) throws PVP2Exception { + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { if(authSession.getUseMandate()) { Element mandate = authSession.getMandate(); if(mandate == null) { - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } Mandate mandateObject = MandateBuilder.buildMandate(mandate); if(mandateObject == null) { - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); if(corporation == null) { Logger.error("No corporation mandate"); - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } IdentificationType id = null; if(corporation.getIdentification().size() == 0) { Logger.error("Failed to generate IdentificationType"); - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } id = corporation.getIdentification().get(0); /*if(authSession.getBusinessService()) { @@ -49,16 +48,16 @@ public class MandateLegalPersonSourcePinAttributeBuilder extends BaseAttributeBu }*/ /*if(id == null) { Logger.error("Failed to generate IdentificationType"); - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); }*/ - return buildStringAttribute(MANDATE_LEG_PER_SOURCE_PIN_FRIENDLY_NAME, + return g.buildStringAttribute(MANDATE_LEG_PER_SOURCE_PIN_FRIENDLY_NAME, MANDATE_LEG_PER_SOURCE_PIN_NAME, id.getValue().getValue()); } return null; } - public Attribute buildEmpty() { - return buildemptyAttribute(MANDATE_LEG_PER_SOURCE_PIN_FRIENDLY_NAME, MANDATE_LEG_PER_SOURCE_PIN_NAME); + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(MANDATE_LEG_PER_SOURCE_PIN_FRIENDLY_NAME, MANDATE_LEG_PER_SOURCE_PIN_NAME); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonSourcePinTypeAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonSourcePinTypeAttributeBuilder.java index 44b58d04f..d40cb2f99 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonSourcePinTypeAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonSourcePinTypeAttributeBuilder.java @@ -1,6 +1,5 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; @@ -9,59 +8,53 @@ import at.gv.e_government.reference.namespace.persondata._20020228_.Identificati import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; -public class MandateLegalPersonSourcePinTypeAttributeBuilder extends - BaseAttributeBuilder { - +public class MandateLegalPersonSourcePinTypeAttributeBuilder implements IPVPAttributeBuilder { + public String getName() { return MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME; } - - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) - throws PVP2Exception { + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { if (authSession.getUseMandate()) { Element mandate = authSession.getMandate(); if (mandate == null) { - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } Mandate mandateObject = MandateBuilder.buildMandate(mandate); if (mandateObject == null) { - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } - CorporateBodyType corporation = mandateObject.getMandator() - .getCorporateBody(); + CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); if (corporation == null) { Logger.error("No corporate mandate"); - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } IdentificationType id = null; - if(corporation.getIdentification().size() == 0) { + if (corporation.getIdentification().size() == 0) { Logger.error("Failed to generate IdentificationType"); - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } - id = corporation.getIdentification().get(0); - /*id = MandateBuilder.getBPKIdentification(corporate); - if (id == null) { - Logger.error("Failed to generate IdentificationType"); - throw new NoMandateDataAvailableException(); - }*/ - return buildStringAttribute( - MANDATE_LEG_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, - MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME, id.getType()); + id = corporation.getIdentification().get(0); + /* + * id = MandateBuilder.getBPKIdentification(corporate); if (id == null) { + * Logger.error("Failed to generate IdentificationType"); throw new + * NoMandateDataAttributeException(); } + */ + return g.buildStringAttribute(MANDATE_LEG_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME, + id.getType()); } return null; - + } - - public Attribute buildEmpty() { - return buildemptyAttribute( - MANDATE_LEG_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, - MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME); + + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(MANDATE_LEG_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME); } - + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonBPKAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonBPKAttributeBuilder.java index dc4e9dd49..b6c7389e0 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonBPKAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonBPKAttributeBuilder.java @@ -1,6 +1,5 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; @@ -11,52 +10,51 @@ import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.BuildException; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; -public class MandateNaturalPersonBPKAttributeBuilder extends BaseAttributeBuilder { - +public class MandateNaturalPersonBPKAttributeBuilder implements IPVPAttributeBuilder { + public String getName() { return MANDATE_NAT_PER_BPK_NAME; } - - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) throws PVP2Exception { - if(authSession.getUseMandate()) { + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { + if (authSession.getUseMandate()) { Element mandate = authSession.getMandate(); - if(mandate == null) { - throw new NoMandateDataAvailableException(); + if (mandate == null) { + throw new NoMandateDataAttributeException(); } Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if(mandateObject == null) { - throw new NoMandateDataAvailableException(); + if (mandateObject == null) { + throw new NoMandateDataAttributeException(); } - PhysicalPersonType physicalPerson = mandateObject.getMandator() - .getPhysicalPerson(); + PhysicalPersonType physicalPerson = mandateObject.getMandator().getPhysicalPerson(); if (physicalPerson == null) { Logger.error("No physicalPerson mandate"); - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } IdentificationType id = null; id = physicalPerson.getIdentification().get(0); -// if(authSession.getBusinessService()) { -// id = MandateBuilder.getWBPKIdentification(physicalPerson); -// } else { -// id = MandateBuilder.getBPKIdentification(physicalPerson); -// } - if(id == null) { + // if(authSession.getBusinessService()) { + // id = MandateBuilder.getWBPKIdentification(physicalPerson); + // } else { + // id = MandateBuilder.getBPKIdentification(physicalPerson); + // } + if (id == null) { Logger.error("Failed to generate IdentificationType"); - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } String bpk; try { - + if (id.getType().equals(Constants.URN_PREFIX_BASEID)) { - if (authSession.getBusinessService()) { + if (authSession.getBusinessService()) { bpk = new BPKBuilder().buildWBPK(id.getValue().getValue(), oaParam.getIdentityLinkDomainIdentifier()); } @@ -65,26 +63,24 @@ public class MandateNaturalPersonBPKAttributeBuilder extends BaseAttributeBuilde bpk = new BPKBuilder().buildBPK(id.getValue().getValue(), oaParam.getTarget()); } - - } else + + } else bpk = id.getValue().getValue(); - } catch (BuildException e ){ + } + catch (BuildException e) { Logger.error("Failed to generate IdentificationType"); - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } - - return buildStringAttribute(MANDATE_NAT_PER_BPK_FRIENDLY_NAME, - MANDATE_NAT_PER_BPK_NAME, bpk); + + return g.buildStringAttribute(MANDATE_NAT_PER_BPK_FRIENDLY_NAME, MANDATE_NAT_PER_BPK_NAME, bpk); } return null; } - public Attribute buildEmpty() { - return buildemptyAttribute(MANDATE_NAT_PER_BPK_FRIENDLY_NAME, - MANDATE_NAT_PER_BPK_NAME); + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(MANDATE_NAT_PER_BPK_FRIENDLY_NAME, MANDATE_NAT_PER_BPK_NAME); } - - + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonBirthDateAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonBirthDateAttributeBuilder.java index a87d4d25c..bc719afeb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonBirthDateAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonBirthDateAttributeBuilder.java @@ -5,7 +5,6 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; -import org.opensaml.saml2.core.Attribute; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; @@ -13,62 +12,55 @@ import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPers import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.InvalidDateFormatException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.InvalidDateFormatAttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; -public class MandateNaturalPersonBirthDateAttributeBuilder extends - BaseAttributeBuilder { - +public class MandateNaturalPersonBirthDateAttributeBuilder implements IPVPAttributeBuilder { + public String getName() { return MANDATE_NAT_PER_BIRTHDATE_NAME; } - - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) - throws PVP2Exception { + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { if (authSession.getUseMandate()) { Element mandate = authSession.getMandate(); if (mandate == null) { - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } Mandate mandateObject = MandateBuilder.buildMandate(mandate); if (mandateObject == null) { - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } - PhysicalPersonType physicalPerson = mandateObject.getMandator() - .getPhysicalPerson(); + PhysicalPersonType physicalPerson = mandateObject.getMandator().getPhysicalPerson(); if (physicalPerson == null) { Logger.error("No physicalPerson mandate"); - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } - + String dateOfBirth = physicalPerson.getDateOfBirth(); try { - DateFormat mandateFormat = new SimpleDateFormat( - MandateBuilder.MANDATE_DATE_OF_BIRTH_FORMAT); + DateFormat mandateFormat = new SimpleDateFormat(MandateBuilder.MANDATE_DATE_OF_BIRTH_FORMAT); Date date = mandateFormat.parse(dateOfBirth); - DateFormat pvpDateFormat = new SimpleDateFormat( - MANDATE_NAT_PER_BIRTHDATE_FORMAT_PATTERN); + DateFormat pvpDateFormat = new SimpleDateFormat(MANDATE_NAT_PER_BIRTHDATE_FORMAT_PATTERN); String dateString = pvpDateFormat.format(date); - - return buildStringAttribute( - MANDATE_NAT_PER_BIRTHDATE_FRIENDLY_NAME, - MANDATE_NAT_PER_BIRTHDATE_NAME, dateString); - } catch (ParseException e) { + + return g.buildStringAttribute(MANDATE_NAT_PER_BIRTHDATE_FRIENDLY_NAME, MANDATE_NAT_PER_BIRTHDATE_NAME, dateString); + } + catch (ParseException e) { e.printStackTrace(); - throw new InvalidDateFormatException(); + throw new InvalidDateFormatAttributeException(); } } return null; - + } - - public Attribute buildEmpty() { - return buildemptyAttribute(MANDATE_NAT_PER_BIRTHDATE_FRIENDLY_NAME, - MANDATE_NAT_PER_BIRTHDATE_NAME); + + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(MANDATE_NAT_PER_BIRTHDATE_FRIENDLY_NAME, MANDATE_NAT_PER_BIRTHDATE_NAME); } - + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonFamilyNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonFamilyNameAttributeBuilder.java index 6744e5d20..0e40f9e04 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonFamilyNameAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonFamilyNameAttributeBuilder.java @@ -2,7 +2,6 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; import java.util.Iterator; -import org.opensaml.saml2.core.Attribute; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; @@ -11,32 +10,32 @@ import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPers import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; -public class MandateNaturalPersonFamilyNameAttributeBuilder extends BaseAttributeBuilder { +public class MandateNaturalPersonFamilyNameAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_NAT_PER_FAMILY_NAME_NAME; } - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) throws PVP2Exception { + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { if(authSession.getUseMandate()) { Element mandate = authSession.getMandate(); if(mandate == null) { - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } Mandate mandateObject = MandateBuilder.buildMandate(mandate); if(mandateObject == null) { - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } PhysicalPersonType physicalPerson = mandateObject.getMandator().getPhysicalPerson(); if(physicalPerson == null) { Logger.error("No physicalPerson mandate"); - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } StringBuilder sb = new StringBuilder(); @@ -46,15 +45,15 @@ public class MandateNaturalPersonFamilyNameAttributeBuilder extends BaseAttribu sb.append(" " + fNamesit.next().getValue()); } - return buildStringAttribute(MANDATE_NAT_PER_FAMILY_NAME_FRIENDLY_NAME, + return g.buildStringAttribute(MANDATE_NAT_PER_FAMILY_NAME_FRIENDLY_NAME, MANDATE_NAT_PER_FAMILY_NAME_NAME, sb.toString()); } return null; } - public Attribute buildEmpty() { - return buildemptyAttribute(MANDATE_NAT_PER_FAMILY_NAME_FRIENDLY_NAME, + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(MANDATE_NAT_PER_FAMILY_NAME_FRIENDLY_NAME, MANDATE_NAT_PER_FAMILY_NAME_NAME); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java index 67aa8df0e..88efc3717 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java @@ -2,7 +2,6 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; import java.util.Iterator; -import org.opensaml.saml2.core.Attribute; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; @@ -10,51 +9,49 @@ import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPers import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; -public class MandateNaturalPersonGivenNameAttributeBuilder extends BaseAttributeBuilder { - +public class MandateNaturalPersonGivenNameAttributeBuilder implements IPVPAttributeBuilder { + public String getName() { return MANDATE_NAT_PER_GIVEN_NAME_NAME; } - - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) throws PVP2Exception { - if(authSession.getUseMandate()) { + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { + if (authSession.getUseMandate()) { Element mandate = authSession.getMandate(); - if(mandate == null) { - throw new NoMandateDataAvailableException(); + if (mandate == null) { + throw new NoMandateDataAttributeException(); } Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if(mandateObject == null) { - throw new NoMandateDataAvailableException(); + if (mandateObject == null) { + throw new NoMandateDataAttributeException(); } PhysicalPersonType physicalPerson = mandateObject.getMandator().getPhysicalPerson(); - if(physicalPerson == null) { + if (physicalPerson == null) { Logger.error("No physicalPerson mandate"); - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } StringBuilder sb = new StringBuilder(); Iterator gNamesit = physicalPerson.getName().getGivenName().iterator(); - while(gNamesit.hasNext()) { + while (gNamesit.hasNext()) { sb.append(" " + gNamesit.next()); } - return buildStringAttribute(MANDATE_NAT_PER_GIVEN_NAME_FRIENDLY_NAME, - MANDATE_NAT_PER_GIVEN_NAME_NAME, sb.toString()); + return g.buildStringAttribute(MANDATE_NAT_PER_GIVEN_NAME_FRIENDLY_NAME, MANDATE_NAT_PER_GIVEN_NAME_NAME, sb.toString()); } return null; } - public Attribute buildEmpty() { - return buildemptyAttribute(MANDATE_NAT_PER_GIVEN_NAME_FRIENDLY_NAME, - MANDATE_NAT_PER_GIVEN_NAME_NAME); + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(MANDATE_NAT_PER_GIVEN_NAME_FRIENDLY_NAME, MANDATE_NAT_PER_GIVEN_NAME_NAME); } - + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonSourcePinAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonSourcePinAttributeBuilder.java index aa8061506..b0c2261ef 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonSourcePinAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonSourcePinAttributeBuilder.java @@ -1,6 +1,5 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; @@ -9,35 +8,33 @@ import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPers import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; -public class MandateNaturalPersonSourcePinAttributeBuilder extends - BaseAttributeBuilder { +public class MandateNaturalPersonSourcePinAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_NAT_PER_SOURCE_PIN_NAME; } - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) - throws PVP2Exception { + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { if(authSession.getUseMandate()) { Element mandate = authSession.getMandate(); if(mandate == null) { - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } Mandate mandateObject = MandateBuilder.buildMandate(mandate); if(mandateObject == null) { - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } PhysicalPersonType physicalPerson = mandateObject.getMandator() .getPhysicalPerson(); if (physicalPerson == null) { Logger.error("No physicalPerson mandate"); - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } IdentificationType id = null; id = physicalPerson.getIdentification().get(0); @@ -48,17 +45,17 @@ public class MandateNaturalPersonSourcePinAttributeBuilder extends }*/ if(id == null) { Logger.error("Failed to generate IdentificationType"); - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } - return buildStringAttribute(MANDATE_NAT_PER_SOURCE_PIN_FRIENDLY_NAME, + return g.buildStringAttribute(MANDATE_NAT_PER_SOURCE_PIN_FRIENDLY_NAME, MANDATE_NAT_PER_SOURCE_PIN_NAME, id.getValue().getValue()); } return null; } - public Attribute buildEmpty() { - return buildemptyAttribute(MANDATE_NAT_PER_SOURCE_PIN_FRIENDLY_NAME, + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(MANDATE_NAT_PER_SOURCE_PIN_FRIENDLY_NAME, MANDATE_NAT_PER_SOURCE_PIN_NAME); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonSourcePinTypeAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonSourcePinTypeAttributeBuilder.java index 6ef2f5fa5..54b0b8d74 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonSourcePinTypeAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonSourcePinTypeAttributeBuilder.java @@ -1,6 +1,5 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; @@ -9,35 +8,33 @@ import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPers import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; -public class MandateNaturalPersonSourcePinTypeAttributeBuilder extends - BaseAttributeBuilder { +public class MandateNaturalPersonSourcePinTypeAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_NAT_PER_SOURCE_PIN_TYPE_NAME; } - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) - throws PVP2Exception { + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { if(authSession.getUseMandate()) { Element mandate = authSession.getMandate(); if(mandate == null) { - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } Mandate mandateObject = MandateBuilder.buildMandate(mandate); if(mandateObject == null) { - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } PhysicalPersonType physicalPerson = mandateObject.getMandator() .getPhysicalPerson(); if (physicalPerson == null) { Logger.error("No physicalPerson mandate"); - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } IdentificationType id = null; id = physicalPerson.getIdentification().get(0); @@ -48,17 +45,17 @@ public class MandateNaturalPersonSourcePinTypeAttributeBuilder extends }*/ if(id == null) { Logger.error("Failed to generate IdentificationType"); - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } - return buildStringAttribute(MANDATE_NAT_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, + return g.buildStringAttribute(MANDATE_NAT_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, MANDATE_NAT_PER_SOURCE_PIN_TYPE_NAME, id.getType()); } return null; } - public Attribute buildEmpty() { - return buildemptyAttribute(MANDATE_NAT_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(MANDATE_NAT_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, MANDATE_NAT_PER_SOURCE_PIN_TYPE_NAME); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepDescAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepDescAttributeBuilder.java index 66ac56d00..80393fb50 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepDescAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepDescAttributeBuilder.java @@ -1,27 +1,26 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; import org.w3c.dom.Element; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AttributeExtractor; -public class MandateProfRepDescAttributeBuilder extends BaseAttributeBuilder { +public class MandateProfRepDescAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_PROF_REP_DESC_NAME; } - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) throws PVP2Exception { + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { if(authSession.getUseMandate()) { Element mandate = authSession.getMandate(); if(mandate == null) { - throw new NoMandateDataAvailableException(); + throw new NoMandateDataAttributeException(); } String text = AttributeExtractor.extractSAMLAttributeOA( @@ -32,7 +31,7 @@ public class MandateProfRepDescAttributeBuilder extends BaseAttributeBuilder { return null; } - return buildStringAttribute(MANDATE_PROF_REP_DESC_FRIENDLY_NAME, + return g.buildStringAttribute(MANDATE_PROF_REP_DESC_FRIENDLY_NAME, MANDATE_PROF_REP_DESC_NAME, text); } @@ -40,8 +39,8 @@ public class MandateProfRepDescAttributeBuilder extends BaseAttributeBuilder { } - public Attribute buildEmpty() { - return buildemptyAttribute(MANDATE_PROF_REP_DESC_FRIENDLY_NAME, + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(MANDATE_PROF_REP_DESC_FRIENDLY_NAME, MANDATE_PROF_REP_DESC_NAME); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepOIDAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepOIDAttributeBuilder.java index d708cba95..e3bfda252 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepOIDAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepOIDAttributeBuilder.java @@ -1,48 +1,42 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; import org.w3c.dom.Element; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AttributeExtractor; -public class MandateProfRepOIDAttributeBuilder extends BaseAttributeBuilder { - +public class MandateProfRepOIDAttributeBuilder implements IPVPAttributeBuilder { + public String getName() { return MANDATE_PROF_REP_OID_NAME; } - - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) throws PVP2Exception { - if(authSession.getUseMandate()) { + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { + if (authSession.getUseMandate()) { Element mandate = authSession.getMandate(); - if(mandate == null) { - throw new NoMandateDataAvailableException(); + if (mandate == null) { + throw new NoMandateDataAttributeException(); } - String oid = AttributeExtractor.extractSAMLAttributeOA( - EXT_SAML_MANDATE_OID, - authSession); + String oid = AttributeExtractor.extractSAMLAttributeOA(EXT_SAML_MANDATE_OID, authSession); - if(oid == null) { + if (oid == null) { return null; } - return buildStringAttribute(MANDATE_PROF_REP_OID_FRIENDLY_NAME, - MANDATE_PROF_REP_OID_NAME, oid); + return g.buildStringAttribute(MANDATE_PROF_REP_OID_FRIENDLY_NAME, MANDATE_PROF_REP_OID_NAME, oid); } return null; } - public Attribute buildEmpty() { - return buildemptyAttribute(MANDATE_PROF_REP_OID_FRIENDLY_NAME, - MANDATE_PROF_REP_OID_NAME); + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(MANDATE_PROF_REP_OID_FRIENDLY_NAME, MANDATE_PROF_REP_OID_NAME); } } - \ No newline at end of file diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateReferenceValueAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateReferenceValueAttributeBuilder.java index 5a50473d3..ad664486b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateReferenceValueAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateReferenceValueAttributeBuilder.java @@ -1,43 +1,41 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; -public class MandateReferenceValueAttributeBuilder extends BaseAttributeBuilder { - +public class MandateReferenceValueAttributeBuilder implements IPVPAttributeBuilder { + public String getName() { return MANDATE_REFERENCE_VALUE_NAME; } - - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) throws PVP2Exception { - if(authSession.getUseMandate()) { + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { + if (authSession.getUseMandate()) { Element mandate = authSession.getMandate(); - if(mandate == null) { - throw new NoMandateDataAvailableException(); + if (mandate == null) { + throw new NoMandateDataAttributeException(); } Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if(mandateObject == null) { - throw new NoMandateDataAvailableException(); + if (mandateObject == null) { + throw new NoMandateDataAttributeException(); } - return buildStringAttribute(MANDATE_REFERENCE_VALUE_FRIENDLY_NAME, - MANDATE_REFERENCE_VALUE_NAME, mandateObject.getMandateID()); + return g.buildStringAttribute(MANDATE_REFERENCE_VALUE_FRIENDLY_NAME, MANDATE_REFERENCE_VALUE_NAME, + mandateObject.getMandateID()); } return null; } - public Attribute buildEmpty() { - return buildemptyAttribute(MANDATE_REFERENCE_VALUE_FRIENDLY_NAME, - MANDATE_REFERENCE_VALUE_NAME); + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(MANDATE_REFERENCE_VALUE_FRIENDLY_NAME, MANDATE_REFERENCE_VALUE_NAME); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateTypeAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateTypeAttributeBuilder.java index bc7fdaf73..76dc1cb83 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateTypeAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateTypeAttributeBuilder.java @@ -1,41 +1,41 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.ResponderErrorException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; -public class MandateTypeAttributeBuilder extends BaseAttributeBuilder { - +public class MandateTypeAttributeBuilder implements IPVPAttributeBuilder { + public String getName() { return MANDATE_TYPE_NAME; } - - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) throws ResponderErrorException { - if(authSession.getUseMandate()) { + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { + if (authSession.getUseMandate()) { Element mandate = authSession.getMandate(); - if(mandate == null) { - throw new ResponderErrorException("No mandate data available", null); + if (mandate == null) { + throw new NoMandateDataAttributeException(); } Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if(mandateObject == null) { - throw new ResponderErrorException("No mandate data available", null); + if (mandateObject == null) { + throw new NoMandateDataAttributeException(); } - return buildStringAttribute(MANDATE_TYPE_FRIENDLY_NAME, MANDATE_TYPE_NAME, mandateObject.getAnnotation()); + return g.buildStringAttribute(MANDATE_TYPE_FRIENDLY_NAME, MANDATE_TYPE_NAME, mandateObject.getAnnotation()); } return null; } - public Attribute buildEmpty() { - return buildemptyAttribute(MANDATE_TYPE_FRIENDLY_NAME, MANDATE_TYPE_NAME); + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(MANDATE_TYPE_FRIENDLY_NAME, MANDATE_TYPE_NAME); } - + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/PVPVersionAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/PVPVersionAttributeBuilder.java index 545d70d76..149513764 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/PVPVersionAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/PVPVersionAttributeBuilder.java @@ -1,24 +1,23 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; - import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -public class PVPVersionAttributeBuilder extends BaseAttributeBuilder { - +public class PVPVersionAttributeBuilder implements IPVPAttributeBuilder { + public String getName() { return PVP_VERSION_NAME; } - - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) { - return buildStringAttribute(PVP_VERSION_FRIENDLY_NAME, PVP_VERSION_NAME, PVP_VERSION_2_1); + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { + return g.buildStringAttribute(PVP_VERSION_FRIENDLY_NAME, PVP_VERSION_NAME, PVP_VERSION_2_1); } - - public Attribute buildEmpty() { - return buildemptyAttribute(PVP_VERSION_FRIENDLY_NAME, PVP_VERSION_NAME); + + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(PVP_VERSION_FRIENDLY_NAME, PVP_VERSION_NAME); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/PrincipalNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/PrincipalNameAttributeBuilder.java index 7ca7eb829..2de5ae79a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/PrincipalNameAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/PrincipalNameAttributeBuilder.java @@ -1,24 +1,23 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.opensaml.saml2.core.Attribute; - import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -public class PrincipalNameAttributeBuilder extends BaseAttributeBuilder { - +public class PrincipalNameAttributeBuilder implements IPVPAttributeBuilder { + public String getName() { return PRINCIPAL_NAME_NAME; } - - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) { - return buildStringAttribute(PRINCIPAL_NAME_FRIENDLY_NAME, PRINCIPAL_NAME_NAME, authSession.getIdentityLink().getFamilyName()); + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { + return g.buildStringAttribute(PRINCIPAL_NAME_FRIENDLY_NAME, PRINCIPAL_NAME_NAME, authSession.getIdentityLink().getFamilyName()); } - - public Attribute buildEmpty() { - return buildemptyAttribute(PRINCIPAL_NAME_FRIENDLY_NAME, PRINCIPAL_NAME_NAME); + + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(PRINCIPAL_NAME_FRIENDLY_NAME, PRINCIPAL_NAME_NAME); } - + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java index fec21df9e..1d494c512 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java @@ -1,11 +1,8 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.requestHandler; -import java.util.Date; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.joda.time.DateTime; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.core.Assertion; import org.opensaml.saml2.core.AuthnRequest; @@ -54,19 +51,10 @@ public class AuthnRequestHandler implements IRequestHandler, PVPConstants { Issuer nissuer = SAML2Utils.createSAMLObject(Issuer.class); - - //TODO: check! - //change to entity value from entity name to IDP EntityID (URL) - nissuer.setValue(PVPConfiguration.getInstance().getIDPPublicPath()); - //nissuer.setValue(PVPConfiguration.getInstance().getIDPIssuerName()); + nissuer.setValue(PVPConfiguration.getInstance().getIDPIssuerName()); nissuer.setFormat(NameID.ENTITY); - authResponse.setIssuer(nissuer); authResponse.setInResponseTo(authnRequest.getID()); - - //SAML2 response required IssueInstant - authResponse.setIssueInstant(new DateTime()); - authResponse.getAssertions().add(assertion); authResponse.setStatus(SAML2Utils.getSuccessStatus()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/MetadataSignatureFilter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/MetadataSignatureFilter.java index e85d87aa3..e9d41b7ee 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/MetadataSignatureFilter.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/MetadataSignatureFilter.java @@ -91,12 +91,10 @@ public class MetadataSignatureFilter implements MetadataFilter { throw new MOAIDException("Root element of metadata file has to be signed", null); } processEntitiesDescriptor(entitiesDescriptor); - - } else if (metadata instanceof EntityDescriptor) { + } /*else if (metadata instanceof EntityDescriptor) { EntityDescriptor entityDescriptor = (EntityDescriptor) metadata; processEntityDescriptorr(entityDescriptor); - - } else { + } */else { throw new MOAIDException("Invalid Metadata file Root element is no EntitiesDescriptor", null); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java index d0c28538c..e40d11128 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java @@ -209,7 +209,6 @@ public class AuthenticationSessionStoreage { //Assertion requires an unique artifact if (result.size() != 1) { Logger.trace("No entries found."); - tx.commit(); throw new MOADatabaseException("No session found with this sessionID"); } -- cgit v1.2.3 From 0652e7c7a912804fada38062561931e16cc09026 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 17 Jan 2014 12:22:40 +0100 Subject: test --- .../main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java | 3 +++ .../at/gv/egovernment/moa/id/protocols/oauth20/OAuth20TokenAction.java | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java index 556d26c67..58d1ba0df 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java @@ -80,6 +80,9 @@ public class MOAIDAuthInitializer { MailcapCommandMap mc = new MailcapCommandMap(); CommandMap.setDefaultCommandMap(mc); + Logger.info("Loading security providers."); + //IAIK.addAsProvider(); + // create some properties and get the default Session Properties props = new Properties(); props.put("mail.smtp.host", "localhost"); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20TokenAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20TokenAction.java index d66f9cb2a..22ed20d70 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20TokenAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20TokenAction.java @@ -194,7 +194,7 @@ public class OAuth20TokenAction implements IAction { // add properties and sign // HmacSHA256Signer signer = new HmacSHA256Signer("testSigner", "key_id", // "super_secure_pwd".getBytes()); - // Signer signer = OAuth20Util.loadSigner(authData.getIssuer(), oaParam.getoAuth20Config()); + //Signer signer = OAuth20Util.loadSigner(authData.getIssuer(), oaParam.getoAuth20Config()); Signer signer = OAuth20Util.loadSigner(authData.getIssuer()); JsonToken token = new JsonToken(signer); OAuth20Util.addProperytiesToJsonObject(token.getPayloadAsJsonObject(), params); -- cgit v1.2.3 From 4216a1b9910506f2699a5a7cfa38be9762d654be Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 20 Jan 2014 10:32:32 +0100 Subject: Exthex OAuth second version --- .../moa/id/auth/MOAIDAuthInitializer.java | 3 - .../id/protocols/oauth20/OAuth20AuthAction.java | 92 ------ .../moa/id/protocols/oauth20/OAuth20Protocol.java | 166 ---------- .../id/protocols/oauth20/OAuth20TokenAction.java | 349 --------------------- .../egovernment/moa/id/protocols/oauth20/Pair.java | 23 ++ .../attributes/OAuth20AttributeBuilder.java | 161 ++++++++++ .../OpenIdAuthenticationTimeAttribute.java | 25 ++ .../attributes/OpenIdExpirationTimeAttribute.java | 29 ++ .../attributes/OpenIdIssueInstantAttribute.java | 27 ++ .../oauth20/attributes/OpenIdIssuerAttribute.java | 25 ++ .../OpenIdSubjectIdentifierAttribute.java | 25 ++ .../attributes/ProfileDateOfBirthAttribute.java | 25 ++ .../attributes/ProfileFamilyNameAttribute.java | 25 ++ .../attributes/ProfileGivenNameAttribute.java | 25 ++ .../oauth20/json/OAuth20SHA256Signer.java | 99 ++++++ .../oauth20/json/OAuth20SHA256Verifier.java | 62 ++++ .../oauth20/json/OAuth20SignatureUtil.java | 94 ++++++ .../id/protocols/oauth20/json/OAuthJsonToken.java | 27 ++ .../oauth20/json/OAuthSignatureAlgorithm.java | 62 ++++ .../moa/id/protocols/oauth20/json/OAuthSigner.java | 7 + .../oauth20/protocol/OAuth20AuthAction.java | 112 +++++++ .../oauth20/protocol/OAuth20AuthRequest.java | 134 ++++++++ .../oauth20/protocol/OAuth20BaseRequest.java | 121 +++++++ .../oauth20/protocol/OAuth20Protocol.java | 167 ++++++++++ .../oauth20/protocol/OAuth20TokenAction.java | 164 ++++++++++ .../oauth20/protocol/OAuth20TokenRequest.java | 118 +++++++ .../oauth20/requests/OAuth20AuthRequest.java | 134 -------- .../oauth20/requests/OAuth20BaseRequest.java | 118 ------- .../oauth20/requests/OAuth20TokenRequest.java | 118 ------- .../builder/attributes/BaseAttributeBuilder.java | 63 ---- .../builder/attributes/IAttributeGenerator.java | 11 + .../builder/attributes/IPVPAttributeBuilder.java | 8 + .../builder/attributes/SamlAttributeGenerator.java | 65 ++++ .../attributes/exceptions/AttributeException.java | 11 + .../InvalidDateFormatAttributeException.java | 13 + .../NoMandateDataAttributeException.java | 10 + .../exceptions/UnavailableAttributeException.java | 18 ++ 37 files changed, 1693 insertions(+), 1043 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20AuthAction.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Protocol.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20TokenAction.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/Pair.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdAuthenticationTimeAttribute.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdExpirationTimeAttribute.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssueInstantAttribute.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssuerAttribute.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdSubjectIdentifierAttribute.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileDateOfBirthAttribute.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileFamilyNameAttribute.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileGivenNameAttribute.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Signer.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Verifier.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SignatureUtil.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthJsonToken.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSignatureAlgorithm.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSigner.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20Protocol.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20AuthRequest.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20BaseRequest.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20TokenRequest.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BaseAttributeBuilder.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IAttributeGenerator.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IPVPAttributeBuilder.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/SamlAttributeGenerator.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/AttributeException.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/InvalidDateFormatAttributeException.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/NoMandateDataAttributeException.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/UnavailableAttributeException.java (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java index 58d1ba0df..556d26c67 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java @@ -80,9 +80,6 @@ public class MOAIDAuthInitializer { MailcapCommandMap mc = new MailcapCommandMap(); CommandMap.setDefaultCommandMap(mc); - Logger.info("Loading security providers."); - //IAIK.addAsProvider(); - // create some properties and get the default Session Properties props = new Properties(); props.put("mail.smtp.host", "localhost"); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20AuthAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20AuthAction.java deleted file mode 100644 index 949b06bb2..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20AuthAction.java +++ /dev/null @@ -1,92 +0,0 @@ -package at.gv.egovernment.moa.id.protocols.oauth20; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.moduls.IAction; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ResponseTypeException; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ServerErrorException; -import at.gv.egovernment.moa.id.protocols.oauth20.requests.OAuth20AuthRequest; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.logging.Logger; - -public class OAuth20AuthAction implements IAction { - - public String processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, - AuthenticationSession moasession) throws MOAIDException { - - OAuth20AuthRequest oAuthRequest = (OAuth20AuthRequest) req; - - // OAAuthParameter oaParam = - // AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(oAuthRequest.getOAURL()); - // AuthenticationData authData = - // AuthenticationServer.buildAuthenticationData(moasession, oaParam, - // oAuthRequest.getTarget()); - - String responseType = oAuthRequest.getResponseType(); - - String code = AuthenticationSessionStoreage.changeSessionID(moasession); - Logger.debug("Stored session with id: " + code); - if (responseType.equals(OAuth20Constants.RESPONSE_CODE)) { - OAuth20SessionObject o = new OAuth20SessionObject(); - o.setScope(oAuthRequest.getScope()); - o.setCode(code); - moasession.setoAuth20SessionObject(o); - try { - AuthenticationSessionStoreage.storeSession(moasession); - } - catch (MOADatabaseException e) { - throw new OAuth20ServerErrorException(); - } - - Logger.debug("Saved OAuth20SessionObject in session with id: " + moasession.getSessionID()); - } else if (responseType.equals(OAuth20Constants.RESPONSE_TOKEN)) { - throw new OAuth20ResponseTypeException(); - } - - // add code and state to redirect url - httpResp.setStatus(HttpServletResponse.SC_FOUND); - String redirectURI = oAuthRequest.getRedirectUri(); - String state = oAuthRequest.getState(); - - redirectURI = this.addURLParameter(redirectURI, OAuth20Constants.RESPONSE_CODE, code); - redirectURI = this.addURLParameter(redirectURI, OAuth20Constants.PARAM_STATE, state); - - String finalUrl = redirectURI; - httpResp.addHeader("Location", finalUrl); - Logger.debug("REDIRECT TO: " + finalUrl.toString()); - return null; - } - - /* - * (non-Javadoc) - * @see - * at.gv.egovernment.moa.id.moduls.IAction#needAuthentication(at.gv.egovernment.moa.id.moduls - * .IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) { - return true; - } - - private String addURLParameter(String url, String name, String value) { - String param = name + "=" + value; - if (url.indexOf("?") < 0) { - return url + "?" + param; - } else { - return url + "&" + param; - } - } - - /* - * (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IAction#getDefaultActionName() - */ - public String getDefaultActionName() { - return OAuth20Protocol.AUTH_ACTION; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Protocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Protocol.java deleted file mode 100644 index 2c8aa8a73..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Protocol.java +++ /dev/null @@ -1,166 +0,0 @@ -package at.gv.egovernment.moa.id.protocols.oauth20; - -import java.net.URLEncoder; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringUtils; - -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.moduls.IAction; -import at.gv.egovernment.moa.id.moduls.IModulInfo; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; -import at.gv.egovernment.moa.id.protocols.oauth20.requests.OAuth20BaseRequest; -import at.gv.egovernment.moa.logging.Logger; - -import com.google.gson.JsonObject; - -public class OAuth20Protocol implements IModulInfo { - - public static final String NAME = OAuth20Protocol.class.getName(); - public static final String PATH = "id_oauth20"; - - public static final String AUTH_ACTION = "AUTH"; - public static final String TOKEN_ACTION = "TOKEN"; - - private static HashMap actions = new HashMap(); - - static { - actions.put(AUTH_ACTION, new OAuth20AuthAction()); - actions.put(TOKEN_ACTION, new OAuth20TokenAction()); - } - - public String getName() { - return NAME; - } - - public String getPath() { - return PATH; - } - - public IAction getAction(String action) { - return actions.get(action); - } - - /* - * (non-Javadoc) - * @see - * at.gv.egovernment.moa.id.moduls.IModulInfo#preProcess(javax.servlet.http.HttpServletRequest, - * javax.servlet.http.HttpServletResponse, java.lang.String) - */ - public IRequest preProcess(HttpServletRequest request, HttpServletResponse resp, String action) throws MOAIDException { - // validation is done inside creation - OAuth20BaseRequest res = OAuth20BaseRequest.newInstance(action, request); - Logger.debug("Created: " + res); - return res; - } - - /* - * (non-Javadoc) - * @see - * at.gv.egovernment.moa.id.moduls.IModulInfo#canHandleRequest(javax.servlet.http.HttpServletRequest - * , javax.servlet.http.HttpServletResponse) - */ - public IAction canHandleRequest(HttpServletRequest request, HttpServletResponse response) { - if (request.getParameter("action").equals(AUTH_ACTION)) { - return getAction(AUTH_ACTION); - } else if (request.getParameter("action").equals(TOKEN_ACTION)) { - return getAction(TOKEN_ACTION); - } - - return null;// getAction(AUTH_ACTION); - } - - /* - * (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IModulInfo#generateErrorMessage(java.lang.Throwable, - * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, - * at.gv.egovernment.moa.id.moduls.IRequest) - */ - public boolean generateErrorMessage(Throwable e, HttpServletRequest request, HttpServletResponse response, IRequest protocolRequest) - throws Throwable { - - StringBuilder url = new StringBuilder(); - - String paramRedirect = request.getParameter(OAuth20Constants.PARAM_REDIRECT_URI); - - if (e instanceof OAuth20Exception) { - - String action = request.getParameter("action"); - - Logger.debug("Going to throw O OAuth20Exception for action: " + action); - OAuth20Exception oAuth20Exception = ((OAuth20Exception) e); - - String errorCode = oAuth20Exception.getErrorCode(); - String errorDescription = oAuth20Exception.getMessage(); - // String errorUri = "http://tools.ietf.org/html/draft-ietf-oauth-v2-11"; - - if (action.equals(AUTH_ACTION)) { - - // check if given redirect url is ok - if (StringUtils.isNotEmpty(paramRedirect) && OAuth20Util.isUrl(paramRedirect)) { - url.append(paramRedirect); - - // otherwise throw an - } else { - throw new MOAIDException("oauth20.01", new Object[] {}); - } - - String state = request.getParameter(OAuth20Constants.PARAM_STATE); - - OAuth20Util.addParameterToURL(url, OAuth20Constants.PARAM_ERROR, errorCode); - OAuth20Util.addParameterToURL(url, OAuth20Constants.PARAM_ERROR_DESCRIPTION, - URLEncoder.encode(oAuth20Exception.getMessageId() + ": " + errorDescription, "UTF-8")); - // OAuth20Util.addParameterToURL(url, OAuth20Constants.PARAM_ERROR_URI, errorUri); - OAuth20Util.addParameterToURL(url, OAuth20Constants.PARAM_STATE, state); - - response.setContentType("text/html"); - response.setStatus(HttpServletResponse.SC_FOUND); - response.addHeader("Location", url.toString()); - Logger.debug("REDIRECT TO: " + url.toString()); - return true; - - } else if (action.equals(TOKEN_ACTION)) { - Map params = new HashMap(); - params.put(OAuth20Constants.PARAM_ERROR, errorCode); - params.put(OAuth20Constants.PARAM_ERROR_DESCRIPTION, - URLEncoder.encode(oAuth20Exception.getMessageId() + ": " + errorDescription, "UTF-8")); - // params.put(OAuth20Constants.PARAM_ERROR_URI, errorUri); - - // create response - JsonObject jsonObject = new JsonObject(); - OAuth20Util.addProperytiesToJsonObject(jsonObject, params); - String jsonResponse = jsonObject.toString(); - Logger.debug("JSON Response: " + jsonResponse); - - // write respone to http response - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.getOutputStream().print(jsonResponse); - response.getOutputStream().close(); - - return true; - } - - } - - return false; - - } - - /* - * (non-Javadoc) - * @see - * at.gv.egovernment.moa.id.moduls.IModulInfo#validate(javax.servlet.http.HttpServletRequest, - * javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.moduls.IRequest) - */ - public boolean validate(HttpServletRequest request, HttpServletResponse response, IRequest pending) { - // we validate in the preProcess - return true; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20TokenAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20TokenAction.java deleted file mode 100644 index 22ed20d70..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20TokenAction.java +++ /dev/null @@ -1,349 +0,0 @@ -package at.gv.egovernment.moa.id.protocols.oauth20; - -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.UUID; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import net.oauth.jsontoken.JsonToken; -import net.oauth.jsontoken.crypto.Signer; - -import org.w3c.dom.Element; - -import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; -import at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBodyType; -import at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType; -import at.gv.e_government.reference.namespace.persondata._20020228_.PersonNameType.FamilyName; -import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.builder.BPKBuilder; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.exception.BuildException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.id.moduls.IAction; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ServerErrorException; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20UnauthorizedClientException; -import at.gv.egovernment.moa.id.protocols.oauth20.requests.OAuth20TokenRequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AttributeExtractor; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.IdentityLinkReSigner; -import at.gv.egovernment.moa.id.util.MandateBuilder; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.Base64Utils; -import at.gv.egovernment.moa.util.Constants; -import at.gv.egovernment.moa.util.DOMUtils; - -import com.google.gson.JsonObject; - -public class OAuth20TokenAction implements IAction { - - private int expirationTime = 5 * 60; // in seconds - - public class Pair { - private T1 first; - private T2 second; - - public Pair(T1 newFirst, T2 newSecond) { - first = newFirst; - second = newSecond; - } - - public T1 getFirst() { - return first; - } - - public T2 getSecond() { - return second; - } - } - - public String processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, - AuthenticationSession moasession) throws MOAIDException { - - AuthenticationSession session = null; - try { - OAuth20TokenRequest oAuthRequest = (OAuth20TokenRequest) req; - - session = AuthenticationSessionStoreage.getSession(oAuthRequest.getCode()); - if (session == null) { - throw new OAuth20UnauthorizedClientException(); - } - - OAuth20SessionObject auth20SessionObject = session.getoAuth20SessionObject(); - Logger.debug("Loaded OAuth20SessionObject from session: " + auth20SessionObject); - - // do checking for different grant types and code - if (!auth20SessionObject.getCode().equals(oAuthRequest.getCode())) { - throw new OAuth20UnauthorizedClientException(); - - } - - final String accessToken = UUID.randomUUID().toString(); - - // create response - Map params = new HashMap(); - params.put(OAuth20Constants.RESPONSE_ACCESS_TOKEN, accessToken); - params.put(OAuth20Constants.RESPONSE_TOKEN_TYPE, OAuth20Constants.RESPONSE_TOKEN_TYPE_VALUE_BEARER); - params.put(OAuth20Constants.RESPONSE_EXPIRES_IN, this.expirationTime); - - // build id token and scope - Pair pair = buildIdToken(auth20SessionObject.getScope(), oAuthRequest, session); - Logger.debug("RESPONSE ID_TOKEN: " + pair.getFirst()); - params.put(OAuth20Constants.RESPONSE_ID_TOKEN, pair.getFirst()); - Logger.debug("RESPONSE SCOPE: " + pair.getSecond()); - params.put(OAuth20Constants.PARAM_SCOPE, pair.getSecond()); - - // create response - JsonObject jsonObject = new JsonObject(); - OAuth20Util.addProperytiesToJsonObject(jsonObject, params); - String jsonResponse = jsonObject.toString(); - Logger.debug("JSON Response: " + jsonResponse); - - // write respone to http response - httpResp.setContentType("application/json"); - httpResp.setStatus(HttpServletResponse.SC_OK); - httpResp.getOutputStream().print(jsonResponse); - httpResp.getOutputStream().close(); - - return null; - } - catch (Exception e) { - throw new OAuth20ServerErrorException(); - } - finally { - ConfigurationDBUtils.closeSession(); - -// if (session != null) { -// // destroy session for clean up -// try { -// Logger.debug("Going to destroy session: " + session.getSessionID()); -// AuthenticationSessionStoreage.destroySession(session.getSessionID()); -// } -// catch (MOADatabaseException e) { -// } -// } - } - } - - /* - * (non-Javadoc) - * @see - * at.gv.egovernment.moa.id.moduls.IAction#needAuthentication(at.gv.egovernment.moa.id.moduls - * .IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) { - return false; - } - - /* - * (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IAction#getDefaultActionName() - */ - public String getDefaultActionName() { - return OAuth20Protocol.TOKEN_ACTION; - } - - private Pair buildIdToken(String scope, OAuth20TokenRequest oAuthRequest, AuthenticationSession session) - throws Exception { - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(oAuthRequest.getOAURL()); - AuthenticationData authData = AuthenticationServer.buildAuthenticationData(session, oaParam, oAuthRequest.getTarget()); - - Map params = new HashMap(); - StringBuilder resultScopes = new StringBuilder(); - // always fill with open id - this.fillScopeOpenId(params, authData); - resultScopes.append("openId"); - - for (String s : scope.split(" ")) { - - try { - if (s.equalsIgnoreCase("profile")) { - this.fillScopeProfile(params, authData); - resultScopes.append(" profile"); - } else if (s.equalsIgnoreCase("eID")) { - this.fillScopeEID(params, authData, session); - resultScopes.append(" eID"); - } else if (s.equalsIgnoreCase("eID_gov") && oaParam.getBusinessService()) { - this.fillScopeEID_GOV(params, authData, session); - resultScopes.append(" eID_gov"); - } else if (s.equalsIgnoreCase("mandate") && session.getUseMandate() && oaParam.getBusinessService()) { - this.fillScopeMandate(params, oaParam, authData, session); - resultScopes.append(" mandate"); - } - } - catch (Exception e) { - Logger.warn(e.getMessage(), e); - } - // TODO parser STORK - } - - // add properties and sign - // HmacSHA256Signer signer = new HmacSHA256Signer("testSigner", "key_id", - // "super_secure_pwd".getBytes()); - //Signer signer = OAuth20Util.loadSigner(authData.getIssuer(), oaParam.getoAuth20Config()); - Signer signer = OAuth20Util.loadSigner(authData.getIssuer()); - JsonToken token = new JsonToken(signer); - OAuth20Util.addProperytiesToJsonObject(token.getPayloadAsJsonObject(), params); - return new Pair(token.serializeAndSign(), resultScopes.toString()); - } - - private void fillScopeProfile(Map params, AuthenticationData authData) { - params.put("given_name", authData.getGivenName()); - params.put("family_name", authData.getFamilyName()); - params.put("birthdate", authData.getDateOfBirth()); - } - - private void fillScopeOpenId(Map params, AuthenticationData authData) { - params.put("iss", authData.getIssuer()); - params.put("sub", authData.getBPK()); - // params.put("aud", ""); // not used - params.put("exp", (long) (new Date().getTime() / 1000 + this.expirationTime)); - params.put("iat", (long) (new Date().getTime() / 1000)); - params.put("auth_time", (long) (authData.getTimestamp().getTime() / 1000)); - // params.put("acr", ""); //? - } - - private void fillScopeEID(Map params, AuthenticationData authData, AuthenticationSession session) throws Exception { - params.put(PVPConstants.EID_CCS_URL_FRIENDLY_NAME, authData.getBkuURL()); - // params.put("ENC-BPK-LIST", ); // not used - // params.put("MAIL", ); //not used - // params.put("TEL", ); //not used - - params.put(PVPConstants.EID_CITIZEN_QAA_LEVEL_FRIENDLY_NAME, 4); - params.put(PVPConstants.EID_ISSUING_NATION_FRIENDLY_NAME, "AT"); - params.put(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME, authData.getBPKType()); - params.put(PVPConstants.EID_AUTH_BLOCK_FRIENDLY_NAME, Base64Utils.encode(session.getAuthBlock().getBytes())); - params.put(PVPConstants.EID_SIGNER_CERTIFICATE_FRIENDLY_NAME, Base64Utils.encode(session.getEncodedSignerCertificate())); - // params.put(PVPConstants.EID_STORK_TOKEN_FRIENDLY_NAME, ); //not used - - // bpk - String bpk = authData.getBPK(); - String type = authData.getBPKType(); - if (type.startsWith(Constants.URN_PREFIX_WBPK)) - type = type.substring((Constants.URN_PREFIX_WBPK + "+").length()); - else if (type.startsWith(Constants.URN_PREFIX_CDID)) type = type.substring((Constants.URN_PREFIX_CDID + "+").length()); - if (bpk.length() > PVPConstants.BPK_MAX_LENGTH) { - bpk = bpk.substring(0, PVPConstants.BPK_MAX_LENGTH); - } - params.put(PVPConstants.BPK_FRIENDLY_NAME, type + ":" + bpk); - } - - private void fillScopeEID_GOV(Map params, AuthenticationData authData, AuthenticationSession session) - throws Exception { - params.put(PVPConstants.EID_SOURCE_PIN_FRIENDLY_NAME, authData.getIdentificationValue()); - params.put(PVPConstants.EID_SOURCE_PIN_TYPE_FRIENDLY_NAME, authData.getIdentificationType()); - - IdentityLinkReSigner identitylinkresigner = IdentityLinkReSigner.getInstance(); - Element resignedilAssertion = identitylinkresigner.resignIdentityLink(authData.getIdentityLink().getSamlAssertion()); - params.put(PVPConstants.EID_IDENTITY_LINK_FRIENDLY_NAME, - Base64Utils.encode(DOMUtils.serializeNode(resignedilAssertion).getBytes())); - } - - private void fillScopeMandate(Map params, OAAuthParameter oaParam, AuthenticationData authData, - AuthenticationSession session) { - Element mandate = session.getMandate(); - - if (mandate == null) { - throw new OAuth20ServerErrorException(); - } - Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if (mandateObject == null) { - throw new OAuth20ServerErrorException(); - } - - params.put(PVPConstants.MANDATE_TYPE_FRIENDLY_NAME, mandateObject.getAnnotation()); - params.put(PVPConstants.MANDATE_REFERENCE_VALUE_FRIENDLY_NAME, mandateObject.getMandateID()); - - // natural person - PhysicalPersonType physicalPerson = mandateObject.getMandator().getPhysicalPerson(); - if (physicalPerson != null && physicalPerson.getIdentification().size() != 0) { - IdentificationType id = physicalPerson.getIdentification().get(0); - params.put(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_FRIENDLY_NAME, id.getValue().getValue()); - params.put(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, id.getType()); - - try { - String bpk; - if (id.getType().equals(Constants.URN_PREFIX_BASEID)) { - if (session.getBusinessService()) { - bpk = new BPKBuilder().buildWBPK(id.getValue().getValue(), oaParam.getIdentityLinkDomainIdentifier()); - } else { - bpk = new BPKBuilder().buildBPK(id.getValue().getValue(), oaParam.getTarget()); - } - } else { - bpk = id.getValue().getValue(); - } - params.put(PVPConstants.MANDATE_NAT_PER_BPK_FRIENDLY_NAME, bpk); - } - catch (BuildException e) { - // ignore - } - - // params.put(PVPConstants.MANDATE_NAT_PER_ENC_BPK_LIST_FRIENDLY_NAME, ); //not used - - StringBuilder sb = new StringBuilder(); - Iterator fNamesit = physicalPerson.getName().getFamilyName().iterator(); - - while (fNamesit.hasNext()) { - sb.append(" " + fNamesit.next().getValue()); - } - params.put(PVPConstants.MANDATE_NAT_PER_FAMILY_NAME_FRIENDLY_NAME, sb.toString()); - - sb = new StringBuilder(); - Iterator gNamesit = physicalPerson.getName().getGivenName().iterator(); - - while (gNamesit.hasNext()) { - sb.append(" " + gNamesit.next()); - } - params.put(PVPConstants.MANDATE_NAT_PER_GIVEN_NAME_FRIENDLY_NAME, sb.toString()); - - try { - DateFormat mandateFormat = new SimpleDateFormat(MandateBuilder.MANDATE_DATE_OF_BIRTH_FORMAT); - Date date = mandateFormat.parse(physicalPerson.getDateOfBirth()); - DateFormat pvpDateFormat = new SimpleDateFormat(PVPConstants.MANDATE_NAT_PER_BIRTHDATE_FORMAT_PATTERN); - String dateString = pvpDateFormat.format(date); - params.put(PVPConstants.MANDATE_NAT_PER_BIRTHDATE_FRIENDLY_NAME, dateString); - } - catch (ParseException e) { - // ignore - } - - } - - // legal person - CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); - if (corporation != null && corporation.getIdentification().size() != 0) { - IdentificationType id = corporation.getIdentification().get(0); - params.put(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_FRIENDLY_NAME, id.getValue().getValue()); - params.put(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, id.getType()); - params.put(PVPConstants.MANDATE_LEG_PER_FULL_NAME_FRIENDLY_NAME, corporation.getFullName()); - } - - String oid = AttributeExtractor.extractSAMLAttributeOA(EXT_SAML_MANDATE_OID, session); - if (oid != null) { - params.put(PVPConstants.MANDATE_PROF_REP_OID_FRIENDLY_NAME, oid); - } - - String text = AttributeExtractor.extractSAMLAttributeOA(EXT_SAML_MANDATE_OIDTEXTUALDESCRIPTION, session); - - if (text != null) { - params.put(PVPConstants.MANDATE_PROF_REP_DESC_FRIENDLY_NAME, oid); - } - - // params.put("MANDATE-FULL-MANDATE-LIST", ); // not used - - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/Pair.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/Pair.java new file mode 100644 index 000000000..6aeac1247 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/Pair.java @@ -0,0 +1,23 @@ +package at.gv.egovernment.moa.id.protocols.oauth20; + +public class Pair { + private final P1 first; + private final P2 second; + + private Pair(final P1 newFirst, final P2 newSecond) { + this.first = newFirst; + this.second = newSecond; + } + + public P1 getFirst() { + return this.first; + } + + public P2 getSecond() { + return this.second; + } + + public static Pair newInstance(final P1 newFirst, final P2 newSecond) { + return new Pair(newFirst, newSecond); + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java new file mode 100644 index 000000000..6e5d0c2f0 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java @@ -0,0 +1,161 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.attributes; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.StringUtils; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.protocols.oauth20.Pair; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.BPKAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDAuthBlock; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDCcsURL; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDCitizenQAALevelAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDIdentityLinkBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDIssuingNationAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDSectorForIDAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDSignerCertificate; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDSourcePIN; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDSourcePINType; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeGenerator; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateLegalPersonFullNameAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateLegalPersonSourcePinAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateLegalPersonSourcePinTypeAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonBPKAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonBirthDateAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonFamilyNameAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonGivenNameAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonSourcePinAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonSourcePinTypeAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateProfRepDescAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateProfRepOIDAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateReferenceValueAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateTypeAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.logging.Logger; + +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; + +public final class OAuth20AttributeBuilder { + + private OAuth20AttributeBuilder() { + throw new InstantiationError(); + } + + private static IAttributeGenerator> generator = new IAttributeGenerator>() { + + public Pair buildStringAttribute(final String friendlyName, final String name, final String value) { + return Pair.newInstance(friendlyName, new JsonPrimitive(value)); + } + + public Pair buildIntegerAttribute(final String friendlyName, final String name, final int value) { + return Pair.newInstance(friendlyName, new JsonPrimitive(value)); + } + + public Pair buildLongAttribute(final String friendlyName, final String name, final long value) { + return Pair.newInstance(friendlyName, new JsonPrimitive(value)); + } + + public Pair buildEmptyAttribute(final String friendlyName, final String name) { + return Pair.newInstance(friendlyName, new JsonPrimitive("")); + } + + }; + + private static final List buildersOpenId = new ArrayList(); + private static final List buildersProfile = new ArrayList(); + private static final List buildersEID = new ArrayList(); + private static final List buildersEIDGov = new ArrayList(); + private static final List buildersMandate = new ArrayList(); + + static { + // openId + buildersOpenId.add(new OpenIdIssuerAttribute()); + buildersOpenId.add(new OpenIdSubjectIdentifierAttribute()); + buildersOpenId.add(new OpenIdExpirationTimeAttribute()); + buildersOpenId.add(new OpenIdIssueInstantAttribute()); + buildersOpenId.add(new OpenIdAuthenticationTimeAttribute()); + + // profile + buildersProfile.add(new ProfileGivenNameAttribute()); + buildersProfile.add(new ProfileFamilyNameAttribute()); + buildersProfile.add(new ProfileDateOfBirthAttribute()); + + // EID + buildersEID.add(new EIDCcsURL()); + buildersEID.add(new EIDCitizenQAALevelAttributeBuilder()); + buildersEID.add(new EIDIssuingNationAttributeBuilder()); + buildersEID.add(new EIDSectorForIDAttributeBuilder()); + buildersEID.add(new EIDAuthBlock()); + buildersEID.add(new EIDSignerCertificate()); + buildersEID.add(new BPKAttributeBuilder()); + + // eID_gov + buildersEIDGov.add(new EIDSourcePIN()); + buildersEIDGov.add(new EIDSourcePINType()); + buildersEIDGov.add(new EIDIdentityLinkBuilder()); + + // mandate + buildersMandate.add(new MandateTypeAttributeBuilder()); + buildersMandate.add(new MandateReferenceValueAttributeBuilder()); + + buildersMandate.add(new MandateNaturalPersonSourcePinAttributeBuilder()); + buildersMandate.add(new MandateNaturalPersonSourcePinTypeAttributeBuilder()); + buildersMandate.add(new MandateNaturalPersonBPKAttributeBuilder()); + buildersMandate.add(new MandateNaturalPersonFamilyNameAttributeBuilder()); + buildersMandate.add(new MandateNaturalPersonGivenNameAttributeBuilder()); + buildersMandate.add(new MandateNaturalPersonBirthDateAttributeBuilder()); + + buildersMandate.add(new MandateLegalPersonSourcePinAttributeBuilder()); + buildersMandate.add(new MandateLegalPersonSourcePinTypeAttributeBuilder()); + buildersMandate.add(new MandateLegalPersonFullNameAttributeBuilder()); + + buildersMandate.add(new MandateProfRepOIDAttributeBuilder()); + buildersMandate.add(new MandateProfRepDescAttributeBuilder()); + } + + private static void addAttibutes(final List builders, final JsonObject jsonObject, + final AuthenticationSession authSession, final OAAuthParameter oaParam, final AuthenticationData authData) { + for (IAttributeBuilder b : builders) { + try { + Pair attribute = b.build(authSession, oaParam, authData, generator); + if (attribute != null && !StringUtils.isEmpty(attribute.getSecond().getAsString())) { + jsonObject.add(attribute.getFirst(), attribute.getSecond()); + } + } + catch (AttributeException e) { + Logger.warn("Cannot add attribute " + b.getName(), e); + } + } + } + + public static void addScopeOpenId(final JsonObject jsonObject, final AuthenticationSession authSession, + final OAAuthParameter oaParam, final AuthenticationData authData) { + addAttibutes(buildersOpenId, jsonObject, authSession, oaParam, authData); + } + + public static void addScopeProfile(final JsonObject jsonObject, final AuthenticationSession authSession, + final OAAuthParameter oaParam, final AuthenticationData authData) { + addAttibutes(buildersProfile, jsonObject, authSession, oaParam, authData); + } + + public static void addScopeEID(final JsonObject jsonObject, final AuthenticationSession authSession, + final OAAuthParameter oaParam, final AuthenticationData authData) { + addAttibutes(buildersEID, jsonObject, authSession, oaParam, authData); + } + + public static void addScopeEIDGov(final JsonObject jsonObject, final AuthenticationSession authSession, + final OAAuthParameter oaParam, final AuthenticationData authData) { + addAttibutes(buildersEIDGov, jsonObject, authSession, oaParam, authData); + } + + public static void addScopeMandate(final JsonObject jsonObject, final AuthenticationSession authSession, + final OAAuthParameter oaParam, final AuthenticationData authData) { + addAttibutes(buildersMandate, jsonObject, authSession, oaParam, authData); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdAuthenticationTimeAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdAuthenticationTimeAttribute.java new file mode 100644 index 000000000..566257122 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdAuthenticationTimeAttribute.java @@ -0,0 +1,25 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.attributes; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeGenerator; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; + +public class OpenIdAuthenticationTimeAttribute implements IAttributeBuilder { + + public String getName() { + return "auth_time"; + } + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { + return g.buildLongAttribute(this.getName(), "", ((long) (authData.getTimestamp().getTime() / 1000))); + } + + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(this.getName(), ""); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdExpirationTimeAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdExpirationTimeAttribute.java new file mode 100644 index 000000000..bb1a25acc --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdExpirationTimeAttribute.java @@ -0,0 +1,29 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.attributes; + +import java.util.Date; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeGenerator; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; + +public class OpenIdExpirationTimeAttribute implements IAttributeBuilder { + + public static final int expirationTime = 5 * 60; // in seconds + + public String getName() { + return "exp"; + } + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { + return g.buildLongAttribute(this.getName(), "", (long) (new Date().getTime() / 1000 + expirationTime)); + } + + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(this.getName(), ""); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssueInstantAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssueInstantAttribute.java new file mode 100644 index 000000000..f85f1d39c --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssueInstantAttribute.java @@ -0,0 +1,27 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.attributes; + +import java.util.Date; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeGenerator; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; + +public class OpenIdIssueInstantAttribute implements IAttributeBuilder { + + public String getName() { + return "iat"; + } + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { + return g.buildLongAttribute(this.getName(), "", (long) (new Date().getTime() / 1000)); + } + + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(this.getName(), ""); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssuerAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssuerAttribute.java new file mode 100644 index 000000000..e12d2e718 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssuerAttribute.java @@ -0,0 +1,25 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.attributes; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeGenerator; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; + +public class OpenIdIssuerAttribute implements IAttributeBuilder { + + public String getName() { + return "iss"; + } + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { + return g.buildStringAttribute(this.getName(), "", authData.getIssuer()); + } + + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(this.getName(), ""); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdSubjectIdentifierAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdSubjectIdentifierAttribute.java new file mode 100644 index 000000000..36efb18e9 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdSubjectIdentifierAttribute.java @@ -0,0 +1,25 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.attributes; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeGenerator; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; + +public class OpenIdSubjectIdentifierAttribute implements IAttributeBuilder { + + public String getName() { + return "sub"; + } + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { + return g.buildStringAttribute(this.getName(), "", authData.getBPK()); + } + + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(this.getName(), ""); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileDateOfBirthAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileDateOfBirthAttribute.java new file mode 100644 index 000000000..b9d7b984e --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileDateOfBirthAttribute.java @@ -0,0 +1,25 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.attributes; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeGenerator; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; + +public class ProfileDateOfBirthAttribute implements IAttributeBuilder { + + public String getName() { + return "birthdate"; + } + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { + return g.buildStringAttribute(this.getName(), "", authData.getDateOfBirth()); + } + + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(this.getName(), ""); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileFamilyNameAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileFamilyNameAttribute.java new file mode 100644 index 000000000..eef4931bf --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileFamilyNameAttribute.java @@ -0,0 +1,25 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.attributes; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeGenerator; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; + +public class ProfileFamilyNameAttribute implements IAttributeBuilder { + + public String getName() { + return "family_name"; + } + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { + return g.buildStringAttribute(this.getName(), "", authData.getFamilyName()); + } + + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(this.getName(), ""); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileGivenNameAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileGivenNameAttribute.java new file mode 100644 index 000000000..8cb13b912 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileGivenNameAttribute.java @@ -0,0 +1,25 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.attributes; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeGenerator; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; + +public class ProfileGivenNameAttribute implements IAttributeBuilder { + + public String getName() { + return "given_name"; + } + + public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, + IAttributeGenerator g) throws AttributeException { + return g.buildStringAttribute(this.getName(), "", authData.getGivenName()); + } + + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(this.getName(), ""); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Signer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Signer.java new file mode 100644 index 000000000..9755e3c0a --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Signer.java @@ -0,0 +1,99 @@ +/** + * Copyright 2010 Google Inc. + * + * Licensed 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 at.gv.egovernment.moa.id.protocols.oauth20.json; + +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.PrivateKey; +import java.security.Signature; +import java.security.SignatureException; + +import net.oauth.jsontoken.crypto.AbstractSigner; +import net.oauth.jsontoken.crypto.RsaSHA256Signer; +import net.oauth.jsontoken.crypto.SignatureAlgorithm; + +/** + * Signer that can sign byte arrays using a {@link PrivateKey} and SHA-256.
+ * This is something like a copy of the {@link RsaSHA256Signer}. + * + */ +public class OAuth20SHA256Signer extends AbstractSigner implements OAuthSigner { + + private final Signature signature; + private final PrivateKey signingKey; + private final OAuthSignatureAlgorithm algorithm; + + /** + * Public constructor. + * + * @param issuer + * The id of this signer, to be included in the JSON Token's envelope. + * @param keyId + * The id of the key used by this signer, to be included in the JSON Token's + * envelope. + * @param key + * the private key to be used for signing. + * @throws InvalidKeyException + * if the key is unsuitable for RSA signing. + */ + public OAuth20SHA256Signer(final String issuer, final String keyId, final PrivateKey key) throws InvalidKeyException { + super(issuer, keyId); + + this.signingKey = key; + this.algorithm = OAuth20SignatureUtil.findSignature(key); + + try { + this.signature = this.algorithm.getSignatureInstance(); + this.signature.initSign(signingKey); + } + catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("Cannot get algorithm for the given private key", e); + } + catch (NoSuchProviderException e) { + throw new IllegalStateException("Cannot get algorithm for the given private key", e); + } + } + + /* + * (non-Javadoc) + * @see net.oauth.jsontoken.crypto.Signer#getSignatureAlgorithm() + */ + public SignatureAlgorithm getSignatureAlgorithm() { + // it is fine to return RS256 because we overwrite the JsonToken for the algorithm name. But + // we need the internal SHA256 which is used. + return SignatureAlgorithm.RS256; + } + + /* + * (non-Javadoc) + * @see net.oauth.jsontoken.crypto.Signer#sign(byte[]) + */ + public byte[] sign(byte[] source) throws SignatureException { + try { + signature.initSign(signingKey); + } + catch (InvalidKeyException e) { + throw new RuntimeException("key somehow became invalid since calling the constructor"); + } + signature.update(source); + return signature.sign(); + } + + public OAuthSignatureAlgorithm getOAuthSignatureAlgorithm() { + return this.algorithm; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Verifier.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Verifier.java new file mode 100644 index 000000000..e7e18cbd9 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Verifier.java @@ -0,0 +1,62 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.json; + +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.PublicKey; +import java.security.Signature; +import java.security.SignatureException; + +import net.oauth.jsontoken.crypto.RsaSHA256Verifier; +import net.oauth.jsontoken.crypto.Verifier; + +/** + * A verifier that can verify signatures on byte arrays using a {@link PublicKey} and SHA-256.
+ * This is something like a copy of the {@link RsaSHA256Verifier}. + */ +public class OAuth20SHA256Verifier implements Verifier { + + private final PublicKey verificationKey; + private final Signature signer; + + /** + * Public Constructor. + * + * @param verificationKey + * the key used to verify the signature. + */ + public OAuth20SHA256Verifier(final PublicKey verificationKey) { + this.verificationKey = verificationKey; + + try { + this.signer = OAuth20SignatureUtil.findSignature(verificationKey).getSignatureInstance(); + this.signer.initVerify(verificationKey); + } + catch (InvalidKeyException e) { + throw new IllegalStateException("key is invalid", e); + } + catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("Cannot get algorithm for the given private key", e); + } + catch (NoSuchProviderException e) { + throw new IllegalStateException("Cannot get algorithm for the given private key", e); + } + } + + /* + * (non-Javadoc) + * @see net.oauth.jsontoken.crypto.Verifier#verifySignature(byte[], byte[]) + */ + public void verifySignature(byte[] source, byte[] signature) throws SignatureException { + try { + signer.initVerify(verificationKey); + } + catch (InvalidKeyException e) { + throw new RuntimeException("key someone become invalid since calling the constructor"); + } + signer.update(source); + if (!signer.verify(signature)) { + throw new SignatureException("signature did not verify"); + } + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SignatureUtil.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SignatureUtil.java new file mode 100644 index 000000000..78653ceb2 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SignatureUtil.java @@ -0,0 +1,94 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.json; + +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import java.security.interfaces.ECPrivateKey; +import java.security.interfaces.ECPublicKey; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; + +import org.apache.commons.lang.StringUtils; +import org.opensaml.xml.security.x509.BasicX509Credential; + +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Configuration; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20CertificateErrorException; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.KeyStoreUtils; + +public final class OAuth20SignatureUtil { + + private OAuth20SignatureUtil() { + throw new InstantiationError(); + } + + static OAuthSignatureAlgorithm findSignature(final PrivateKey key) { + Logger.debug("OAuth - Looking for signature for key " + key.getClass()); + if (key instanceof RSAPrivateKey) { + Logger.debug("OAuth - going to uses SHA256withRSA signature"); + return OAuthSignatureAlgorithm.RS256; + } else if (key instanceof ECPrivateKey) { + Logger.debug("OAuth - going to uses SHA256withECDSA signature"); + return OAuthSignatureAlgorithm.ECDSA256; + } else if (key instanceof iaik.security.ecc.ecdsa.ECPrivateKey) { + Logger.debug("OAuth - going to uses SHA256withECDSA signature with iaik"); + return OAuthSignatureAlgorithm.ECDSA256_IAKIK; + } else { + throw new IllegalStateException("Cannot find an alorithm for the given private key"); + } + } + + static OAuthSignatureAlgorithm findSignature(final PublicKey key) { + if (key instanceof RSAPublicKey) { + Logger.debug("OAuth - going to uses SHA256withRSA signature"); + return OAuthSignatureAlgorithm.RS256; + } else if (key instanceof ECPublicKey) { + Logger.debug("OAuth - going to uses SHA256withECDSA signature"); + return OAuthSignatureAlgorithm.ECDSA256; + } else if (key instanceof iaik.security.ecc.ecdsa.ECPublicKey) { + Logger.debug("OAuth - going to uses SHA256withECDSA signature with iaik"); + return OAuthSignatureAlgorithm.ECDSA256_IAKIK; + } else { + throw new IllegalStateException("Cannot find an alorithm for the given private key"); + } + } + + public static OAuthSigner loadSigner(String issuer) throws OAuth20Exception { + OAuth20Configuration globalConfig = OAuth20Configuration.getInstance(); + + if (StringUtils.isEmpty(globalConfig.getJWTKeyStore())) { + throw new OAuth20CertificateErrorException("keystore"); + } + + if (StringUtils.isEmpty(globalConfig.getJWTKeyName())) { + throw new OAuth20CertificateErrorException("key name"); + } + + try { + KeyStore ks = KeyStoreUtils.loadKeyStore(globalConfig.getJWTKeyStore(), globalConfig.getJWTKeyStorePassword()); + + X509Certificate certificate = (X509Certificate) ks.getCertificate(globalConfig.getJWTKeyName()); + + PrivateKey privateKey = (PrivateKey) ks.getKey(globalConfig.getJWTKeyName(), globalConfig.getJWTKeyPassword() + .toCharArray()); + BasicX509Credential credential = new BasicX509Credential(); + credential.setEntityCertificate(certificate); + credential.setPrivateKey(privateKey); + + // Logger.debug("Going to use X509Certificate:"); + // Logger.debug(certificate); + // Logger.debug("Going to use private key:"); + // Logger.debug(privateKey); + + return new OAuth20SHA256Signer(issuer, globalConfig.getJWTKeyName(), credential.getPrivateKey()); + + } + catch (Exception e) { + Logger.error(e.getMessage(), e); + throw new OAuth20CertificateErrorException("keystore"); + } + + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthJsonToken.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthJsonToken.java new file mode 100644 index 000000000..1792ec91e --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthJsonToken.java @@ -0,0 +1,27 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.json; + +import net.oauth.jsontoken.JsonToken; + +import com.google.gson.JsonObject; + +public class OAuthJsonToken extends JsonToken { + + private final OAuthSigner signer; + + public OAuthJsonToken(OAuthSigner signer) { + super(signer); + this.signer = signer; + } + + @Override + public JsonObject getHeader() { + JsonObject header = new JsonObject(); + header.addProperty(ALGORITHM_HEADER, signer.getOAuthSignatureAlgorithm().getAlgorithm()); + String keyId = getKeyId(); + if (keyId != null) { + header.addProperty(KEY_ID_HEADER, keyId); + } + return header; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSignatureAlgorithm.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSignatureAlgorithm.java new file mode 100644 index 000000000..5e023ff35 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSignatureAlgorithm.java @@ -0,0 +1,62 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.json; + +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.Signature; + +import org.apache.commons.lang.StringUtils; + +/** + * Enum of the signature algorithms supported by this package. + */ +public enum OAuthSignatureAlgorithm { + ECDSA256("SHA256withECDSA", "ECDSA256", null), RS256("SHA256withRSA", "RS256", null), ECDSA256_IAKIK("SHA1withECDSA", "ECDSA256", + "IAIK_ECC"); + + private final String signatureName; + private final String algorithm; + private final String providerName; + + private OAuthSignatureAlgorithm(final String signatureName, final String hashAlg, final String providerName) { + this.signatureName = signatureName; + this.algorithm = hashAlg; + this.providerName = providerName; + } + + /** + * What the signature algorithm is named in the "alg" parameter in a JSON Token's envelope. + */ + public String getAlgorithm() { + return this.algorithm; + } + + /** + * + * @return the signature name like SHA256withECDSA or SHA256withRSA + */ + public String getSignatureName() { + return this.signatureName; + } + + /** + * Calls {@link Signature#getInstance(String)} with the defined signature name + * + * @return + * @throws NoSuchAlgorithmException + * @throws NoSuchProviderException + */ + public Signature getSignatureInstance() throws NoSuchAlgorithmException, NoSuchProviderException { + if (!StringUtils.isEmpty(this.providerName)) { + return Signature.getInstance(this.signatureName, this.providerName); + } else { + return Signature.getInstance(this.signatureName); + } + } + + /** + * Given the name of the algorithm in the envelope, returns the corresponding enum instance. + */ + public static OAuthSignatureAlgorithm getFromJsonName(String name) { + return OAuthSignatureAlgorithm.valueOf(name); + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSigner.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSigner.java new file mode 100644 index 000000000..265afa7e7 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSigner.java @@ -0,0 +1,7 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.json; + +import net.oauth.jsontoken.crypto.Signer; + +public interface OAuthSigner extends Signer { + public abstract OAuthSignatureAlgorithm getOAuthSignatureAlgorithm(); +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java new file mode 100644 index 000000000..68f508103 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java @@ -0,0 +1,112 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.protocol; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.moduls.IAction; +import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20SessionObject; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ResponseTypeException; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ServerErrorException; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.logging.Logger; + +class OAuth20AuthAction implements IAction { + + public String processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, + AuthenticationSession moasession) throws MOAIDException { + + OAuth20AuthRequest oAuthRequest = (OAuth20AuthRequest) req; + + // OAAuthParameter oaParam = + // AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(oAuthRequest.getOAURL()); + // AuthenticationData authData = + // AuthenticationServer.buildAuthenticationData(moasession, oaParam, + // oAuthRequest.getTarget()); + + String responseType = oAuthRequest.getResponseType(); + AuthenticationSession session = null; + + try { + session = AuthenticationSessionStoreage.createSession(); + + String code = session.getSessionID();// AuthenticationSessionStoreage.changeSessionID(moasession); + Logger.debug("Stored session with id: " + code); + OAuth20SessionObject o = new OAuth20SessionObject(); + if (responseType.equals(OAuth20Constants.RESPONSE_CODE)) { + o.setScope(oAuthRequest.getScope()); + o.setCode(code); + o.setAuthDataSession(moasession); + + } else if (responseType.equals(OAuth20Constants.RESPONSE_TOKEN)) { + throw new OAuth20ResponseTypeException(); + } + + // store data in oath session + session.setoAuth20SessionObject(o); + AuthenticationSessionStoreage.storeSession(session); + Logger.debug("Saved OAuth20SessionObject in session with id: " + session.getSessionID()); + + // add code and state to redirect url + httpResp.setStatus(HttpServletResponse.SC_FOUND); + String redirectURI = oAuthRequest.getRedirectUri(); + String state = oAuthRequest.getState(); + + redirectURI = this.addURLParameter(redirectURI, OAuth20Constants.RESPONSE_CODE, code); + redirectURI = this.addURLParameter(redirectURI, OAuth20Constants.PARAM_STATE, state); + + String finalUrl = redirectURI; + httpResp.addHeader("Location", finalUrl); + Logger.debug("REDIRECT TO: " + finalUrl.toString()); + } + catch (Exception e) { + try { + if (session != null) { + Logger.debug("Going to destroy session: " + session.getSessionID()); + AuthenticationSessionStoreage.destroySession(session.getSessionID()); + } + } + catch (MOADatabaseException e1) { + } + if (e instanceof OAuth20Exception) { + throw (OAuth20Exception) e; + } + throw new OAuth20ServerErrorException(); + } + + return null; + } + + /* + * (non-Javadoc) + * @see + * at.gv.egovernment.moa.id.moduls.IAction#needAuthentication(at.gv.egovernment.moa.id.moduls + * .IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) { + return true; + } + + private String addURLParameter(String url, String name, String value) { + String param = name + "=" + value; + if (url.indexOf("?") < 0) { + return url + "?" + param; + } else { + return url + "&" + param; + } + } + + /* + * (non-Javadoc) + * @see at.gv.egovernment.moa.id.moduls.IAction#getDefaultActionName() + */ + public String getDefaultActionName() { + return OAuth20Protocol.AUTH_ACTION; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java new file mode 100644 index 000000000..eafc56214 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java @@ -0,0 +1,134 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.protocol; + +import javax.servlet.http.HttpServletRequest; + +import at.gv.egovernment.moa.id.commons.db.dao.config.OAOAUTH20; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Util; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20AccessDeniedException; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ResponseTypeException; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20WrongParameterException; + +class OAuth20AuthRequest extends OAuth20BaseRequest { + + private static final long serialVersionUID = 1L; + + private String responseType; + private String state; + private String redirectUri; + private String scope; + private String clientID; + + /** + * @return the responseType + */ + public String getResponseType() { + return responseType; + } + + /** + * @param responseType + * the responseType to set + */ + public void setResponseType(String responseType) { + this.responseType = responseType; + } + + /** + * @return the state + */ + public String getState() { + return state; + } + + /** + * @param state + * the state to set + */ + public void setState(String state) { + this.state = state; + } + + /** + * @return the redirectUri + */ + public String getRedirectUri() { + return redirectUri; + } + + /** + * @param redirectUri + * the redirectUri to set + */ + public void setRedirectUri(String redirectUri) { + this.redirectUri = redirectUri; + } + + /** + * @return the scope + */ + public String getScope() { + return scope; + } + + /** + * @param scope + * the scope to set + */ + public void setScope(String scope) { + this.scope = scope; + } + + /** + * @return the clientID + */ + public String getClientID() { + return clientID; + } + + /** + * @param clientID + * the clientID to set + */ + public void setClientID(String clientID) { + this.clientID = clientID; + } + + @Override + protected void populateSpecialParameters(HttpServletRequest request) throws OAuth20Exception { + this.setResponseType(this.getParam(request, OAuth20Constants.PARAM_RESPONSE_TYPE, true)); + this.setState(this.getParam(request, OAuth20Constants.PARAM_STATE, true)); + this.setRedirectUri(this.getParam(request, OAuth20Constants.PARAM_REDIRECT_URI, true)); + this.setClientID(this.getParam(request, OAuth20Constants.PARAM_CLIENT_ID, true)); + this.setScope(this.getParam(request, OAuth20Constants.PARAM_SCOPE, false)); + + // check for response type + if (!this.responseType.equals(OAuth20Constants.RESPONSE_CODE)) { + throw new OAuth20ResponseTypeException(); + } + + // check state for invalid characters (like < > & ; ... javascript ... to prevent xss) + if (!OAuth20Util.isValidStateValue(this.getState())) { + throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_STATE); + } + + // check if client id and redirect uri are ok + try { + // OAOAUTH20 cannot be null at this point. check was done in base request + OAOAUTH20 oAuthConfig = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(this.getOAURL()) + .getoAuth20Config(); + + if (!this.getClientID().equals(oAuthConfig.getOAuthClientId()) + || !this.getRedirectUri().equals(oAuthConfig.getOAuthRedirectUri())) { + throw new OAuth20AccessDeniedException(); + } + } + catch (ConfigurationException e) { + throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID); + } + + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java new file mode 100644 index 000000000..e6766ddd5 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java @@ -0,0 +1,121 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.protocol; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang.StringUtils; + +import at.gv.egovernment.moa.id.commons.db.dao.config.OAOAUTH20; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.moduls.RequestImpl; +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20InvalidRequestException; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ServerErrorException; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20WrongParameterException; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.logging.Logger; + +abstract class OAuth20BaseRequest extends RequestImpl { + + private static final long serialVersionUID = 1L; + + protected Set allowedParameters = new HashSet(); + + protected OAuth20BaseRequest() { + + } + + protected String getParam(final HttpServletRequest request, final String name, final boolean isNeeded) throws OAuth20Exception { + String param = request.getParameter(name); + Logger.debug("Reading param " + name + " from HttpServletRequest with value " + param); + + if (isNeeded && StringUtils.isEmpty(param)) { + throw new OAuth20WrongParameterException(name); + } + + this.allowedParameters.add(name); + + return param; + } + + protected void populateParameters(final HttpServletRequest request) throws OAuth20Exception { + + // moa id - load oa with client id! + try { + String oaURL = StringEscapeUtils.escapeHtml(this.getParam(request, OAuth20Constants.PARAM_CLIENT_ID, true)); + if (!ParamValidatorUtils.isValidOA(oaURL)) { + throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID); + } + this.setOAURL(oaURL); + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(oaURL); + + if (oaParam == null) { + throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID); + } + this.setTarget(oaParam.getTarget()); + + OAOAUTH20 config = oaParam.getoAuth20Config(); + if (config == null) { + throw new OAuth20InvalidRequestException(); + } + if (StringUtils.isEmpty(config.getOAuthClientSecret()) || StringUtils.isEmpty(config.getOAuthClientId()) + || StringUtils.isEmpty(config.getOAuthRedirectUri())) { + throw new OAuth20ServerErrorException(); + } + } + catch (ConfigurationException e) { + throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID); + } + + // oAuth + this.populateSpecialParameters(request); + + // cleanup parameters + this.checkAllowedParameters(request); + } + + private void checkAllowedParameters(final HttpServletRequest request) { + Logger.debug("Going to check for allowed parameters"); + this.allowedParameters.add(OAuth20Constants.PARAM_MOA_ACTION); + this.allowedParameters.add(OAuth20Constants.PARAM_MOA_MOD); + + @SuppressWarnings("rawtypes") + Iterator iter = request.getParameterMap().keySet().iterator(); + while (iter.hasNext()) { + String name = (String) iter.next(); + if (!this.allowedParameters.contains(name)) { + + Logger.debug("Found wrong parameter: " + name); + throw new OAuth20WrongParameterException(name); + } + } + + } + + protected abstract void populateSpecialParameters(final HttpServletRequest request) throws OAuth20Exception; + + public static OAuth20BaseRequest newInstance(final String action, final HttpServletRequest request) throws OAuth20Exception { + OAuth20BaseRequest res; + + if (action.equals(OAuth20Protocol.AUTH_ACTION)) { + res = new OAuth20AuthRequest(); + } else if (action.equals(OAuth20Protocol.TOKEN_ACTION)) { + res = new OAuth20TokenRequest(); + } else { + throw new OAuth20InvalidRequestException(); + } + + res.setAction(action); + res.setModule(OAuth20Protocol.NAME); + + res.populateParameters(request); + return res; + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20Protocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20Protocol.java new file mode 100644 index 000000000..db18b3a3e --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20Protocol.java @@ -0,0 +1,167 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.protocol; + +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; + +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.moduls.IAction; +import at.gv.egovernment.moa.id.moduls.IModulInfo; +import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Util; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; +import at.gv.egovernment.moa.logging.Logger; + +import com.google.gson.JsonObject; + +public class OAuth20Protocol implements IModulInfo { + + public static final String NAME = OAuth20Protocol.class.getName(); + public static final String PATH = "id_oauth20"; + + public static final String AUTH_ACTION = "AUTH"; + public static final String TOKEN_ACTION = "TOKEN"; + + private static HashMap actions = new HashMap(); + + static { + actions.put(AUTH_ACTION, new OAuth20AuthAction()); + actions.put(TOKEN_ACTION, new OAuth20TokenAction()); + } + + public String getName() { + return NAME; + } + + public String getPath() { + return PATH; + } + + public IAction getAction(String action) { + return actions.get(action); + } + + /* + * (non-Javadoc) + * @see + * at.gv.egovernment.moa.id.moduls.IModulInfo#preProcess(javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse, java.lang.String) + */ + public IRequest preProcess(HttpServletRequest request, HttpServletResponse resp, String action) throws MOAIDException { + // validation is done inside creation + OAuth20BaseRequest res = OAuth20BaseRequest.newInstance(action, request); + Logger.debug("Created: " + res); + return res; + } + + /* + * (non-Javadoc) + * @see + * at.gv.egovernment.moa.id.moduls.IModulInfo#canHandleRequest(javax.servlet.http.HttpServletRequest + * , javax.servlet.http.HttpServletResponse) + */ + public IAction canHandleRequest(HttpServletRequest request, HttpServletResponse response) { + if (request.getParameter("action").equals(AUTH_ACTION)) { + return getAction(AUTH_ACTION); + } else if (request.getParameter("action").equals(TOKEN_ACTION)) { + return getAction(TOKEN_ACTION); + } + + return null;// getAction(AUTH_ACTION); + } + + /* + * (non-Javadoc) + * @see at.gv.egovernment.moa.id.moduls.IModulInfo#generateErrorMessage(java.lang.Throwable, + * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, + * at.gv.egovernment.moa.id.moduls.IRequest) + */ + public boolean generateErrorMessage(Throwable e, HttpServletRequest request, HttpServletResponse response, IRequest protocolRequest) + throws Throwable { + + StringBuilder url = new StringBuilder(); + + String paramRedirect = request.getParameter(OAuth20Constants.PARAM_REDIRECT_URI); + + if (e instanceof OAuth20Exception) { + + String action = request.getParameter("action"); + + Logger.debug("Going to throw O OAuth20Exception for action: " + action); + OAuth20Exception oAuth20Exception = ((OAuth20Exception) e); + + String errorCode = oAuth20Exception.getErrorCode(); + String errorDescription = oAuth20Exception.getMessage(); + // String errorUri = "http://tools.ietf.org/html/draft-ietf-oauth-v2-11"; + + if (action.equals(AUTH_ACTION)) { + + // check if given redirect url is ok + if (StringUtils.isNotEmpty(paramRedirect) && OAuth20Util.isUrl(paramRedirect)) { + url.append(paramRedirect); + + // otherwise throw an + } else { + throw new MOAIDException("oauth20.01", new Object[] {}); + } + + String state = request.getParameter(OAuth20Constants.PARAM_STATE); + + OAuth20Util.addParameterToURL(url, OAuth20Constants.PARAM_ERROR, errorCode); + OAuth20Util.addParameterToURL(url, OAuth20Constants.PARAM_ERROR_DESCRIPTION, + URLEncoder.encode(oAuth20Exception.getMessageId() + ": " + errorDescription, "UTF-8")); + // OAuth20Util.addParameterToURL(url, OAuth20Constants.PARAM_ERROR_URI, errorUri); + OAuth20Util.addParameterToURL(url, OAuth20Constants.PARAM_STATE, state); + + response.setContentType("text/html"); + response.setStatus(HttpServletResponse.SC_FOUND); + response.addHeader("Location", url.toString()); + Logger.debug("REDIRECT TO: " + url.toString()); + return true; + + } else if (action.equals(TOKEN_ACTION)) { + Map params = new HashMap(); + params.put(OAuth20Constants.PARAM_ERROR, errorCode); + params.put(OAuth20Constants.PARAM_ERROR_DESCRIPTION, + URLEncoder.encode(oAuth20Exception.getMessageId() + ": " + errorDescription, "UTF-8")); + // params.put(OAuth20Constants.PARAM_ERROR_URI, errorUri); + + // create response + JsonObject jsonObject = new JsonObject(); + OAuth20Util.addProperytiesToJsonObject(jsonObject, params); + String jsonResponse = jsonObject.toString(); + Logger.debug("JSON Response: " + jsonResponse); + + // write respone to http response + response.setContentType("application/json"); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.getOutputStream().print(jsonResponse); + response.getOutputStream().close(); + + return true; + } + + } + + return false; + + } + + /* + * (non-Javadoc) + * @see + * at.gv.egovernment.moa.id.moduls.IModulInfo#validate(javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.moduls.IRequest) + */ + public boolean validate(HttpServletRequest request, HttpServletResponse response, IRequest pending) { + // we validate in the preProcess + return true; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java new file mode 100644 index 000000000..b01b2eae7 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java @@ -0,0 +1,164 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.protocol; + +import java.security.SignatureException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.moduls.IAction; +import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20SessionObject; +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Util; +import at.gv.egovernment.moa.id.protocols.oauth20.Pair; +import at.gv.egovernment.moa.id.protocols.oauth20.attributes.OAuth20AttributeBuilder; +import at.gv.egovernment.moa.id.protocols.oauth20.attributes.OpenIdExpirationTimeAttribute; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ServerErrorException; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20UnauthorizedClientException; +import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuth20SignatureUtil; +import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuthJsonToken; +import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuthSigner; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.logging.Logger; + +import com.google.gson.JsonObject; + +class OAuth20TokenAction implements IAction { + + public String processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, + AuthenticationSession moasession) throws MOAIDException { + + AuthenticationSession session = null; + try { + OAuth20TokenRequest oAuthRequest = (OAuth20TokenRequest) req; + + session = AuthenticationSessionStoreage.getSession(oAuthRequest.getCode()); + if (session == null) { + throw new OAuth20UnauthorizedClientException(); + } + + OAuth20SessionObject auth20SessionObject = session.getoAuth20SessionObject(); + Logger.debug("Loaded OAuth20SessionObject from session: " + session.getSessionID()); + + // do checking for different grant types and code + if (auth20SessionObject == null || !auth20SessionObject.getCode().equals(oAuthRequest.getCode())) { + throw new OAuth20UnauthorizedClientException(); + } else { + Logger.debug("Loaded of OAuth20SessionObject was successful"); + } + + final String accessToken = UUID.randomUUID().toString(); + + // create response + Map params = new HashMap(); + params.put(OAuth20Constants.RESPONSE_ACCESS_TOKEN, accessToken); + params.put(OAuth20Constants.RESPONSE_TOKEN_TYPE, OAuth20Constants.RESPONSE_TOKEN_TYPE_VALUE_BEARER); + params.put(OAuth20Constants.RESPONSE_EXPIRES_IN, OpenIdExpirationTimeAttribute.expirationTime); + + // build id token and scope + Pair pair = buildIdToken(auth20SessionObject.getScope(), oAuthRequest, + auth20SessionObject.getAuthDataSession()); + Logger.debug("RESPONSE ID_TOKEN: " + pair.getFirst()); + params.put(OAuth20Constants.RESPONSE_ID_TOKEN, pair.getFirst()); + Logger.debug("RESPONSE SCOPE: " + pair.getSecond()); + params.put(OAuth20Constants.PARAM_SCOPE, pair.getSecond()); + + // create response + JsonObject jsonObject = new JsonObject(); + OAuth20Util.addProperytiesToJsonObject(jsonObject, params); + String jsonResponse = jsonObject.toString(); + Logger.debug("JSON Response: " + jsonResponse); + + // write respone to http response + httpResp.setContentType("application/json"); + httpResp.setStatus(HttpServletResponse.SC_OK); + httpResp.getOutputStream().print(jsonResponse); + httpResp.getOutputStream().close(); + + return null; + } + catch (Exception e) { + Logger.error(e.getMessage(), e); + throw new OAuth20ServerErrorException(); + } + + finally { + if (session != null) { + // destroy session for clean up + try { + Logger.debug("Going to destroy session: " + session.getSessionID()); + AuthenticationSessionStoreage.destroySession(session.getSessionID()); + } + catch (MOADatabaseException e) { + } + } + } + } + + /* + * (non-Javadoc) + * @see + * at.gv.egovernment.moa.id.moduls.IAction#needAuthentication(at.gv.egovernment.moa.id.moduls + * .IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) { + return false; + } + + /* + * (non-Javadoc) + * @see at.gv.egovernment.moa.id.moduls.IAction#getDefaultActionName() + */ + public String getDefaultActionName() { + return OAuth20Protocol.TOKEN_ACTION; + } + + private Pair buildIdToken(String scope, OAuth20TokenRequest oAuthRequest, AuthenticationSession session) + throws MOAIDException, SignatureException { + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(oAuthRequest.getOAURL()); + AuthenticationData authData = AuthenticationServer.buildAuthenticationData(session, oaParam, oAuthRequest.getTarget()); + + OAuthSigner signer = OAuth20SignatureUtil.loadSigner(authData.getIssuer()); + OAuthJsonToken token = new OAuthJsonToken(signer); + + StringBuilder resultScopes = new StringBuilder(); + // always fill with open id + OAuth20AttributeBuilder.addScopeOpenId(token.getPayloadAsJsonObject(), session, oaParam, authData); + resultScopes.append("openId"); + + for (String s : scope.split(" ")) { + if (s.equalsIgnoreCase("profile")) { + OAuth20AttributeBuilder.addScopeProfile(token.getPayloadAsJsonObject(), session, oaParam, authData); + resultScopes.append(" profile"); + } else if (s.equalsIgnoreCase("eID")) { + OAuth20AttributeBuilder.addScopeEID(token.getPayloadAsJsonObject(), session, oaParam, authData); + resultScopes.append(" eID"); + } else if (s.equalsIgnoreCase("eID_gov") && oaParam.getBusinessService()) { + OAuth20AttributeBuilder.addScopeEIDGov(token.getPayloadAsJsonObject(), session, oaParam, authData); + resultScopes.append(" eID_gov"); + } else if (s.equalsIgnoreCase("mandate") && session.getUseMandate() && oaParam.getBusinessService()) { + OAuth20AttributeBuilder.addScopeMandate(token.getPayloadAsJsonObject(), session, oaParam, authData); + resultScopes.append(" mandate"); + } + // TODO parser STORK + } + + // add properties and sign + // HmacSHA256Signer signer = new HmacSHA256Signer("testSigner", "key_id", + // "super_secure_pwd".getBytes()); + // Signer signer = OAuth20Util.loadSigner(authData.getIssuer(), oaParam.getoAuth20Config()); + + return Pair.newInstance(token.serializeAndSign(), resultScopes.toString()); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java new file mode 100644 index 000000000..99682076d --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java @@ -0,0 +1,118 @@ +package at.gv.egovernment.moa.id.protocols.oauth20.protocol; + +import javax.servlet.http.HttpServletRequest; + +import at.gv.egovernment.moa.id.commons.db.dao.config.OAOAUTH20; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20AccessDeniedException; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20InvalidGrantException; +import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20WrongParameterException; + +class OAuth20TokenRequest extends OAuth20BaseRequest { + + private static final long serialVersionUID = 1L; + + private String code; + private String grantType; + private String clientID; + private String clientSecret; + + /** + * @return the code + */ + public String getCode() { + return code; + } + + /** + * @param code + * the code to set + */ + public void setCode(String code) { + this.code = code; + } + + /** + * @return the grantType + */ + public String getGrantType() { + return grantType; + } + + /** + * @param grantType + * the grantType to set + */ + public void setGrantType(String grantType) { + this.grantType = grantType; + } + + /** + * @return the clientID + */ + public String getClientID() { + return clientID; + } + + /** + * @param clientID + * the clientID to set + */ + public void setClientID(String clientID) { + this.clientID = clientID; + } + + /** + * @return the clientSecret + */ + public String getClientSecret() { + return clientSecret; + } + + /** + * @param clientSecret + * the clientSecret to set + */ + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } + + @Override + protected void populateSpecialParameters(HttpServletRequest request) throws OAuth20Exception { + this.setCode(this.getParam(request, OAuth20Constants.RESPONSE_CODE, true)); + this.setGrantType(this.getParam(request, OAuth20Constants.PARAM_GRANT_TYPE, true)); + this.setClientID(this.getParam(request, OAuth20Constants.PARAM_CLIENT_ID, true)); + this.setClientSecret(this.getParam(request, OAuth20Constants.PARAM_CLIENT_SECRET, true)); + + // check for grant type + if (!this.getGrantType().equals(OAuth20Constants.PARAM_GRANT_TYPE_VALUE_AUTHORIZATION_CODE)) { + throw new OAuth20InvalidGrantException(); + } + + // check if client id and secret are ok + try { + // OAOAUTH20 cannot be null at this point. check was done in base request + OAOAUTH20 oAuthConfig = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(this.getOAURL()) + .getoAuth20Config(); + + if (!this.getClientID().equals(oAuthConfig.getOAuthClientId())) { + throw new OAuth20AccessDeniedException(); + } + + if (!this.getClientSecret().equals(oAuthConfig.getOAuthClientSecret())) { + throw new OAuth20AccessDeniedException(); + } + + } + catch (ConfigurationException e) { + throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID); + } + + //add valid parameters + this.allowedParameters.add(OAuth20Constants.PARAM_SCOPE); + this.allowedParameters.add(OAuth20Constants.PARAM_REDIRECT_URI); + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20AuthRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20AuthRequest.java deleted file mode 100644 index 8aac75413..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20AuthRequest.java +++ /dev/null @@ -1,134 +0,0 @@ -package at.gv.egovernment.moa.id.protocols.oauth20.requests; - -import javax.servlet.http.HttpServletRequest; - -import at.gv.egovernment.moa.id.commons.db.dao.config.OAOAUTH20; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; -import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Util; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20AccessDeniedException; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ResponseTypeException; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20WrongParameterException; - -public class OAuth20AuthRequest extends OAuth20BaseRequest { - - private static final long serialVersionUID = 1L; - - private String responseType; - private String state; - private String redirectUri; - private String scope; - private String clientID; - - /** - * @return the responseType - */ - public String getResponseType() { - return responseType; - } - - /** - * @param responseType - * the responseType to set - */ - public void setResponseType(String responseType) { - this.responseType = responseType; - } - - /** - * @return the state - */ - public String getState() { - return state; - } - - /** - * @param state - * the state to set - */ - public void setState(String state) { - this.state = state; - } - - /** - * @return the redirectUri - */ - public String getRedirectUri() { - return redirectUri; - } - - /** - * @param redirectUri - * the redirectUri to set - */ - public void setRedirectUri(String redirectUri) { - this.redirectUri = redirectUri; - } - - /** - * @return the scope - */ - public String getScope() { - return scope; - } - - /** - * @param scope - * the scope to set - */ - public void setScope(String scope) { - this.scope = scope; - } - - /** - * @return the clientID - */ - public String getClientID() { - return clientID; - } - - /** - * @param clientID - * the clientID to set - */ - public void setClientID(String clientID) { - this.clientID = clientID; - } - - @Override - protected void populateSpecialParameters(HttpServletRequest request) throws OAuth20Exception { - this.setResponseType(this.getParam(request, OAuth20Constants.PARAM_RESPONSE_TYPE, true)); - this.setState(this.getParam(request, OAuth20Constants.PARAM_STATE, true)); - this.setRedirectUri(this.getParam(request, OAuth20Constants.PARAM_REDIRECT_URI, true)); - this.setClientID(this.getParam(request, OAuth20Constants.PARAM_CLIENT_ID, true)); - this.setScope(this.getParam(request, OAuth20Constants.PARAM_SCOPE, false)); - - // check for response type - if (!this.responseType.equals(OAuth20Constants.RESPONSE_CODE)) { - throw new OAuth20ResponseTypeException(); - } - - // check state for invalid characters (like < > & ; ... javascript ... to prevent xss) - if (!OAuth20Util.isValidStateValue(this.getState())) { - throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_STATE); - } - - // check if client id and redirect uri are ok - try { - // OAOAUTH20 cannot be null at this point. check was done in base request - OAOAUTH20 oAuthConfig = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(this.getOAURL()) - .getoAuth20Config(); - - if (!this.getClientID().equals(oAuthConfig.getOAuthClientId()) - || !this.getRedirectUri().equals(oAuthConfig.getOAuthRedirectUri())) { - throw new OAuth20AccessDeniedException(); - } - } - catch (ConfigurationException e) { - throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID); - } - - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20BaseRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20BaseRequest.java deleted file mode 100644 index 05362c977..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20BaseRequest.java +++ /dev/null @@ -1,118 +0,0 @@ -package at.gv.egovernment.moa.id.protocols.oauth20.requests; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.lang.StringEscapeUtils; -import org.apache.commons.lang.StringUtils; - -import at.gv.egovernment.moa.id.commons.db.dao.config.OAOAUTH20; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.moduls.RequestImpl; -import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; -import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Protocol; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20InvalidRequestException; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ServerErrorException; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20WrongParameterException; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.logging.Logger; - -public abstract class OAuth20BaseRequest extends RequestImpl { - - private static final long serialVersionUID = 1L; - - protected Set allowedParameters = new HashSet(); - - protected String getParam(final HttpServletRequest request, final String name, final boolean isNeeded) throws OAuth20Exception { - String param = request.getParameter(name); - Logger.debug("Reading param " + name + " from HttpServletRequest with value " + param); - - if (isNeeded && StringUtils.isEmpty(param)) { - throw new OAuth20WrongParameterException(name); - } - - this.allowedParameters.add(name); - - return param; - } - - protected void populateParameters(final HttpServletRequest request) throws OAuth20Exception { - - // moa id - load oa with client id! - try { - String oaURL = StringEscapeUtils.escapeHtml(this.getParam(request, OAuth20Constants.PARAM_CLIENT_ID, true)); - if (!ParamValidatorUtils.isValidOA(oaURL)) { - throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID); - } - this.setOAURL(oaURL); - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(oaURL); - - if (oaParam == null) { - throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID); - } - this.setTarget(oaParam.getTarget()); - - OAOAUTH20 config = oaParam.getoAuth20Config(); - if (config == null) { - throw new OAuth20InvalidRequestException(); - } - if (StringUtils.isEmpty(config.getOAuthClientSecret()) || StringUtils.isEmpty(config.getOAuthClientId()) - || StringUtils.isEmpty(config.getOAuthRedirectUri())) { - throw new OAuth20ServerErrorException(); - } - } - catch (ConfigurationException e) { - throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID); - } - - // oAuth - this.populateSpecialParameters(request); - - // cleanup parameters - this.checkAllowedParameters(request); - } - - private void checkAllowedParameters(final HttpServletRequest request) { - Logger.debug("Going to check for allowed parameters"); - this.allowedParameters.add(OAuth20Constants.PARAM_MOA_ACTION); - this.allowedParameters.add(OAuth20Constants.PARAM_MOA_MOD); - - @SuppressWarnings("rawtypes") - Iterator iter = request.getParameterMap().keySet().iterator(); - while (iter.hasNext()) { - String name = (String) iter.next(); - if (!this.allowedParameters.contains(name)) { - - Logger.debug("Found wrong parameter: " + name); - throw new OAuth20WrongParameterException(name); - } - } - - } - - protected abstract void populateSpecialParameters(final HttpServletRequest request) throws OAuth20Exception; - - public static OAuth20BaseRequest newInstance(final String action, final HttpServletRequest request) throws OAuth20Exception { - OAuth20BaseRequest res; - - if (action.equals(OAuth20Protocol.AUTH_ACTION)) { - res = new OAuth20AuthRequest(); - } else if (action.equals(OAuth20Protocol.TOKEN_ACTION)) { - res = new OAuth20TokenRequest(); - } else { - throw new OAuth20InvalidRequestException(); - } - - res.setAction(action); - res.setModule(OAuth20Protocol.NAME); - - res.populateParameters(request); - return res; - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20TokenRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20TokenRequest.java deleted file mode 100644 index 6d69f8238..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/requests/OAuth20TokenRequest.java +++ /dev/null @@ -1,118 +0,0 @@ -package at.gv.egovernment.moa.id.protocols.oauth20.requests; - -import javax.servlet.http.HttpServletRequest; - -import at.gv.egovernment.moa.id.commons.db.dao.config.OAOAUTH20; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20AccessDeniedException; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20InvalidGrantException; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20WrongParameterException; - -public class OAuth20TokenRequest extends OAuth20BaseRequest { - - private static final long serialVersionUID = 1L; - - private String code; - private String grantType; - private String clientID; - private String clientSecret; - - /** - * @return the code - */ - public String getCode() { - return code; - } - - /** - * @param code - * the code to set - */ - public void setCode(String code) { - this.code = code; - } - - /** - * @return the grantType - */ - public String getGrantType() { - return grantType; - } - - /** - * @param grantType - * the grantType to set - */ - public void setGrantType(String grantType) { - this.grantType = grantType; - } - - /** - * @return the clientID - */ - public String getClientID() { - return clientID; - } - - /** - * @param clientID - * the clientID to set - */ - public void setClientID(String clientID) { - this.clientID = clientID; - } - - /** - * @return the clientSecret - */ - public String getClientSecret() { - return clientSecret; - } - - /** - * @param clientSecret - * the clientSecret to set - */ - public void setClientSecret(String clientSecret) { - this.clientSecret = clientSecret; - } - - @Override - protected void populateSpecialParameters(HttpServletRequest request) throws OAuth20Exception { - this.setCode(this.getParam(request, OAuth20Constants.RESPONSE_CODE, true)); - this.setGrantType(this.getParam(request, OAuth20Constants.PARAM_GRANT_TYPE, true)); - this.setClientID(this.getParam(request, OAuth20Constants.PARAM_CLIENT_ID, true)); - this.setClientSecret(this.getParam(request, OAuth20Constants.PARAM_CLIENT_SECRET, true)); - - // check for grant type - if (!this.getGrantType().equals(OAuth20Constants.PARAM_GRANT_TYPE_VALUE_AUTHORIZATION_CODE)) { - throw new OAuth20InvalidGrantException(); - } - - // check if client id and secret are ok - try { - // OAOAUTH20 cannot be null at this point. check was done in base request - OAOAUTH20 oAuthConfig = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(this.getOAURL()) - .getoAuth20Config(); - - if (!this.getClientID().equals(oAuthConfig.getOAuthClientId())) { - throw new OAuth20AccessDeniedException(); - } - - if (!this.getClientSecret().equals(oAuthConfig.getOAuthClientSecret())) { - throw new OAuth20AccessDeniedException(); - } - - } - catch (ConfigurationException e) { - throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID); - } - - //add valid parameters - this.allowedParameters.add(OAuth20Constants.PARAM_SCOPE); - this.allowedParameters.add(OAuth20Constants.PARAM_REDIRECT_URI); - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BaseAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BaseAttributeBuilder.java deleted file mode 100644 index 4accca580..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BaseAttributeBuilder.java +++ /dev/null @@ -1,63 +0,0 @@ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; - -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.core.AttributeValue; -import org.opensaml.xml.Configuration; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.schema.XSInteger; -import org.opensaml.xml.schema.XSString; -import org.opensaml.xml.schema.impl.XSIntegerBuilder; -import org.opensaml.xml.schema.impl.XSStringBuilder; - -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; - -public abstract class BaseAttributeBuilder implements PVPConstants, MOAIDAuthConstants, IAttributeBuilder { - - - protected static XMLObject buildAttributeStringValue(String value) { - XSStringBuilder stringBuilder = (XSStringBuilder) Configuration.getBuilderFactory().getBuilder(XSString.TYPE_NAME); - XSString stringValue = stringBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME); - stringValue.setValue(value); - return stringValue; - } - - protected static XMLObject buildAttributeIntegerValue(int value) { - XSIntegerBuilder integerBuilder = (XSIntegerBuilder) Configuration.getBuilderFactory().getBuilder(XSInteger.TYPE_NAME); - XSInteger integerValue = integerBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSInteger.TYPE_NAME); - integerValue.setValue(value); - return integerValue; - } - - protected static Attribute buildStringAttribute(String friendlyName, - String name, String value) { - Attribute attribute = - SAML2Utils.createSAMLObject(Attribute.class); - attribute.setFriendlyName(friendlyName); - attribute.setName(name); - attribute.setNameFormat(Attribute.URI_REFERENCE); - attribute.getAttributeValues().add(buildAttributeStringValue(value)); - return attribute; - } - - protected static Attribute buildIntegerAttribute(String friendlyName, - String name, int value) { - Attribute attribute = - SAML2Utils.createSAMLObject(Attribute.class); - attribute.setFriendlyName(friendlyName); - attribute.setName(name); - attribute.setNameFormat(Attribute.URI_REFERENCE); - attribute.getAttributeValues().add(buildAttributeIntegerValue(value)); - return attribute; - } - - protected static Attribute buildemptyAttribute(String friendlyName, String name) { - Attribute attribute = - SAML2Utils.createSAMLObject(Attribute.class); - attribute.setFriendlyName(friendlyName); - attribute.setName(name); - attribute.setNameFormat(Attribute.URI_REFERENCE); - return attribute; - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IAttributeGenerator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IAttributeGenerator.java new file mode 100644 index 000000000..48502b77b --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IAttributeGenerator.java @@ -0,0 +1,11 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; + +public interface IAttributeGenerator { + public abstract ATT buildStringAttribute(final String friendlyName, final String name, final String value); + + public abstract ATT buildIntegerAttribute(final String friendlyName, final String name, final int value); + + public abstract ATT buildLongAttribute(final String friendlyName, final String name, final long value); + + public abstract ATT buildEmptyAttribute(final String friendlyName, final String name); +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IPVPAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IPVPAttributeBuilder.java new file mode 100644 index 000000000..cf40f96f4 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IPVPAttributeBuilder.java @@ -0,0 +1,8 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; + +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; + +interface IPVPAttributeBuilder extends PVPConstants, MOAIDAuthConstants, IAttributeBuilder { + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/SamlAttributeGenerator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/SamlAttributeGenerator.java new file mode 100644 index 000000000..170c72fb4 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/SamlAttributeGenerator.java @@ -0,0 +1,65 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; + +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.core.AttributeValue; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSInteger; +import org.opensaml.xml.schema.XSString; +import org.opensaml.xml.schema.impl.XSIntegerBuilder; +import org.opensaml.xml.schema.impl.XSStringBuilder; + +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; + +public class SamlAttributeGenerator implements IAttributeGenerator { + + private XMLObject buildAttributeStringValue(String value) { + XSStringBuilder stringBuilder = (XSStringBuilder) Configuration.getBuilderFactory().getBuilder(XSString.TYPE_NAME); + XSString stringValue = stringBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME); + stringValue.setValue(value); + return stringValue; + } + + private XMLObject buildAttributeIntegerValue(int value) { + XSIntegerBuilder integerBuilder = (XSIntegerBuilder) Configuration.getBuilderFactory().getBuilder(XSInteger.TYPE_NAME); + XSInteger integerValue = integerBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSInteger.TYPE_NAME); + integerValue.setValue(value); + return integerValue; + } + + public Attribute buildStringAttribute(final String friendlyName, final String name, final String value) { + Attribute attribute = SAML2Utils.createSAMLObject(Attribute.class); + attribute.setFriendlyName(friendlyName); + attribute.setName(name); + attribute.setNameFormat(Attribute.URI_REFERENCE); + attribute.getAttributeValues().add(buildAttributeStringValue(value)); + return attribute; + } + + public Attribute buildIntegerAttribute(final String friendlyName, final String name, final int value) { + Attribute attribute = SAML2Utils.createSAMLObject(Attribute.class); + attribute.setFriendlyName(friendlyName); + attribute.setName(name); + attribute.setNameFormat(Attribute.URI_REFERENCE); + attribute.getAttributeValues().add(buildAttributeIntegerValue(value)); + return attribute; + } + + public Attribute buildEmptyAttribute(final String friendlyName, final String name) { + Attribute attribute = SAML2Utils.createSAMLObject(Attribute.class); + attribute.setFriendlyName(friendlyName); + attribute.setName(name); + attribute.setNameFormat(Attribute.URI_REFERENCE); + return attribute; + } + + public Attribute buildLongAttribute(String friendlyName, String name, long value) { + Attribute attribute = SAML2Utils.createSAMLObject(Attribute.class); + attribute.setFriendlyName(friendlyName); + attribute.setName(name); + attribute.setNameFormat(Attribute.URI_REFERENCE); + attribute.getAttributeValues().add(buildAttributeIntegerValue((int) value)); + return attribute; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/AttributeException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/AttributeException.java new file mode 100644 index 000000000..245858ad1 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/AttributeException.java @@ -0,0 +1,11 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions; + +public class AttributeException extends Exception { + + private static final long serialVersionUID = 1L; + + public AttributeException(String message) { + super(message); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/InvalidDateFormatAttributeException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/InvalidDateFormatAttributeException.java new file mode 100644 index 000000000..61540d53f --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/InvalidDateFormatAttributeException.java @@ -0,0 +1,13 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions; + +public class InvalidDateFormatAttributeException extends AttributeException { + + private static final long serialVersionUID = 1L; + + public InvalidDateFormatAttributeException() { + super("Date format is invalid."); + } + + + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/NoMandateDataAttributeException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/NoMandateDataAttributeException.java new file mode 100644 index 000000000..7bb09fd85 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/NoMandateDataAttributeException.java @@ -0,0 +1,10 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions; + +public class NoMandateDataAttributeException extends AttributeException { + + private static final long serialVersionUID = 1L; + + public NoMandateDataAttributeException() { + super("Mandate data is not available."); + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/UnavailableAttributeException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/UnavailableAttributeException.java new file mode 100644 index 000000000..df3933774 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/UnavailableAttributeException.java @@ -0,0 +1,18 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions; + +public class UnavailableAttributeException extends AttributeException { + + private static final long serialVersionUID = 1L; + + private String attributeName; + + public UnavailableAttributeException(String attributeName) { + super("Attribute " + attributeName + " is not available."); + this.attributeName = attributeName; + } + + public String getAttributeName() { + return attributeName; + } + +} -- cgit v1.2.3 From 51c45b375485399d36e33f1ab4cf76e9273222e3 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 21 Jan 2014 13:00:34 +0100 Subject: implement SAML2 assertion encryption --- .../id/protocols/pvp2x/binding/PostBinding.java | 2 +- .../builder/assertion/PVP2AssertionBuilder.java | 2 +- .../InvalidAssertionEncryptionException.java | 14 ++++ .../pvp2x/requestHandler/AuthnRequestHandler.java | 94 +++++++++++++++++++++- 4 files changed, 107 insertions(+), 5 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidAssertionEncryptionException.java (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java index 232ad315f..2fe52d032 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java @@ -67,7 +67,7 @@ public class PostBinding implements IDecoder, IEncoder { .buildObject(); service.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); service.setLocation(targetLocation); - context.setOutboundSAMLMessageSigningCredential(credentials); + context.setOutboundSAMLMessageSigningCredential(credentials); context.setPeerEntityEndpoint(service); // context.setOutboundMessage(authReq); context.setOutboundSAMLMessage(response); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java index f21567245..eaa570ab1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java @@ -144,7 +144,7 @@ public class PVP2AssertionBuilder implements PVPConstants { SPSSODescriptor spSSODescriptor = peerEntity .getSPSSODescriptor(SAMLConstants.SAML20P_NS); - + Integer aIdx = authnRequest.getAttributeConsumingServiceIndex(); int idx = 0; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidAssertionEncryptionException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidAssertionEncryptionException.java new file mode 100644 index 000000000..142227a59 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidAssertionEncryptionException.java @@ -0,0 +1,14 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +import org.opensaml.saml2.core.StatusCode; + +public class InvalidAssertionEncryptionException extends PVP2Exception { + + private static final long serialVersionUID = 6513388841485355549L; + + public InvalidAssertionEncryptionException() { + super("pvp2.16", new Object[]{}); + this.statusCodeValue = StatusCode.REQUESTER_URI; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java index fec21df9e..c3884f9d8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java @@ -1,22 +1,45 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.requestHandler; +import java.util.ArrayList; import java.util.Date; +import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.joda.time.DateTime; +import org.opensaml.Configuration; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.core.Assertion; import org.opensaml.saml2.core.AuthnRequest; +import org.opensaml.saml2.core.EncryptedAssertion; import org.opensaml.saml2.core.Issuer; import org.opensaml.saml2.core.NameID; import org.opensaml.saml2.core.Response; +import org.opensaml.saml2.core.impl.EncryptedAssertionBuilder; +import org.opensaml.saml2.encryption.Encrypter; +import org.opensaml.saml2.encryption.Encrypter.KeyPlacement; import org.opensaml.saml2.metadata.AssertionConsumerService; import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.KeyDescriptor; import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.security.MetadataCredentialResolver; +import org.opensaml.security.MetadataCriteria; import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.xml.encryption.EncryptionConstants; +import org.opensaml.xml.encryption.EncryptionException; +import org.opensaml.xml.encryption.EncryptionParameters; +import org.opensaml.xml.encryption.KeyEncryptionParameters; +import org.opensaml.xml.security.CriteriaSet; import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.credential.Credential; +import org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.security.criteria.EntityIDCriteria; +import org.opensaml.xml.security.criteria.UsageCriteria; +import org.opensaml.xml.security.keyinfo.KeyInfoGeneratorFactory; +import org.opensaml.xml.security.x509.BasicX509Credential; +import org.opensaml.xml.security.x509.X509Credential; +import org.opensaml.xml.signature.KeyInfo; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; @@ -30,6 +53,8 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion.PVP2AssertionB import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.BindingNotSupportedException; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.InvalidAssertionConsumerServiceException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.InvalidAssertionEncryptionException; +import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.logging.Logger; @@ -49,10 +74,9 @@ public class AuthnRequestHandler implements IRequestHandler, PVPConstants { EntityDescriptor peerEntity = obj.getEntityMetadata(); Assertion assertion = PVP2AssertionBuilder.buildAssertion(authnRequest, authSession, peerEntity); - + Response authResponse = SAML2Utils.createSAMLObject(Response.class); - Issuer nissuer = SAML2Utils.createSAMLObject(Issuer.class); //TODO: check! @@ -67,7 +91,6 @@ public class AuthnRequestHandler implements IRequestHandler, PVPConstants { //SAML2 response required IssueInstant authResponse.setIssueInstant(new DateTime()); - authResponse.getAssertions().add(assertion); authResponse.setStatus(SAML2Utils.getSuccessStatus()); Integer aIdx = authnRequest.getAssertionConsumerServiceIndex(); @@ -84,10 +107,75 @@ public class AuthnRequestHandler implements IRequestHandler, PVPConstants { .getAssertionConsumerServices().get(idx); if (consumerService == null) { + //TODO: maybe use default ConsumerService + throw new InvalidAssertionConsumerServiceException(idx); + } String oaURL = consumerService.getLocation(); + //check, if metadata includes an encryption key + MetadataCredentialResolver mdCredResolver = + new MetadataCredentialResolver(MOAMetadataProvider.getInstance()); + + CriteriaSet criteriaSet = new CriteriaSet(); + criteriaSet.add( new EntityIDCriteria(obj.getSamlRequest().getIssuer().getValue()) ); + criteriaSet.add( new MetadataCriteria(SPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS) ); + criteriaSet.add( new UsageCriteria(UsageType.ENCRYPTION) ); + + X509Credential encryptionCredentials = null; + try { + encryptionCredentials = (X509Credential) mdCredResolver.resolveSingle(criteriaSet); + + } catch (SecurityException e2) { + Logger.warn("Can not extract the Assertion Encryption-Key from metadata", e2); + throw new InvalidAssertionEncryptionException(); + + } + + if (encryptionCredentials != null) { + //encrypt SAML2 assertion + + try { + + EncryptionParameters dataEncParams = new EncryptionParameters(); + dataEncParams.setAlgorithm(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128); + + List keyEncParamList = new ArrayList(); + KeyEncryptionParameters keyEncParam = new KeyEncryptionParameters(); + + keyEncParam.setEncryptionCredential(encryptionCredentials); + keyEncParam.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP); + KeyInfoGeneratorFactory kigf = Configuration.getGlobalSecurityConfiguration() + .getKeyInfoGeneratorManager().getDefaultManager() + .getFactory(encryptionCredentials); + keyEncParam.setKeyInfoGenerator(kigf.newInstance()); + keyEncParamList.add(keyEncParam); + + Encrypter samlEncrypter = new Encrypter(dataEncParams, keyEncParamList); + //samlEncrypter.setKeyPlacement(KeyPlacement.INLINE); + samlEncrypter.setKeyPlacement(KeyPlacement.PEER); + + EncryptedAssertion encryptAssertion = null; + + encryptAssertion = samlEncrypter.encrypt(assertion); + + authResponse.getEncryptedAssertions().add(encryptAssertion); + + } catch (EncryptionException e1) { + Logger.warn("Can not encrypt the PVP2 assertion", e1); + throw new InvalidAssertionEncryptionException(); + + } + + } else { + authResponse.getAssertions().add(assertion); + + } + + + + IEncoder binding = null; if (consumerService.getBinding().equals( -- cgit v1.2.3 From dd4a77caa66368ca257fcf5a1f87d0dab90477f5 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 21 Jan 2014 18:00:41 +0100 Subject: BUGFIX: RedirectBinding validate signatures which exists, but signature is not required changes for WKO: Allow Metadata with no AttributeConsumerService Allow AuthnRequest with no RequestedAuthnContext Allow AuthnRequest with no AssertionConsumerServiceIndex Use Metadata->AssertionConsumerService->isDefaut flag --- .../moa/id/protocols/pvp2x/PVP2XProtocol.java | 25 +++-- .../protocols/pvp2x/binding/RedirectBinding.java | 10 +- .../builder/assertion/PVP2AssertionBuilder.java | 122 +++++++++++---------- .../pvp2x/requestHandler/AuthnRequestHandler.java | 26 ++++- .../moa/id/protocols/pvp2x/utils/SAML2Utils.java | 16 +++ .../pvp2x/verification/SAMLVerificationEngine.java | 1 + 6 files changed, 130 insertions(+), 70 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java index bef58ab59..dc2330f40 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java @@ -124,7 +124,6 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { RequestAbstractType samlReq = moaRequest.getSamlRequest(); //String xml = PrettyPrinter.prettyPrint(SAML2Utils.asDOMDocument(samlReq)); - //Logger.info("SAML : " + xml); if(!moaRequest.isVerified()) { @@ -137,6 +136,12 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { throw new MOAIDException("Unsupported request", new Object[] {}); } + EntityDescriptor metadata = moaRequest.getEntityMetadata(); + if(metadata == null) { + throw new NoMetadataInformationException(); + } + SPSSODescriptor spSSODescriptor = metadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS); + AuthnRequest authnRequest = (AuthnRequest)samlReq; Integer aIdx = authnRequest.getAssertionConsumerServiceIndex(); @@ -144,6 +149,9 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { if(aIdx != null) { assertionidx = aIdx.intValue(); + + } else { + assertionidx = SAML2Utils.getDefaultAssertionConsumerServiceIndex(spSSODescriptor); } aIdx = authnRequest.getAttributeConsumingServiceIndex(); @@ -153,13 +161,14 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { attributeIdx = aIdx.intValue(); } - EntityDescriptor metadata = moaRequest.getEntityMetadata(); - if(metadata == null) { - throw new NoMetadataInformationException(); - } - SPSSODescriptor spSSODescriptor = metadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS); AssertionConsumerService consumerService = spSSODescriptor.getAssertionConsumerServices().get(assertionidx); - AttributeConsumingService attributeConsumer = spSSODescriptor.getAttributeConsumingServices().get(attributeIdx); + + AttributeConsumingService attributeConsumer = null; + + if (spSSODescriptor.getAttributeConsumingServices() != null && + spSSODescriptor.getAttributeConsumingServices().size() > 0) { + attributeConsumer = spSSODescriptor.getAttributeConsumingServices().get(attributeIdx); + } String oaURL = moaRequest.getEntityMetadata().getEntityID(); String binding = consumerService.getBinding(); @@ -176,7 +185,7 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { String useMandate = request.getParameter(PARAM_USEMANDATE); if(useMandate != null) { - if(useMandate.equals("true")) { + if(useMandate.equals("true") && attributeConsumer != null) { if(!CheckMandateAttributes.canHandleMandate(attributeConsumer)) { throw new MandateAttributesNotHandleAbleException(); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java index 418c4a60c..9b43fb999 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java @@ -3,11 +3,13 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.binding; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.jcp.xml.dsig.internal.dom.DOMURIDereferencer; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.BasicSAMLMessageContext; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.binding.decoding.HTTPRedirectDeflateDecoder; import org.opensaml.saml2.binding.encoding.HTTPRedirectDeflateEncoder; +import org.opensaml.saml2.binding.security.SAML2AuthnRequestsSignedRule; import org.opensaml.saml2.binding.security.SAML2HTTPRedirectDeflateSignatureRule; import org.opensaml.saml2.core.RequestAbstractType; import org.opensaml.saml2.core.Response; @@ -31,6 +33,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; +import at.gv.egovernment.moa.util.DOMUtils; public class RedirectBinding implements IDecoder, IEncoder { @@ -84,13 +87,18 @@ public class RedirectBinding implements IDecoder, IEncoder { SAML2HTTPRedirectDeflateSignatureRule signatureRule = new SAML2HTTPRedirectDeflateSignatureRule( TrustEngineFactory.getSignatureKnownKeysTrustEngine()); + SAML2AuthnRequestsSignedRule signedRole = new SAML2AuthnRequestsSignedRule(); + + BasicSecurityPolicy policy = new BasicSecurityPolicy(); policy.getPolicyRules().add(signatureRule); + policy.getPolicyRules().add(signedRole); + SecurityPolicyResolver resolver = new StaticSecurityPolicyResolver( policy); messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); messageContext.setSecurityPolicyResolver(resolver); - + decode.decode(messageContext); signatureRule.evaluate(messageContext); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java index eaa570ab1..d1d79373c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java @@ -64,46 +64,48 @@ public class PVP2AssertionBuilder implements PVPConstants { RequestedAuthnContext reqAuthnContext = authnRequest .getRequestedAuthnContext(); - if (reqAuthnContext == null) { - throw new NoAuthContextException(); - } - - boolean stork_qaa_1_4_found = false; - AuthnContextClassRef authnContextClassRef = SAML2Utils .createSAMLObject(AuthnContextClassRef.class); - - List reqAuthnContextClassRefIt = reqAuthnContext - .getAuthnContextClassRefs(); - if (reqAuthnContextClassRefIt.size() == 0) { - stork_qaa_1_4_found = true; + if (reqAuthnContext == null) { authnContextClassRef.setAuthnContextClassRef(STORK_QAA_1_4); - - } else { - for (AuthnContextClassRef authnClassRef : reqAuthnContextClassRefIt) { - String qaa_uri = authnClassRef.getAuthnContextClassRef(); - if (qaa_uri.trim().equals(STORK_QAA_1_4) - || qaa_uri.trim().equals(STORK_QAA_1_3) - || qaa_uri.trim().equals(STORK_QAA_1_2) - || qaa_uri.trim().equals(STORK_QAA_1_1)) { - - if (authSession.isForeigner()) { - //TODO: insert QAA check - - stork_qaa_1_4_found = false; - - } else { - stork_qaa_1_4_found = true; - authnContextClassRef.setAuthnContextClassRef(STORK_QAA_1_4); + + } else { + + boolean stork_qaa_1_4_found = false; + + List reqAuthnContextClassRefIt = reqAuthnContext + .getAuthnContextClassRefs(); + + if (reqAuthnContextClassRefIt.size() == 0) { + stork_qaa_1_4_found = true; + authnContextClassRef.setAuthnContextClassRef(STORK_QAA_1_4); + + } else { + for (AuthnContextClassRef authnClassRef : reqAuthnContextClassRefIt) { + String qaa_uri = authnClassRef.getAuthnContextClassRef(); + if (qaa_uri.trim().equals(STORK_QAA_1_4) + || qaa_uri.trim().equals(STORK_QAA_1_3) + || qaa_uri.trim().equals(STORK_QAA_1_2) + || qaa_uri.trim().equals(STORK_QAA_1_1)) { + + if (authSession.isForeigner()) { + //TODO: insert QAA check + + stork_qaa_1_4_found = false; + + } else { + stork_qaa_1_4_found = true; + authnContextClassRef.setAuthnContextClassRef(STORK_QAA_1_4); + } + break; } - break; } } - } - - if (!stork_qaa_1_4_found) { - throw new QAANotSupportedException(STORK_QAA_1_4); + + if (!stork_qaa_1_4_found) { + throw new QAANotSupportedException(STORK_QAA_1_4); + } } // reqAuthnContextClassRefIt = reqAuthnContext.getAuthnContextClassRefs() @@ -150,10 +152,8 @@ public class PVP2AssertionBuilder implements PVPConstants { if (aIdx != null) { idx = aIdx.intValue(); - } - - AttributeConsumingService attributeConsumingService = spSSODescriptor - .getAttributeConsumingServices().get(idx); + + } AttributeStatement attributeStatement = SAML2Utils .createSAMLObject(AttributeStatement.class); @@ -197,32 +197,38 @@ public class PVP2AssertionBuilder implements PVPConstants { .buildAuthenticationData(authSession, oaParam, oaParam.getTarget()); - Iterator it = attributeConsumingService - .getRequestAttributes().iterator(); - while (it.hasNext()) { - RequestedAttribute reqAttribut = it.next(); - try { - Attribute attr = PVPAttributeBuilder.buildAttribute( - reqAttribut.getName(), authSession, oaParam, authData); - if (attr == null) { + if (spSSODescriptor.getAttributeConsumingServices() != null && + spSSODescriptor.getAttributeConsumingServices().size() > 0) { + + AttributeConsumingService attributeConsumingService = spSSODescriptor + .getAttributeConsumingServices().get(idx); + + Iterator it = attributeConsumingService + .getRequestAttributes().iterator(); + while (it.hasNext()) { + RequestedAttribute reqAttribut = it.next(); + try { + Attribute attr = PVPAttributeBuilder.buildAttribute( + reqAttribut.getName(), authSession, oaParam, authData); + if (attr == null) { + if (reqAttribut.isRequired()) { + throw new UnprovideableAttributeException( + reqAttribut.getName()); + } + } else { + attributeStatement.getAttributes().add(attr); + } + } catch (PVP2Exception e) { + Logger.error( + "Attribute generation failed! for " + + reqAttribut.getFriendlyName(), e); if (reqAttribut.isRequired()) { throw new UnprovideableAttributeException( reqAttribut.getName()); } - } else { - attributeStatement.getAttributes().add(attr); - } - } catch (PVP2Exception e) { - Logger.error( - "Attribute generation failed! for " - + reqAttribut.getFriendlyName(), e); - if (reqAttribut.isRequired()) { - throw new UnprovideableAttributeException( - reqAttribut.getName()); } } } - if (attributeStatement.getAttributes().size() > 0) { assertion.getAttributeStatements().add(attributeStatement); } @@ -294,7 +300,7 @@ public class PVP2AssertionBuilder implements PVPConstants { SubjectConfirmationData subjectConfirmationData = SAML2Utils .createSAMLObject(SubjectConfirmationData.class); subjectConfirmationData.setInResponseTo(authnRequest.getID()); - subjectConfirmationData.setNotOnOrAfter(new DateTime().plusMinutes(20)); + subjectConfirmationData.setNotOnOrAfter(new DateTime().plusMinutes(5)); //TL: change from entityID to destination URL AssertionConsumerService consumerService = spSSODescriptor @@ -319,7 +325,7 @@ public class PVP2AssertionBuilder implements PVPConstants { audienceRestriction.getAudiences().add(audience); conditions.setNotBefore(new DateTime()); - conditions.setNotOnOrAfter(new DateTime().plusMinutes(20)); + conditions.setNotOnOrAfter(new DateTime().plusMinutes(5)); // conditions.setNotOnOrAfter(new DateTime()); conditions.getAudienceRestrictions().add(audienceRestriction); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java index c3884f9d8..4128a406b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java @@ -1,11 +1,13 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.requestHandler; +import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.xml.transform.TransformerException; import org.joda.time.DateTime; import org.opensaml.Configuration; @@ -30,6 +32,7 @@ import org.opensaml.xml.encryption.EncryptionConstants; import org.opensaml.xml.encryption.EncryptionException; import org.opensaml.xml.encryption.EncryptionParameters; import org.opensaml.xml.encryption.KeyEncryptionParameters; +import org.opensaml.xml.io.MarshallingException; import org.opensaml.xml.security.CriteriaSet; import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.security.credential.Credential; @@ -55,6 +58,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.BindingNotSupportedEx import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.InvalidAssertionConsumerServiceException; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.InvalidAssertionEncryptionException; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.PrettyPrinter; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.logging.Logger; @@ -93,15 +97,18 @@ public class AuthnRequestHandler implements IRequestHandler, PVPConstants { authResponse.setStatus(SAML2Utils.getSuccessStatus()); + SPSSODescriptor spSSODescriptor = peerEntity + .getSPSSODescriptor(SAMLConstants.SAML20P_NS); + Integer aIdx = authnRequest.getAssertionConsumerServiceIndex(); int idx = 0; if (aIdx != null) { idx = aIdx.intValue(); + + } else { + idx = SAML2Utils.getDefaultAssertionConsumerServiceIndex(spSSODescriptor); } - - SPSSODescriptor spSSODescriptor = peerEntity - .getSPSSODescriptor(SAMLConstants.SAML20P_NS); AssertionConsumerService consumerService = spSSODescriptor .getAssertionConsumerServices().get(idx); @@ -201,6 +208,10 @@ public class AuthnRequestHandler implements IRequestHandler, PVPConstants { binding.encodeRespone(req, resp, authResponse, oaURL); // TODO add remoteSessionID to AuthSession ExternalPVPSessionStore +// Logger logger = new Logger(); +// logger.debug("Redirect Binding Request = " + PrettyPrinter.prettyPrint(SAML2Utils.asDOMDocument(authResponse))); + + return assertion.getID(); } catch (MessageEncodingException e) { @@ -209,6 +220,15 @@ public class AuthnRequestHandler implements IRequestHandler, PVPConstants { } catch (SecurityException e) { Logger.error("Security exception", e); throw new MOAIDException("pvp2.01", null, e); +// } catch (TransformerException e) { +// Logger.error("Security exception", e); +// throw new MOAIDException("pvp2.01", null, e); +// } catch (IOException e) { +// Logger.error("Security exception", e); +// throw new MOAIDException("pvp2.01", null, e); +// } catch (MarshallingException e) { +// Logger.error("Security exception", e); +// throw new MOAIDException("pvp2.01", null, e); } } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/SAML2Utils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/SAML2Utils.java index 7bb5b052f..373bca902 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/SAML2Utils.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/SAML2Utils.java @@ -2,6 +2,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.utils; import java.io.IOException; import java.security.NoSuchAlgorithmException; +import java.util.List; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; @@ -13,6 +14,8 @@ import org.opensaml.Configuration; import org.opensaml.common.impl.SecureRandomIdentifierGenerator; import org.opensaml.saml2.core.Status; import org.opensaml.saml2.core.StatusCode; +import org.opensaml.saml2.metadata.AssertionConsumerService; +import org.opensaml.saml2.metadata.SPSSODescriptor; import org.opensaml.xml.XMLObject; import org.opensaml.xml.XMLObjectBuilderFactory; import org.opensaml.xml.io.Marshaller; @@ -77,4 +80,17 @@ public class SAML2Utils { status.setStatusCode(statusCode); return status; } + + public static int getDefaultAssertionConsumerServiceIndex(SPSSODescriptor spSSODescriptor) { + + List assertionConsumerList = spSSODescriptor.getAssertionConsumerServices(); + + for (AssertionConsumerService el : assertionConsumerList) { + if (el.isDefault()) + return el.getIndex(); + + } + + return 0; + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java index 628da6773..4823d7629 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java @@ -41,6 +41,7 @@ public class SAMLVerificationEngine { public void verifyRequest(RequestAbstractType samlObj, SignatureTrustEngine sigTrustEngine ) throws org.opensaml.xml.security.SecurityException, Exception { SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); + try { profileValidator.validate(samlObj.getSignature()); } catch (ValidationException e) { -- cgit v1.2.3 From f5f8575182680e61068e6225e3fc67b92187ac54 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 22 Jan 2014 11:47:59 +0100 Subject: add additional log messages --- .../at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java | 3 +++ .../gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java | 3 +++ 2 files changed, 6 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java index 2fe52d032..9319c306b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java @@ -27,6 +27,7 @@ import org.opensaml.xml.security.credential.Credential; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; +import at.gv.egovernment.moa.logging.Logger; public class PostBinding implements IDecoder, IEncoder { @@ -45,6 +46,8 @@ public class PostBinding implements IDecoder, IEncoder { Credential credentials = CredentialProvider .getIDPSigningCredential(); + Logger.debug("create SAML POSTBinding response"); + // VelocityEngine engine = // VelocityProvider.getClassPathVelocityEngine(); VelocityEngine engine = new VelocityEngine(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java index 9b43fb999..78b63e041 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java @@ -33,6 +33,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; +import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.DOMUtils; public class RedirectBinding implements IDecoder, IEncoder { @@ -50,6 +51,8 @@ public class RedirectBinding implements IDecoder, IEncoder { Credential credentials = CredentialProvider .getIDPSigningCredential(); + Logger.debug("create SAML RedirectBinding response"); + HTTPRedirectDeflateEncoder encoder = new HTTPRedirectDeflateEncoder(); HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter( resp, true); -- cgit v1.2.3 From d9550b5e3f24a0f6013502dcc632c4d2730a6749 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 22 Jan 2014 13:28:46 +0100 Subject: change PVP2 AssertionBuilder to use the same DateTime at every position --- .../pvp2x/builder/assertion/PVP2AssertionBuilder.java | 12 ++++++------ .../protocols/pvp2x/requestHandler/AuthnRequestHandler.java | 6 ++++-- 2 files changed, 10 insertions(+), 8 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java index d1d79373c..9e2c89583 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java @@ -57,7 +57,7 @@ import at.gv.egovernment.moa.util.Constants; public class PVP2AssertionBuilder implements PVPConstants { public static Assertion buildAssertion(AuthnRequest authnRequest, - AuthenticationSession authSession, EntityDescriptor peerEntity) + AuthenticationSession authSession, EntityDescriptor peerEntity, DateTime date) throws MOAIDException { Assertion assertion = SAML2Utils.createSAMLObject(Assertion.class); @@ -137,7 +137,7 @@ public class PVP2AssertionBuilder implements PVPConstants { AuthnStatement authnStatement = SAML2Utils .createSAMLObject(AuthnStatement.class); String remoteSessionID = SAML2Utils.getSecureIdentifier(); - authnStatement.setAuthnInstant(new DateTime()); + authnStatement.setAuthnInstant(date); // currently dummy id ... authnStatement.setSessionIndex(remoteSessionID); authnStatement.setAuthnContext(authnContext); @@ -300,7 +300,7 @@ public class PVP2AssertionBuilder implements PVPConstants { SubjectConfirmationData subjectConfirmationData = SAML2Utils .createSAMLObject(SubjectConfirmationData.class); subjectConfirmationData.setInResponseTo(authnRequest.getID()); - subjectConfirmationData.setNotOnOrAfter(new DateTime().plusMinutes(5)); + subjectConfirmationData.setNotOnOrAfter(date.plusMinutes(5)); //TL: change from entityID to destination URL AssertionConsumerService consumerService = spSSODescriptor @@ -323,9 +323,9 @@ public class PVP2AssertionBuilder implements PVPConstants { audience.setAudienceURI(peerEntity.getEntityID()); audienceRestriction.getAudiences().add(audience); - conditions.setNotBefore(new DateTime()); + conditions.setNotBefore(date); - conditions.setNotOnOrAfter(new DateTime().plusMinutes(5)); + conditions.setNotOnOrAfter(date.plusMinutes(5)); // conditions.setNotOnOrAfter(new DateTime()); conditions.getAudienceRestrictions().add(audienceRestriction); @@ -342,7 +342,7 @@ public class PVP2AssertionBuilder implements PVPConstants { assertion.setIssuer(issuer); assertion.setSubject(subject); assertion.setID(SAML2Utils.getSecureIdentifier()); - assertion.setIssueInstant(new DateTime()); + assertion.setIssueInstant(date); return assertion; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java index 4128a406b..89285bad1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java @@ -77,7 +77,9 @@ public class AuthnRequestHandler implements IRequestHandler, PVPConstants { AuthnRequest authnRequest = (AuthnRequest) obj.getSamlRequest(); EntityDescriptor peerEntity = obj.getEntityMetadata(); - Assertion assertion = PVP2AssertionBuilder.buildAssertion(authnRequest, authSession, peerEntity); + DateTime date = new DateTime(); + + Assertion assertion = PVP2AssertionBuilder.buildAssertion(authnRequest, authSession, peerEntity, date); Response authResponse = SAML2Utils.createSAMLObject(Response.class); @@ -93,7 +95,7 @@ public class AuthnRequestHandler implements IRequestHandler, PVPConstants { authResponse.setInResponseTo(authnRequest.getID()); //SAML2 response required IssueInstant - authResponse.setIssueInstant(new DateTime()); + authResponse.setIssueInstant(date); authResponse.setStatus(SAML2Utils.getSuccessStatus()); -- cgit v1.2.3 From 587971b14627083236df96b8a79f005f92990d75 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 23 Jan 2014 14:03:23 +0100 Subject: some short changes --- .../at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java | 7 ++++++- .../protocols/oauth20/attributes/OAuth20AttributeBuilder.java | 2 +- .../moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java | 4 ++-- .../MandateNaturalPersonSourcePinAttributeBuilder.java | 10 ++++++---- 4 files changed, 15 insertions(+), 8 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java index 556d26c67..c98af695b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java @@ -26,6 +26,8 @@ package at.gv.egovernment.moa.id.auth; import iaik.pki.PKIException; import iaik.pki.jsse.IAIKX509TrustManager; +import iaik.security.ecc.provider.ECCProvider; +import iaik.security.provider.IAIK; import java.io.IOException; import java.security.GeneralSecurityException; @@ -79,7 +81,7 @@ public class MOAIDAuthInitializer { // register content data handlers for S/MIME types MailcapCommandMap mc = new MailcapCommandMap(); CommandMap.setDefaultCommandMap(mc); - + // create some properties and get the default Session Properties props = new Properties(); props.put("mail.smtp.host", "localhost"); @@ -130,6 +132,9 @@ public class MOAIDAuthInitializer { "init.01", null), e); } + IAIK.addAsProvider(); + ECCProvider.addAsProvider(); + // Initializes SSLSocketFactory store SSLUtils.initialize(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java index 6e5d0c2f0..a9ef8a19b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java @@ -128,7 +128,7 @@ public final class OAuth20AttributeBuilder { } } catch (AttributeException e) { - Logger.warn("Cannot add attribute " + b.getName(), e); + Logger.info("Cannot add attribute " + b.getName()); } } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java index b01b2eae7..3dceaecdf 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java @@ -143,10 +143,10 @@ class OAuth20TokenAction implements IAction { } else if (s.equalsIgnoreCase("eID")) { OAuth20AttributeBuilder.addScopeEID(token.getPayloadAsJsonObject(), session, oaParam, authData); resultScopes.append(" eID"); - } else if (s.equalsIgnoreCase("eID_gov") && oaParam.getBusinessService()) { + } else if (s.equalsIgnoreCase("eID_gov")) { OAuth20AttributeBuilder.addScopeEIDGov(token.getPayloadAsJsonObject(), session, oaParam, authData); resultScopes.append(" eID_gov"); - } else if (s.equalsIgnoreCase("mandate") && session.getUseMandate() && oaParam.getBusinessService()) { + } else if (s.equalsIgnoreCase("mandate")) { OAuth20AttributeBuilder.addScopeMandate(token.getPayloadAsJsonObject(), session, oaParam, authData); resultScopes.append(" mandate"); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonSourcePinAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonSourcePinAttributeBuilder.java index b0c2261ef..7c59faeb2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonSourcePinAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonSourcePinAttributeBuilder.java @@ -38,11 +38,13 @@ public class MandateNaturalPersonSourcePinAttributeBuilder implements IPVPAttri } IdentificationType id = null; id = physicalPerson.getIdentification().get(0); - /*if(authSession.getBusinessService()) { + + if(authSession.getBusinessService()) { id = MandateBuilder.getWBPKIdentification(physicalPerson); - } else { - id = MandateBuilder.getBPKIdentification(physicalPerson); - }*/ + +// } else { +// id = MandateBuilder.getBPKIdentification(physicalPerson); + } if(id == null) { Logger.error("Failed to generate IdentificationType"); throw new NoMandateDataAttributeException(); -- cgit v1.2.3 From 1f46df486fbab558fb3e935dfed160f26e698ac0 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 24 Jan 2014 08:04:12 +0100 Subject: -- Solve merge problems (AuthnRequestHandler.java & mandateReferenceValueAttributeBuilder) -- Change sessionmanagement betweem AuthAction and TokenAction to AssertionStorage class -- add class definieten to HTML config element --- .../moa/id/auth/data/AuthenticationSession.java | 28 +++++++------- .../id/protocols/oauth20/OAuth20SessionObject.java | 6 +-- .../oauth20/protocol/OAuth20AuthAction.java | 30 +++++++-------- .../oauth20/protocol/OAuth20TokenAction.java | 45 ++++++++++++++-------- .../MandateReferenceValueAttributeBuilder.java | 44 +-------------------- .../pvp2x/requestHandler/AuthnRequestHandler.java | 1 + 6 files changed, 65 insertions(+), 89 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java index 1061a2802..9aecefd43 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java @@ -207,7 +207,7 @@ public class AuthenticationSession implements Serializable { private boolean ssoRequested = false; - private OAuth20SessionObject oAuth20SessionObject; +// private OAuth20SessionObject oAuth20SessionObject; // /** // * Indicates if target from configuration is used or not @@ -963,18 +963,18 @@ public class AuthenticationSession implements Serializable { } /** - * @return the oAuth20SessionObject - */ - public OAuth20SessionObject getoAuth20SessionObject() { - return oAuth20SessionObject; - } - - /** - * @param oAuth20SessionObject - * the oAuth20SessionObject to set - */ - public void setoAuth20SessionObject(OAuth20SessionObject oAuth20SessionObject) { - this.oAuth20SessionObject = oAuth20SessionObject; - } +// * @return the oAuth20SessionObject +// */ +// public OAuth20SessionObject getoAuth20SessionObject() { +// return oAuth20SessionObject; +// } +// +// /** +// * @param oAuth20SessionObject +// * the oAuth20SessionObject to set +// */ +// public void setoAuth20SessionObject(OAuth20SessionObject oAuth20SessionObject) { +// this.oAuth20SessionObject = oAuth20SessionObject; +// } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java index 20711373e..4c7d1a37b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java @@ -15,7 +15,7 @@ public class OAuth20SessionObject implements Serializable { private String code; - private AuthenticationSession authDataSession; + private String authDataSession; public String getScope() { return scope; @@ -40,11 +40,11 @@ public class OAuth20SessionObject implements Serializable { this.code = code; } - public AuthenticationSession getAuthDataSession() { + public String getAuthDataSession() { return authDataSession; } - public void setAuthDataSession(AuthenticationSession authDataSession) { + public void setAuthDataSession(String authDataSession) { this.authDataSession = authDataSession; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java index 68f508103..17649487a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java @@ -13,7 +13,9 @@ import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20SessionObject; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ResponseTypeException; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ServerErrorException; +import at.gv.egovernment.moa.id.storage.AssertionStorage; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; class OAuth20AuthAction implements IAction { @@ -32,25 +34,25 @@ class OAuth20AuthAction implements IAction { String responseType = oAuthRequest.getResponseType(); AuthenticationSession session = null; + String code = Random.nextRandom(); + try { - session = AuthenticationSessionStoreage.createSession(); - - String code = session.getSessionID();// AuthenticationSessionStoreage.changeSessionID(moasession); + Logger.debug("Stored session with id: " + code); OAuth20SessionObject o = new OAuth20SessionObject(); if (responseType.equals(OAuth20Constants.RESPONSE_CODE)) { o.setScope(oAuthRequest.getScope()); o.setCode(code); - o.setAuthDataSession(moasession); + o.setAuthDataSession(moasession.getSessionID()); } else if (responseType.equals(OAuth20Constants.RESPONSE_TOKEN)) { throw new OAuth20ResponseTypeException(); } - // store data in oath session - session.setoAuth20SessionObject(o); - AuthenticationSessionStoreage.storeSession(session); - Logger.debug("Saved OAuth20SessionObject in session with id: " + session.getSessionID()); + // store data in oath session + AssertionStorage.getInstance().put(code, o); + + Logger.debug("Saved OAuth20SessionObject in session with id: " + code); // add code and state to redirect url httpResp.setStatus(HttpServletResponse.SC_FOUND); @@ -65,14 +67,12 @@ class OAuth20AuthAction implements IAction { Logger.debug("REDIRECT TO: " + finalUrl.toString()); } catch (Exception e) { - try { - if (session != null) { - Logger.debug("Going to destroy session: " + session.getSessionID()); - AuthenticationSessionStoreage.destroySession(session.getSessionID()); - } - } - catch (MOADatabaseException e1) { + + //remove OAuthSessionObject if it already exists + if (AssertionStorage.getInstance().containsKey(code)) { + AssertionStorage.getInstance().remove(code); } + if (e instanceof OAuth20Exception) { throw (OAuth20Exception) e; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java index 3dceaecdf..b975b5594 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java @@ -28,6 +28,7 @@ import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Unauthorized import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuth20SignatureUtil; import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuthJsonToken; import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuthSigner; +import at.gv.egovernment.moa.id.storage.AssertionStorage; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; @@ -38,25 +39,41 @@ class OAuth20TokenAction implements IAction { public String processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, AuthenticationSession moasession) throws MOAIDException { - AuthenticationSession session = null; + + OAuth20SessionObject auth20SessionObject = null; try { OAuth20TokenRequest oAuthRequest = (OAuth20TokenRequest) req; + + try { + Logger.debug("Loaded OAuth20SessionObject from session: " + oAuthRequest.getCode()); + + auth20SessionObject = + AssertionStorage.getInstance().get(oAuthRequest.getCode(), OAuth20SessionObject.class); - session = AuthenticationSessionStoreage.getSession(oAuthRequest.getCode()); - if (session == null) { + } catch (MOADatabaseException e) { throw new OAuth20UnauthorizedClientException(); + } - - OAuth20SessionObject auth20SessionObject = session.getoAuth20SessionObject(); - Logger.debug("Loaded OAuth20SessionObject from session: " + session.getSessionID()); - + // do checking for different grant types and code if (auth20SessionObject == null || !auth20SessionObject.getCode().equals(oAuthRequest.getCode())) { throw new OAuth20UnauthorizedClientException(); } else { Logger.debug("Loaded of OAuth20SessionObject was successful"); } + + Logger.debug("Load MOASession from database"); + AuthenticationSession session = AuthenticationSessionStoreage.getSession(auth20SessionObject.getAuthDataSession()); + if (session == null) { + Logger.warn("NO MOASession found with SessionID " + auth20SessionObject.getAuthDataSession()); + throw new OAuth20UnauthorizedClientException(); + + } else { + Logger.debug("Loading of MOASession was successful."); + + } + final String accessToken = UUID.randomUUID().toString(); // create response @@ -67,7 +84,7 @@ class OAuth20TokenAction implements IAction { // build id token and scope Pair pair = buildIdToken(auth20SessionObject.getScope(), oAuthRequest, - auth20SessionObject.getAuthDataSession()); + session); Logger.debug("RESPONSE ID_TOKEN: " + pair.getFirst()); params.put(OAuth20Constants.RESPONSE_ID_TOKEN, pair.getFirst()); Logger.debug("RESPONSE SCOPE: " + pair.getSecond()); @@ -93,14 +110,12 @@ class OAuth20TokenAction implements IAction { } finally { - if (session != null) { + if (auth20SessionObject != null) { // destroy session for clean up - try { - Logger.debug("Going to destroy session: " + session.getSessionID()); - AuthenticationSessionStoreage.destroySession(session.getSessionID()); - } - catch (MOADatabaseException e) { - } + + Logger.debug("Going to destroy session: " + auth20SessionObject.getCode()); + AssertionStorage.getInstance().remove(auth20SessionObject.getCode()); + } } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateReferenceValueAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateReferenceValueAttributeBuilder.java index 2c4eb15de..dc1a4f04b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateReferenceValueAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateReferenceValueAttributeBuilder.java @@ -1,36 +1,22 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import org.w3c.dom.Element; - -import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; -import at.gv.egovernment.moa.id.util.MandateBuilder; public class MandateReferenceValueAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_REFERENCE_VALUE_NAME; } - public Attribute build(AuthenticationSession authSession, public ATT build(AuthenticationSession authSession, OAAuthParameter oaParam, AuthenticationData authData, IAttributeGenerator g) throws AttributeException { if (authSession.getUseMandate()) { - Element mandate = authSession.getMandate(); - if (mandate == null) { - throw new NoMandateDataAttributeException(); - } - Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if (mandateObject == null) { - throw new NoMandateDataAttributeException(); - } - + return g.buildStringAttribute(MANDATE_REFERENCE_VALUE_FRIENDLY_NAME, MANDATE_REFERENCE_VALUE_NAME, - mandateObject.getMandateID()); + authSession.getMandateReferenceValue()); } return null; @@ -40,29 +26,3 @@ public class MandateReferenceValueAttributeBuilder implements IPVPAttributeBuild return g.buildEmptyAttribute(MANDATE_REFERENCE_VALUE_FRIENDLY_NAME, MANDATE_REFERENCE_VALUE_NAME); } } - - public Attribute build(AuthenticationSession authSession, - OAAuthParameter oaParam, AuthenticationData authData) throws PVP2Exception { - if(authSession.getUseMandate()) { - -// Element mandate = authSession.getMandate(); -// if(mandate == null) { -// throw new NoMandateDataAvailableException(); -// } -// Mandate mandateObject = MandateBuilder.buildMandate(mandate); -// if(mandateObject == null) { -// throw new NoMandateDataAvailableException(); -// } - - return buildStringAttribute(MANDATE_REFERENCE_VALUE_FRIENDLY_NAME, - MANDATE_REFERENCE_VALUE_NAME, authSession.getMandateReferenceValue()); - } - return null; - - } - - public Attribute buildEmpty() { - return buildemptyAttribute(MANDATE_REFERENCE_VALUE_FRIENDLY_NAME, - MANDATE_REFERENCE_VALUE_NAME); - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java index 0c7dea3c8..9de385307 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java @@ -9,6 +9,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.TransformerException; +import org.joda.time.DateTime; import org.opensaml.Configuration; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.core.Assertion; -- cgit v1.2.3 From 653fd79254188db598c0b980640fab912c9e39f7 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 24 Jan 2014 11:32:38 +0100 Subject: --use differend keys for SAML2 metadata signing and SAML2 assertion signing -- move oAuth idToken generation to OAuth20AuthAction, because MOASession does not exits anymore in OAuth20TokenAction if no SSO is used. --- .../id/protocols/oauth20/OAuth20SessionObject.java | 9 +- .../oauth20/protocol/OAuth20AuthAction.java | 96 +++++++++++++++++++--- .../oauth20/protocol/OAuth20TokenAction.java | 84 +------------------ .../moa/id/protocols/pvp2x/MetadataAction.java | 25 +++--- .../protocols/pvp2x/binding/ArtifactBinding.java | 2 +- .../id/protocols/pvp2x/binding/PostBinding.java | 4 +- .../protocols/pvp2x/binding/RedirectBinding.java | 2 +- .../id/protocols/pvp2x/binding/SoapBinding.java | 2 +- .../protocols/pvp2x/config/PVPConfiguration.java | 27 ++++-- .../protocols/pvp2x/signer/CredentialProvider.java | 58 +++++++++++-- 10 files changed, 177 insertions(+), 132 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java index 4c7d1a37b..d5dd70c11 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java @@ -1,6 +1,7 @@ package at.gv.egovernment.moa.id.protocols.oauth20; import java.io.Serializable; +import java.util.Map; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; @@ -15,7 +16,7 @@ public class OAuth20SessionObject implements Serializable { private String code; - private String authDataSession; + private Map authDataSession; public String getScope() { return scope; @@ -40,12 +41,12 @@ public class OAuth20SessionObject implements Serializable { this.code = code; } - public String getAuthDataSession() { + public Map getAuthDataSession() { return authDataSession; } - public void setAuthDataSession(String authDataSession) { - this.authDataSession = authDataSession; + public void setAuthDataSession(Map idToken) { + this.authDataSession = idToken; } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java index 17649487a..a5c8bb16e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java @@ -1,18 +1,33 @@ package at.gv.egovernment.moa.id.protocols.oauth20.protocol; +import java.security.SignatureException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import at.gv.egovernment.moa.id.auth.AuthenticationServer; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.data.AuthenticationData; import at.gv.egovernment.moa.id.moduls.IAction; import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20SessionObject; +import at.gv.egovernment.moa.id.protocols.oauth20.Pair; +import at.gv.egovernment.moa.id.protocols.oauth20.attributes.OAuth20AttributeBuilder; +import at.gv.egovernment.moa.id.protocols.oauth20.attributes.OpenIdExpirationTimeAttribute; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ResponseTypeException; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ServerErrorException; +import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuth20SignatureUtil; +import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuthJsonToken; +import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuthSigner; import at.gv.egovernment.moa.id.storage.AssertionStorage; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.Random; @@ -23,27 +38,24 @@ class OAuth20AuthAction implements IAction { public String processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, AuthenticationSession moasession) throws MOAIDException { - OAuth20AuthRequest oAuthRequest = (OAuth20AuthRequest) req; - - // OAAuthParameter oaParam = - // AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(oAuthRequest.getOAURL()); - // AuthenticationData authData = - // AuthenticationServer.buildAuthenticationData(moasession, oaParam, - // oAuthRequest.getTarget()); - + OAuth20AuthRequest oAuthRequest = (OAuth20AuthRequest) req; String responseType = oAuthRequest.getResponseType(); - AuthenticationSession session = null; String code = Random.nextRandom(); try { - + + String accessToken = UUID.randomUUID().toString(); + Logger.debug("Stored session with id: " + code); OAuth20SessionObject o = new OAuth20SessionObject(); if (responseType.equals(OAuth20Constants.RESPONSE_CODE)) { o.setScope(oAuthRequest.getScope()); o.setCode(code); - o.setAuthDataSession(moasession.getSessionID()); + + //generate idToken from MOASession + Map idToken = generateIDToken(o, oAuthRequest, moasession, accessToken); + o.setAuthDataSession(idToken); } else if (responseType.equals(OAuth20Constants.RESPONSE_TOKEN)) { throw new OAuth20ResponseTypeException(); @@ -65,6 +77,8 @@ class OAuth20AuthAction implements IAction { String finalUrl = redirectURI; httpResp.addHeader("Location", finalUrl); Logger.debug("REDIRECT TO: " + finalUrl.toString()); + + return accessToken; } catch (Exception e) { @@ -79,7 +93,65 @@ class OAuth20AuthAction implements IAction { throw new OAuth20ServerErrorException(); } - return null; + } + + private Map generateIDToken(OAuth20SessionObject auth20SessionObject, + OAuth20AuthRequest oAuthRequest, AuthenticationSession moasession, String accessToken) throws SignatureException, MOAIDException { + + // create response + Map params = new HashMap(); + params.put(OAuth20Constants.RESPONSE_ACCESS_TOKEN, accessToken); + params.put(OAuth20Constants.RESPONSE_TOKEN_TYPE, OAuth20Constants.RESPONSE_TOKEN_TYPE_VALUE_BEARER); + params.put(OAuth20Constants.RESPONSE_EXPIRES_IN, OpenIdExpirationTimeAttribute.expirationTime); + + // build id token and scope + Pair pair = buildIdToken(auth20SessionObject.getScope(), oAuthRequest, + moasession); + Logger.debug("RESPONSE ID_TOKEN: " + pair.getFirst()); + params.put(OAuth20Constants.RESPONSE_ID_TOKEN, pair.getFirst()); + Logger.debug("RESPONSE SCOPE: " + pair.getSecond()); + params.put(OAuth20Constants.PARAM_SCOPE, pair.getSecond()); + + return params; + + } + + private Pair buildIdToken(String scope, OAuth20AuthRequest oAuthRequest, AuthenticationSession session) + throws MOAIDException, SignatureException { + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(oAuthRequest.getOAURL()); + AuthenticationData authData = AuthenticationServer.buildAuthenticationData(session, oaParam, oAuthRequest.getTarget()); + + OAuthSigner signer = OAuth20SignatureUtil.loadSigner(authData.getIssuer()); + OAuthJsonToken token = new OAuthJsonToken(signer); + + StringBuilder resultScopes = new StringBuilder(); + // always fill with open id + OAuth20AttributeBuilder.addScopeOpenId(token.getPayloadAsJsonObject(), session, oaParam, authData); + resultScopes.append("openId"); + + for (String s : scope.split(" ")) { + if (s.equalsIgnoreCase("profile")) { + OAuth20AttributeBuilder.addScopeProfile(token.getPayloadAsJsonObject(), session, oaParam, authData); + resultScopes.append(" profile"); + } else if (s.equalsIgnoreCase("eID")) { + OAuth20AttributeBuilder.addScopeEID(token.getPayloadAsJsonObject(), session, oaParam, authData); + resultScopes.append(" eID"); + } else if (s.equalsIgnoreCase("eID_gov")) { + OAuth20AttributeBuilder.addScopeEIDGov(token.getPayloadAsJsonObject(), session, oaParam, authData); + resultScopes.append(" eID_gov"); + } else if (s.equalsIgnoreCase("mandate")) { + OAuth20AttributeBuilder.addScopeMandate(token.getPayloadAsJsonObject(), session, oaParam, authData); + resultScopes.append(" mandate"); + } + // TODO parser STORK + } + + // add properties and sign + // HmacSHA256Signer signer = new HmacSHA256Signer("testSigner", "key_id", + // "super_secure_pwd".getBytes()); + // Signer signer = OAuth20Util.loadSigner(authData.getIssuer(), oaParam.getoAuth20Config()); + + return Pair.newInstance(token.serializeAndSign(), resultScopes.toString()); } /* diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java index b975b5594..f3638d63e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java @@ -1,35 +1,19 @@ package at.gv.egovernment.moa.id.protocols.oauth20.protocol; -import java.security.SignatureException; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import at.gv.egovernment.moa.id.auth.AuthenticationServer; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.AuthenticationData; import at.gv.egovernment.moa.id.moduls.IAction; import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20SessionObject; import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Util; -import at.gv.egovernment.moa.id.protocols.oauth20.Pair; -import at.gv.egovernment.moa.id.protocols.oauth20.attributes.OAuth20AttributeBuilder; -import at.gv.egovernment.moa.id.protocols.oauth20.attributes.OpenIdExpirationTimeAttribute; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ServerErrorException; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20UnauthorizedClientException; -import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuth20SignatureUtil; -import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuthJsonToken; -import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuthSigner; import at.gv.egovernment.moa.id.storage.AssertionStorage; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; import com.google.gson.JsonObject; @@ -61,38 +45,10 @@ class OAuth20TokenAction implements IAction { } else { Logger.debug("Loaded of OAuth20SessionObject was successful"); } - - - Logger.debug("Load MOASession from database"); - AuthenticationSession session = AuthenticationSessionStoreage.getSession(auth20SessionObject.getAuthDataSession()); - if (session == null) { - Logger.warn("NO MOASession found with SessionID " + auth20SessionObject.getAuthDataSession()); - throw new OAuth20UnauthorizedClientException(); - - } else { - Logger.debug("Loading of MOASession was successful."); - - } - - final String accessToken = UUID.randomUUID().toString(); - - // create response - Map params = new HashMap(); - params.put(OAuth20Constants.RESPONSE_ACCESS_TOKEN, accessToken); - params.put(OAuth20Constants.RESPONSE_TOKEN_TYPE, OAuth20Constants.RESPONSE_TOKEN_TYPE_VALUE_BEARER); - params.put(OAuth20Constants.RESPONSE_EXPIRES_IN, OpenIdExpirationTimeAttribute.expirationTime); - - // build id token and scope - Pair pair = buildIdToken(auth20SessionObject.getScope(), oAuthRequest, - session); - Logger.debug("RESPONSE ID_TOKEN: " + pair.getFirst()); - params.put(OAuth20Constants.RESPONSE_ID_TOKEN, pair.getFirst()); - Logger.debug("RESPONSE SCOPE: " + pair.getSecond()); - params.put(OAuth20Constants.PARAM_SCOPE, pair.getSecond()); // create response JsonObject jsonObject = new JsonObject(); - OAuth20Util.addProperytiesToJsonObject(jsonObject, params); + OAuth20Util.addProperytiesToJsonObject(jsonObject, auth20SessionObject.getAuthDataSession()); String jsonResponse = jsonObject.toString(); Logger.debug("JSON Response: " + jsonResponse); @@ -137,43 +93,5 @@ class OAuth20TokenAction implements IAction { public String getDefaultActionName() { return OAuth20Protocol.TOKEN_ACTION; } - - private Pair buildIdToken(String scope, OAuth20TokenRequest oAuthRequest, AuthenticationSession session) - throws MOAIDException, SignatureException { - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(oAuthRequest.getOAURL()); - AuthenticationData authData = AuthenticationServer.buildAuthenticationData(session, oaParam, oAuthRequest.getTarget()); - - OAuthSigner signer = OAuth20SignatureUtil.loadSigner(authData.getIssuer()); - OAuthJsonToken token = new OAuthJsonToken(signer); - - StringBuilder resultScopes = new StringBuilder(); - // always fill with open id - OAuth20AttributeBuilder.addScopeOpenId(token.getPayloadAsJsonObject(), session, oaParam, authData); - resultScopes.append("openId"); - for (String s : scope.split(" ")) { - if (s.equalsIgnoreCase("profile")) { - OAuth20AttributeBuilder.addScopeProfile(token.getPayloadAsJsonObject(), session, oaParam, authData); - resultScopes.append(" profile"); - } else if (s.equalsIgnoreCase("eID")) { - OAuth20AttributeBuilder.addScopeEID(token.getPayloadAsJsonObject(), session, oaParam, authData); - resultScopes.append(" eID"); - } else if (s.equalsIgnoreCase("eID_gov")) { - OAuth20AttributeBuilder.addScopeEIDGov(token.getPayloadAsJsonObject(), session, oaParam, authData); - resultScopes.append(" eID_gov"); - } else if (s.equalsIgnoreCase("mandate")) { - OAuth20AttributeBuilder.addScopeMandate(token.getPayloadAsJsonObject(), session, oaParam, authData); - resultScopes.append(" mandate"); - } - // TODO parser STORK - } - - // add properties and sign - // HmacSHA256Signer signer = new HmacSHA256Signer("testSigner", "key_id", - // "super_secure_pwd".getBytes()); - // Signer signer = OAuth20Util.loadSigner(authData.getIssuer(), oaParam.getoAuth20Config()); - - return Pair.newInstance(token.serializeAndSign(), resultScopes.toString()); - } - } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java index e6a8c9661..1c7b1c718 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java @@ -78,17 +78,10 @@ public class MetadataAction implements IAction { keyInfoFactory.setEmitEntityIDAsKeyName(true); keyInfoFactory.setEmitEntityCertificate(true); KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); - - Credential credential = CredentialProvider - .getIDPSigningCredential(); - - KeyDescriptor signKeyDescriptor = SAML2Utils - .createSAMLObject(KeyDescriptor.class); - signKeyDescriptor.setUse(UsageType.SIGNING); - signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(credential)); - + + Credential metadataSigningCredential = CredentialProvider.getIDPMetaDataSigningCredential(); Signature signature = CredentialProvider - .getIDPSignature(credential); + .getIDPSignature(metadataSigningCredential); idpEntitiesDescriptor.setSignature(signature); @@ -139,9 +132,17 @@ public class MetadataAction implements IAction { idpSSODescriptor.getArtifactResolutionServices().add( artifactResolutionService); }*/ + + //set assertion signing key + Credential assertionSigingCredential = CredentialProvider + .getIDPAssertionSigningCredential(); + KeyDescriptor signKeyDescriptor = SAML2Utils + .createSAMLObject(KeyDescriptor.class); + signKeyDescriptor.setUse(UsageType.SIGNING); + signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(assertionSigingCredential)); idpSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); - + idpSSODescriptor.getAttributes().addAll(PVPAttributeBuilder.buildSupportedEmptyAttributes()); NameIDFormat persistenNameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); @@ -184,7 +185,7 @@ public class MetadataAction implements IAction { String metadataXML = sw.toString(); - System.out.println("METADATA: " + metadataXML); + //System.out.println("METADATA: " + metadataXML); httpResp.setContentType("text/xml"); httpResp.getOutputStream().write(metadataXML.getBytes()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/ArtifactBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/ArtifactBinding.java index c486d3ff2..57fa50384 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/ArtifactBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/ArtifactBinding.java @@ -37,7 +37,7 @@ public class ArtifactBinding implements IDecoder, IEncoder { throws MessageEncodingException, SecurityException { try { Credential credentials = CredentialProvider - .getIDPSigningCredential(); + .getIDPAssertionSigningCredential(); Signature signer = CredentialProvider.getIDPSignature(credentials); response.setSignature(signer); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java index 9319c306b..625782cab 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java @@ -44,7 +44,7 @@ public class PostBinding implements IDecoder, IEncoder { try { Credential credentials = CredentialProvider - .getIDPSigningCredential(); + .getIDPAssertionSigningCredential(); Logger.debug("create SAML POSTBinding response"); @@ -103,7 +103,7 @@ public class PostBinding implements IDecoder, IEncoder { RequestAbstractType inboundMessage = (RequestAbstractType) messageContext .getInboundMessage(); - + MOARequest request = new MOARequest(inboundMessage); request.setVerified(false); request.setEntityMetadata(messageContext.getPeerEntityMetadata()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java index 78b63e041..0fd639c1b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java @@ -49,7 +49,7 @@ public class RedirectBinding implements IDecoder, IEncoder { throws MessageEncodingException, SecurityException { try { Credential credentials = CredentialProvider - .getIDPSigningCredential(); + .getIDPAssertionSigningCredential(); Logger.debug("create SAML RedirectBinding response"); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java index 3974e7fd5..1cfb0103e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java @@ -65,7 +65,7 @@ public class SoapBinding implements IDecoder, IEncoder { throws MessageEncodingException, SecurityException, PVP2Exception { try { Credential credentials = CredentialProvider - .getIDPSigningCredential(); + .getIDPAssertionSigningCredential(); HTTPSOAP11Encoder encoder = new HTTPSOAP11Encoder(); HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter( diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java index 116d3b740..b41331dab 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java @@ -46,10 +46,15 @@ public class PVPConfiguration { public static final String PVP2_POST = "/pvp2/post"; public static final String PVP_CONFIG_FILE = "pvp2config.properties"; + public static final String IDP_JAVAKEYSTORE = "idp.ks.file"; - public static final String IDP_KEYALIAS = "idp.ks.alias"; public static final String IDP_KS_PASS = "idp.ks.kspassword"; - public static final String IDP_KEY_PASS = "idp.ks.keypassword"; + + public static final String IDP_KEYALIASMETADATA = "idp.ks.metadata.alias"; + public static final String IDP_KEY_PASSMETADATA = "idp.ks.metadata.keypassword"; + + public static final String IDP_KEYALIASASSERTION = "idp.ks.assertion.sign.alias"; + public static final String IDP_KEY_PASSASSERTION = "idp.ks.assertion.sign.keypassword"; public static final String IDP_ISSUER_NAME = "idp.issuer.name"; @@ -115,17 +120,25 @@ public class PVPConfiguration { public String getIDPKeyStoreFilename() { return props.getProperty(IDP_JAVAKEYSTORE); } - + public String getIDPKeyStorePassword() { return props.getProperty(IDP_KS_PASS); } - public String getIDPKeyAlias() { - return props.getProperty(IDP_KEYALIAS); + public String getIDPKeyAliasMetadata() { + return props.getProperty(IDP_KEYALIASMETADATA); + } + + public String getIDPKeyPasswordMetadata() { + return props.getProperty(IDP_KEY_PASSMETADATA); + } + + public String getIDPKeyAliasAssertionSign() { + return props.getProperty(IDP_KEYALIASASSERTION); } - public String getIDPKeyPassword() { - return props.getProperty(IDP_KEY_PASS); + public String getIDPKeyPasswordAssertionSign() { + return props.getProperty(IDP_KEY_PASSASSERTION); } public String getIDPIssuerName() { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/CredentialProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/CredentialProvider.java index cf0f48f1c..511caa908 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/CredentialProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/CredentialProvider.java @@ -1,6 +1,8 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.signer; import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.interfaces.RSAPrivateKey; import org.opensaml.xml.security.credential.Credential; import org.opensaml.xml.security.credential.UsageType; @@ -13,35 +15,73 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.KeyStoreUtils; +import at.gv.egovernment.moa.util.MiscUtil; public class CredentialProvider { - public static Credential getIDPSigningCredential() + + private static KeyStore keyStore = null; + + public static Credential getIDPMetaDataSigningCredential() throws CredentialsNotAvailableException { - KeyStore keyStore; PVPConfiguration config = PVPConfiguration.getInstance(); try { - keyStore = KeyStoreUtils.loadKeyStore(config.getIDPKeyStoreFilename(), - config.getIDPKeyStorePassword()); + + if (keyStore == null) + keyStore = KeyStoreUtils.loadKeyStore(config.getIDPKeyStoreFilename(), + config.getIDPKeyStorePassword()); KeyStoreX509CredentialAdapter credentials = new KeyStoreX509CredentialAdapter( - keyStore, config.getIDPKeyAlias(), config - .getIDPKeyPassword().toCharArray()); + keyStore, config.getIDPKeyAliasMetadata(), config + .getIDPKeyPasswordMetadata().toCharArray()); credentials.setUsageType(UsageType.SIGNING); return credentials; } catch (Exception e) { - Logger.error("Failed to generate IDP Signing credentials"); + Logger.error("Failed to generate IDP Metadata Signing credentials"); e.printStackTrace(); throw new CredentialsNotAvailableException(e.getMessage(), null); } } + public static Credential getIDPAssertionSigningCredential() + throws CredentialsNotAvailableException { + PVPConfiguration config = PVPConfiguration.getInstance(); + try { + if (keyStore == null) + keyStore = KeyStoreUtils.loadKeyStore(config.getIDPKeyStoreFilename(), + config.getIDPKeyStorePassword()); + + KeyStoreX509CredentialAdapter credentials = new KeyStoreX509CredentialAdapter( + keyStore, config.getIDPKeyAliasAssertionSign(), config + .getIDPKeyPasswordAssertionSign().toCharArray()); + + credentials.setUsageType(UsageType.SIGNING); + return credentials; + } catch (Exception e) { + Logger.error("Failed to generate IDP Assertion Signing credentials"); + e.printStackTrace(); + throw new CredentialsNotAvailableException(e.getMessage(), null); + } + } + public static Signature getIDPSignature(Credential credentials) { + + PrivateKey privatekey = credentials.getPrivateKey(); + Signature signer = SAML2Utils.createSAMLObject(Signature.class); - signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); - signer.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); + + if (privatekey instanceof RSAPrivateKey) { + signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); + + } else if (privatekey instanceof iaik.security.ecc.ecdsa.ECPrivateKey) { + signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA1); + + } + + signer.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); signer.setSigningCredential(credentials); return signer; + } public static Credential getSPTrustedCredential(String entityID) -- cgit v1.2.3 From cea2f395ec773b386ec628d60120752cf320f6b6 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 27 Jan 2014 16:27:02 +0100 Subject: add PVP2 Demo Application change SZRGWClient to JAXWs --- .../moa/id/auth/AuthenticationServer.java | 109 +++++++++++++-------- .../moa/id/auth/stork/STORKResponseProcessor.java | 3 + .../moa/id/client/LaxHostNameVerifier.java | 16 +++ .../gv/egovernment/moa/id/client/SZRGWClient.java | 81 +++++++++++++++ .../moa/id/client/SZRGWClientException.java | 17 ++++ .../moa/id/protocols/pvp2x/MetadataAction.java | 8 ++ 6 files changed, 192 insertions(+), 42 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/LaxHostNameVerifier.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/SZRGWClient.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/SZRGWClientException.java (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java index af23d4c78..278f93f14 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java @@ -54,6 +54,7 @@ import org.apache.xpath.XPathAPI; import org.opensaml.saml2.metadata.RequestedAttribute; import org.opensaml.xml.util.Base64; import org.opensaml.xml.util.XMLHelper; +import org.springframework.util.xml.DomUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -95,10 +96,12 @@ import at.gv.egovernment.moa.id.auth.validator.IdentityLinkValidator; import at.gv.egovernment.moa.id.auth.validator.InfoboxValidator; import at.gv.egovernment.moa.id.auth.validator.VerifyXMLSignatureResponseValidator; import at.gv.egovernment.moa.id.auth.validator.parep.ParepUtils; -import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.CreateIdentityLinkResponse; -import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClient; -import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClientException; +//import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.CreateIdentityLinkResponse; +//import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClient; +//import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClientException; import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWConstants; +import at.gv.egovernment.moa.id.client.SZRGWClient; +import at.gv.egovernment.moa.id.client.SZRGWClientException; import at.gv.egovernment.moa.id.commons.db.dao.config.IdentificationNumber; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.ConfigurationException; @@ -125,6 +128,8 @@ import at.gv.egovernment.moa.util.FileUtils; import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.StringUtils; import at.gv.egovernment.moa.util.XPathUtils; +import at.gv.util.xsd.srzgw.CreateIdentityLinkRequest; +import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse; import eu.stork.mw.messages.saml.STORKAuthnRequest; import eu.stork.vidp.messages.builder.STORKMessagesBuilder; import eu.stork.vidp.messages.common.STORKConstants; @@ -1689,58 +1694,78 @@ public class AuthenticationServer implements MOAIDAuthConstants { * @return Identity link assertion * @throws SZRGWClientException */ - public CreateIdentityLinkResponse getIdentityLink(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, Element signature) throws SZRGWClientException { + public at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.CreateIdentityLinkResponse + getIdentityLink(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, Element signature) throws SZRGWClientException { - SZRGWClient client = new SZRGWClient(); + SZRGWClient client = null; - try { + try { AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); ConnectionParameter connectionParameters = authConf.getForeignIDConnectionParameter(); - client.setAddress(connectionParameters.getUrl()); - if (connectionParameters.getUrl().toLowerCase().startsWith("https:")) { - Logger.debug("Initialisiere SSL Verbindung"); - try { - client.setSSLSocketFactory(SSLUtils.getSSLSocketFactory(AuthConfigurationProvider.getInstance(), connectionParameters)); - } catch (IOException e) { - Logger.error("Could not initialize SSL Factory", e); - throw new SZRGWClientException("Could not initialize SSL Factory"); - } catch (GeneralSecurityException e) { - Logger.error("Could not initialize SSL Factory", e); - throw new SZRGWClientException("Could not initialize SSL Factory"); - } catch (PKIException e) { - Logger.error("Could not initialize SSL Factory", e); - throw new SZRGWClientException("Could not initialize SSL Factory"); - } - } + client = new SZRGWClient(connectionParameters); + + + CreateIdentityLinkRequest request = new CreateIdentityLinkRequest(); + request.setSignature(DOMUtils.serializeNode(signature).getBytes()); + + CreateIdentityLinkResponse response = client.sentCreateIDLRequest(request , connectionParameters.getUrl()); + + + +// client.setAddress(connectionParameters.getUrl()); +// if (connectionParameters.getUrl().toLowerCase().startsWith("https:")) { +// Logger.debug("Initialisiere SSL Verbindung"); +// try { +// client.setSSLSocketFactory(SSLUtils.getSSLSocketFactory(AuthConfigurationProvider.getInstance(), connectionParameters)); +// } catch (IOException e) { +// Logger.error("Could not initialize SSL Factory", e); +// throw new SZRGWClientException("Could not initialize SSL Factory"); +// } catch (GeneralSecurityException e) { +// Logger.error("Could not initialize SSL Factory", e); +// throw new SZRGWClientException("Could not initialize SSL Factory"); +// } catch (PKIException e) { +// Logger.error("Could not initialize SSL Factory", e); +// throw new SZRGWClientException("Could not initialize SSL Factory"); +// } +// } Logger.info("Starte Kommunikation mit dem Stammzahlenregister Gateway(" + connectionParameters.getUrl() + ")..."); } catch (ConfigurationException e) { Logger.warn(e); Logger.warn(MOAIDMessageProvider.getInstance().getMessage("config.12", null )); - } + } catch (TransformerException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } - // create request - CreateIdentityLinkResponse response = null; - Element request = null; - try { - Document doc = client.buildGetIdentityLinkRequest(PEPSIdentifier, PEPSFirstname, PEPSFamilyname, PEPSDateOfBirth, signature); - request = doc.getDocumentElement(); - - // send request - response = client.createIdentityLinkResponse(request); - } catch (SZRGWClientException e) { - // give him a second try - Nach dem Starten des Tomcat wird beim ersten Mal das Client-Zertifikat offenbar vom HTTPClient nicht mitgeschickt. - try { - response = client.createIdentityLinkResponse(request); - } - catch (SZRGWClientException e1) { - throw new SZRGWClientException(e1); - } - } +// // create request +// CreateIdentityLinkResponse response = null; +// Element request = null; +// try { +// Document doc = client.buildGetIdentityLinkRequest(PEPSIdentifier, PEPSFirstname, PEPSFamilyname, PEPSDateOfBirth, signature); +// request = doc.getDocumentElement(); +// +// // send request +// response = client.createIdentityLinkResponse(request, connectionParameters.getUrl()); +// +// +// +// } catch (SZRGWClientException e) { +// // give him a second try - Nach dem Starten des Tomcat wird beim ersten Mal das Client-Zertifikat offenbar vom HTTPClient nicht mitgeschickt. +//// try { +//// response = client.createIdentityLinkResponse(request); +//// } +//// catch (SZRGWClientException e1) { +//// throw new SZRGWClientException(e1); +//// } +// } - return response; + return null; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java index a87e9a8c0..a6e595239 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java @@ -351,6 +351,9 @@ public class STORKResponseProcessor { } catch (ParseException e) { Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e); throw new STORKException("Error parsing IdentityLink received from SZR-Gateway: ", e); + } catch (at.gv.egovernment.moa.id.client.SZRGWClientException e) { + Logger.error("Error connecting SZR-Gateway: ", e); + throw new STORKException("Error connecting SZR-Gateway: ", e); } return identityLink; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/LaxHostNameVerifier.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/LaxHostNameVerifier.java new file mode 100644 index 000000000..a4fe4ab7b --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/LaxHostNameVerifier.java @@ -0,0 +1,16 @@ +package at.gv.egovernment.moa.id.client; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLSession; + +public class LaxHostNameVerifier implements HostnameVerifier { + + /* + * (non-Javadoc) + * @see javax.net.ssl.HostnameVerifier#verify(java.lang.String, javax.net.ssl.SSLSession) + */ + public boolean verify(String arg0, SSLSession arg1) { + return true; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/SZRGWClient.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/SZRGWClient.java new file mode 100644 index 000000000..37c2ebae0 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/SZRGWClient.java @@ -0,0 +1,81 @@ +package at.gv.egovernment.moa.id.client; + +import java.net.URL; +import java.util.Map; + +import javax.net.ssl.SSLSocketFactory; +import javax.xml.namespace.QName; + +import at.gv.egovernment.moa.id.config.ConnectionParameter; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.util.SSLUtils; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; +import at.gv.util.wsdl.szrgw.SZRGWService; +import at.gv.util.wsdl.szrgw.SZRGWType; +import at.gv.util.xsd.srzgw.CreateIdentityLinkRequest; +import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse; + +import com.sun.xml.ws.developer.JAXWSProperties; +import javax.xml.ws.BindingProvider; + +public class SZRGWClient { + + private SSLSocketFactory sslContext = null; + + public SZRGWClient(ConnectionParameter szrgwconnection) throws SZRGWClientException { + initial(szrgwconnection); + } + + public CreateIdentityLinkResponse sentCreateIDLRequest(CreateIdentityLinkRequest request, String serviceUrl) throws SZRGWClientException { + MiscUtil.assertNotNull(request, "createIDLRequest"); + MiscUtil.assertNotNull(serviceUrl, "serviceURL"); + + URL url = SZRGWClient.class.getResource("/resources/wsdl/szrgw/szrgw.wsdl"); + SZRGWService service = new SZRGWService(url, new QName("http://reference.e-government.gv.at/namespace/szrgw/20070807/wsdl", "SZRGWService")); + SZRGWType port = service.getSZRGWPort(); + + + + + BindingProvider bindingProvider = (BindingProvider) port; + Map requestContext = bindingProvider.getRequestContext(); + requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, serviceUrl); + + + // check for ssl + if (serviceUrl.toLowerCase().startsWith("https")) { + Logger.trace("Using ssl for SZRGW client request."); + if (sslContext == null) { + throw new SZRGWClientException("SSL context from configuration is empty. Please configure an SSL context in the configuration first.", null); + } + + requestContext.put(JAXWSProperties.SSL_SOCKET_FACTORY, sslContext); + + // check for lax hostname + if (true) { + Logger.trace("LaxHostnameVerifier enabled. This setting is not recommended to use."); + requestContext.put(JAXWSProperties.HOSTNAME_VERIFIER, new LaxHostNameVerifier()); + } + } + + + return port.szrgwOperation(request); + + } + + + private void initial(ConnectionParameter szrgwconnection) throws at.gv.egovernment.moa.id.client.SZRGWClientException{ + try { + sslContext = SSLUtils.getSSLSocketFactory( + AuthConfigurationProvider.getInstance(), + szrgwconnection); + + } catch (Exception e) { + Logger.warn("SZRGW Client initialization FAILED.", e); + throw new SZRGWClientException("SZRGW Client initialization FAILED.", null); + + } + + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/SZRGWClientException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/SZRGWClientException.java new file mode 100644 index 000000000..4eb268ce9 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/SZRGWClientException.java @@ -0,0 +1,17 @@ +package at.gv.egovernment.moa.id.client; + +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; + +public class SZRGWClientException extends MOAIDException{ + + private static final long serialVersionUID = 1L; + + public SZRGWClientException(String messageId, Object[] parameters) { + super(messageId, parameters); + } + + public SZRGWClientException(SZRGWClientException e1) { + super("", null, e1); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java index 1c7b1c718..c80dbf321 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java @@ -27,9 +27,12 @@ import org.opensaml.xml.io.Marshaller; import org.opensaml.xml.security.credential.Credential; import org.opensaml.xml.security.credential.UsageType; import org.opensaml.xml.security.keyinfo.KeyInfoGenerator; +import org.opensaml.xml.security.keyinfo.KeyInfoHelper; import org.opensaml.xml.security.x509.X509KeyInfoGeneratorFactory; +import org.opensaml.xml.signature.KeyInfo; import org.opensaml.xml.signature.Signature; import org.opensaml.xml.signature.Signer; +import org.opensaml.xml.signature.impl.KeyInfoBuilder; import org.w3c.dom.Document; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; @@ -83,6 +86,11 @@ public class MetadataAction implements IAction { Signature signature = CredentialProvider .getIDPSignature(metadataSigningCredential); +// KeyInfoBuilder metadataKeyInfoBuilder = new KeyInfoBuilder(); +// KeyInfo metadataKeyInfo = metadataKeyInfoBuilder.buildObject(); +// //KeyInfoHelper.addCertificate(metadataKeyInfo, metadataSigningCredential.); +// signature.setKeyInfo(metadataKeyInfo ); + idpEntitiesDescriptor.setSignature(signature); IDPSSODescriptor idpSSODescriptor = SAML2Utils -- cgit v1.2.3