2.CAS服务端数据源设置
2.1需求分析
我们现在让用户名密码从我们的优乐选的user表里做验证
2.2配置数据源
(1)修改cas服务端中web-inf下deployerConfigContext.xml,添加如下配置
"dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" p:driverClass="com.mysql.jdbc.Driver" p:jdbcUrl="jdbc:mysql://127.0.0.1:3306/youlexuandb?characterEncoding=utf8" p:user="root" p:password="root" /> "passwordEncoder" class="org.jasig.cas.authentication.handler.DefaultPasswordEncoder" c:encodingAlgorithm="MD5" p:characterEncoding="UTF-8" /> "dbAuthHandler" class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler" p:dataSource-ref="dataSource" p:sql="select password from tb_user where username = ?" p:passwordEncoder-ref="passwordEncoder"/>
然后在配置文件开始部分找到如下配置
<bean id="authenticationManager" class="org.jasig.cas.authentication.PolicyBasedAuthenticationManager"> <constructor-arg> <map> <entry key-ref="proxyAuthenticationHandler" value-ref="proxyPrincipalResolver" />
map> constructor-arg> <property name="authenticationPolicy"> <bean class="org.jasig.cas.authentication.AnyAuthenticationPolicy" /> property> bean>
其中
|
一句是使用固定的用户名和密码,我们在下面可以看到这两个bean ,如果我们使用数据库认证用户名和密码,需要将这句注释掉。
添加下面这一句配置
|
(2)将以下三个jar包放入webapps\cas\WEB-INF\lib下
(这三个jar包在资源\cas\jar目录下)
用数据库中的用户名和密码进行测试
启动tomcat
Demo1
Demo2
3.CAS服务端界面改造
3.1需求分析
我们现在动手将CAS默认的登录页更改为自己的优乐选登陆页
3.2改头换面
3.2.1拷贝资源
(1)将登陆页login.html拷贝到cas系统下WEB-INF\view\jsp\default\ui 目录下
(2)将css、js等文件夹拷贝到cas目录下
(3) 将tomcat7\webapps\cas\WEB-INF\view\jsp\default\ui下的casLoginView.jsp 改名(可以为之后的修改操作做参照),将login.html改名为casLoginView.jsp
3.2.2修改页面
编辑casLoginView.jsp 内容
(1)添加指令-----若为原登录页为html文件,则需要添加
<%@ page pageEncoding="UTF-8" %> <%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
(2)修改form标签
<form:form method="post" id="fm1" commandName="${commandName}" htmlEscape="true" class="sui-form"> ...... form:form>
(3)修改用户名框
<form:input id="username" tabindex="1" accesskey="${userNameAccessKey}" path="username" autocomplete="off" htmlEscape="true" placeholder="邮箱/用户名/手机号" class="span2 input-xfat" />
(4)修改密码框
<form:password id="password" tabindex="2" path="password" accesskey="${passwordAccessKey}" htmlEscape="true" autocomplete="off" placeholder="请输入密码" class="span2 input-xfat" />
(5)修改登陆按钮
<input type="hidden" name="lt" value="${loginTicket}" /> <input type="hidden" name="execution" value="${flowExecutionKey}" /> <input type="hidden" name="_eventId" value="submit" /> <input class="sui-btn btn-block btn-xlarge btn-danger" accesskey="l" value="登陆" type="submit" />
整体代码如下
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> <title>优乐选,欢迎登录title> <link rel="stylesheet" type="text/css" href="css/webbase.css" /> <link rel="stylesheet" type="text/css" href="css/pages-login.css" /> head> <body> <div class="login-box"> <div class="py-container logoArea"> <a href="" class="logo">a> div> <div class="loginArea"> <div class="py-container login"> <div class="loginform"> <ul class="sui-nav nav-tabs tab-wraped"> <li> <a href="#index" data-toggle="tab"> <h3>扫描登录h3> a> li> <li class="active"> <a href="#profile" data-toggle="tab"> <h3>账户登录h3> a> li> ul> <div class="tab-content tab-wraped"> <div id="index" class="tab-pane"> <p>二维码登录,暂为官网二维码p> <img src="img/xg/erweima.png" /> div> <div id="profile" class="tab-pane active"> <form:form method="post" id="fm1" commandName="${commandName}" htmlEscape="true" class="sui-form"> <div class="input-prepend"><span class="add-on loginname">span> <form:input id="username" tabindex="1" accesskey="${userNameAccessKey}" path="username" autocomplete="off" htmlEscape="true" placeholder="邮箱/用户名/手机号" class="span2 input-xfat" /> div> <div class="input-prepend"><span class="add-on loginpwd">span> <form:password id="password" tabindex="2" path="password" accesskey="${passwordAccessKey}" htmlEscape="true" autocomplete="off" placeholder="请输入密码" class="span2 input-xfat" /> div> <div class="setting"> <label class="checkbox inline"> <input name="m1" type="checkbox" value="2" checked=""> 自动登录 label> <span class="forget">忘记密码?span> div> <div class="logined"> <input type="hidden" name="lt" value="${loginTicket}" /> <input type="hidden" name="execution" value="${flowExecutionKey}" /> <input type="hidden" name="_eventId" value="submit" /> <input class="sui-btn btn-block btn-xlarge btn-danger" accesskey="l" value="登陆" type="submit" /> div> form:form> <div class="otherlogin"> <div class="types"> <ul> <li><img src="img/qq.png" width="35px" height="35px" />li> <li><img src="img/sina.png" />li> <li><img src="img/ali.png" />li> <li><img src="img/weixin.png" />li> ul> div> <span class="register"><a href="register.html" target="_blank">立即注册a>span> div> div> div> div> div> div> <div class="py-container copyright"> <ul> <li>关于我们li> <li>联系我们li> <li>联系客服li> <li>商家入驻li> <li>营销中心li> <li>手机优乐选li> <li>销售联盟li> <li>优乐选社区li> ul> <div class="address">地址:XXXdiv> <div class="beian">XXXdiv> div> div> <script type="text/javascript" src="js/plugins/jquery/jquery.min.js">script> <script type="text/javascript" src="js/plugins/jquery.easing/jquery.easing.min.js">script> <script type="text/javascript" src="js/plugins/sui/sui.min.js">script> <script type="text/javascript" src="js/plugins/jquery-placeholder/jquery.placeholder.min.js">script> <script type="text/javascript" src="js/pages/login.js">script> body> html>
3.3错误提示(选做 国际化内容)
在表单内加入错误提示框
<form:errors path="*" id="msg" cssClass="errors" element="div" htmlEscape="false" />
测试:输入错误的用户名和密码,提示是英文。这个提示信息是在WEB-INF\classes目录下的messages.properties文件中
authenticationFailure.AccountNotFoundException=Invalid credentials.
authenticationFailure.FailedLoginException=Invalid credentials.
设置国际化为zn_CN ,修改cas-servlet.xml
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" p:defaultLocale="zh_CN" />
我们需要将此信息拷贝到messages_zh_CN.properties下,并改为中文提示(转码)
authenticationFailure.AccountNotFoundException=\u7528\u6237\u4E0D\u5B58\u5728.
authenticationFailure.FailedLoginException=\u5BC6\u7801\u9519\u8BEF.
第一个是用户名不存在时的错误提示
第二个是密码错误的提示
4. CAS客户端与SpringSecurity集成
4.1 Spring Security测试工程搭建
(1)建立Maven项目casclient_demo3 ,引入spring依赖和spring secrity 相关依赖 ,tomcat端口设置为9003
pom.xml约束文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0modelVersion> <groupId>com.luli.demogroupId> <artifactId>casclient_demo3artifactId> <version>0.0.1-SNAPSHOTversion> <packaging>warpackaging> <properties> <spring.version>4.2.4.RELEASEspring.version> properties> <dependencies> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-coreartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webmvcartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-context-supportartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-testartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-jdbcartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>javax.servletgroupId> <artifactId>servlet-apiartifactId> <version>2.5version> <scope>providedscope> dependency> <dependency> <groupId>org.springframework.securitygroupId> <artifactId>spring-security-webartifactId> <version>4.1.0.RELEASEversion> dependency> <dependency> <groupId>org.springframework.securitygroupId> <artifactId>spring-security-configartifactId> <version>4.1.0.RELEASEversion> dependency> dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.pluginsgroupId> <artifactId>maven-compiler-pluginartifactId> <version>3.2version> <configuration> <source>1.7source> <target>1.7target> <encoding>UTF-8encoding> configuration> plugin> <plugin> <groupId>org.apache.tomcat.mavengroupId> <artifactId>tomcat7-maven-pluginartifactId> <configuration> <port>9003port> <path>/path> configuration> plugin> plugins> build> project>
(2)建立web.xml ,添加过滤器等配置
xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <context-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:spring-security.xmlparam-value> context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener listener-class> listener> <filter> <filter-name>springSecurityFilterChainfilter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class> filter> <filter-mapping> <filter-name>springSecurityFilterChainfilter-name> <url-pattern>/*url-pattern> filter-mapping> <servlet> <servlet-name>springmvcservlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class> <init-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:springmvc.xmlparam-value> init-param> servlet> <servlet-mapping> <servlet-name>springmvcservlet-name> <url-pattern>*.dourl-pattern> servlet-mapping> web-app>
(3)创建配置文件spring-security.xml
xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <http pattern="/login.html" security="none">http> <http pattern="/login_error.html" security="none">http> <http use-expressions="false"> <intercept-url pattern="/**" access="ROLE_USER"/> <form-login login-page="/login.html" default-target-url="/index.html" authentication-failure-url="/login_error.html"/> <csrf disabled="true"/> http> <authentication-manager> <authentication-provider> <user-service> <user name="admin" password="123456" authorities="ROLE_USER"/> user-service> authentication-provider> authentication-manager> beans:beans>
(4)添加html页面
4.2 Spring Security与 CAS集成
(1)引入依赖pom.xml
<dependency> <groupId>org.springframework.securitygroupId> <artifactId>spring-security-casartifactId> <version>4.1.0.RELEASEversion> dependency> <dependency> <groupId>org.jasig.cas.clientgroupId> <artifactId>cas-client-coreartifactId> <version>3.3.3version> <exclusions> <exclusion> <groupId>org.slf4jgroupId> <artifactId>log4j-over-slf4jartifactId> exclusion> exclusions> dependency>
(2)修改spring-security.xml
xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <http use-expressions="false" entry-point-ref="casProcessingFilterEntryPoint"> <intercept-url pattern="/**" access="ROLE_USER" /> <csrf disabled="true" /> <custom-filter ref="casAuthenticationFilter" position="CAS_FILTER" /> <custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER" /> <custom-filter ref="singleLogoutFilter" before="CAS_FILTER" /> http> <beans:bean id="casProcessingFilterEntryPoint" class="org.springframework.security.cas.web.CasAuthenticationEntryPoint"> <beans:property name="loginUrl" value="http://localhost:9100/cas/login" /> <beans:property name="serviceProperties" ref="serviceProperties" /> beans:bean> <beans:bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties"> <beans:property name="service" value="http://localhost:9003/login/cas" /> beans:bean> <beans:bean id="casAuthenticationFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter"> <beans:property name="authenticationManager" ref="authenticationManager" /> beans:bean> <authentication-manager alias="authenticationManager"> <authentication-provider ref="casAuthenticationProvider"> authentication-provider> authentication-manager> <beans:bean id="casAuthenticationProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider"> <beans:property name="authenticationUserDetailsService"> <beans:bean class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper"> <beans:constructor-arg ref="userDetailsService" /> beans:bean> beans:property> <beans:property name="serviceProperties" ref="serviceProperties" /> <beans:property name="ticketValidator"> <beans:bean class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator"> <beans:constructor-arg index="0" value="http://localhost:9100/cas" /> beans:bean> beans:property> <beans:property name="key" value="an_id_for_this_auth_provider_only" /> beans:bean> <beans:bean id="userDetailsService" class="com.offcn.demo.service.UserDetailServiceImpl" /> <beans:bean id="singleLogoutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter" /> <beans:bean id="requestSingleLogoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter"> <beans:constructor-arg value="http://localhost:9100/cas/logout?service=http://localhost:9003/index2.html" /> <beans:constructor-arg> <beans:bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler" /> beans:constructor-arg> <beans:property name="filterProcessesUrl" value="/logout/cas" /> beans:bean> beans:beans>
(3)创建UserDetailsServiceImpl
/** * 认证类 */ public class UserDetailServiceImpl implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { //构建角色集合 List<GrantedAuthority> authorities=new ArrayList(); authorities.add(new SimpleGrantedAuthority("ROLE_USER")); return new User(username, "" , authorities); } }
这个类的主要作用是在登陆后得到用户名,可以根据用户名查询角色或执行一些逻辑。
启动tomcat
启动9003 进行登录
再访问9001 和 9002 发现不再需要登录,可以直接进行登录实现单点登录功能。
4.3获取登录名
我们在处理后端逻辑需要获得登录名,那么如何获取单点登录的用户名呢? 其实和我们之前获得用户名的方式是完全相同的,我们下面来做个测试。
(1)web.xml 添加springmvc
<servlet> <servlet-name>springmvcservlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class> <init-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:springmvc.xmlparam-value> init-param> servlet> <servlet-mapping> <servlet-name>springmvcservlet-name> <url-pattern>*.dourl-pattern> servlet-mapping>
(2)创建springmvc.xml
xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.offcn.demo" /> <mvc:annotation-driven /> beans>
(3)创建UserController
@RestController public class UserController { @RequestMapping("/findLoginUser") public void findLoginUser(){ String name = SecurityContextHolder.getContext().getAuthentication().getName(); System.out.println(name); } }
先登录9003
地址栏输入http://localhost:9003/findLoginUser.do 即可在控制台看到输出的登录名。
4.4退出登录
修改spring-security.xml
<beans:bean id="requestSingleLogoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter"> <beans:constructor-arg value="http://localhost:9100/cas/logout?service=http://localhost:9003/index2.html"/> <beans:constructor-arg> <beans:bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/> beans:constructor-arg> <beans:property name="filterProcessesUrl" value="/logout/cas"/> beans:bean>
在页面上添加链接
<a href="/logout/cas">退出登录a>