Simple use of java single sign-on system CAS

Original address http://www.cnblogs.com/ruiati/p/6265194.html

Background
There are several relatively independent java web application systems, each with its own login verification function. When users use different systems, they need to Log in to a different system. Now it is necessary to provide a unified login/logout interface without modifying the original login verification mechanism of each system. So the single sign-on system CAS is used.

Usage steps
To use single sign-on, you need to deploy the CAS system. The CAS server can be directly deployed and run under tomcat. For the CAS server, all web applications to be integrated with single sign-on are its clients. CAS has Client jar package, the client web application needs to introduce the jar package of the CAS client, so that the server side of the CAS system and the client web application side can communicate.

The client web application can communicate with the CAS server by configuring web.xml and adding various filters required by CAS. User information verification is completed on the CAS server. After the verification is passed, the client web application only needs to Complete your own session information.

Each client web application needs to use a common user table.

The first step is to deploy the CAS system server
1. Download CAS Server from the official website http://developer.jasig.org/cas/, decompress cas-server-webapp-3.4.12.war, you can see that it is a standard java The web application can be directly deployed to the webapps directory of tomcat. I assume here that the deployment path is {tomcat_home}/webapps/cas.
2. CAS requires tomcat to configure the SSL protocol by default, and uses the https protocol to communicate. Since the project is an internal system of enterprises and institutions, such a high level of security is not required, and operations can be simplified without using the SSL protocol. Modify the configuration file \WEB-INF\spring-configuration\ticketGrantingTicketCookieGenerator.xml, as follows, change the default true to false.
 
<bean id="ticketGrantingTicketCookieGenerator" class="org.jasig.cas.web.support.CookieRetrievingCookieGenerator"  
        p:cookieSecure="false"  
        p:cookieMaxAge="-1"  
        p:cookieName="CASTGC"  
        p:cookiePath="/cas" />  

3. Configure the authentication logic for login, and modify the configuration file cas\WEB-INF\deployerConfigContext.xml. Configure the authentication method in the authenticationHandlers. I configure the database query statement here to realize the authentication of the username and password.
 
<property name="authenticationHandlers">  
            <list>  
                <!--  
                    | This is the authentication handler that authenticates services by means of callback via SSL, thereby validating  
                    | a server side SSL certificate.  
                    +-->  
                <bean class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"  
                    p:httpClient-ref="httpClient" />  
                <!--  
                    | This is the authentication handler declaration that every CAS deployer will need to change before deploying CAS   
                    | into production.  The default SimpleTestUsernamePasswordAuthenticationHandler authenticates UsernamePasswordCredentials  
                    | where the username equals the password.  You will need to replace this with an AuthenticationHandler that implements your  
                    | local authentication strategy.  You might accomplish this by coding a new such handler and declaring  
                    | edu.someschool.its.cas.MySpecialHandler here, or you might use one of the handlers provided in the adaptors modules.  
                    +-->  
                 <bean class="org.jasig.cas.adaptors.jdbc.SearchModeSearchDatabaseAuthenticationHandler">
                <property name="dataSource" ref="ds"/>

                <property name="tableUsers" value="user"/>
                <property name="fieldUser" value="username"/>
                <property name="fieldPassword" value="password"/>
                </bean>
                <!-- <bean  
                    class="org.jasig.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler" /> -->  
                <bean class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler">  
                    <property name="sql" value="select password from userTable where userName=?" />  
                    <property name="passwordEncoder" ref="passwordEncoder"/>  
                    <property name="dataSource" ref="dataSource" />  
                </bean>  -->
         

 

  

            </list>  
        </property>

Password encryption method I use MD5 here, configure the bean of passwordEncoder
 
<bean id="passwordEncoder" class="org.jasig.cas.authentication.handler.DefaultPasswordEncoder" autowire="byName">  
        <constructor-arg value="MD5"/>  
    </bean>  
Configure a data source named dataSource
[html] view plain copy
 
<bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource">  
        <property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"></property>  
        <property name="driverUrl" value="jdbc:sqlserver://localhost:1433;databaseName=testDB;"></property>  
        <property name="user" value="sa"></property>  
        <property name="password" value="123456"></property>  
        <property name="maximumConnectionCount" value="100"></property>  
        <property name="minimumConnectionCount" value="1"></property>  
    </bean>  

The configuration of the data source is configured according to its actual situation. If the required jar is not under the lib, copy it in by yourself, otherwise the data source will not be connected and an error will be reported.
4. Now the server is configured. If you need to customize the login/logout page (the actual project basically needs to be modified), modify the casLoginView.jsp and casLoginView.jsp under cas\WEB-INF\view\jsp\default\ui\ casLogoutView.jsp is fine. The


second step is to integrate CAS with the client web application.
1. Download the CAS Client from the official website http://developer.jasig.org/cas-clients/ 3.2.1.jar is introduced into the classpath of the web application
2. Configure the web.xml file, mainly to add filters to intercept communication, the following example code, assuming that the port of the web application is 8080
 
<!-- CAS single sign-on (SSO) filter configuration (start) -->  
      
    <!-- This filter is used to implement single sign-out functionality. -->  
    <filter>  
        <filter-name>CAS Single Sign Out Filter</filter-name>  
        <filter-class>org.jasig.cas.client.session.SingleSignOutFilter</filter-class>  
    </filter>  
    <filter-mapping>  
        <filter-name>CAS Single Sign Out Filter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
    <!-- CAS: for single exit -->  
    <listener>  
        <listener-class>org.jasig.cas.client.session.SingleSignOutHttpSessionListener</listener-class>  
    </listener>  
      
    <!-- This filter is responsible for user authentication and must be enabled -->  
    <filter>  
        <filter-name>CASFilter</filter-name>  
        <filter-class>org.jasig.cas.client.authentication.AuthenticationFilter</filter-class>  
        <init-param>  
            <param-name>casServerLoginUrl</param-name>  
            <!-- The following URL is the login address of the Cas server-->  
            <param-value>http://The IP of the server where the CAS server is located:8080/cas/login</param-value>  
        </init-param>  
        <init-param>  
            <param-name>serverName</param-name>  
            <!-- The following URL is the access address of a specific application-->  
            <param-value>http://server IP of the specific web application:8080</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>CASFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
       
    <!-- This filter is responsible for the validation of Tickets, it must be enabled-->  
    <filter>  
        <filter-name>CAS Validation Filter</filter-name>  
        <filter-class>org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter</filter-class>  
        <init-param>  
            <param-name>casServerUrlPrefix</param-name>  
            <!-- The following URL is the authentication address of the Cas server-->  
            <param-value>http://the IP of the server where the CAS server is located:8080/cas</param-value>  
        </init-param>  
        <init-param>  
            <param-name>serverName</param-name>  
            <!-- The following URL is the access address of a specific application-->  
            <param-value>http://server IP of the specific web application:8080</param-value>  
        </init-param>  
        <init-param>  
          <param-name>renew</param-name>  
          <param-value>false</param-value>  
        </init-param>  
        <init-param>  
          <param-name>gateway</param-name>  
          <param-value>false</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>CAS Validation Filter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
       
    <!--  
    This filter is responsible for implementing the package of the HttpServletRequest request,  
    For example, allowing developers to obtain the login name of the SSO login user through the getRemoteUser() method of HttpServletRequest, optional configuration.  
    -->  
    <filter>  
        <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name>  
        <filter-class>org.jasig.cas.client.util.HttpServletRequestWrapperFilter</filter-class>  
    </filter>  
    <filter-mapping>  
        <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
       
    <!--  
    This filter allows developers to obtain the user's login name through org.jasig.cas.client.util.AssertionHolder.  
    比如AssertionHolder.getAssertion().getPrincipal().getName()。  
    -->  
    <filter>  
        <filter-name>CAS Assertion Thread Local Filter</filter-name>  
        <filter-class>org.jasig.cas.client.util.AssertionThreadLocalFilter</filter-class>  
    </filter>  
    <filter-mapping>  
        <filter-name>CAS Assertion Thread Local Filter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
       
    <!-- Automatically set the user information of the system according to the result of single sign-on (implemented by a specific application) -->  
    <filter>  
        <filter-name>CasForInvokeContextFilter</filter-name>  
        <filter-class>com.cm.demo.filter.CasForInvokeContextFilter</filter-class>  
        <init-param>  
          <param-name>appId</param-name>  
          <param-value>a5ea611bbff7474a81753697a1714fb0</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>CasForInvokeContextFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>

  <!-- CAS single sign-on (SSO) filter configuration (end) -->
  
4. Note that in the configuration file in the previous step, the implementation of the filter CasForInvokeContextFilter needs to be implemented in a specific application. Its purpose is that after the CAS server login verification is successful, the user name of the logged in user will be brought back. At this time, the customer The client web application needs to query the user's Id and other information from the database user table according to the user name, and fill it into the Session, so that the original authentication logic of the client application will not be a problem, because we generally pass Verify whether the session contains the ID of the currently logged in user for login verification.
Below is a simple implementation of CasForInvokeContextFilter.
/**
 * The filter user obtains the login user username from the CAS authentication server and fills in the necessary Session.
 * @author jiarong_cheng
 * @created 2012-7-12
 */  
public class CasForInvokeContextFilter implements Filter {  
  
    @Override  
    public void destroy() {  
    }  
  
    @Override  
    public void doFilter(ServletRequest request, ServletResponse response,  
            FilterChain chain) throws IOException, ServletException {  
        HttpSession session = ((HttpServletRequest) request).getSession();  
        //If there is no user information in the session, fill in the user information  
        if (session.getAttribute("j_userId") == null) {  
            //Get the username of the login account from the Cas server  
            Assertion assertion = AssertionHolder.getAssertion();  
            String userName = assertion.getPrincipal().getName();  
  
            try {  
                //According to the user name of the single sign-on account, find the user information from the database user table and fill it into the session  
                User user = UserDao.getUserByName(userName);  
                session.setAttribute("username", userName);  
                session.setAttribute("userId", user.getId());  
            } catch (Exception e) {  
                e.printStackTrace ();  
            }  
        }  
        chain.doFilter(request, response);  
    }  
  
    @Override  
    public void init(FilterConfig config) throws ServletException {  
    }  
}  


At this point, it is completed. When you visit the website of the specific application, such as http://specific application IP: 8080/, you will jump to the login page of the CAS server: http://CAS server IP: 8080/ to log in After the verification is passed, it will jump back to the URL of the application.

The third step single-point logout
This is relatively simple, as long as in the logout event of the system, point the URL access address to the servlet that the CAS service logs out.
http://CAS server IP:8080/cas/logout

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326375324&siteId=291194637