Springboot+springsecurity+springsessiondataredis+cas set up the cluster single-point landing system

Source: Internet
Author: User
Tags auth cas md5 redis ticket tomcat
Springboot+springsecurity+springsessiondataredis+cas set up the cluster single-point landing system Environment Description
Windows 7 64bit
Spring boot:1.4.0.release
spring security:4.1.0.release
cas:4.1.3
nginx: whatever
Building CAS Services 1.Tomcat Configuring SSL 1. Generate a certificate

To enter the directory%tomcat_home% as a command, enter the following command:

Keytool-genkey-alias tomcat_key-keyalg rsa-storepass changeit-keystore server.keystore-validity 3600 

Note:-storepass and-validity can be changed as needed

User name input domain name, such as: test.cas.com, all other to enter to skip, finally confirm, at this time will be generated under%tomcat_home% Server.keystore file 2. Import the certificate into the certificate Truststore of the JDK used by the client

This step is not required for the SSL configuration of Tomcat, but is required for CAS SSO, otherwise the following error will occur:
Edu.yale.its.tp.cas.client.CASAuthenticationException:Unable to validate Proxyticketvalidate.

The import process is divided into 2 steps, the first step is to export the certificate, the second step is to import to the certificate Truststore, the command is as follows:

Keytool-export-trustcacerts-alias tomcat_key-file server.cer-keystore server.keystore-storepass Changeit 

Keytool-import-trustcacerts-alias tomcat_key-file server.cer-keystore d:/"program Files"/java/jdk1.8.0_60/jre/lib/ Security/cacerts-storepass Changeit

Other useful Keytool commands (list all existing certificates in the trust certificate store and delete a certificate in the library):

Keytool-list-keystore%java_home%/jre/lib/security/cacerts >t.txt 
keytool-delete-trustcacerts-alias Tomcat _key-keystore%java_home%/jre/lib/security/cacerts-storepass Changeit 
3.tomcat SSL Enabled

Configuration server.xml:

<connector
       protocol= "Org.apache.coyote.http11.Http11NioProtocol"
       port= "9443" maxthreads=
       " Scheme= "https" secure= "true" sslenabled= "true"
       keystorefile= "Server.keystore"
       keystorepass= "Changeit" Clientauth= "false" sslprotocol= "TLS"/>
configuration of the 2.CAS service 1. Deploy CAS Web server:Download the corresponding version of CAS server source code from Https://github.com/apereo

Unzip, using the MAVEN command MVN package to compile the CAs, there are 2 issues that may occur:

A. Unit test does not pass = = "Try to add-dmaven.test.skip=true skip;"

B. Compile to half compile but = = "Enter Cas-server-core, execute command mvn install-dmaven.test.skip=true first compile the core into jar package, then proceed."

3. Copy the war package from the packaged Cas-server-webapp to Tomcat, and run Tomcat to try it first;
Note: If you feel trouble, you can search the Internet for Cas-server-webapp, use a war package that others have played

4. Place the war packet in Tomcat's WebApps directory 2. Get user information from a database

1. Modify the Deployerconfigcontext.xml in%tomcathome%\webapps\cas\web-inf:

 <constructor-arg> <map> <!--| IMPORTANT |
               Every handler requires a unique name. | If more than one instance of the same handler class are configured, you must explicitly |
               Set its name to something and than its default name (typically, the simple class name).
            -<!--<entry key-ref= "Proxyauthenticationhandler" value-ref= "Proxyprincipalresolver"/>-->
            <!--<entry key-ref= "Primaryauthenticationhandler" value-ref= "Primaryprincipalresolver"/>--> <entry key-ref= "Dbauthhandler" value-ref= "Primaryprincipalresolver"/> </map> </constructor -arg> <bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" p:driverclass= " Com.mysql.jdbc.Driver "p:jdbcurl=" Jdbc:mysql://127.0.0.1:3306/demo2?characterencoding=utf8 "p:user=" root "p:pa Ssword= "System"/> <bean ID= "Passwordencoder" class= "Org.jasig.cas.authentication.handler.DefaultPasswordEncoder" c:encodingalgorithm= "MD5" p:characterencoding= "UTF-8"/> <bean id= "Dbauthhandler" class= "Org.jasig.cas.adaptors.jdbc.QueryDatabaseAuth  
  Enticationhandler "p:datasource-ref=" DataSource "p:sql=" select Password_hash from jhi_user where login =? "
 p:passwordencoder-ref= "Passwordencoder"/>

Note: Using MySQL database in configuration, C3P0 connection pool, need to introduce related jar package

Put the C3p0-0.9.1.1.jar,cas-server-support-jdbc-4.1.3.jar,mysql-connector-java-5.1.32.jar into%tomcathome%\webapps\cas\ In Web-inf\lib

2. Modify%tomcathome%\webapps\cas\web-inf\classes\services\apereo-10000002.json

"ServiceId": "^http.*",
3. Set the ST (service ticket) expiration policy

Modify%tomcathome%\webapps\cas\web-inf\spring-configuration\ticketexpirationpolicies.xml

<bean id= "Serviceticketexpirationpolicy"
class= " Org.jasig.cas.ticket.support.MultiTimeUseOrTimeoutExpirationPolicy "
c:numberofuses=" "C:timetokill=" ${ st.timetokillinseconds:1000} "c:timeunit-ref=" SECONDS "/>

Note: Modify as needed

At this point, the required configuration is complete, the browser: Http://test.cas.com/cas, the login test.
Note: test.cas.com is the domain name of the machine where the CAS service is located (such as no domain name configuration, can modify the native hosts,127.0.0.1 test.cas.com to achieve the test results) Integration springsecurity and CAS 1. Introduction of dependencies in the Springboot project:

    <!--security--
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency >
        <groupId>org.springframework.security</groupId>
        <artifactId> spring-security-data</artifactid>
    </dependency>
    <dependency>
        <groupId> Org.springframework.security</groupid>
        <artifactId>spring-security-cas</artifactId>
    </dependency>
