1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
|
public static final String DJI_ACS_URL = "https://es-flight-api.djigate.com/manage/api/v1/sso/acs";
private static final long ALLOWED_CLOCK_SKEW_SECONDS = 5 * 60;
private static final int MAX_INFLATED_SIZE = 100 * 1024;
public void handleSsoRequestWithConfig( String samlRequest, DjiSsoConfigResp config, HttpServletResponse response) throws Exception {
AuthnRequest authnRequest = decodeSamlRequest(samlRequest); log.info("收到大疆SAML认证请求,ID: {}, 使用邮箱: {}", authnRequest.getID(), config.getSsoEmail());
validateAuthnRequest(authnRequest);
Response samlResponse = buildSamlResponseWithEmail(authnRequest, config.getSsoEmail());
sendResponseToAcs(samlResponse, response);
log.info("SAML Response已发送到大疆ACS,邮箱: {}", config.getSsoEmail()); }
public AuthnRequest decodeSamlRequest(String samlRequest) throws Exception { byte[] decoded = Base64.getDecoder().decode(samlRequest); byte[] inflated = inflate(decoded); AuthnRequest authnRequest = (AuthnRequest) XMLObjectSupport.unmarshallFromInputStream( XMLObjectProviderRegistrySupport.getParserPool(), new ByteArrayInputStream(inflated) ); return authnRequest; }
private void validateAuthnRequest(AuthnRequest authnRequest) { DateTime issueInstant = authnRequest.getIssueInstant(); if (issueInstant == null) { log.warn("SAML AuthnRequest 缺少 IssueInstant"); throw new ServiceException(ResultCodeEnum.PARAMETER_ERROR, "AuthnRequest 缺少 IssueInstant"); } DateTime now = DateTime.now(); int secondsDiff = Math.abs(Seconds.secondsBetween(issueInstant, now).getSeconds()); if(secondsDiff > ALLOWED_CLOCK_SKEW_SECONDS) { log.warn("IssueInstant 偏差超过 5 分钟"); throw new ServiceException(ResultCodeEnum.PARAMETER_ERROR, "IssueInstant 偏差超过 5 分钟"); }
Issuer issuer = authnRequest.getIssuer(); if (issuer == null || StrUtil.isBlank(issuer.getValue())) { log.warn("SAML AuthnRequest 缺少 Issuer"); throw new ServiceException(ResultCodeEnum.PARAMETER_ERROR, "AuthnRequest 缺少 Issuer"); } URI uri = URI.create(issuer.getValue()); String path = uri.getPath(); String newPath = path.replaceFirst("^/[^/]+", ""); String result = uri.getScheme() + "://" + uri.getHost() + newPath; if (!DJI_ACS_URL.equals(result)) { log.warn("SAML AuthnRequest Issuer 不匹配,期望: {}, 实际: {}", DJI_ACS_URL, result); throw new ServiceException(ResultCodeEnum.PARAMETER_ERROR, "AuthnRequest Issuer 不合法"); }
String destination = authnRequest.getDestination(); if (StrUtil.isNotBlank(destination) && !destination.equals(ssoLocation)) { log.warn("SAML AuthnRequest Destination 不匹配,期望: {}, 实际: {}", ssoLocation, destination); throw new ServiceException(ResultCodeEnum.PARAMETER_ERROR, "AuthnRequest Destination 不合法"); } }
private Response buildSamlResponseWithEmail(AuthnRequest authnRequest, String ssoEmail) throws Exception { log.info("构建SAML Response,邮箱: {}", ssoEmail);
Response response = (Response) XMLObjectSupport.buildXMLObject(Response.DEFAULT_ELEMENT_NAME); response.setID("_" + generateId()); response.setIssueInstant(new DateTime()); response.setDestination(DJI_ACS_URL); response.setIssuer(buildIssuer()); response.setStatus(buildStatus());
Assertion assertion = buildAssertion(authnRequest, ssoEmail); response.getAssertions().add(assertion);
signResponse(response);
return response; }
private void sendResponseToAcs(Response samlResponse, HttpServletResponse response) throws Exception { MessageContext<SAMLObject> context = new MessageContext<>(); context.setMessage(samlResponse);
SignatureSigningParameters signingParameters = new SignatureSigningParameters(); signingParameters.setSigningCredential(buildCredential()); signingParameters.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); signingParameters.setSignatureCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
SecurityParametersContext securityContext = context.getSubcontext(SecurityParametersContext.class, true); securityContext.setSignatureSigningParameters(signingParameters);
VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "class"); velocityEngine.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); velocityEngine.init();
SAMLPeerEntityContext peerEntityContext = context.getSubcontext(SAMLPeerEntityContext.class, true); SAMLEndpointContext endpointContext = peerEntityContext.getSubcontext(SAMLEndpointContext.class, true);
SingleSignOnService endpoint = new SingleSignOnServiceBuilder().buildObject(); endpoint.setLocation(DJI_ACS_URL); endpoint.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); endpointContext.setEndpoint(endpoint);
HTTPPostEncoder encoder = new HTTPPostEncoder(); encoder.setHttpServletResponse(response); encoder.setMessageContext(context); encoder.setVelocityEngine(velocityEngine); encoder.initialize(); encoder.encode(); }
private String generateId() { return UUID.randomUUID().toString().replace("-", ""); }
private Issuer buildIssuer() { Issuer issuer = (Issuer) XMLObjectSupport.buildXMLObject(Issuer.DEFAULT_ELEMENT_NAME); issuer.setValue(entityId); return issuer; }
private Status buildStatus() { Status status = (Status) XMLObjectSupport.buildXMLObject(Status.DEFAULT_ELEMENT_NAME); StatusCode statusCode = (StatusCode) XMLObjectSupport.buildXMLObject(StatusCode.DEFAULT_ELEMENT_NAME); statusCode.setValue(StatusCode.SUCCESS); status.setStatusCode(statusCode); return status; }
private Assertion buildAssertion(AuthnRequest authnRequest, String ssoEmail) { Assertion assertion = (Assertion) XMLObjectSupport.buildXMLObject(Assertion.DEFAULT_ELEMENT_NAME); assertion.setID("_" + generateId()); assertion.setIssueInstant(new DateTime()); assertion.setIssuer(buildIssuer());
Subject subject = (Subject) XMLObjectSupport.buildXMLObject(Subject.DEFAULT_ELEMENT_NAME); NameID nameID = (NameID) XMLObjectSupport.buildXMLObject(NameID.DEFAULT_ELEMENT_NAME); nameID.setFormat("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"); nameID.setValue(ssoEmail);
SubjectConfirmation subjectConfirmation = (SubjectConfirmation) XMLObjectSupport.buildXMLObject(SubjectConfirmation.DEFAULT_ELEMENT_NAME); subjectConfirmation.setMethod(SubjectConfirmation.METHOD_BEARER);
SubjectConfirmationData data = (SubjectConfirmationData) XMLObjectSupport.buildXMLObject(SubjectConfirmationData.DEFAULT_ELEMENT_NAME); String acsUrl = authnRequest.getAssertionConsumerServiceURL(); data.setRecipient(StrUtil.isNotBlank(acsUrl) ? acsUrl : DJI_ACS_URL); data.setNotOnOrAfter(new DateTime().plusMinutes(5)); data.setInResponseTo(authnRequest.getID());
subjectConfirmation.setSubjectConfirmationData(data); subject.getSubjectConfirmations().add(subjectConfirmation); subject.setNameID(nameID); assertion.setSubject(subject);
Conditions conditions = (Conditions) XMLObjectSupport.buildXMLObject(Conditions.DEFAULT_ELEMENT_NAME); conditions.setNotBefore(new DateTime().minusSeconds(60)); conditions.setNotOnOrAfter(new DateTime().plusMinutes(5)); assertion.setConditions(conditions);
AuthnStatement authnStatement = (AuthnStatement) XMLObjectSupport.buildXMLObject(AuthnStatement.DEFAULT_ELEMENT_NAME); authnStatement.setAuthnInstant(new DateTime()); authnStatement.setSessionIndex("session_" + generateId()); authnStatement.setSessionNotOnOrAfter(new DateTime().plusHours(8));
AuthnContext authnContext = (AuthnContext) XMLObjectSupport.buildXMLObject(AuthnContext.DEFAULT_ELEMENT_NAME); AuthnContextClassRef classRef = (AuthnContextClassRef) XMLObjectSupport.buildXMLObject(AuthnContextClassRef.DEFAULT_ELEMENT_NAME); classRef.setAuthnContextClassRef(AuthnContext.PASSWORD_AUTHN_CTX); authnContext.setAuthnContextClassRef(classRef); authnStatement.setAuthnContext(authnContext); assertion.getAuthnStatements().add(authnStatement);
return assertion; }
private void signResponse(Response response) throws Exception { Signature signature = (Signature) XMLObjectSupport.buildXMLObject(Signature.DEFAULT_ELEMENT_NAME); BasicX509Credential credential = buildCredential(); signature.setSigningCredential(credential); signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
response.setSignature(signature);
marshallResponse(response);
Signer.signObject(signature); }
private void marshallResponse(Response response) throws MarshallingException { Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(response);
marshaller.marshall(response); }
private BasicX509Credential buildCredential() throws Exception { X509Certificate cert = CertificateUtils.loadCertificate(CERTIFICATE_PATH); PrivateKey privateKey = CertificateUtils.loadPrivateKey(PRIVATE_KEY_PATH);
BasicX509Credential credential = new BasicX509Credential(cert); credential.setEntityCertificate(cert); credential.setPrivateKey(privateKey); credential.setEntityId(entityId); return credential; }
private byte[] inflate(byte[] input) throws IOException, java.util.zip.DataFormatException { Inflater inflater = new Inflater(true); inflater.setInput(input);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024];
while (!inflater.finished()) { int count = inflater.inflate(buffer); outputStream.write(buffer, 0, count); if (outputStream.size() > MAX_INFLATED_SIZE) { throw new IOException("SAMLRequest 解压后数据超过最大限制"); } }
outputStream.close(); return outputStream.toByteArray(); }
|