Home php教程 php手册 php 用CAS实现SSO单点登陆及登出功能

php 用CAS实现SSO单点登陆及登出功能

Jun 06, 2016 pm 08:02 PM
cas php sso Function accomplish Sign out Login

php用CAS实现SSO单点登陆及登出功能 一..CAS服务器搭建 CAS服务器端下载地址:http://downloads.jasig.org/cas/ 解压cas-server-4.0.0-release.zip将modules目录下的cas-server-webapp-4.0.0.war改名称为cas.war复制到 tomcat的webapps下,启动tomcat,访问:

php用CAS实现SSO单点登陆及登出功能


一..CAS服务器搭建

CAS服务器端下载地址:http://downloads.jasig.org/cas/ 

解压cas-server-4.0.0-release.zip将modules目录下的cas-server-webapp-4.0.0.war改名称为cas.war复制到tomcat的webapps下,启动tomcat,访问:http://localhost:8080/cas/login 就可以看到登录界面了:

php 用CAS实现SSO单点登陆及登出功能

cas服务端默认采用的是 用户名=密码的验证,并且采用的是https验证,需要给tomact配置证书,本系统没有采用https验证,若采用https验证可参考:

 http://blog.csdn.net/haydenwang8287/archive/2010/07/26/5765941.aspx

1.若不采用http验证,服务器需配置如下:

找到文件cas/WEB-INF/deployerConfigContext.xml的如下内容:

<bean class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"></bean> 
Copy after login

增加参数p:requireSecure="false",是否需要安全验证,即HTTPS,false为不采用,加上去之后,如下:

<bean class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler" p:httpclient-ref="httpClient" p:requiresecure="false"></bean>
Copy after login
找到文件:cas/WEB-INF/spring-configuration/ticketGrantingTicketCookieGenerator.xml的如下内容:
<bean id="ticketGrantingTicketCookieGenerator" class="org.jasig.cas.web.support.CookieRetrievingCookieGenerator" p:cookiesecure="true" p:cookiemaxage="-1" p:cookiename="CASTGC" p:cookiepath="/cas"></bean>
Copy after login
参数p:cookieSecure="true",同理为HTTPS验证相关,TRUE为采用HTTPS验证,FALSE为不采用https验证。
参数p:cookieMaxAge="-1",简单说是COOKIE的最大生命周期,-1为无生命周期,即只在当前打开的IE窗口有效,IE关闭或重新打开其它窗口,仍会要求验证。可以根据需要修改为大于0的数字,比如3600等,意思是在3600秒内,打开任意IE窗口,都不需要验证。

服务器端退出地址:http://localhost:8080/cas/logout,如图:

php 用CAS实现SSO单点登陆及登出功能

若希望退出后能返回则需要配置服务端cas-servlet.xml配置

增加属性 p:followServiceRedirects="true"

退出链接为:http://localhost:8080/cas/logout?service=http://localhost:8080/Casclient/index.jsp

2.更改服务器验证方式,采用数据库验证

修改配置文件deployerConfigContext.xml,加dbcp连接池:(以oracle为例)

<bean id="casDataSource" class="org.apache.commons.dbcp.BasicDataSource">  
     <property name="driverClassName">  
          <value>oracle.jdbc.driver.OracleDriver</value>  
     </property>  
     <property name="url">  
          <value>jdbc:oracle:thin:@192.168.18.26:1521:orcl</value>  
     </property>  
     <property name="username">  
          <value>test</value>  
     </property>  
     <property name="password">  
          <value>test</value>  
     </property>  
   </bean>
Copy after login

需要的jar包有:(cas-server-support-jdbc-3.4.4.jar,commons-dbcp-1.2.1.jar,commons-pool-1.3.jar,ojdbc14_g.jar) 

配置加密方式,cas内置的有MD5加密,也可以写自己的加密类,实现org.jasig.cas.authentication.handler.PasswordEncoder接口即可:

<bean id="passwordEncoder" class="org.jasig.cas.authentication.handler.DefaultPasswordEncoder" autowire="byName">        
    <constructor-arg value="MD5"></constructor-arg>    
   </bean>
Copy after login
注释掉默认的验证方式,采用数据库查询验证:
<property name="authenticationHandlers">  
     <list>  
     <!----注释掉这里的默认验证方式,采用以下验证QueryDatabaseAuthenticationHandler-->  
    <!--  <bean class="org.jasig.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler" /> -->    
     <bean class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler">  
      <property name="dataSource" ref="casDataSource"></property>  
      <property name="sql" value="select password from userinfo where lower(username) = lower(?)"></property>  
      <property name="passwordEncoder" ref="passwordEncoder"></property>  
     </bean>  
   </list>  
  </property> 
Copy after login
服务器配置完成