2. Configuration Classes
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity (prepostenabled = true, securedenabled = true) public Class Securityconfiguration extends Websecurityconfigureradapter {@Inject public void Configureglobal (Authenticat
    Ionmanagerbuilder auth) throws Exception {Auth.authenticationprovider (Casauthenticationprovider ()); } @Override public void Configure (Websecurity Web) throws Exception {web.ignoring (). ANTMATC Hers (httpmethod.options, "/**"). Antmatchers ("/app/**/*.{ js,html} "). Antmatchers ("/bower_components/** "). Antmatchers ("/i18n/** "). Antmatchers (
    "/content/**"). Antmatchers ("/test/**");
    } @Bean Public Passwordencoder Passwordencoder () {return new Standardpasswordencoder ("tnappsk1234");
        } @Bean Public Serviceproperties serviceproperties () {serviceproperties sp = new serviceproperties (); Get s from CAS serverT after the redirected Url,casauthenticationfilter is captured, the default ends with/login/cas String fstr = "Http://test.tn.com/login/cas";
        Sp.setservice (FSTR);
        Sp.setsendrenew (FALSE);
    return SP; } @Bean Public Casauthenticationentrypoint casauthenticationentrypoint () {Casauthenticationentrypoint EP
        = new Casauthenticationentrypoint ();
        Ep.setserviceproperties (Serviceproperties ());
        CAS Server login Path Ep.setloginurl ("Https://test.cas.com:9443/cas/login");
    return EP;  } @Bean Public Casauthenticationprovider Casauthenticationprovider () {Casauthenticationprovider Pro = new
        Casauthenticationprovider ();
        Pro.setserviceproperties (Serviceproperties ());
        Pro.setauthenticationuserdetailsservice (Customuserdetailsservice ());
        Pro.setticketvalidator (Cas20serviceticketvalidator ());
        Pro.setkey ("an_id_for_this_auth_provider_only");
    return pro; } @Bean public Cas20serviceticketvalidator CAs20ServiceTicketValidator () {//cas server path return new Cas20serviceticketvalidator ("Https://test.cas.com:9
    443/cas ");  } @Bean Public authenticationuserdetailsservice<casassertionauthenticationtoken> customuserdetailsservice ()
        {set<string> admins = new hashset<string> ();

        String adminusername = "admin";
        Admins.add ("admin");
        if (adminusername! = null &&!adminusername.isempty ()) {Admins.add (adminusername);
    } return new Customuserdetailsservice (admins); } @Bean Public Casauthenticationfilter Casauthenticationfilter () throws exception{Casauthenticationfilte
        R af = new Casauthenticationfilter ();
        Af.setsessionauthenticationstrategy (Sessionstrategy ());
        Af.setauthenticationmanager (AuthenticationManager ());
    Return AF; } @Bean Public Sessionauthenticationstrategy sessionstrategy () {sessionauthenticationstrategy sessIonstrategy = new Sessionfixationprotectionstrategy ();
    return sessionstrategy; } @Bean Public Singlesignoutfilter singlesignoutfilter () {Singlesignoutfilter singlesignoutfilter = new
        Singlesignoutfilter ();
        Singlesignoutfilter.setignoreinitconfiguration (TRUE);
        Singlesignoutfilter.setcasserverurlprefix ("Https://test.cas.com:9443/cas");
    return singlesignoutfilter; } @Bean Public Logoutfilter requestcasgloballogoutfilter () {Logoutfilter logoutfilter = new Logoutfilter
        ("Https://test.cas.com:9443/cas/logout?service=http://test.tn.com", New Securitycontextlogouthandler ());
        Logoutfilter.setfilterprocessesurl ("/api/logout");
        Logoutfilter.setlogoutrequestmatcher (New Antpathrequestmatcher ("/api/logout", "POST"));
    return logoutfilter; } @Override protected void Configure (Httpsecurity http) throws Exception {http.exceptionhandling (). authe Nticationentrypoint (casauthenticationentrYpoint ()). and (). addfilter (Casauthenticationfilter ()). Addfilterbefore (Singlesignoutfilter (), CasA

        Uthenticationfilter.class). Addfilterbefore (Requestcasgloballogoutfilter (), logoutfilter.class);
            http. CSRF (). Disable (). Headers (). Frameoptions (). disable (). and () . Authorizerequests (). Antmatchers ("/api/register"). Denyall (). Antmatchers ("/api/activate "). Permitall (). Antmatchers ("/api/content-items/category "). Permitall (). Antmatchers ("/api/authenti Cate "). Permitall (). Antmatchers ("/api/account/reset_password/init "). Permitall (). Antmatchers ("/api /account/reset_password/finish "). Permitall (). Antmatchers ("/api/profile-info "). Permitall (). AntMat
            Chers ("/api/**"). Authenticated (). Antmatchers ("/management/**"). Hasauthority (Authoritiesconstants.admin) . Antmatchers ("/v2/api-docs/** "). Permitall (). Antmatchers ("/swagger-resources/configuration/ui "). Permitall (). Antmatcher
    S ("/swagger-ui/index.html"). Hasauthority (Authoritiesconstants.admin); } @Bean Public Securityevaluationcontextextension securityevaluationcontextextension () {return new secur
    Ityevaluationcontextextension ();
 }
}

Note: the password passwordencoder (), needs to be configured to be consistent with CAs, using MD5, which is misconfigured here

Main: Casauthenticationfilter,casauthenticationentrypoint,casauthenticationprovider configuration,
Refer to the Spring security official documentation CAS authentication section for details:

http://docs.spring.io/spring-security/site/docs/4.2.0.RELEASE/reference/htmlsingle/#cas using Redis to do HTTP Session Sharing

Use Redis for the caching of HTTP sessions so that when you redirect from CAs server back to the service URL for a class of apps (with multiple machines forming a cluster), you can specify the same domain name, so that the session is shared. 1. Introduction of Dependency

<!--Redis--
<dependency>
    <groupId>org.springframework.boot</groupId>
    < artifactid>spring-boot-starter-redis</artifactid>
</dependency>

<dependency>
  <groupId>org.springframework.session</groupId>
  <artifactId>spring-session-data-redis< /artifactid>
</dependency>
2. Configuration Classes
@Configuration
@EnableRedisHttpSession Public
class Redissessionconfig {
    /**
     * Modifies how data is stored in Redis, Easy Commissioning
     * @Title: Sessionredistemplate 
     * @Description: TODO
     * @param connectionfactory
     * @return
     * @ return:redistemplate<object,object>
     */
    @Bean public
    redistemplate<object, object> Sessionredistemplate (
            redisconnectionfactory connectionfactory) {
        redistemplate<object, Object> Template = new Redistemplate<object, object> ();
        Template.setkeyserializer (New Genericjackson2jsonredisserializer ());
        Template.sethashkeyserializer (New Genericjackson2jsonredisserializer ());
        Template.setconnectionfactory (connectionfactory);
        return template;
    }
}
load Balancing with Nginx to modify the nginx.conf, load balancer uses a polling strategy:
http{ 
  upstream tn { 
    Server test.tn.com:6900; 
    Server test.tn.com:6901; 
  } 

  server{ 
    Listen; 
    Location/{ 
     proxy_pass http://tn; 
    } 
 }
Modify Hosts
127.0.0.1 test.tn.com  //webapp
127.0.0.1 test.cas.com//cas Server

Start Nginx Boot

Browser, Access Http://test.tn.com/xxx/xxx (Managed method), jump to CAS Server, login to verify identity, redirect back to the previous URL, constantly refreshed, by observing the day, requesting distribution to different WebApp

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.