一般来说, Web 应用的安全性包括用户认证( Authentication )和用户授权( Authorization )两个部分。用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户授权指的是验证某个用户是否有权限执行某个操作。在一 个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的 角色,而每个角色则对应一系列的权限。

对于上面提到的两种应用情景, Spring Security 框架都有很好的支持。在用户认证方面, Spring Security 框架支持主流的认证方式,包括 HTTP 基本认证、 HTTP 表单验证、 HTTP 摘要认证、 OpenID 和 LDAP 等。在用户授权方面, Spring Security 提供了基于角色的访问控制和访问控制列表( Access Control List , ACL ),可以对应用中的领域对象进行细粒度的控制。

若 Spring Security 整合 CAS 单点登录 , 使用 CAS 进行认证和获取授权信息 使用 Spring Security 验证权限 ,则可以很好的把公共的认证和授权与具体应用剥离开来,同时简化应用的配置。本文就 Spring Security 与 CAS 的整合进行说明。

一 、基本需求

1. jdk 5.0

2. tomcat 6

3. Spring 3.0.5.RELEASE

4. Spring Security 3.1.0.RELEASE

5. CAS cas-server-3.4.7, cas-client-3.2.0

6. 使用http协议进行传输

7. 通过jdbc进行用户验证,需要通过casserver提供除登录用户名以外的附加信息(用于Spring Security 进行验证权限)


二、搭建CAS Server


1. 把从 http://www.jasig.org/cas/download 上下载cas解压找到
cas-server-3.4.7-releasecas-server-3.4.7modulescas-server-webapp-3.4.7.war
, 解压cas-server-webapp-3.4.7.war ,部署在至tomcat上端口为 8080的server上,如部署路径为
http://localhost:8080/cas 。为了达到需求目的,我们主要需要对
/WEB-INF/deployerConfigContext.xml 文件进行修改。

2.

使用

jdbc

数据源进行用户认证,需要修改

deployerConfigContext.xml

authenticationHandlers

方式

<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.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler" / -->

//

数据库认证方式

<!--DATABASE -- >

<bean class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler">

<property name="dataSource" ref="dataSource" />

<property name="sql" value="select password from t_admin_user where login_name=?" />

</bean>

</list>

<property name="authenticationHandlers">

<!-- DATABASE

增加数据源配置

-->

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>

<property
name="url"><value>jdbc:mysql:///cas?useUnicode=true&amp;characterEncoding=utf-8</value></property>

<property name="username"><value>root</value></property>

</bean>

3.

通过

casserver

提供除登录用户名以外的附加信息(用于

Spring Security

进行验证权限),修改

/WEB-INF/

deployerConfigContext

.xml

3.1

修改

credentialsToPrincipalResolvers

<property name="credentialsToPrincipalResolvers">

<list>

<bean class="org.jasig.cas.authentication.principal.UsernamePasswordCredentialsToPrincipalResolver" > 

<property name="attributeRepository" ref="attributeRepository" /> //

增加此属性,为认证过的用户的

Principal

添加属性

</bean>

<bean class="org.jasig.cas.authentication.principal.HttpBasedServiceCredentialsToPrincipalResolver" />

</list>

</property>

3.2

修改该文件中默认的

attributeRepositorybean

配置

<!--

使用

SingleRowJdbcPersonAttributeDao

获取更多用户的信息

-->

<bean id="attributeRepository" class="org.jasig.services.persondir.support.jdbc.SingleRowJdbcPersonAttributeDao">

<constructor-arg index="0" ref="dataSource"/>

<constructor-arg index="1" value="select role_name,group_name from role where login_name = ?"/> 

<!--

这里的

key

需写

username,value

对应数据库用户名字段

-->

<property name="queryAttributeMapping">

<map>

<entry key="username" value="login_name"/>

</map>

</property>

<!--key

对应数据库字段,

value

对应客户端获取参数

-->

<property name="resultAttributeMapping">

<map>

<entry key="role_name" value="authorities"/> //

这个从数据库中获取的角色,用于在应用中

security

的权限验证

</map>

</property>

</bean>

3.3

修改该文件中最默认的

serviceRegistryDao

中的属性全部注释掉

这个

bean

中的

RegisteredServiceImpl

ignoreAttributes

属性将决定是否添加

attributes

属性内容,默认为

false:

不添加,只有去掉这个配置,

cas server

才会将获取的用户的附加属性添加到认证用的

Principal

attributes

中去。

<bean id="serviceRegistryDao" class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl"></bean>

3.4

若采用

CAS

Cas20ServiceTicketValidator

认证,则需要修改

WEB-INFviewjspprotocol2.0casServiceValidationSuccess.jsp

文件,才能把获取的属性传递至客户端

<%@ page session="false" %>

<%@ taglib prefix="c" uri="

http://java.sun.com/jsp/jstl/core

" %>

<%@ taglib uri="

http://java.sun.com/jsp/jstl/functions

" prefix="fn" %>

<cas:serviceResponse xmlns:cas=\'http://www.yale.edu/tp/cas\'>

<cas:authenticationSuccess>

<cas:user>${fn:escapeXml(assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].principal.id)}</cas:user>

<c:if test="${not empty pgtIou}">

<cas:proxyGrantingTicket>${pgtIou}</cas:proxyGrantingTicket>

</c:if>

<c:if test="${fn:length(assertion.chainedAuthentications) > 1}">

<cas:proxies>

<c:forEach var="proxy" items="${assertion.chainedAuthentications}"
varStatus="loopStatus" begin="0"
end="${fn:length(assertion.chainedAuthentications)-2}" step="1">

<cas:proxy>${fn:escapeXml(proxy.principal.id)}</cas:proxy>

</c:forEach>

</cas:proxies>

</c:if>

<!--

增加如下内容

-->

<c:if
test="${fn:length(assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].principal.attributes)>
0}">

<cas:attributes>

<c:forEach 

var="attr"

items="${assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].principal.attributes}"

varStatus="loopStatus" 

begin="0"

end="${fn:length(assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].principal.attributes)-1}"

step="1">

<cas:${fn:escapeXml(attr.key)}>${fn:escapeXml(attr.value)}</cas:${fn:escapeXml(attr.key)}>

</c:forEach>

</cas:attributes>

</c:if>

</cas:authenticationSuccess>

</cas:serviceResponse>

至此,

CAS Server

搭建完毕。

三、搭建

CAS Client

(即

Spring Security

)应用

1. CAS Client

下需要把

spring-security-cas-3.1.0.M2.jar

Spring Security

相关的

jar

引入,把

cas-client-core-3.2.0.jar

引入,用于从

cas server

上获取相关认证与授权信息。

2. CAS Client

应用的

web.xml

增加如下

<!--

spring

配置文件


-

->

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:applicationContext-security-ns.xml</param-value>

</context-param>

<!-- spring security filter -->

<filter>

<filter-name>springSecurityFilterChain</filter-name>

<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>

</filter>

<filter-mapping>

<filter-name>springSecurityFilterChain</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

<!-- spring

默认侦听器

-->

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

3. spring security

文件的配置

applicationContext-security-ns.xml

<?xml version="1.0"?>

<beans xmlns="

http://www.springframework.org/schema/beans



xmlns:security="

http://www.springframework.org/schema/security



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-3.0.xsd

http://www.springframework.org/schema/security

http://www.springframework.org/schema/security/spring-security-3.1.xsd

">

<!--

Enable security, let the casAuthenticationEntryPoint handle all intercepted urls.

The CAS_FILTER needs to be in the right position within the filter chain.

--> 

<security:http entry-point-ref="casAuthenticationEntryPoint" auto-config="true">

<security:intercept-url pattern="/**" access="ROLE_USER"></security:intercept-url>

<security:custom-filter position="CAS_FILTER" ref="casAuthenticationFilter"></security:custom-filter>

</security:http>

<!--

Required for the casProcessingFilter, so define it explicitly set and

specify an Id Even though the authenticationManager is created by

default when namespace based config is used.

-->

<security:authentication-manager alias="authenticationManager">

<security:authentication-provider ref="casAuthenticationProvider"></security:authentication-provider>

</security:authentication-manager>

<!--

This section is used to configure CAS. The service is the

actual redirect that will be triggered after the CAS login sequence.

-->

<bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties">

//http://localhost:8088/SpringSecurity

具体应用

// j_spring_cas_security_check spring

的虚拟

URL

,此标志标识使用

CAS authentication upon return from CAS SSO login.

<property name="service" value="

http://localhost:8088/SpringSecurity/j_spring_cas_security_check"></property

>

<property name="sendRenew" value="false"></property>

</bean>

<!--

The CAS filter handles the redirect from the CAS server and starts the ticket validation.

-->

<bean id="casAuthenticationFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter">

<property name="authenticationManager" ref="authenticationManager"></property>

</bean>

<!--

The entryPoint intercepts all the CAS authentication requests.

It redirects to the CAS loginUrl for the CAS login page.

-->

<bean id="casAuthenticationEntryPoint" class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">

<property name="loginUrl" value="

http://localhost:8080/cas/login"></property

> //SSO

登录地址

<property name="serviceProperties" ref="serviceProperties"></property>

</bean>

<!--

Handles the CAS ticket processing.

-->

<bean id="casAuthenticationProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider">

<property name="authenticationUserDetailsService" ref="authenticationUserDetailsService"/>

<property name="serviceProperties" ref="serviceProperties"></property>

<property name="ticketValidator">

<bean class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator">

<constructor-arg index="0" value="

http://localhost:8080/cas

" /> //SSO

验证地址

</bean>

</property>

<property name="key" value="cas"></property>

</bean>

<!-- authorities

对应

CAS server

登录属性,

在此设置到

spirng security

中,用于

spring security

的验证

-->

<bean id="authenticationUserDetailsService"
class="org.springframework.security.cas.userdetails.GrantedAuthorityFromAssertionAttributesUserDetailsService">

<constructor-arg>

<array>

<value>authorities</value>

</array>

</constructor-arg>

</bean>

</beans>

至此,

CAS

客户端搭建完毕。

四、总结

通过上述的配置,则具体应用在使用的时候,用户认证和授权则无需过问,只需在应用中配置相关的角色访问权限即可。即,只需对下面的红色部分进行修改,即可以完成应用的认证和授权工作。大大简化了应用和认证与授权的剥离工作

<security:http entry-point-ref="casAuthenticationEntryPoint" auto-config="true">

<security:intercept-url pattern="/**" access="ROLE_USER"></security:intercept-url> 

<security:custom-filter position="CAS_FILTER" ref="casAuthenticationFilter"></security:custom-filter>

</security:http>

五、扩展

若在同一

SSO

下有多个应用,

同一户在不同应用下有不同的角色

,则考虑扩展获取用户权限的环节;资源和角色在数据库中进行配置等等。

CAS Spring Security 3 整合配置(转)的更多相关文章

  1. Spring Security 3整合CAS 实现SSO

    spring security 3整合cas client用于实现各Application之间的单点登录. 1. 需要准备的jar spring-security-core-3.0.8.RELEASE ...

  2. Thymeleaf 3与Spring MVC 4 整合配置

    Thymeleaf 3与Spring MVC 4 整合配置 Maven 依赖配置 Spring 相关依赖就不说了 <dependency> <groupId>org.thyme ...

  3. Spring Security基于Java配置

    Maven依赖 <dependencies> <!-- ... other dependency elements ... --> <dependency> < ...

  4. spring boot rest 接口集成 spring security(2) - JWT配置

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  5. Spring Security(三) —— 核心配置解读

    摘要: 原创出处 https://www.cnkirito.moe/spring-security-3/ 「老徐」欢迎转载,保留摘要,谢谢! 3 核心配置解读 上一篇文章<Spring Secu ...

  6. spring-security-4 (2)spring security 基于Java配置的搭建

    一.spring security的模块 搭建spring security首先我们要导入必须的jar,即maven的依赖.spring security按模块划分,一个模块对应一个jar. spri ...

  7. 【JavaEE】SSH+Spring Security基础上配置AOP+log4j

    Spring Oauth2大多数情况下还是用不到的,主要使用的还是Spring+SpringMVC+Hibernate,有时候加上SpringSecurity,因此,本文及以后的文章的example中 ...

  8. spring security 3.2 配置详解(结合数据库)

    没事就来了解下spring security.网上找了很多资料.有过时的,也有不是很全面的.各种问题也算是让我碰了个遍.这样吧.我先把整个流程写下来,之后在各个易混点分析吧. 1.建立几个必要的页面. ...

  9. Spring Security Oauth2 的配置

    使用oauth2保护你的应用,可以分为简易的分为三个步骤 配置资源服务器 配置认证服务器 配置spring security 前两点是oauth2的主体内容,但前面我已经描述过了,spring sec ...

随机推荐

  1. CheckBox和RadioButton以及RadioGroup

    CheckBox:复选框 有两种状态 选中状态(true),未选状态(false) 属性 android:checked= "false"(表示该复选框未被选中) RadioGro ...

  2. PostgreSQL服务端监听设置及client连接方法

    背景介绍: PostgreSQL服务端执行在RedHat Linux上,IP为:192.168.230.128 client安装在Windows XP上, IP为:192.168.230.1 配置方法 ...

  3. XSS跨站攻击

    目录 1 XSS跨站攻击简介 1 1.1 什么是XSS 1 1.2 XSS的分类 1 1.3 XSS的危害 1 2 XSS的攻击原理 1 2.1 本地式漏洞攻击 1 2.2 存储式漏洞攻击 2 2.3 ...

  4. SQL Server 2008备份数据库失败,拒绝访问的原因

    原文:SQL Server 2008备份数据库失败,拒绝访问的原因 备份数据到特定目录是出现拒绝访问,然后测试备份到C盘根目录正常. 查了下原因: 是因为那个目录没有Authenticated Use ...

  5. 牛逼的验证码,printf返回值

    牛逼的验证码,如下图, 结果是4321,为什么呢,主要是printf返回值问题?那么printf到底返回什么? 经查阅,printf的返回值是打印的字符个数,因此结果是4321就很明显了.

  6. matlab 2014a 改为英文版本号

    1. 在 Matlab 的安装目录以下找到例如以下的路径,X:\MATLAB\R2014a\java\jar,当中 X 为安装盘符,这个不用过多解释了,然后找到目录 zh_CN.此目录就是中文界面的语 ...

  7. sscanf,sscanf_s及其相关使用方法

    #include<stdio.h> 定义函数 int sscanf (const char *str,const char * format,........); 函数说明   sscan ...

  8. 网站可以免费做业务CMS讨论

    中国现在用PHPCMS   DEDECMS织梦    科学新闻CMS  帝国.Discuz.Ecshop等待,但他们个人利益免费,业务.政府.授权费. 什么CMS它可以自由地做商务网站? 考虑到下面几 ...

  9. [置顶] ffmpg简介以及用它实现音频视频合并(java)

    1.简介     FFmpeg是一个自由软件,可以运行音频和视频多种格式的录影.转档.流功能. 2.下载     源代码 git://git.libav.org/libav.git     Windo ...

  10. SplitContainer如何实现左侧导航,正确显示和导航内容

    关于这种类型的设计有很多的实现,这样,我首先解释一下我使用: 我的原则是实现方式,将form嵌panel在,作为一个子窗口. 如下面的代码细节: Form form = new DataSelect( ...