📄 identitytokenissuer.java
字号:
/* * Copyright 2005,2006 WSO2, Inc. http://www.wso2.org * * 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 org.wso2.solutions.identity.sts;import org.apache.axiom.om.OMElement;import org.apache.axiom.om.OMFactory;import org.apache.axiom.om.OMNode;import org.apache.axiom.om.util.UUIDGenerator;import org.apache.axiom.soap.SOAPEnvelope;import org.apache.axis2.context.MessageContext;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.rahas.RahasConstants;import org.apache.rahas.RahasData;import org.apache.rahas.Token;import org.apache.rahas.TokenIssuer;import org.apache.rahas.TrustException;import org.apache.rahas.TrustUtil;import org.apache.ws.security.WSConstants;import org.apache.ws.security.message.WSSecEncryptedKey;import org.apache.ws.security.message.token.SecurityTokenReference;import org.apache.ws.security.util.WSSecurityUtil;import org.apache.ws.security.util.XmlSchemaDateFormat;import org.apache.xml.security.encryption.EncryptedData;import org.apache.xml.security.encryption.XMLCipher;import org.apache.xml.security.keys.KeyInfo;import org.joda.time.DateTime;import org.opensaml.SAMLException;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.wso2.solutions.identity.IdentityConstants;import org.wso2.solutions.identity.IdentityProviderConstants;import org.wso2.solutions.identity.IdentityProviderException;import org.wso2.solutions.identity.admin.ParameterAdmin;import org.wso2.solutions.identity.admin.ReportAdmin;import org.wso2.solutions.identity.i18n.Messages;import org.wso2.solutions.identity.persistence.IPPersistenceManager;import org.wso2.solutions.identity.persistence.dataobject.ActionDO;import org.wso2.solutions.identity.persistence.dataobject.InfoCardDO;import org.wso2.solutions.identity.persistence.dataobject.IssuedTokensDO;import org.wso2.solutions.identity.sts.IdentityProviderData.RequestedClaimData;import org.wso2.solutions.identity.sts.saml.SAML1TokenBuilder;import org.wso2.solutions.identity.sts.saml.SAML2TokenBuilder;import org.wso2.solutions.identity.sts.saml.SAMLTokenBuilder;import org.wso2.solutions.identity.sts.saml.SAMLTokenDirector;import org.wso2.solutions.identity.util.IdentityUtil;import javax.crypto.SecretKey;import javax.xml.namespace.QName;import javax.xml.parsers.DocumentBuilderFactory;import java.io.ByteArrayInputStream;import java.security.cert.X509Certificate;import java.text.DateFormat;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.Iterator;import java.util.Map;import java.util.TimeZone;/** * This is the main token issuer implementation identity provider. Two types of * credential mechanisms are supported: * * <ul> * <li>Username and Password Credential</li> * <li>Self-issued Token Credential</li> * </ul> * * Supported list of claims can be configured and the values of those supported * claims will be obtained from the user store setup to work with the identity * provider. */public class IdentityTokenIssuer implements TokenIssuer { private static Log log = LogFactory.getLog(IdentityTokenIssuer.class); private final static String WSS_SAML_NS = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#"; protected IdentityProviderData ipData = null; public final static String ISSUER_SELF = IdentityConstants.NS + "/issuer/self"; private static Log tokenIssuerLog = LogFactory .getLog(IdentityProviderConstants.TOKEN_ISSUSER_LOG); private static Messages messages = Messages .getInstance(IdentityProviderConstants.RESOURCES); private boolean isTokenLogDebug = false; public IdentityTokenIssuer() { isTokenLogDebug = tokenIssuerLog.isDebugEnabled(); } /** * {@inheritDoc} */ public String getResponseAction(RahasData data) throws TrustException { return RahasConstants.WST_NS_05_02 + RahasConstants.RSTR_ACTION_ISSUE; } /** * {@inheritDoc} */ public SOAPEnvelope issue(RahasData data) throws TrustException { boolean debug = log.isDebugEnabled(); if (debug) { log.debug("issue"); } try { if (debug) { log.debug("Request: \n" + data.getRstElement().toString() + "\n\n"); } ipData = getIdentityProviderData(data); boolean isValidCard = isValidCard(ipData.getCardID()); if (debug) { log.debug("Card is validated"); } if (isValidCard == false) { String msg = "Invalid information card"; log.error(msg); ReportAdmin.record(ipData.getUserIdentifier(), ActionDO.ACTION_TOKEN_ISSUE_FAILURE, msg); throw new TrustException(TrustException.REQUEST_FAILED); } if (isTokenLogDebug) { tokenIssuerLog.debug(messages.getMessage("validInfoCard", new String[] { ipData.getCardID() })); } return createResponse(data); } catch (Exception e) { throw new TrustException(TrustException.REQUEST_FAILED, e); } finally { log.info("Issued token"); } } /** * Create the response SOAP envelope. * * @param data * WS-Trust information in the issue request. * @return response SOAP envelope. * @throws TrustException */ private SOAPEnvelope createResponse(RahasData rahasData) throws TrustException { try { MessageContext inMsgCtx = rahasData.getInMessageContext(); SOAPEnvelope env = TrustUtil.createSOAPEnvelope(inMsgCtx .getEnvelope().getNamespace().getNamespaceURI()); Document doc = ((Element) env).getOwnerDocument(); // Create EncryptedKey WSSecEncryptedKey encryptedKey = null; X509Certificate serviceCert = ipData.getRpCert(); if (serviceCert != null) { encryptedKey = new WSSecEncryptedKey(); encryptedKey.setUseThisCert(serviceCert); encryptedKey.setKeySize(256); encryptedKey.setKeyEncAlgo(WSConstants.KEYTRANSPORT_RSAOEP); encryptedKey .setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER); encryptedKey.prepare(doc, null); Element encrKeyElem = encryptedKey.getEncryptedKeyElement(); // Create KeyInfo structure - START Element keyInfoElem = doc.createElementNS(WSConstants.SIG_NS, "KeyInfo"); ((OMElement) encrKeyElem).declareNamespace(WSConstants.SIG_NS, WSConstants.SIG_PREFIX); ((OMElement) encrKeyElem).declareNamespace(WSConstants.ENC_NS, WSConstants.ENC_PREFIX); keyInfoElem.appendChild(encrKeyElem); // Create KeyInfo structure - END } if (!checkIsValidTokenType(ipData)) { throw new IdentityProviderException("invalidTokenType", new Object[] { ipData.getRequiredTokenType() }); } DateTime notBefore = new DateTime(); DateTime notAfter = new DateTime(notBefore.getMillis() + (300 * 1000)); String assertionId = UUIDGenerator.getUUID(); if (isTokenLogDebug) { tokenIssuerLog.debug(messages.getMessage( "startSAMLTokenCreation", new String[] { ipData .getCardID() })); } Element assertionNode = createSAMLAssertionAsDOM(ipData, rahasData, notBefore, notAfter, assertionId); if (isTokenLogDebug) { tokenIssuerLog.debug(messages.getMessage( "finishSAMLTokenCreation", new String[] { ipData .getCardID() })); } OMElement rstrElem = createRSTR(rahasData, notBefore.toDate(), notAfter.toDate(), env, doc, assertionNode, assertionId, encryptedKey); if (isTokenLogDebug) { tokenIssuerLog.debug(messages.getMessage("RSTRCreationDone", new String[] { ipData.getCardID() })); } if (log.isDebugEnabled()) { log.debug("Response created"); log.debug("Response body : \n" + rstrElem.toString() + "\n\n"); } IPPersistenceManager dbman = IPPersistenceManager .getPersistanceManager(); InfoCardDO card = dbman.getInfoCard(ipData.getCardID()); IssuedTokensDO tok = new IssuedTokensDO(); tok.setCard(card); tok.setDateExpires(notAfter.toDate()); tok.setDateIssued(notBefore.toDate()); if (rahasData.getTokenType() == null || rahasData.getTokenType().trim().length() == 0) { tok.setTokenType(ipData.getDefautTokenType()); } else { tok.setTokenType(rahasData.getTokenType()); } dbman.create(tok); return env; } catch (Exception e) { log.error(e.getMessage()); try { ReportAdmin.record(ipData.getUserIdentifier(), ActionDO.ACTION_TOKEN_ISSUE_FAILURE, e.getMessage()); } catch (IdentityProviderException e1) { throw new TrustException(TrustException.REQUEST_FAILED, e1); } throw new TrustException(TrustException.REQUEST_FAILED, e); } finally { log.info("Response ready for : " + ipData.getCardID()); } } /** * Create the <code>wst:RequstedSecurityTokenRespoonse</code> element. * * @param data * WS-Trust information in the issue request * @param notBefore * Created time * @param notAfter * Expiration time * @param env * Response SOAP envelope * @param doc * <code>org.w3.dom.Document</code> instance of the response * SOAP envelope * @param assertion * SAML Assertion to be sent in the response. * @param encryptedKey * Key used to encrypt the SAML assertion. * @return <code>wst:RequstedSecurityTokenRespoonse</code> element. * @throws TrustException * @throws SAMLException */ protected OMElement createRSTR(RahasData data, Date notBefore, Date notAfter, SOAPEnvelope env, Document doc, Node assertionElem, String assertionId, WSSecEncryptedKey encryptedKey) throws TrustException, SAMLException, IdentityProviderException { if (log.isDebugEnabled()) { log.debug("Begin RSTR Element creation."); } int wstVersion = data.getVersion(); MessageContext inMsgCtx = data.getInMessageContext();
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -