分享

Spring Security 4.0 CAS实现单点登录

 再生资源保存站 2017-05-02
     1、各framework版本信息
     JDK 8
     Tomcat 7
     SpringMVC-4.2.0.RELEASE
     Spring Security 4.2.0.RELEASE
     CAS-Client 3.3.3
     CAS-Server 4.0.0

2、MAVEN的pom.xml
   
Java代码  收藏代码
  1. <!--Spring -->  
  2.     <dependency>  
  3.         <groupId>org.springframework</groupId>  
  4.         <artifactId>spring-core</artifactId>  
  5.         <version>${spring.version}</version>  
  6.     </dependency>  
  7.     <dependency>  
  8.         <groupId>org.springframework</groupId>  
  9.         <artifactId>spring-beans</artifactId>  
  10.         <version>${spring.version}</version>  
  11.     </dependency>  
  12.     <dependency>  
  13.         <groupId>org.springframework</groupId>  
  14.         <artifactId>spring-context</artifactId>  
  15.         <version>${spring.version}</version>  
  16.     </dependency>  
  17.     <dependency>  
  18.         <groupId>org.springframework</groupId>  
  19.         <artifactId>spring-context-support</artifactId>  
  20.         <version>${spring.version}</version>  
  21.     </dependency>  
  22.     <dependency>  
  23.         <groupId>org.springframework</groupId>  
  24.         <artifactId>spring-aop</artifactId>  
  25.         <version>${spring.version}</version>  
  26.     </dependency>  
  27.     <dependency>  
  28.         <groupId>org.springframework</groupId>  
  29.         <artifactId>spring-aspects</artifactId>  
  30.         <version>${spring.version}</version>  
  31.     </dependency>  
  32.     <dependency>  
  33.         <groupId>org.springframework</groupId>  
  34.         <artifactId>spring-tx</artifactId>  
  35.         <version>${spring.version}</version>  
  36.     </dependency>  
  37.     <dependency>  
  38.         <groupId>org.springframework</groupId>  
  39.         <artifactId>spring-orm</artifactId>  
  40.         <version>${spring.version}</version>  
  41.     </dependency>  
  42.     <dependency>  
  43.         <groupId>org.springframework</groupId>  
  44.         <artifactId>spring-expression</artifactId>  
  45.         <version>${spring.version}</version>  
  46.     </dependency>  
  47.     <dependency>  
  48.         <groupId>org.springframework</groupId>  
  49.         <artifactId>spring-instrument</artifactId>  
  50.         <version>${spring.version}</version>  
  51.     </dependency>  
  52.     <dependency>  
  53.         <groupId>org.springframework</groupId>  
  54.         <artifactId>spring-instrument-tomcat</artifactId>  
  55.         <version>${spring.version}</version>  
  56.     </dependency>  
  57.     <dependency>  
  58.         <groupId>org.springframework</groupId>  
  59.         <artifactId>spring-jdbc</artifactId>  
  60.         <version>${spring.version}</version>  
  61.     </dependency>  
  62.     <dependency>  
  63.         <groupId>org.springframework</groupId>  
  64.         <artifactId>spring-web</artifactId>  
  65.         <version>${spring.version}</version>  
  66.     </dependency>  
  67.     <dependency>  
  68.         <groupId>org.springframework</groupId>  
  69.         <artifactId>spring-webmvc</artifactId>  
  70.         <version>${spring.version}</version>  
  71.     </dependency>  
  72.     <dependency>  
  73.         <groupId>org.springframework</groupId>  
  74.         <artifactId>spring-webmvc-portlet</artifactId>  
  75.         <version>${spring.version}</version>  
  76.     </dependency>  
  77.     <dependency>  
  78.         <groupId>org.springframework.security</groupId>  
  79.         <artifactId>spring-security-web</artifactId>  
  80.         <version>${spring.security.version}</version>  
  81.     </dependency>  
  82.     <dependency>  
  83.         <groupId>org.springframework.security</groupId>  
  84.         <artifactId>spring-security-config</artifactId>  
  85.         <version>${spring.security.version}</version>  
  86.     </dependency>  
  87.     <dependency>  
  88.         <groupId>org.springframework.security</groupId>  
  89.         <artifactId>spring-security-cas</artifactId>  
  90.         <version>${spring.security.version}</version>  
  91.     </dependency>  
  92.     <dependency>  
  93.         <groupId>org.jasig.cas.client</groupId>  
  94.         <artifactId>cas-client-core</artifactId>  
  95.         <version>3.3.3</version>  
  96.         <!-- 排除log4j包冲突 -->  
  97.         <exclusions>  
  98.             <exclusion>  
  99.                 <groupId>org.slf4j</groupId>  
  100.                 <artifactId>log4j-over-slf4j</artifactId>  
  101.             </exclusion>  
  102.         </exclusions>  
  103.     </dependency>  


