ConsumerEndpoint.java 11.7 KB
Newer Older
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
 * 
 * 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.
 */
 

MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
package org.maxkey.authz.saml20.consumer.endpoint;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
33
import org.maxkey.authn.RealmAuthenticationProvider;
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
34 35 36 37
import org.maxkey.authz.saml.common.EndpointGenerator;
import org.maxkey.authz.saml.common.TrustResolver;
import org.maxkey.authz.saml.service.IDService;
import org.maxkey.authz.saml.service.TimeService;
MaxKey单点登录官方's avatar
update  
MaxKey单点登录官方 已提交
38
import org.maxkey.authz.saml20.binding.ExtractBindingAdapter;
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
39 40 41 42 43
import org.maxkey.authz.saml20.consumer.AuthnRequestGenerator;
import org.maxkey.authz.saml20.consumer.spring.IdentityProviderAuthenticationException;
import org.maxkey.authz.saml20.consumer.spring.ServiceProviderAuthenticationException;
import org.maxkey.authz.saml20.provider.xml.AuthnResponseGenerator;
import org.maxkey.authz.saml20.xml.SAML2ValidatorSuite;
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
44
import org.maxkey.constants.ConstantsLoginType;
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
45
import org.maxkey.crypto.keystore.KeyStoreLoader;
MaxKey单点登录官方's avatar
m-11/6  
MaxKey单点登录官方 已提交
46
import org.maxkey.domain.apps.AppsSAML20Details;
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
47
import org.maxkey.persistence.service.AppsSaml20DetailsService;
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
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
import org.opensaml.common.binding.SAMLMessageContext;
import org.opensaml.common.binding.security.IssueInstantRule;
import org.opensaml.common.binding.security.MessageReplayRule;
import org.opensaml.saml2.core.Assertion;
import org.opensaml.saml2.core.Response;
import org.opensaml.saml2.core.StatusCode;
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.CredentialResolver;
import org.opensaml.xml.security.credential.KeyStoreCredentialResolver;
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.validation.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


@Controller
public class ConsumerEndpoint {

	private final static Logger logger = LoggerFactory.getLogger(ConsumerEndpoint.class);

	@Autowired
	@Qualifier("spKeyStoreLoader")
	private KeyStoreLoader keyStoreLoader;

	@Autowired
	@Qualifier("timeService")
	private TimeService timeService;

	@Autowired
	@Qualifier("idService")
	private IDService idService;
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
91 92 93 94
	
	@Autowired
    @Qualifier("authenticationProvider")
    RealmAuthenticationProvider authenticationProvider ;
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
95 96 97 98 99

	private String singleSignOnServiceURL;
	private String assertionConsumerServiceURL;
	
	@Autowired
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
100
	@Qualifier("extractRedirectBindingAdapter")
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
101 102 103
	private ExtractBindingAdapter extractBindingAdapter;

	@Autowired
MaxKey单点登录官方's avatar
m-11/6  
MaxKey单点登录官方 已提交
104
	private AppsSaml20DetailsService saml20DetailsService;
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
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

	@Autowired
	@Qualifier("issueInstantRule")
	private IssueInstantRule issueInstantRule;

	@Autowired
	@Qualifier("messageReplayRule")
	private MessageReplayRule messageReplayRule;

	EndpointGenerator endpointGenerator;
	AuthnRequestGenerator authnRequestGenerator;
	CredentialResolver credentialResolver;

	Credential signingCredential;
	
	SAML2ValidatorSuite validatorSuite = new SAML2ValidatorSuite();

	@RequestMapping(value = "/consumer/saml/v20/{spId}")
	public ModelAndView consumer(HttpServletRequest request,
			HttpServletResponse response, @PathVariable("spId") String spId)
			throws Exception {

		logger.debug("Attempting authentication.");
		// 初始化SP 证书
		initCredential(spId);

		SAMLMessageContext messageContext=null;

		/*try {
			messageContext = bindingAdapter.extractSAMLMessageContext(request);
		} catch (MessageDecodingException me) {
			logger.error("Could not decode SAML Response", me);
			throw new Exception(me);
		} catch (SecurityException se) {
			logger.error("Could not decode SAML Response", se);
			throw new Exception(se);
		}*/

		logger.debug("Message received from issuer: "
				+ messageContext.getInboundMessageIssuer());

		if (!(messageContext.getInboundSAMLMessage() instanceof Response)) {
			logger.error("SAML Message was not a Response");
			throw new Exception();
		}
		List<Assertion> assertionList = ((Response) messageContext
				.getInboundSAMLMessage()).getAssertions();



		String credentials = extractBindingAdapter.extractSAMLMessage(request);

		// 未认证token
		Response samlResponse=(Response) messageContext.getInboundSAMLMessage();
		
		AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
	

		try {
			validatorSuite.validate(samlResponse);
		} catch (ValidationException ve) {
			logger.warn("Response Message failed Validation", ve);
			throw new ServiceProviderAuthenticationException("Invalid SAML REsponse Message", ve);
		}

		
		checkResponseStatus(samlResponse);

		Assertion assertion = samlResponse.getAssertions().get(0);
		
		logger.debug("authenticationResponseIssuingEntityName {}" ,samlResponse.getIssuer().getValue()); 
		
		String username=assertion.getSubject().getNameID().getValue();
		
		logger.debug("assertion.getID() " ,assertion.getID());
		logger.debug("assertion.getSubject().getNameID().getValue() ", username);
		
	
		logger.debug("assertion.getID() ", assertion.getAuthnStatements());
		
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
185
		authenticationProvider.trustAuthentication(username, ConstantsLoginType.SAMLTRUST,"","","success");
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
186 187 188 189 190 191 192 193 194 195 196 197

		ModelAndView mav = new ModelAndView();
		mav.addObject("username", username);

		mav.setViewName("redirect:/consumer/saml/v20/forward/webseal/eai");
		return mav;
	}



	public void afterPropertiesSet() throws Exception {

MaxKey单点登录官方's avatar
update  
MaxKey单点登录官方 已提交
198
		authnRequestGenerator = new AuthnRequestGenerator(keyStoreLoader.getEntityName(), timeService, idService);
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
199 200 201
		endpointGenerator = new EndpointGenerator();

		CriteriaSet criteriaSet = new CriteriaSet();
MaxKey单点登录官方's avatar
update  
MaxKey单点登录官方 已提交
202
		criteriaSet.add(new EntityIDCriteria(keyStoreLoader.getEntityName()));
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
		criteriaSet.add(new UsageCriteria(UsageType.SIGNING));

		try {
			signingCredential = credentialResolver.resolveSingle(criteriaSet);
		} catch (SecurityException e) {
			logger.error("证书解析出错", e);
			throw new Exception(e);
		}
		Validate.notNull(signingCredential);

	}

