Advertisement
ijhar

samlconfiguration

Apr 13th, 2020
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 18.55 KB | None | 0 0
  1. package com.quarks.config;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collection;
  5. import java.util.HashMap;
  6. import java.util.List;
  7. import java.util.Map;
  8. import java.util.Timer;
  9.  
  10. import com.quarks.security.SAMLUserDetailsServiceImpl;
  11. import org.apache.commons.httpclient.HttpClient;
  12. import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
  13. import org.apache.velocity.app.VelocityEngine;
  14. import org.opensaml.saml2.metadata.provider.HTTPMetadataProvider;
  15. import org.opensaml.saml2.metadata.provider.MetadataProvider;
  16. import org.opensaml.saml2.metadata.provider.MetadataProviderException;
  17. import org.opensaml.xml.parse.ParserPool;
  18. import org.opensaml.xml.parse.StaticBasicParserPool;
  19. import org.springframework.beans.factory.annotation.Autowired;
  20. import org.springframework.beans.factory.annotation.Qualifier;
  21. import org.springframework.beans.factory.DisposableBean;
  22. import org.springframework.beans.factory.InitializingBean;
  23. import org.springframework.beans.factory.annotation.Value;
  24. import org.springframework.context.annotation.Bean;
  25. import org.springframework.context.annotation.Configuration;
  26. import org.springframework.core.io.DefaultResourceLoader;
  27. import org.springframework.core.io.Resource;
  28. import org.springframework.security.authentication.AuthenticationManager;
  29. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  30. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  31. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  32. import org.springframework.security.saml.SAMLAuthenticationProvider;
  33. import org.springframework.security.saml.SAMLBootstrap;
  34. import org.springframework.security.saml.SAMLDiscovery;
  35. import org.springframework.security.saml.SAMLEntryPoint;
  36. import org.springframework.security.saml.SAMLProcessingFilter;
  37. import org.springframework.security.saml.SAMLWebSSOHoKProcessingFilter;
  38. import org.springframework.security.saml.context.SAMLContextProviderImpl;
  39. import org.springframework.security.saml.key.JKSKeyManager;
  40. import org.springframework.security.saml.key.KeyManager;
  41. import org.springframework.security.saml.log.SAMLDefaultLogger;
  42. import org.springframework.security.saml.metadata.CachingMetadataManager;
  43. import org.springframework.security.saml.metadata.ExtendedMetadata;
  44. import org.springframework.security.saml.metadata.ExtendedMetadataDelegate;
  45. import org.springframework.security.saml.metadata.MetadataDisplayFilter;
  46. import org.springframework.security.saml.metadata.MetadataGenerator;
  47. import org.springframework.security.saml.metadata.MetadataGeneratorFilter;
  48. import org.springframework.security.saml.parser.ParserPoolHolder;
  49. import org.springframework.security.saml.processor.HTTPArtifactBinding;
  50. import org.springframework.security.saml.processor.HTTPPAOS11Binding;
  51. import org.springframework.security.saml.processor.HTTPPostBinding;
  52. import org.springframework.security.saml.processor.HTTPRedirectDeflateBinding;
  53. import org.springframework.security.saml.processor.HTTPSOAP11Binding;
  54. import org.springframework.security.saml.processor.SAMLBinding;
  55. import org.springframework.security.saml.processor.SAMLProcessorImpl;
  56. import org.springframework.security.saml.util.VelocityFactory;
  57. import org.springframework.security.saml.websso.ArtifactResolutionProfile;
  58. import org.springframework.security.saml.websso.ArtifactResolutionProfileImpl;
  59. import org.springframework.security.saml.websso.SingleLogoutProfile;
  60. import org.springframework.security.saml.websso.SingleLogoutProfileImpl;
  61. import org.springframework.security.saml.websso.WebSSOProfile;
  62. import org.springframework.security.saml.websso.WebSSOProfileConsumer;
  63. import org.springframework.security.saml.websso.WebSSOProfileConsumerHoKImpl;
  64. import org.springframework.security.saml.websso.WebSSOProfileConsumerImpl;
  65. import org.springframework.security.saml.websso.WebSSOProfileECPImpl;
  66. import org.springframework.security.saml.websso.WebSSOProfileImpl;
  67. import org.springframework.security.saml.websso.WebSSOProfileOptions;
  68. import org.springframework.security.web.DefaultSecurityFilterChain;
  69. import org.springframework.security.web.FilterChainProxy;
  70. import org.springframework.security.web.SecurityFilterChain;
  71. import org.springframework.security.web.access.channel.ChannelProcessingFilter;
  72. import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
  73. import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
  74. import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
  75. import org.springframework.security.web.csrf.CsrfFilter;
  76. import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
  77. import org.springframework.core.env.Environment;
  78.  
  79.  
  80. @Configuration
  81. public class SAMLWebSecurityConfig extends WebSecurityConfigurerAdapter implements InitializingBean, DisposableBean {
  82.  
  83. private Timer backgroundTaskTimer;
  84. private MultiThreadedHttpConnectionManager multiThreadedHttpConnectionManager;
  85.  
  86. /*@Value("${metaDataUrl}")
  87. String metadataUrl;
  88.  
  89. @Value("${keyAlias}")
  90. String keyAlias;
  91.  
  92. @Value("${keyStorePass}")
  93. String storePass;
  94.  
  95. @Value("${keyStorePath}")
  96. String keyStoreFilePath;*/
  97.  
  98. @Value("${security.saml2.metadata-url}")
  99. String metadataUrl;
  100.  
  101. @Value("${server.ssl.key-alias}")
  102. String keyAlias;
  103.  
  104. @Value("${server.ssl.key-store-password}")
  105. String storePass;
  106.  
  107. @Value("${server.ssl.key-store}")
  108. String keyStoreFilePath;
  109.  
  110.  
  111. public void init() {
  112. this.backgroundTaskTimer = new Timer(true);
  113. this.multiThreadedHttpConnectionManager = new MultiThreadedHttpConnectionManager();
  114. }
  115.  
  116. public void shutdown() {
  117. this.backgroundTaskTimer.purge();
  118. this.backgroundTaskTimer.cancel();
  119. this.multiThreadedHttpConnectionManager.shutdown();
  120. }
  121.  
  122. @Autowired
  123. private SAMLUserDetailsServiceImpl samlUserDetailsServiceImpl;
  124.  
  125. // Initialization of the velocity engine
  126. @Bean
  127. public VelocityEngine velocityEngine() {
  128. return VelocityFactory.getEngine();
  129. }
  130.  
  131. // XML parser pool needed for OpenSAML parsing
  132. @Bean(initMethod = "initialize")
  133. public StaticBasicParserPool parserPool() {
  134. return new StaticBasicParserPool();
  135. }
  136.  
  137. @Bean(name = "parserPoolHolder")
  138. public ParserPoolHolder parserPoolHolder() {
  139. return new ParserPoolHolder();
  140. }
  141.  
  142. // Bindings, encoders and decoders used for creating and parsing messages
  143. @Bean
  144. public HttpClient httpClient() {
  145. return new HttpClient(this.multiThreadedHttpConnectionManager);
  146. }
  147.  
  148. // SAML Authentication Provider responsible for validating of received SAML
  149. // messages
  150. @Bean
  151. public SAMLAuthenticationProvider samlAuthenticationProvider() {
  152. SAMLAuthenticationProvider samlAuthenticationProvider = new SAMLAuthenticationProvider();
  153. samlAuthenticationProvider.setUserDetails(samlUserDetailsServiceImpl);
  154. samlAuthenticationProvider.setForcePrincipalAsString(false);
  155. return samlAuthenticationProvider;
  156. }
  157.  
  158. // Provider of default SAML Context
  159. @Bean
  160. public SAMLContextProviderImpl contextProvider() {
  161. return new SAMLContextProviderImpl();
  162. }
  163.  
  164. // Initialization of OpenSAML library
  165. @Bean
  166. public static SAMLBootstrap sAMLBootstrap() {
  167. return new SAMLBootstrap();
  168. }
  169.  
  170. // Logger for SAML messages and events
  171. @Bean
  172. public SAMLDefaultLogger samlLogger() {
  173. return new SAMLDefaultLogger();
  174. }
  175.  
  176. // SAML 2.0 WebSSO Assertion Consumer
  177. @Bean
  178. public WebSSOProfileConsumer webSSOprofileConsumer() {
  179. return new WebSSOProfileConsumerImpl();
  180. }
  181.  
  182. // SAML 2.0 Holder-of-Key WebSSO Assertion Consumer
  183. @Bean
  184. public WebSSOProfileConsumerHoKImpl hokWebSSOprofileConsumer() {
  185. return new WebSSOProfileConsumerHoKImpl();
  186. }
  187.  
  188. // SAML 2.0 Web SSO profile
  189. @Bean
  190. public WebSSOProfile webSSOprofile() {
  191. return new WebSSOProfileImpl();
  192. }
  193.  
  194. // SAML 2.0 Holder-of-Key Web SSO profile
  195. @Bean
  196. public WebSSOProfileConsumerHoKImpl hokWebSSOProfile() {
  197. return new WebSSOProfileConsumerHoKImpl();
  198. }
  199.  
  200. // SAML 2.0 ECP profile
  201. @Bean
  202. public WebSSOProfileECPImpl ecpprofile() {
  203. return new WebSSOProfileECPImpl();
  204. }
  205.  
  206. @Bean
  207. public SingleLogoutProfile logoutprofile() {
  208. return new SingleLogoutProfileImpl();
  209. }
  210.  
  211. // Central storage of cryptographic keys
  212. @Bean
  213. public KeyManager keyManager() {
  214. DefaultResourceLoader loader = new DefaultResourceLoader();
  215. Resource storeFile = loader
  216. .getResource(keyStoreFilePath);
  217. Map<String, String> passwords = new HashMap<String, String>();
  218. passwords.put(keyAlias, storePass);
  219. return new JKSKeyManager(storeFile, storePass, passwords, keyAlias);
  220. }
  221.  
  222. @Bean
  223. public WebSSOProfileOptions defaultWebSSOProfileOptions() {
  224. WebSSOProfileOptions webSSOProfileOptions = new WebSSOProfileOptions();
  225. webSSOProfileOptions.setIncludeScoping(false);
  226. return webSSOProfileOptions;
  227. }
  228.  
  229. // Entry point to initialize authentication, default values taken from
  230. // properties file
  231. @Bean
  232. public SAMLEntryPoint samlEntryPoint() {
  233. SAMLEntryPoint samlEntryPoint = new SAMLEntryPoint();
  234. samlEntryPoint.setDefaultProfileOptions(defaultWebSSOProfileOptions());
  235. return samlEntryPoint;
  236. }
  237.  
  238. // Setup advanced info about metadata
  239. @Bean
  240. public ExtendedMetadata extendedMetadata() {
  241. ExtendedMetadata extendedMetadata = new ExtendedMetadata();
  242. extendedMetadata.setIdpDiscoveryEnabled(true);
  243. extendedMetadata.setSigningAlgorithm("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
  244. extendedMetadata.setDigestMethodAlgorithm("http://www.w3.org/2001/04/xmlenc#sha256");
  245. extendedMetadata.setSignMetadata(true);
  246. extendedMetadata.setEcpEnabled(true);
  247. return extendedMetadata;
  248. }
  249.  
  250. // IDP Discovery Service
  251. @Bean
  252. public SAMLDiscovery samlIDPDiscovery() {
  253. SAMLDiscovery idpDiscovery = new SAMLDiscovery();
  254. idpDiscovery.setIdpSelectionPath("/ats/ssoLogin");
  255. return idpDiscovery;
  256. }
  257.  
  258. @Bean
  259. @Qualifier("idp-ssocircle")
  260. public ExtendedMetadataDelegate ssoCircleExtendedMetadataProvider()
  261. throws MetadataProviderException {
  262. HTTPMetadataProvider httpMetadataProvider = new HTTPMetadataProvider(
  263. this.backgroundTaskTimer, httpClient(), metadataUrl);
  264. httpMetadataProvider.setParserPool(parserPool());
  265. ExtendedMetadataDelegate extendedMetadataDelegate =
  266. new ExtendedMetadataDelegate(httpMetadataProvider, extendedMetadata());
  267. extendedMetadataDelegate.setMetadataTrustCheck(true);
  268. extendedMetadataDelegate.setMetadataRequireSignature(false);
  269. backgroundTaskTimer.purge();
  270. return extendedMetadataDelegate;
  271. }
  272.  
  273. // IDP Metadata configuration - paths to metadata of IDPs in circle of trust
  274. // is here
  275. // Do no forget to call iniitalize method on providers
  276. @Bean
  277. @Qualifier("metadata")
  278. public CachingMetadataManager metadata() throws MetadataProviderException {
  279. List<MetadataProvider> providers = new ArrayList<MetadataProvider>();
  280. providers.add(ssoCircleExtendedMetadataProvider());
  281. return new CachingMetadataManager(providers);
  282. }
  283.  
  284. // Filter automatically generates default SP metadata
  285. @Bean
  286. public MetadataGenerator metadataGenerator() {
  287. MetadataGenerator metadataGenerator = new MetadataGenerator();
  288. metadataGenerator.setEntityId("com:quarks:bccl:talman");
  289. metadataGenerator.setExtendedMetadata(extendedMetadata());
  290. metadataGenerator.setIncludeDiscoveryExtension(false);
  291. metadataGenerator.setKeyManager(keyManager());
  292. return metadataGenerator;
  293. }
  294.  
  295. // The filter is waiting for connections on URL suffixed with filterSuffix
  296. // and presents SP metadata there
  297. @Bean
  298. public MetadataDisplayFilter metadataDisplayFilter() {
  299. return new MetadataDisplayFilter();
  300. }
  301.  
  302. // Handler deciding where to redirect user after successful login
  303. @Bean
  304. public SavedRequestAwareAuthenticationSuccessHandler successRedirectHandler() {
  305. SavedRequestAwareAuthenticationSuccessHandler successRedirectHandler =
  306. new SavedRequestAwareAuthenticationSuccessHandler();
  307. successRedirectHandler.setDefaultTargetUrl("/ats/ssoLogin");
  308. return successRedirectHandler;
  309. }
  310. // Handler deciding where to redirect user after failed login
  311. @Bean
  312. public SimpleUrlAuthenticationFailureHandler authenticationFailureHandler() {
  313. SimpleUrlAuthenticationFailureHandler failureHandler =
  314. new SimpleUrlAuthenticationFailureHandler();
  315. failureHandler.setUseForward(true);
  316. failureHandler.setDefaultFailureUrl("/error");
  317. return failureHandler;
  318. }
  319.  
  320. @Bean
  321. public SAMLWebSSOHoKProcessingFilter samlWebSSOHoKProcessingFilter() throws Exception {
  322. SAMLWebSSOHoKProcessingFilter samlWebSSOHoKProcessingFilter = new SAMLWebSSOHoKProcessingFilter();
  323. samlWebSSOHoKProcessingFilter.setAuthenticationSuccessHandler(successRedirectHandler());
  324. samlWebSSOHoKProcessingFilter.setAuthenticationManager(authenticationManager());
  325. samlWebSSOHoKProcessingFilter.setAuthenticationFailureHandler(authenticationFailureHandler());
  326. return samlWebSSOHoKProcessingFilter;
  327. }
  328.  
  329. // Processing filter for WebSSO profile messages
  330. @Bean
  331. public SAMLProcessingFilter samlWebSSOProcessingFilter() throws Exception {
  332. SAMLProcessingFilter samlWebSSOProcessingFilter = new SAMLProcessingFilter();
  333. samlWebSSOProcessingFilter.setAuthenticationManager(authenticationManager());
  334. samlWebSSOProcessingFilter.setAuthenticationSuccessHandler(successRedirectHandler());
  335. samlWebSSOProcessingFilter.setAuthenticationFailureHandler(authenticationFailureHandler());
  336. return samlWebSSOProcessingFilter;
  337. }
  338.  
  339. @Bean
  340. public MetadataGeneratorFilter metadataGeneratorFilter() {
  341. return new MetadataGeneratorFilter(metadataGenerator());
  342. }
  343.  
  344. // Bindings
  345. private ArtifactResolutionProfile artifactResolutionProfile() {
  346. final ArtifactResolutionProfileImpl artifactResolutionProfile =
  347. new ArtifactResolutionProfileImpl(httpClient());
  348. artifactResolutionProfile.setProcessor(new SAMLProcessorImpl(soapBinding()));
  349. return artifactResolutionProfile;
  350. }
  351.  
  352. @Bean
  353. public HTTPArtifactBinding artifactBinding(ParserPool parserPool, VelocityEngine velocityEngine) {
  354. return new HTTPArtifactBinding(parserPool, velocityEngine, artifactResolutionProfile());
  355. }
  356.  
  357. @Bean
  358. public HTTPSOAP11Binding soapBinding() {
  359. return new HTTPSOAP11Binding(parserPool());
  360. }
  361.  
  362. @Bean
  363. public HTTPPostBinding httpPostBinding() {
  364. return new HTTPPostBinding(parserPool(), velocityEngine());
  365. }
  366.  
  367. @Bean
  368. public HTTPRedirectDeflateBinding httpRedirectDeflateBinding() {
  369. return new HTTPRedirectDeflateBinding(parserPool());
  370. }
  371.  
  372. @Bean
  373. public HTTPSOAP11Binding httpSOAP11Binding() {
  374. return new HTTPSOAP11Binding(parserPool());
  375. }
  376.  
  377. @Bean
  378. public HTTPPAOS11Binding httpPAOS11Binding() {
  379. return new HTTPPAOS11Binding(parserPool());
  380. }
  381.  
  382. // Processor
  383. @Bean
  384. public SAMLProcessorImpl processor() {
  385. Collection<SAMLBinding> bindings = new ArrayList<SAMLBinding>();
  386. bindings.add(httpRedirectDeflateBinding());
  387. bindings.add(httpPostBinding());
  388. bindings.add(artifactBinding(parserPool(), velocityEngine()));
  389. bindings.add(httpSOAP11Binding());
  390. bindings.add(httpPAOS11Binding());
  391. return new SAMLProcessorImpl(bindings);
  392. }
  393.  
  394. /**
  395. * Define the security filter chain in order to support SSO Auth by using SAML 2.0
  396. * @return Filter chain proxy
  397. * @throws Exception
  398. */
  399. @Bean
  400. public FilterChainProxy samlFilter() throws Exception {
  401. List<SecurityFilterChain> chains = new ArrayList<SecurityFilterChain>();
  402. chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/ats/ssoLogin/**"),
  403. samlEntryPoint()));
  404. chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/metadata/**"),
  405. metadataDisplayFilter()));
  406. chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSO/**"),
  407. samlWebSSOProcessingFilter()));
  408. chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSOHoK/**"),
  409. samlWebSSOHoKProcessingFilter()));
  410. chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/discovery/**"),
  411. samlIDPDiscovery()));
  412. return new FilterChainProxy(chains);
  413. }
  414.  
  415. /**
  416. * Returns the authentication manager currently used by Spring.
  417. * It represents a bean definition with the aim allow wiring from
  418. * other classes performing the Inversion of Control (IoC).
  419. * @throws Exception
  420. */
  421. @Bean
  422. @Override
  423. public AuthenticationManager authenticationManagerBean() throws Exception {
  424. return super.authenticationManagerBean();
  425. }
  426.  
  427. /**
  428. * Defines the web based security configuration.
  429. * @param http It allows configuring web based security for specific http requests.
  430. * @throws Exception
  431. */
  432. @Override
  433. protected void configure(HttpSecurity http) throws Exception {
  434. http
  435. .httpBasic()
  436. .authenticationEntryPoint(samlEntryPoint());
  437. http
  438. .addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class)
  439. .addFilterAfter(samlFilter(), BasicAuthenticationFilter.class);
  440. }
  441.  
  442. /**
  443. * Sets a custom authentication provider.
  444. * @param auth SecurityBuilder used to create an AuthenticationManager.
  445. * @throws Exception
  446. */
  447. @Override
  448. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  449. auth
  450. .authenticationProvider(samlAuthenticationProvider());
  451. }
  452.  
  453. @Override
  454. public void afterPropertiesSet() throws Exception {
  455. init();
  456. }
  457.  
  458. @Override
  459. public void destroy() throws Exception {
  460. shutdown();
  461. }
  462.  
  463. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement