SAML20DetailsController.java 9.3 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
package org.maxkey.web.apps.contorller;

MaxKey单点登录官方's avatar
a  
MaxKey单点登录官方 已提交
20 21 22 23
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
24 25 26 27
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
M
Apps  
MaxKey 已提交
28
import org.maxkey.authn.annotation.CurrentUser;
MaxKey单点登录官方's avatar
a  
MaxKey单点登录官方 已提交
29
import org.maxkey.authz.saml20.metadata.MetadataDescriptorUtil;
MaxKey单点登录官方's avatar
jks  
MaxKey单点登录官方 已提交
30
import org.maxkey.configuration.ApplicationConfig;
M
v 3.3.0  
MaxKey 已提交
31
import org.maxkey.constants.ConstsProtocols;
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
32
import org.maxkey.crypto.ReciprocalUtils;
MaxKey单点登录官方's avatar
a  
MaxKey单点登录官方 已提交
33 34 35
import org.maxkey.crypto.cert.X509CertUtils;
import org.maxkey.crypto.keystore.KeyStoreLoader;
import org.maxkey.crypto.keystore.KeyStoreUtil;
M
Apps  
MaxKey 已提交
36 37
import org.maxkey.entity.Message;
import org.maxkey.entity.UserInfo;
M
MaxKey 已提交
38
import org.maxkey.entity.apps.AppsSAML20Details;
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
39
import org.maxkey.persistence.service.AppsSaml20DetailsService;
MaxKey单点登录官方's avatar
a  
MaxKey单点登录官方 已提交
40 41 42
import org.opensaml.common.xml.SAMLConstants;
import org.opensaml.saml2.metadata.EntityDescriptor;
import org.opensaml.saml2.metadata.SPSSODescriptor;
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
43 44 45
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
MaxKey单点登录官方's avatar
a  
MaxKey单点登录官方 已提交
46
import org.springframework.beans.factory.annotation.Qualifier;
M
Apps  
MaxKey 已提交
47 48
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
49 50
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
M
Apps  
MaxKey 已提交
51
import org.springframework.web.bind.annotation.RequestBody;
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
52
import org.springframework.web.bind.annotation.RequestMapping;
M
Apps  
MaxKey 已提交
53
import org.springframework.web.bind.annotation.RequestParam;
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
54 55 56 57 58
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping(value={"/apps/saml20"})
MaxKey单点登录官方's avatar
a  
MaxKey单点登录官方 已提交
59
public class SAML20DetailsController   extends BaseAppContorller {
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
60 61
	final static Logger _logger = LoggerFactory.getLogger(SAML20DetailsController.class);
	
MaxKey单点登录官方's avatar
a  
MaxKey单点登录官方 已提交
62 63 64 65
	@Autowired
	@Qualifier("keyStoreLoader")
	private KeyStoreLoader idpKeyStoreLoader;
	
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
66
	@Autowired
MaxKey单点登录官方's avatar
m-11/6  
MaxKey单点登录官方 已提交
67
	AppsSaml20DetailsService saml20DetailsService;
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
68
	
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
69
	@Autowired
MaxKey单点登录官方's avatar
jks  
MaxKey单点登录官方 已提交
70
	ApplicationConfig applicationConfig;
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
71
	
M
Apps  
MaxKey 已提交
72 73
	@RequestMapping(value = { "/init" }, produces = {MediaType.APPLICATION_JSON_VALUE})
	public ResponseEntity<?> init() {
MaxKey单点登录官方's avatar
m-11/6  
MaxKey单点登录官方 已提交
74
		AppsSAML20Details saml20Details=new AppsSAML20Details();
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
75
		saml20Details.setSecret(ReciprocalUtils.generateKey(""));
M
v 3.3.0  
MaxKey 已提交
76
		saml20Details.setProtocol(ConstsProtocols.SAML20);
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
77
		saml20Details.setId(saml20Details.generateId());
M
Apps  
MaxKey 已提交
78
		return new Message<AppsSAML20Details>(saml20Details).buildResponse();
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
79 80
	}
	
M
Apps  
MaxKey 已提交
81 82 83 84 85 86 87 88 89
	@RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE})
	public ResponseEntity<?> get(@PathVariable("id") String id) {
		AppsSAML20Details saml20Details=saml20DetailsService.getAppDetails(id , false);
		decoderSecret(saml20Details);
		saml20Details.transIconBase64();
		//modelAndView.addObject("model",saml20Details);
		//modelAndView.addObject("authzURI",applicationConfig.getAuthzUri());
		return new Message<AppsSAML20Details>(saml20Details).buildResponse();
	}
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
90
	
M
Apps  
MaxKey 已提交
91 92 93 94 95
	@ResponseBody
	@RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE})
	public ResponseEntity<?> add(
			@RequestBody AppsSAML20Details saml20Details,
			@CurrentUser UserInfo currentUser) {
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
96
		_logger.debug("-Add  :" + saml20Details);
M
Apps  
MaxKey 已提交
97
		
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
98 99 100 101 102
		try {
			transform(saml20Details);
		} catch (Exception e) {
			e.printStackTrace();
		}
M
Apps  
MaxKey 已提交
103
		saml20Details.setInstId(currentUser.getInstId());
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
104
		saml20DetailsService.insert(saml20Details);
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
105
		if (appsService.insertApp(saml20Details)) {
M
Apps  
MaxKey 已提交
106
			return new Message<AppsSAML20Details>(Message.SUCCESS).buildResponse();
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
107
		} else {
M
Apps  
MaxKey 已提交
108
			return new Message<AppsSAML20Details>(Message.FAIL).buildResponse();
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
109 110 111
		}
	}
	
M
Apps  
MaxKey 已提交
112 113 114 115 116 117
	@ResponseBody
	@RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE})
	public ResponseEntity<?> update(
			@RequestBody AppsSAML20Details saml20Details,
			@CurrentUser UserInfo currentUser) {
		_logger.debug("-update  :" + saml20Details);
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
118 119 120 121 122
		try {
			transform(saml20Details);
		} catch (Exception e) {
			e.printStackTrace();
		}
M
Apps  
MaxKey 已提交
123
		saml20Details.setInstId(currentUser.getInstId());
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
124
		saml20DetailsService.update(saml20Details);
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
125
		if (appsService.updateApp(saml20Details)) {
M
Apps  
MaxKey 已提交
126
		    return new Message<AppsSAML20Details>(Message.SUCCESS).buildResponse();
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
127
		} else {
M
Apps  
MaxKey 已提交
128
			return new Message<AppsSAML20Details>(Message.FAIL).buildResponse();
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
129 130 131 132
		}
	}
	
	@ResponseBody
M
Apps  
MaxKey 已提交
133 134 135 136 137 138 139
	@RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE})
	public ResponseEntity<?> delete(
			@RequestParam("ids") String ids,
			@CurrentUser UserInfo currentUser) {
		_logger.debug("-delete  ids : {} " , ids);
		if (saml20DetailsService.deleteBatch(ids)&&appsService.deleteBatch(ids)) {
			 return new Message<AppsSAML20Details>(Message.SUCCESS).buildResponse();
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
140
		} else {
M
Apps  
MaxKey 已提交
141
			return new Message<AppsSAML20Details>(Message.FAIL).buildResponse();
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
142 143 144
		}
	}
	
M
Apps  
MaxKey 已提交
145 146 147 148
	//////////////////////////////

	

MaxKey单点登录官方's avatar
m-11/6  
MaxKey单点登录官方 已提交
149
	protected AppsSAML20Details transform(AppsSAML20Details samlDetails) throws Exception{
MaxKey单点登录官方's avatar
a  
MaxKey单点登录官方 已提交
150 151 152
		
		super.transform(samlDetails);
		
153 154 155 156 157 158
		if(null==samlDetails.getFileType()||samlDetails.getFileType().equals("certificate")){//certificate file
			try {
			    if (null!=samlDetails.getMetaFile()&&!samlDetails.getMetaFile().isEmpty()) {
					InputStream isCert = samlDetails.getMetaFile().getInputStream();
					X509Certificate trustCert = X509CertUtils.loadCertFromInputStream(isCert);
					samlDetails.setTrustCert(trustCert);
MaxKey单点登录官方's avatar
a  
MaxKey单点登录官方 已提交
159
					isCert.close();
160 161 162 163
			    }
			} catch (IOException e) {
				_logger.error("read certificate file error .", e);
				throw new Exception("read certificate file error", e);
MaxKey单点登录官方's avatar
a  
MaxKey单点登录官方 已提交
164
			}
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
		}else if(samlDetails.getFileType().equals("metadata_file")){//metadata file
		    if (null!=samlDetails.getMetaFile()&&!samlDetails.getMetaFile().isEmpty()) {
		        samlDetails = resolveMetaData(samlDetails,samlDetails.getMetaFile().getInputStream());
		    }
		}else if(samlDetails.getFileType().equals("metadata_url")){//metadata url
		    CloseableHttpClient httpClient = HttpClients.createDefault();
		    HttpPost post = new HttpPost(samlDetails.getMetaUrl());
            CloseableHttpResponse response = httpClient.execute(post);
            samlDetails = resolveMetaData(samlDetails,response.getEntity().getContent());;
            response.close();
            httpClient.close();
		}
		
		if(samlDetails.getTrustCert()!=null) {
    		samlDetails.setCertSubject(samlDetails.getTrustCert().getSubjectDN().getName());
    		samlDetails.setCertExpiration(samlDetails.getTrustCert().getNotAfter().toString());
    
MaxKey单点登录官方's avatar
v3.0.0  
MaxKey单点登录官方 已提交
182
    		samlDetails.setCertIssuer(X509CertUtils.getCommonName(samlDetails.getTrustCert().getIssuerX500Principal()));
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    		
    		KeyStore keyStore = KeyStoreUtil.clone(idpKeyStoreLoader.getKeyStore(),idpKeyStoreLoader.getKeystorePassword());
    
    		KeyStore trustKeyStore = null;
    		if (!samlDetails.getEntityId().equals("")) {
    			trustKeyStore = KeyStoreUtil.importTrustCertificate(keyStore,samlDetails.getTrustCert(), samlDetails.getEntityId());
    		} else {
    			trustKeyStore = KeyStoreUtil.importTrustCertificate(keyStore,samlDetails.getTrustCert());
    		}
    
    		byte[] keyStoreByte = KeyStoreUtil.keyStore2Bytes(trustKeyStore,idpKeyStoreLoader.getKeystorePassword());
    
    		// store KeyStore content
    		samlDetails.setKeyStore(keyStoreByte);
		}
MaxKey单点登录官方's avatar
a  
MaxKey单点登录官方 已提交
198 199 200
		
		return samlDetails;
	}
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
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
	public AppsSAML20Details resolveMetaData(AppsSAML20Details samlDetails,InputStream inputStream) throws Exception {
	    X509Certificate trustCert = null;
	    EntityDescriptor entityDescriptor;
        try {
            entityDescriptor = MetadataDescriptorUtil.getInstance().getEntityDescriptor(inputStream);
        } catch (IOException e) {
            _logger.error("metadata  file resolve error .", e);
            throw new Exception("metadata  file resolve error", e);
        }
        SPSSODescriptor sPSSODescriptor = entityDescriptor.getSPSSODescriptor(SAMLConstants.SAML20P_NS);
        String b64Encoder = sPSSODescriptor.getKeyDescriptors().get(0).getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0).getValue();

        trustCert = X509CertUtils.loadCertFromB64Encoded(b64Encoder);
        
        samlDetails.setTrustCert(trustCert);
        samlDetails.setSpAcsUrl(sPSSODescriptor.getAssertionConsumerServices().get(0).getLocation());
        samlDetails.setEntityId(entityDescriptor.getEntityID());
        
        if(samlDetails.getIssuer()==null || samlDetails.getIssuer().equals("")) {
            samlDetails.setIssuer(entityDescriptor.getEntityID());
        }
        
        if(samlDetails.getAudience()==null || samlDetails.getAudience().equals("")) {
            samlDetails.setAudience(entityDescriptor.getEntityID());
        }

        _logger.info("SPSSODescriptor EntityID "+ entityDescriptor.getEntityID());
        return samlDetails;
	}
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
231 232
	
}