	/**
	 * 初始化sp证书
	 * 
	 * @throws Exception
	 */
	private void initCredential(String spId) throws Exception {
		// 1. 获取 sp keyStore
MaxKey单点登录官方's avatar
m-11/6  
MaxKey单点登录官方 已提交
222
		AppsSAML20Details saml20Details = saml20DetailsService.get(spId);
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
223 224 225 226 227 228 229 230 231
		if (saml20Details == null) {
			// TODO
			logger.error("spid[" + spId + "] not exists");
			throw new Exception();
		}
		byte[] keyStoreBytes = saml20Details.getKeyStore();
		InputStream keyStoreStream = new ByteArrayInputStream(keyStoreBytes);

		try {
MaxKey单点登录官方's avatar
update  
MaxKey单点登录官方 已提交
232 233
			KeyStore keyStore = KeyStore.getInstance(keyStoreLoader.getKeystoreType());
			keyStore.load(keyStoreStream, keyStoreLoader.getKeystorePassword().toCharArray());
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
234 235

			Map<String, String> passwords = new HashMap<String, String>();
MaxKey单点登录官方's avatar
update  
MaxKey单点登录官方 已提交
236
			for (Enumeration<String> en = keyStore.aliases(); en.hasMoreElements();) {
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
237
				String aliase = en.nextElement();
MaxKey单点登录官方's avatar
update  
MaxKey单点登录官方 已提交
238
				if (aliase.equalsIgnoreCase(keyStoreLoader.getEntityName())) {
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
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 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
					passwords.put(aliase, keyStoreLoader.getKeystorePassword());
				}
			}
			// TrustResolver trustResolver = new
			// TrustResolver(keyStore,keyStoreLoader.getIdpIssuingEntityName(),keyStoreLoader.getKeystorePassword());

			AuthnResponseGenerator authnResponseGenerator = new AuthnResponseGenerator(
					keyStoreLoader.getEntityName(), timeService,
					idService);
			// endpointGenerator = new EndpointGenerator();

			CriteriaSet criteriaSet = new CriteriaSet();
			criteriaSet.add(new EntityIDCriteria(keyStoreLoader
					.getEntityName()));
			criteriaSet.add(new UsageCriteria(UsageType.SIGNING));

			KeyStoreCredentialResolver credentialResolver = new KeyStoreCredentialResolver(
					keyStore, passwords);
			signingCredential = credentialResolver.resolveSingle(criteriaSet);
			Validate.notNull(signingCredential);

			// adapter set resolver
			TrustResolver trustResolver = new TrustResolver(keyStore,
					keyStoreLoader.getEntityName(),
					keyStoreLoader.getKeystorePassword(), issueInstantRule,
					messageReplayRule,"POST");
			extractBindingAdapter.setSecurityPolicyResolver(trustResolver
					.getStaticSecurityPolicyResolver());
		} catch (Exception e) {
			logger.error("初始化sp证书出错");
			throw new Exception(e);
		}
	}
	
	
	private void checkResponseStatus(Response samlResponse) {

		
		if(StatusCode.SUCCESS_URI.equals( StringUtils.trim(samlResponse.getStatus().getStatusCode().getValue()))) {
			
			additionalValidationChecksOnSuccessfulResponse(samlResponse);
			
		}
		
		
		else {
			
			StringBuilder extraInformation = extractExtraInformation(samlResponse);
			
			if(extraInformation.length() > 0) {
				logger.warn("Extra information extracted from authentication failure was {}", extraInformation.toString());
				
				throw new IdentityProviderAuthenticationException("Identity Provider has failed the authentication.", extraInformation.toString());
			}
			
			else {
				throw new IdentityProviderAuthenticationException("Identity Provider has failed the authentication.");
			}
			
		}
	}
	
	
	private void additionalValidationChecksOnSuccessfulResponse(
			Response samlResponse) {
		//saml validator suite does not check for assertions on successful auths
		if(samlResponse.getAssertions().isEmpty()){
			throw new ServiceProviderAuthenticationException("Successful Response did not contain any assertions");
		}
		
		//nor authnStatements
		else if(samlResponse.getAssertions().get(0).getAuthnStatements().isEmpty()){
			throw new ServiceProviderAuthenticationException("Successful Response did not contain an assertions with an AuthnStatement");
		}

		//we require at attribute statements
		else if(samlResponse.getAssertions().get(0).getAttributeStatements().isEmpty()){
			throw new ServiceProviderAuthenticationException("Successful Response did not contain an assertions with an AttributeStatements");

		}
		//we will require an issuer
		else if(samlResponse.getIssuer() == null) {
			throw new ServiceProviderAuthenticationException("Successful Response did not contain any Issuer");

		}
	}

	private StringBuilder extractExtraInformation(Response samlResponse) {
		StringBuilder extraInformation = new StringBuilder();
		
		if( samlResponse.getStatus().getStatusCode().getStatusCode() !=null ) {
		
			extraInformation.append(samlResponse.getStatus().getStatusCode().getStatusCode().getValue());
		}
		
		if(samlResponse.getStatus().getStatusMessage() != null) {
			if(extraInformation.length() > 0) {
				extraInformation.append("  -  ");
			}
			extraInformation.append(samlResponse.getStatus().getStatusMessage());
		}
		return extraInformation;
	}
}