3、配置CAS-Server
     1)、下载CAS-Server的Zip包[http://developer./cas/]
              解压后将modules文件夹中的[cas-server-webapp-4.0.0.war]放到tomcat的webapps文件夹中、重命名为cas.war。
              启动tomcat、解压war包、浏览器中输入[http://localhost:8080/cas/]
              打开CAS-Server的登录画面、输入默认用户名/密码:[casuser/Mellon]、提示[login success]即登录成功。
     2)、修改CAS-Server配置文件、支持数据库登录校验
              打开[../tomcat/webapps/cas/WEB-INF/deployerConfigContext.xml]文件
     完成的配置文件
    
Java代码  收藏代码
  1.      <?xml version="1.0" encoding="UTF-8"?>  
  2. <!--  
  3.   
  4.     Licensed to Jasig under one or more contributor license  
  5.     agreements. See the NOTICE file distributed with this work  
  6.     for additional information regarding copyright ownership.  
  7.     Jasig licenses this file to you under the Apache License,  
  8.     Version 2.0 (the "License"); you may not use this file  
  9.     except in compliance with the License.  You may obtain a  
  10.     copy of the License at the following location:  
  11.   
  12.       http://www./licenses/LICENSE-2.0  
  13.   
  14.     Unless required by applicable law or agreed to in writing,  
  15.     software distributed under the License is distributed on an  
  16.     "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY  
  17.     KIND, either express or implied.  See the License for the  
  18.     specific language governing permissions and limitations  
  19.     under the License.  
  20.   
  21. -->  
  22. <!--  
  23. | deployerConfigContext.xml centralizes into one file some of the declarative configuration that  
  24. | all CAS deployers will need to modify.  
  25. |  
  26. | This file declares some of the Spring-managed JavaBeans that make up a CAS deployment.    
  27. | The beans declared in this file are instantiated at context initialization time by the Spring   
  28. | ContextLoaderListener declared in web.xml.  It finds this file because this  
  29. | file is among those declared in the context parameter "contextConfigLocation".  
  30. |  
  31. | By far the most common change you will need to make in this file is to change the last bean  
  32. | declaration to replace the default authentication handler with  
  33. | one implementing your approach for authenticating usernames and passwords.  
  34. +-->  
  35.   
  36. <beans xmlns="http://www./schema/beans"  
  37.        xmlns:xsi="http://www./2001/XMLSchema-instance"  
  38.        xmlns:p="http://www./schema/p"  
  39.        xmlns:c="http://www./schema/c"  
  40.        xmlns:tx="http://www./schema/tx"  
  41.        xmlns:util="http://www./schema/util"  
  42.        xmlns:sec="http://www./schema/security"  
  43.        xsi:schemaLocation="http://www./schema/beans http://www./schema/beans/spring-beans-3.2.xsd  
  44.        http://www./schema/tx http://www./schema/tx/spring-tx-3.2.xsd  
  45.        http://www./schema/security http://www./schema/security/spring-security-3.2.xsd  
  46.        http://www./schema/util http://www./schema/util/spring-util.xsd">  
  47.   
  48.     <!--  
  49.        | The authentication manager defines security policy for authentication by specifying at a minimum  
  50.        | the authentication handlers that will be used to authenticate credential. While the AuthenticationManager  
  51.        | interface supports plugging in another implementation, the default PolicyBasedAuthenticationManager should  
  52.        | be sufficient in most cases.  
  53.        +-->  
  54.     <bean id="authenticationManager" class="org.jasig.cas.authentication.PolicyBasedAuthenticationManager">  
  55.         <constructor-arg>  
  56.             <map>  
  57.                 <!--  
  58.                    | IMPORTANT  
  59.                    | Every handler requires a unique name.  
  60.                    | If more than one instance of the same handler class is configured, you must explicitly  
  61.                    | set its name to something other than its default name (typically the simple class name).  
  62.                    -->  
  63.                 <entry key-ref="proxyAuthenticationHandler" value-ref="proxyPrincipalResolver" />  
  64.                 <!-- <entry key-ref="primaryAuthenticationHandler" value-ref="primaryPrincipalResolver" />-->  
  65.                 <entry key-ref="dbAuthHandler" value-ref="primaryPrincipalResolver"/>  
  66.             </map>  
  67.         </constructor-arg>  
  68.   
  69.         <!-- Uncomment the metadata populator to allow clearpass to capture and cache the password  
  70.              This switch effectively will turn on clearpass.  
  71.         <property name="authenticationMetaDataPopulators">  
  72.            <util:list>  
  73.               <bean class="org.jasig.cas.extension.clearpass.CacheCredentialsMetaDataPopulator"  
  74.                     c:credentialCache-ref="encryptedMap" />  
  75.            </util:list>  
  76.         </property>  
  77.         -->  
  78.   
  79.         <!--  
  80.            | Defines the security policy around authentication. Some alternative policies that ship with CAS:  
  81.            |  
  82.            | * NotPreventedAuthenticationPolicy - all credential must either pass or fail authentication  
  83.            | * AllAuthenticationPolicy - all presented credential must be authenticated successfully  
  84.            | * RequiredHandlerAuthenticationPolicy - specifies a handler that must authenticate its credential to pass  
  85.            -->  
  86.         <property name="authenticationPolicy">  
  87.             <bean class="org.jasig.cas.authentication.AnyAuthenticationPolicy" />  
  88.         </property>  
  89.     </bean>  
  90.   
  91.     <!-- Required for proxy ticket mechanism. -->  
  92.     <bean id="proxyAuthenticationHandler"  
  93.           class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"  
  94.           p:httpClient-ref="httpClient" />  
  95.   
  96.     <!--  
  97.        | TODO: Replace this component with one suitable for your enviroment.  
  98.        |  
  99.        | This component provides authentication for the kind of credential used in your environment. In most cases  
  100.        | credential is a username/password pair that lives in a system of record like an LDAP directory.  
  101.        | The most common authentication handler beans:  
  102.        |  
  103.        | * org.jasig.cas.authentication.LdapAuthenticationHandler  
  104.        | * org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler  
  105.        | * org.jasig.cas.adaptors.x509.authentication.handler.support.X509CredentialsAuthenticationHandler  
  106.        | * org.jasig.cas.support.spnego.authentication.handler.support.JCIFSSpnegoAuthenticationHandler  
  107.        -->  
  108.     <bean id="primaryAuthenticationHandler"  
  109.           class="org.jasig.cas.authentication.AcceptUsersAuthenticationHandler">  
  110.         <property name="users">  
  111.             <map>  
  112.                 <entry key="casuser" value="Mellon"/>  
  113.             </map>  
  114.         </property>  
  115.     </bean>  
  116.   
  117.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"  
  118.       p:driverClass="com.mysql.jdbc.Driver"  
  119.       p:jdbcUrl="jdbc:mysql://11.11.11.118:28306/flow?characterEncoding=utf8"  
  120.       p:user="root"  
  121.       p:password="root" />  
  122.   
  123.     <bean id="passwordEncoder" class="org.jasig.cas.authentication.handler.DefaultPasswordEncoder"  
  124.       c:encodingAlgorithm="MD5"  
  125.       p:characterEncoding="UTF-8" />  
  126.   
  127.     <bean id="dbAuthHandler"  
  128.       class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler"  
  129.       p:dataSource-ref="dataSource"  
  130.       p:sql="select password from user where name = ?"  
  131.       p:passwordEncoder-ref="passwordEncoder"/>  
  132.       <!-- p:passwordEncoder-ref="passwordEncoder" --><!-- 暂时不使用密码加密 -->  
  133.   
  134.     <!-- Required for proxy ticket mechanism -->  
  135.     <bean id="proxyPrincipalResolver"  
  136.           class="org.jasig.cas.authentication.principal.BasicPrincipalResolver" />  
  137.   
  138.     <!--  
  139.        | Resolves a principal from a credential using an attribute repository that is configured to resolve  
  140.        | against a deployer-specific store (e.g. LDAP).  
  141.        -->  
  142.     <bean id="primaryPrincipalResolver"  
  143.           class="org.jasig.cas.authentication.principal.PersonDirectoryPrincipalResolver" >  
  144.         <property name="attributeRepository" ref="attributeRepository" />  
  145.     </bean>  
  146.   
  147.     <!--  
  148.     Bean that defines the attributes that a service may return.  This example uses the Stub/Mock version.  A real implementation  
  149.     may go against a database or LDAP server.  The id should remain "attributeRepository" though.  
  150.     +-->  
  151.     <bean id="attributeRepository" class="org.jasig.services.persondir.support.StubPersonAttributeDao"  
  152.             p:backingMap-ref="attrRepoBackingMap" />  
  153.       
  154.     <util:map id="attrRepoBackingMap">  
  155.         <entry key="uid" value="uid" />  
  156.         <entry key="eduPersonAffiliation" value="eduPersonAffiliation" />   
  157.         <entry key="groupMembership" value="groupMembership" />  
  158.     </util:map>  
  159.   
  160.     <!--   
  161.     Sample, in-memory data store for the ServiceRegistry. A real implementation  
  162.     would probably want to replace this with the JPA-backed ServiceRegistry DAO  
  163.     The name of this bean should remain "serviceRegistryDao".  
  164.     +-->  
  165.     <bean id="serviceRegistryDao" class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl"  
  166.             p:registeredServices-ref="registeredServicesList" />  
  167.   
  168.     <util:list id="registeredServicesList">  
  169.         <bean class="org.jasig.cas.services.RegexRegisteredService"  
  170.               p:id="0" p:name="HTTP and IMAP" p:description="Allows HTTP(S) and IMAP(S) protocols"  
  171.               p:serviceId="^(https?|imaps?)://.*" p:evaluationOrder="10000001" />  
  172.         <!--  
  173.         Use the following definition instead of the above to further restrict access  
  174.         to services within your domain (including sub domains).  
  175.         Note that example.com must be replaced with the domain you wish to permit.  
  176.         This example also demonstrates the configuration of an attribute filter  
  177.         that only allows for attributes whose length is 3.  
  178.         -->  
  179.         <!--  
  180.         <bean class="org.jasig.cas.services.RegexRegisteredService">  
  181.             <property name="id" value="1" />  
  182.             <property name="name" value="HTTP and IMAP on example.com" />  
  183.             <property name="description" value="Allows HTTP(S) and IMAP(S) protocols on example.com" />  
  184.             <property name="serviceId" value="^(https?|imaps?)://([A-Za-z0-9_-]+\.)*example\.com/.*" />  
  185.             <property name="evaluationOrder" value="0" />  
  186.             <property name="attributeFilter">  
  187.               <bean class="org.jasig.cas.services.support.RegisteredServiceRegexAttributeFilter" c:regex="^\w{3}$" />   
  188.             </property>  
  189.         </bean>  
  190.         -->  
  191.     </util:list>  
  192.       
  193.     <bean id="auditTrailManager" class="com.github.inspektr.audit.support.Slf4jLoggingAuditTrailManager" />  
  194.       
  195.     <bean id="healthCheckMonitor" class="org.jasig.cas.monitor.HealthCheckMonitor" p:monitors-ref="monitorsList" />  
  196.     
  197.     <util:list id="monitorsList">  
  198.       <bean class="org.jasig.cas.monitor.MemoryMonitor" p:freeMemoryWarnThreshold="10" />  
  199.       <!--  
  200.         NOTE  
  201.         The following ticket registries support SessionMonitor:  
  202.           * DefaultTicketRegistry  
  203.           * JpaTicketRegistry  
  204.         Remove this monitor if you use an unsupported registry.  
  205.       -->  
  206.       <bean class="org.jasig.cas.monitor.SessionMonitor"  
  207.           p:ticketRegistry-ref="ticketRegistry"  
  208.           p:serviceTicketCountWarnThreshold="5000"  
  209.           p:sessionCountWarnThreshold="100000" />  
  210.     </util:list>  
  211. </beans>  
  212.        

     同时需要将[c3p0-0.9.1.2.jar]、[cas-server-support-jdbc-4.0.0.jar](CAS-Servier的module目录中)、[mysql-connector-java-5.x.xx-bin.jar]放入[WEB-INF/lib]目录中。重新启动Tomcat、打开CAS登录画面验证是否可以进行数据库校验。
     注意:1、修改配置文件中的sql文匹配自己的数据库。
                2、密码列采用MD5加密、注意数据匹配

4、配置CAS-Client
      1)、web.xml的配置
     
Java代码  收藏代码
  1.     <context-param>  
  2.      <param-name>contextConfigLocation</param-name>  
  3.      <param-value>classpath:/config/spring/spring.xml, classpath:/config/spring/spring-cas.xml</param-value>  
  4.  </context-param>  
  5.   
  6.  <filter>  
  7.      <filter-name>CAS Single Sign Out Filter</filter-name>  
  8.      <filter-class>org.jasig.cas.client.session.SingleSignOutFilter</filter-class>  
  9.  </filter>  
  10.   
  11.  <filter-mapping>  
  12.      <filter-name>CAS Single Sign Out Filter</filter-name>  
  13.      <url-pattern>/*</url-pattern>  
  14.  </filter-mapping>  
  15.   
  16.  <filter-mapping>  
  17.      <filter-name>springSecurityFilterChain</filter-name>  
  18.      <url-pattern>/*</url-pattern>  
  19.  </filter-mapping>  
  20.  <filter>  
  21.      <filter-name>springSecurityFilterChain</filter-name>  
  22.      <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  23.  </filter>  
  24.   
  25.  <!--  
  26. - Loads the root application context of this web app at startup.  
  27. - The application context is then available via  
  28. - WebApplicationContextUtils.getWebApplicationContext(servletContext).-->  
  29.  <listener>  
  30.      <listener-class>org.jasig.cas.client.session.SingleSignOutHttpSessionListener</listener-class>  
  31.  </listener>  
  32.      

      2)、完整的spring-cas.xml
     
Java代码  收藏代码
  1.       <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www./schema/beans"  
  3.        xmlns:xsi="http://www./2001/XMLSchema-instance"  
  4.        xmlns:p="http://www./schema/p"  
  5.        xmlns:context="http://www./schema/context"  
  6.        xmlns:sec="http://www./schema/security"  
  7.        xsi:schemaLocation="http://www./schema/beans  
  8.        http://www./schema/beans/spring-beans-4.2.xsd  
  9.        http://www./schema/context  
  10.        http://www./schema/context/spring-context-4.2.xsd  
  11.        http://www./schema/security  
  12.        http://www./schema/security/spring-security-4.0.xsd"  
  13.        default-lazy-init="true">  
  14.   
  15.   
  16.     <!-- 浏览权限设定,根据自己的情况修改 -->  
  17.     <sec:http auto-config="false" use-expressions="false" disable-url-rewriting="false"  
  18.               entry-point-ref="casProcessingFilterEntryPoint">  
  19.         <sec:headers disabled="true"/>  
  20.         <sec:csrf disabled="false"/>  
  21.         <sec:intercept-url pattern="/static/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>  
  22.         <sec:intercept-url pattern="/**" access="ROLE_USER"/>  
  23.         <sec:custom-filter position="CAS_FILTER" ref="casAuthenticationFilter" />  
  24.         <sec:logout logout-success-url="/static/html/logout-success.html"/>  
  25.         <sec:custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER"/>  
  26.         <sec:custom-filter ref="singleLogoutFilter" before="CAS_FILTER"/>  
  27.     </sec:http>  
  28.   
  29.     <!-- This filter handles a Single Logout Request from the CAS Server -->  
  30.     <bean id="singleLogoutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter"/>  
  31.   
  32.     <!-- This filter redirects to the CAS Server to signal Single Logout should be performed -->  
  33.     <bean id="requestSingleLogoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">  
  34.         <constructor-arg value="http://localhost:8081/cas/logout"/>  
  35.         <constructor-arg>  
  36.             <bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>  
  37.         </constructor-arg>  
  38.         <property name="filterProcessesUrl" value="/logout/cas"/>  
  39.     </bean>  
  40.   
  41.     <sec:authentication-manager alias="authenticationManager">  
  42.         <sec:authentication-provider ref="casAuthenticationProvider"/>  
  43.     </sec:authentication-manager>  
  44.   
  45.     <bean id="casAuthenticationFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter">  
  46.         <property name="authenticationManager" ref="authenticationManager"/>  
  47.         <!-- 认证失败返回的页面(非403错误)  
  48.         <property name="authenticationFailureHandler">  
  49.             <bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">  
  50.                 <property name="defaultFailureUrl" value="/static/html/errors/403.html"/>  
  51.             </bean>  
  52.         </property>-->  
  53.         <!-- 认证成功返回的页面,此处做了修改,这个类是继续之前的操作。默认的类是设置一个固定的页面  
  54.         <property name="authenticationSuccessHandler">  
  55.             <bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"/>  
  56.         </property>-->  
  57.     </bean>  
  58.   
  59.     <bean id="casProcessingFilterEntryPoint" class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">  
  60.                 <!-- 单点登录服务器登录URL -->  
  61.         <property name="loginUrl" value="http://localhost:8081/cas/login"/>  
  62.           
  63.         <property name="serviceProperties" ref="serviceProperties"/>  
  64.     </bean>  
  65.   
  66.     <bean id="userDetailsManager" class="cn.co.xxx.xxxx.xxxx.xxxx.x.UserDetailsManager"/>  
  67.   
  68.     <bean id="casAuthenticationProvider"  
  69.           class="org.springframework.security.cas.authentication.CasAuthenticationProvider">  
  70.         <property name="authenticationUserDetailsService">  
  71.             <bean class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">  
  72.                 <constructor-arg ref="userDetailsManager" />  
  73.             </bean>  
  74.         </property>  
  75.         <property name="serviceProperties" ref="serviceProperties"/>  
  76.         <property name="ticketValidator">  
  77.             <bean class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator">  
  78.                 <constructor-arg index="0" value="http://localhost:8081/cas"/>  
  79.             </bean>  
  80.         </property>  
  81.         <property name="key" value="an_id_for_this_auth_provider_only"/>  
  82.     </bean>  
  83.   
  84.     <!--  
  85.     <security:user-service id="userService">  
  86. <security:user name="joe" password="joe" authorities="ROLE_USER" />  
  87. ...  
  88. </security:user-service>  
  89.     -->  
  90.   
  91.     <bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties">  
  92.          <!--[login/cas]是Spring Security 4.0后修改的地址、跟3.X版本完全不同、请勿修改-->  
  93.         <property name="service" value="http://localhost:8080/workflow/login/cas"/>  
  94.           
  95.         <property name="sendRenew" value="false"/>  
  96.     </bean>  
  97. </beans>  
  98.         

      3)、UserDetailsManager
     
Java代码  收藏代码
  1. import cn.co.workflow.service.UserIdentityService;  
  2. import org.springframework.beans.factory.annotation.Autowired;  
  3. import org.springframework.security.core.GrantedAuthority;  
  4. import org.springframework.security.core.authority.SimpleGrantedAuthority;  
  5. import org.springframework.security.core.userdetails.UserDetails;  
  6. import org.springframework.security.core.userdetails.UserDetailsService;  
  7. import org.springframework.security.core.userdetails.UsernameNotFoundException;  
  8. import org.springframework.stereotype.Service;  
  9.   
  10. import java.util.ArrayList;  
  11. import java.util.Collection;  
  12. import java.util.List;  
  13.   
  14. /** 
  15.  * Created by liulijun on 15/10/2. 
  16.  */  
  17. public class UserDetailsManager implements UserDetailsService {  
  18.   
  19.        /** 
  20.         * 注入用户信息查询Service 
  21.         */  
  22.     @Autowired  
  23.     private UserIdentityService userIdentityService;  
  24.       
  25.         /** 
  26.          * 此处的参数[loginId]为CAS登录画面输入的用户名 
  27.          */  
  28.     @Override  
  29.     public UserDetails loadUserByUsername(String loginId) throws UsernameNotFoundException {  
  30.         Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();  
  31.   
  32.         UserDetails userDetails = new UserDetails() {  
  33.             /** 
  34.              * Returns the authorities granted to the user. Cannot return <code>null</code>. 
  35.              * 
  36.              * @return the authorities, sorted by natural key (never <code>null</code>) 
  37.              */  
  38.             @Override  
  39.             public Collection<? extends GrantedAuthority> getAuthorities() {  
  40.                 SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");  
  41.                 auths.add(authority);  
  42.   
  43.                 return auths;  
  44.             }  
  45.   
  46.             /** 
  47.              * Returns the password used to authenticate the user. 
  48.              * 
  49.              * @return the password 
  50.              */  
  51.             @Override  
  52.             public String getPassword() {  
  53.                 return "11";  
  54.             }  
  55.   
  56.             /** 
  57.              * Returns the username used to authenticate the user. Cannot return <code>null</code> 
  58.              * . 
  59.              * 
  60.              * @return the username (never <code>null</code>) 
  61.              */  
  62.             @Override  
  63.             public String getUsername() {  
  64.                 return "1";  
  65.             }  
  66.   
  67.             /** 
  68.              * Indicates whether the user's account has expired. An expired account cannot be 
  69.              * authenticated. 
  70.              * 
  71.              * @return <code>true</code> if the user's account is valid (ie non-expired), 
  72.              * <code>false</code> if no longer valid (ie expired) 
  73.              */  
  74.             @Override  
  75.             public boolean isAccountNonExpired() {  
  76.                 return true;  
  77.             }  
  78.   
  79.             /** 
  80.              * Indicates whether the user is locked or unlocked. A locked user cannot be 
  81.              * authenticated. 
  82.              * 
  83.              * @return <code>true</code> if the user is not locked, <code>false</code> otherwise 
  84.              */  
  85.             @Override  
  86.             public boolean isAccountNonLocked() {  
  87.                 return true;  
  88.             }  
  89.   
  90.             /** 
  91.              * Indicates whether the user's credentials (password) has expired. Expired 
  92.              * credentials prevent authentication. 
  93.              * 
  94.              * @return <code>true</code> if the user's credentials are valid (ie non-expired), 
  95.              * <code>false</code> if no longer valid (ie expired) 
  96.              */  
  97.             @Override  
  98.             public boolean isCredentialsNonExpired() {  
  99.                 return true;  
  100.             }  
  101.   
  102.             /** 
  103.              * Indicates whether the user is enabled or disabled. A disabled user cannot be 
  104.              * authenticated. 
  105.              * 
  106.              * @return <code>true</code> if the user is enabled, <code>false</code> otherwise 
  107.              */  
  108.             @Override  
  109.             public boolean isEnabled() {  
  110.                 return true;  
  111.             }  
  112.         };  
  113.   
  114.         return userDetails;  
  115.     }  
  116. }  
  117.         

      4)、logout地址
               http://localhost:8080/workflow/logout/cas
      5)、https
               如果CAS-Server端使用https、请按照普通https配置方式修改即可、注意客户端jre中需要导入证书。同时spring-cas.xml中关于server端的连接需要改为https.
      
      重新启动客户端服务、即可正常访问。

      参考资料:[http://docs./spring-security/site/docs/4.0.2.RELEASE/reference/htmlsingle/#get-source]    

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多