二.配置PHP客户端

PHP客户端下载地址:http://downloads.jasig.org/cas-clients/php/,目前最新版本为CAS-1.2.0.ORC2

新建项目:phpCasClient.将CAS文件夹和CAS.php复制到工程中,修改CAS/client.php,将其中的https改为http,新建php文件:user.php,此文件用于处理单点登陆,内容如下:

Copy after login
Copy after login

<pre name="code" class="php"><?php class user
{
	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function logout()
	{
		session_start();
		//启用单点登录的时候还要到统一认证中心注销  && isset($_SESSION[&#39;phpCAS&#39;]) && $_SESSION[&#39;phpCAS&#39;][&#39;auth_checked&#39;] == &#39;1&#39; 
		
		//引人cas
		include_once &#39;/CAS-1.2.0/CAS.php&#39;;
		
		// initialize phpCAS			
		//phpCAS::client(CAS_VERSION_2_0,&#39;服务地址&#39;,端口号,&#39;cas的访问地址&#39;);
		phpCAS::client(CAS_VERSION_2_0,"192.168.142.1","80","/cas");
		
		//方法一:登出成功后跳转的地址 -- 登出方法中加此句
		/*
		phpCAS::setServerLoginUrl("https://192.168.142.1:80/cas/logout?embed=true&service=http://localhost/phpCasClient/user.php?a=login");
		//no SSL validation for the CAS server
		phpCAS::setNoCasServerValidation();
		phpCAS::logout();*/

		//方法二:退出登录后返回地址 -- 登出方法中加此句
		phpCAS::setNoCasServerValidation();$param=array("service"=>"http://localhost/phpCasClient/user.php?a=login");
		phpCAS::logout($param);
	}
	
	/** 
	 * @desc LoginCas()单点登陆 
	 */
	public function loginCas(){
		Header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
		//引人cas
		include 'CAS-1.2.0/CAS.php';
		// initialize phpCAS 
		//phpCAS::client(CAS_VERSION_2_0,'服务地址',端口号,'cas的访问地址');
		phpCAS::client(CAS_VERSION_2_0,"192.168.142.1","80","/cas",true);

		//可以不用,用于调试,可以通过服务端的cas.log看到验证过程。
		// phpCAS::setDebug();
		//登陆成功后跳转的地址 -- 登陆方法中加此句
		phpCAS::setServerLoginUrl("https://192.168.142.1:80/cas/login?embed=true&cssUrl=http://localhost/phpCasClient/style/login.css&service=http://localhost/phpCasClient/user.php?a=loginCas");
		//no SSL validation for the CAS server 不使用SSL服务校验
		phpCAS::setNoCasServerValidation();
		//这里会检测服务器端的退出的通知,就能实现php和其他语言平台间同步登出了
		phpCAS::handleLogoutRequests();
		
		if(phpCAS::checkAuthentication()){
			//获取登陆的用户名
			$username=phpCAS::getUser();
			//用户登陆成功后,采用js进行页面跳转
			echo "<script language='\"javascript\"'>parent.location.href=&#39;http://localhost/phpCasClient/home.php&#39;;</script>";
		}else{
			// 访问CAS的验证
			phpCAS::forceAuthentication();
		}
		exit;
	}
}
?>
Copy after login


Copy after login
Copy after login

新建视图层,login.html,该页面即为单点登陆页面,内容如下:



<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <title>单点登陆界面</title>


<div class="view">
<table style="width:600; height:333; border:1; align:center; cellpadding:4; bordercolor:#CCCCCC;">
	<tr>
	<td style="width: 50%;align:center;">
			请输入登陆信息:
	</td>
		<td style="width: 50%;">
			<div id="maincol" style="border: 1px solid #ccc;float: left;width: 400px;height: 219px; overflow: hidden;">
				<iframe id="auth-login-iframe" name="auth-login-iframe" style="width:100%; height:100%; marginwidth:0; marginheight:0; frameborder:0; scrolling:no;" src="http://localhost/phpCasClient/user.php?a=loginCas"></iframe>
			</div>
		</td>
	</tr>
  <tr>
  <span style="white-space:pre">	</span><td><a href="http://localhost/phpCasClient/user.php?a=logout">登出</a></td>
  </tr>
</table>
</div>

Copy after login
注意:php配置文件php.ini需要开启php_curl,即 找到 ;extension=php_curl.dll ,将该句前面的分号去掉即可,改为 extension=php_curl.dll

此时,访问login.html,便可以看到单点登陆的界面,登陆成功后,页面跳转到home.php中.

点击 登出,控制层请求user.php的logout方法,处理登出请求.登出成功后,页面跳转到login.html,提示用户登陆


至此,php使用CAS的单点登陆,登出已经操作完毕.





Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles