Spring Security3

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 350

http://www.iteye.

com -

lengyun3566
: lengyun3566 http://lengyun3566.iteye.com

Spring Security 3
http://weibo.com/1920428940

1 / 350

ITeyeDIY 2012-03-12

http://lengyun3566.iteye.com

1. Spring Security
1.1 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.4 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.5 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.6 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.7 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
1.8 Spring Security3doc . . . . . . . . . . . . . . . . . . . . . . . . . 41
1.9 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
1.10 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
1.11 Spring Security3Remember me . . . . . . . . . . . . . . . . . .54
1.12 Spring Security3Remember me . . . . . . . . . . . . . . . . . .60
1.13 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
1.14 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . . . 74
1.15 Spring Security3UserDetailsService . . . . . . . . . . . . . .79
1.16 Spring Security3JdbcDaoImpl . . . . . . . . . . . . . . . . . . .84
1.17 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . . . 90
1.18 Spring Security3salt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

2 / 350

http://lengyun3566.iteye.com

1.19 Spring Security3Remember meSSLdoc


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
1.20 Spring Security3 . . . . . . . . . . . . . . . . . . .110
1.21 Spring Security3 . . .114
1.22 Spring Security3 . . .119
1.23 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .122
1.24 Spring Security3 . . . . . . . . . . . . . . . . .130
1.25 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . .139
1.26 Spring Security3AuthenticationProvider . . . . . . . . . . . . .144
1.27 Spring Security3Session . . . . . . . . . . . . . . . . . . . . .152
1.28 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .162
1.29 Spring Security3Spring Securitybean . . . . . . . .167
1.30 Spring Security3Spring Securitybean . . . . . . . .175
1.31 Spring Security3 . . . . . . . . . . . . . . . . . . . . . .185
1.32 Spring Security3ACL . . . . . . . . . . . . . . . . . . . . . . . .191
1.33 Spring Security3ACL . . . . . . . . . . . . . . . . . . . . . . . . . .204
1.34 Spring Security3ACL . . . . . . . . . . . . . . . . . . . . . . . . . .212
1.35 Spring Security3ACL . . . . . . . . . . . . . . . . . . . . . . . . . .220
1.36 Spring Security3OpenIDSpring Security . . . . . . . . . . . . . . . . .225
1.37 Spring Security3OpenID . . . . . . . . . . . . . . . . . . . . . . .230
1.38 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .239
1.39 Spring Security3LDAPLDAP . . . . . . . . . . . . . . . . . .246

3 / 350

http://lengyun3566.iteye.com

1.40 Spring Security3LDAPLDAP . . . . . . . . . . . . . . . . . .257


1.41 Spring Security3LDAPLDAP . . . . . . . . . . . . . . . . . .266
1.42 Spring Security3CASCAS . . . . . . . . . . . . . . . . . . . . .273
1.43 Spring Security3CASCAS . . . . . . . . . . . . . . . . . . . . .282
1.44 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . .295
1.45 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . .304
1.46 Spring Security3Spring Security . . . . . . . . . . . . . . . . . . . . . . . . . . . .315
1.47 Spring Security3Spring Security 3 . . . . . . . . . . . . . . . . . . . . . . . .332
1.48 Spring Security3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .342

4 / 350

http://lengyun3566.iteye.com

1.1 Spring Security3

1.1 Spring Security3


: 2011-06-02 : Spring
Spring Security3

http://weibo.com/1920428940
http://www.packtpub.com/support?nid=4435

5 / 350

http://lengyun3566.iteye.com

1.2 Spring Security3

1.2 Spring Security3


: 2011-06-02 : Spring, Web, MVC, Security,


21web

Spring3webSpring Security3
Spring Security

l
l web
l
Spring Security

Jim Bob Circle Pant Online Pet Store(JBCPPets.com)

To: Star Developer <stardev@jbcppets.com>


From: Super Visor <theboss@jbcppets.com>
Subject:
Star,

6 / 350

http://lengyun3566.iteye.com

1.2 Spring Security3

Super Visor

Spring
ORMUI

SpringSpring Security3Spring Security2


Spring Security 23Spring Security
Spring Security2
Pet Store

JBCP Pets
web

webMVCSpring MVC
Spring Web FlowStrutsSpringweb stackApache Wicket
Spring Securitywebwebweb
Spring MVC
pet store
Java EE Pet Clinic

7 / 350

http://lengyun3566.iteye.com

1.2 Spring Security3

faade

webBO
SpringORM
hibernateJPAAPIJDBC
HSQL
webORM

8 / 350

http://lengyun3566.iteye.com

1.3 Spring Security3

1.3 Spring Security3


: 2011-06-08 : Spring, Security, Eclipse, ,

Spring

IDE
<!--[if !supportLists]-->l <!--[endif]-->Eclipse 3.43.5 Java EE
http://www.eclipse.org/downloads/
<!--[if !supportLists]-->l <!--[endif]-->Spring IDE2.2(2.2.2)
http://springide.org/blog
EclipseSpring IDE
Spring Tool SuiteSTSEclipseEclipseSpring
SourceSpring IDEhttp://www.springsource.com/
products/springsource-tool-suite-downloadSpringSource
Spring
Eclipse3.4EclipseTomcat6.x
EclipseApache Ant
Apache Mavenmodules

Spring 3Spring Security 3


JavaDoc

e-mail

9 / 350

http://lengyun3566.iteye.com

1.3 Spring Security3

To: Star Developer <stardev@jbcppets.com>


From: Super Visor <theboss@jbcppets.com>
Subject: FW: Security Audit Results
Star,

Super Visor

<!--[if !supportLists]--> l <!--[endif]-->URL


<!--[if !supportLists]--> l <!--[endif]-->
<!--[if !supportLists]--> l <!--[endif]-->
<!--[if !supportLists]--> l <!--[endif]-->
<!--[if !supportLists]--> l <!--[endif]-->SSL
<!--[if !supportLists]--> l <!--[endif]-->

10 / 350

http://lengyun3566.iteye.com

1.3 Spring Security3

URL

<!--[if !supportLists]-->l <!--[endif]-->


<!--[if !supportLists]-->l <!--[endif]-->
<!--[if !supportLists]-->l <!--[endif]-->

{}Spring Security

11 / 350

http://lengyun3566.iteye.com

1.3 Spring Security3

Spring Security

OpenID

Spring Security
web

Spring Security
JDBC

PCI
Spring SecurityAOP

12 / 350

http://lengyun3566.iteye.com

1.3 Spring Security3

SSL

SSLJBCP PetSSL
web

SSL

Spring Security
Spring Security

Spring Security 3
<!--[if !supportLists]-->l <!--[endif]-->
<!--[if !supportLists]-->l <!--[endif]-->
<!--[if !supportLists]-->l <!--[endif]-->
<!--[if !supportLists]-->l <!--[endif]-->
<!--[if !supportLists]-->l <!--[endif]-->
<!--[if !supportLists]-->l <!--[endif]-->session

Spring Security
Spring SecurityjavaSpring
JAASJava EE SecuritySpring
Security
Spring Security

13 / 350

http://lengyun3566.iteye.com

1.3 Spring Security3

<!--[if !supportLists]-->l <!--[endif]-->web


<!--[if !supportLists]-->l <!--[endif]-->
<!--[if !supportLists]-->l <!--[endif]-->
Spring Security

14 / 350

http://lengyun3566.iteye.com

1.4 Spring Security3

1.4 Spring Security3


: 2011-06-11 : Spring, Security, , ,

Spring Security
Spring Security
Spring Security
JBCP Pets

URL

l
lSpring SecurityJBCP Pets
lSpring Security
l
lSpring SecuritySpringSpring Expression Language

Spring Security
JBCP PetSpring Web MVC

Spring Security

15 / 350

http://lengyun3566.iteye.com

1.4 Spring Security3

l e-mailE-mail

e-mailJBCP
Pete-mail
Microsoft Active Directory
l

ATM
RSASecurId

Spring Security
Spring Security
Spring Securityjavaprincipaljava.security.Principal

web servicefeedautomated batch feed


Spring SecurityPrincipal
user

authorities

16 / 350

1.4 Spring Security3

http://lengyun3566.iteye.com

web

<!--[endif]-->

17 / 350

http://lengyun3566.iteye.com

1.4 Spring Security3

Spring Security

access decision manager

JBCP PetsSpring Security

18 / 350

http://lengyun3566.iteye.com

1.5 Spring Security3

1.5 Spring Security3


: 2011-06-15 : Spring, Security, XML, Web,

Spring Security

Spring Security

Spring SecurityXML
XMLSpring Security
web
WEB-INFOdogstore-security.xmlXML
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
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-3.0.xsd">
<http auto-config="true">
<intercept-url pattern="/*" access="ROLE_USER"/>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service>
<user authorities="ROLE_USER" name="guest" password="guest"/>
</user-service>

19 / 350

http://lengyun3566.iteye.com

1.5 Spring Security3

</authentication-provider>
</authentication-manager>
</beans:beans>

Spring SecuritySpring
SecurityXMLsecurityXML
http://www.springframework.org/schema/securityXML
Spring Bean
Spring XMLSpring SecuritySpring
Spring Security
Spring MVCURL
Spring Security

Spring DelegatingFilterProxyweb.xml
Spring SecurityServletRequest
Spring Security
Spring Security

Spring Securityo.s.web.filter.DelegatingFilterProxyservlet

DelegatingFilterProxySpringSpring
webservletSpring BeanServle
web.xmlSpring
MVC<servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filterclass>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
20 / 350

http://lengyun3566.iteye.com

1.5 Spring Security3

<url-pattern>/*</url-pattern>
</filter-mapping>

ServletRequestURL/*
URL
Spring Securitydogstore-security.xml
XMLwebweb.xml

Spring Security XMLweb.xml


Spring webweb.xmlXML
Spring webContextLoaderListenerSpring web servletXML
Spring Security XMLJBCP Pet
Spring MVCXML
web.xmlservlet<servlet-name>
<servlet>
<servlet-name>dogstore</servlet-name>
<servletclass>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

Servlet<servlet-name>dogstoreSpringConvention
over ConfigurationCoCWEB-INFdogstore-servelt.xml
WEB-INFSpring MVC
Spring Web FlowSpring MVCCoCSpring
o.s.web.context.support.XmlWebApplicationContext
JavaDocSpring MVCweb
Spring ApplicationContextSpring MVC servle
Springo.s.web.context.ContextLoaderListenerSpring MVC
ApplicationContextApplicationContextSpring MVC beans
Spring Security

21 / 350

http://lengyun3566.iteye.com

1.5 Spring Security3

webContextLoaderListenerXML<contextparam>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/dogstore-base.xml
</param-value>
</context-param>

dogstore-base.xmlSpring beanbean
Spring SecurityXML<context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/dogstore-security.xml
/WEB-INF/dogstore-base.xml
</param-value>
</context-param>

Spring Securitywebweb
http://localhost:8080/JBCPPets/home.do

Spring Securityguest
JBCP Pets
JBCP Pets

Spring Security

22 / 350

1.5 Spring Security3

http://lengyun3566.iteye.com

Spring Security
URL
<!--[if !supportLists]-->l <!--[endif]-->XML
XML
<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service>
<user authorities="ROLE_USER" name="guest"

password="guest"/>

</user-service>
</authentication-provider>
</authentication-manager>

XML
authentication provider

<!--[if !supportLists]-->l <!--[endif]-->

<!--[if !supportLists]-->l <!--[endif]-->JBCP


form

Spring Security

<!--[if !supportLists]-->l <!--[endif]-->Spring Security


servlet
<!--[if !supportLists]-->l <!--[endif]-->IDEEclipseservlet

<!--[if !supportLists]-->l <!--[endif]-->XML


org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'beans'

23 / 350

http://lengyun3566.iteye.com

1.5 Spring Security3

Spring SecurityXML
schameXMLXML
<!--[if !supportLists]-->l <!--[endif]-->SpringSpring Security
Spring jar

24 / 350

http://lengyun3566.iteye.com

1.6 Spring Security3

1.6 Spring Security3


: 2011-06-24 : Spring, Security, Servlet, Web,

web
Spring Security
auto-confighttp
Spring Security

webSpring Security

Spring Securitydelegatesservletweb

ServletServlet Filterjavax.servlet.Filter
servletJBCP Pets
servletSpring MVC servletweb servlet
servlet

Spring SecurityXMLservletJava EE
servletFilter chainJava EE Servlet API
javax.servlet.FilterChainwebservlet

servelt

25 / 350

http://lengyun3566.iteye.com

1.6 Spring Security3

servlet
servletserveltresponse

Spring SecurityVirtualFilterChain
Spring Security XMLURLJava EE
web
Servlet
servletwebAOP
serveltSpring
Security

Spring Security
Spring Security

JBCP Pets

SecurityContextRepository
o.s.s.web.context.SecurityContextPersistenceFilter

SecurityContextSecurityContext
session

URL
o.s.s.web.authentication.logout.LogoutFilter

/j_spring_security_logout

form
o.s.s.web.authentication.UsernamePasswordAuthenticationFilter

/j_spring_security_checkURL

26 / 350

http://lengyun3566.iteye.com

1.6 Spring Security3

o.s.s.web.authentication.ui.DefaultLoginPageGeneratingFilter

o.s.s.web.authentication.www.BasicAuthenticationFilter

fornOpenIDU

/spring_security_login

HTTP

o.s.s.web.savedrequest.

RequestCacheAwareFilter

o.s.s.web.servletapi.
SecurityContextHolderAwareRequest
Filter

o.s.s.web.authentication.
AnonymousAuthenticationFilter

o.s.s.web.session.
SessionManagementFilter

HttpServletRequestWrappe
o.s.s.web.

servletapi.SecurityContextHolderAwareR

HttpServletRequest

token

session
session

o.s.s.web.access.

ExceptionTranslationFilter

o.s.s.web.access.intercept.
FilterSecurityInterceptor

Access

Spring Security25
javax.servlet.Filter
XMLauto-config

27 / 350

http://lengyun3566.iteye.com

1.6 Spring Security3

Spring Bean

DelegatingFilterProxySpring Security
web.xmlDelegatingFilterProxy

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

Spring Security
DelegatingFilterProxyDelegatingFilterProxySpring WebApplicationContext
beanfilter-nameDelegatingFilterProxy
Javadoc

auto-config
Spring Security 3auto-config
<!--[if !supportLists]-->l <!--[endif]-->HTTP
<!--[if !supportLists]-->l <!--[endif]-->Form
<!--[if !supportLists]-->l <!--[endif]-->
auto-config

auto-configSpring Security3auto-config
Spring Security2auto-configsecurity
13Spring Security 3Spring Security23
28 / 350

1.6 Spring Security3

http://lengyun3566.iteye.com

<http>

form

form
form
CASLDAP
form

web

AbstractAuthenticationProcessingFilter

form POSTSSO

Authentication

AuthenticationManager

Authentication

AuthenticationProvider

29 / 350

AuthenticationManager
AuthenticationProvider

1.6 Spring Security3

http://lengyun3566.iteye.com

o.s.s.core.Authentication
o.s.s.core.
GrantedAuthorityAuthentication
Authentication
Authentication

Object getPrincipal()

Object getCredentials()

List<GrantedAuthority>
getAuthorities()

Object getDetails()

Authenticationjava.lang.Object
Authentication
AuthenticationProviderAuthenticationManager
Spring SecurityAuthenticationManager
o.s.s.authentication.ProviderManagerAuthenticationProvider
AuthenticationProviderProviderManager

30 / 350

http://lengyun3566.iteye.com

1.6 Spring Security3

web

UsernamePasswordAuthenticationFilterUsernamePasswordAuthenticationToken
AuthenticationHttpServletRequet

spring_security_login
JBCP Petshttp://localhost:8080/
JBCPPets/spring_security_login

URLspring_security_login
DefaultLoginPageGeneratingFilter

URLSpring
SecuritySpring SecuritySpring Security

springURL
formHTMLUsernamePasswordAuthenticationFilter

<form name='f' action='/JBCPPets/j_spring_security_check'


method='POST'>
User:<input type='text' name='j_username' value=''>

31 / 350

http://lengyun3566.iteye.com

1.6 Spring Security3

Password:<input type='password' name='j_password'/>


<input name="submit" type="submit"/>
<input name="reset" type="reset"/>
</form>

form(j_usernamej_passwordformaction
j_spring_security_check
UsernamePasswordAuthenticationFilterJava EE Servlet 2.x
SRV.12.5.3formformactionj_security_check
Java EE servlet-basedservlet

servlet
UsernamePasswordAuthenticationFilter
UsernamePasswordAuthenticationFilter

UsernamePasswordAuthenticationFilter<http><form-login>
auto-config<form-login>
j_spring_security_check
UsernamePasswordAuthenticationFilterformURLSpring Security
URLURL

<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service>

32 / 350

1.6 Spring Security3

http://lengyun3566.iteye.com

<user authorities="ROLE_USER" name="guest" password="guest"/>


</user-service>
</authentication-provider>
</authentication-manager>

AuthenticationProvidersecurity
AuthenticationManager
AuthenticationProvider<authentication-provider>
o.s.s.authentication.dao.DaoAuthenticationProvider<authentication-provider>
AuthenticationProviderAuthenticationManager
AuthenticationManager
DaoAuthenticationProviderAuthenticationProvider
o.s.s.core.userdetails.UserDetailsServiceUserDetailsService
o.s.s.core.userdetails.UserDetails
UserDetailsJavadocAuthentication

Authentication

UserDetails

UserDetails

e-mail

<user-service>o.s.s.core.userdetails.memory.InMemoryDaoImpl
UserDetailsServiceXML
service

33 / 350

1.6 Spring Security3

http://lengyun3566.iteye.com

DaoAuthenticationProviderAuthenticationManager

Spring Security
JDBCJBCP Pets

Spring Securityexpected exceptions


Spring Security

o.s.s.core.AuthenticationException
AuthenticationException
<!--[if !supportLists]-->l <!--[endif]-->authenticationAuthentication
<!--[if !supportLists]-->l <!--[endif]-->extraInformation
UsernameNotFoundException

extraInformation

BadCredentialsException

UserDetails

LockedException

UserDetails

UsernameNotFoundException

GrantedAuthority

34 / 350

String

http://lengyun3566.iteye.com

1.6 Spring Security3

request
HTTPHTTP 403

35 / 350

http://lengyun3566.iteye.com

1.7 Spring Security3

1.7 Spring Security3


: 2011-06-24 : Spring, Access, Bean, Security,

Spring SecurityserveltFilterSecurityInterceptor
FilterSecurityInterceptor
Authentication
(List<GrantedAuthority>
getAuthorities()

Spring Security
access decision manager
Spring Securityo.s.s.access.AccessDecisionManager

<!--[if !supportLists]-->l <!--[endif]-->supports


AccessDecisionManager
<!--[if !supportLists]-->l <!--[endif]-->decide
AccessDecisionManagerdecide

AuthenticationException
o.s.s.access.AccessDeniedException

AccessDecisionManagerSpring bean
AccessDecisionManagerAccessDecisionVoter
36 / 350

1.7 Spring Security3

http://lengyun3566.iteye.com

voter
<!--[if !supportLists]-->l <!--[endif]-->URLIP
<!--[if !supportLists]-->l <!--[endif]-->
<!--[if !supportLists]-->l <!--[endif]-->
<!--[if !supportLists]-->l <!--[endif]-->
AccessDecisionManagerConfigAttribute
web URL
ROLE_USER

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

Spring Security
o.s.s.access.AccessDecisionVoter

Grant (ACCESS_GRANTED)

Deny (ACCESS_DENIED)

Abstain (ACCESS_ABSTAIN)

<!--[if !supportLists]-->l <!--[endif]->


<!--[if !supportLists]-->l <!--[endif]->

37 / 350

1.7 Spring Security3

http://lengyun3566.iteye.com

Spring Security
web

web

ConfigAttributeDefaultFilterInvocationSecurityMetadataSource
ConfigAttribute

access decision
Spring SecuritysecurityAccessDecisionManager<http>accessdecision-manager-refAccessDecisionManagerSpring BeanSpring Security
o.s.s.access.vote

AffirmativeBased

ConsensusBased

AccessDecisionManager

UnanimousBased

38 / 350

http://lengyun3566.iteye.com

1.7 Spring Security3

UnanimousBasedaccess decision manager


UnanimousBased
<http>access-decision-manager-ref

<http auto-config="true"
access-decision-manager-ref="unanimousBased" >

Spring Beanbeanidbean
dogstore-base.xmlid

<bean class="org.springframework.security.access.vote.UnanimousBased"
id="unanimousBased">
<property name="decisionVoters">
<list>
<ref bean="roleVoter"/>
<ref bean="authenticatedVoter"/>
</list>
</property>
</bean>
<bean class="org.springframework.security.access.vote.RoleVoter"
id="roleVoter"/>
<bean class="org.springframework.security.access.vote.
AuthenticatedVoter" id="authenticatedVoter"/>

39 / 350

http://lengyun3566.iteye.com

1.7 Spring Security3

decisionVotersAccessDecisionManager
AccessDecisionManager
security
Spring SecurityAccessDecisionVoter

o.s.s.access.
vote.RoleVoter

GrantedAuthorityaccess
GrantedAuthority

access="ROLE_USER,ROLE_ADMI

ROLE_

<!--[if !supportLists]-->l <!--[endif]->IS_AUTHENTICATED_FULLY

o.s.s.access.
vote.AuthenticatedVoter

<!--[if !supportLists]-->l <!--[endif]--

access="

>IS_AUTHENTICATED_REMEMBERED

IS_AUTHENTICATED_ANONYMO

remember me

<!--[if !supportLists]-->l <!--[endif]->IS_AUTHENTICATED_ANONYMOUSLY

40 / 350

http://lengyun3566.iteye.com

1.8 Spring Security3doc

1.8 Spring Security3doc


: 2011-06-25 : Spring, Access, Web, Security,
doc

Spring
RoleVoter
Spring SpEL <http> use-expressions

<http auto-config="true"
use-expressions="true">

access SpEL SpEL


ROLE_USER

SpEL Tapestry Object Graph Notation Language


(OGNL) JSP JSF Unified Expression Language

use-expressions SpEL
RoleVoter

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

41 / 350

http://lengyun3566.iteye.com

1.8 Spring Security3doc

SpEL hasRole

<http auto-config="true" use-expressions="true">


<intercept-url pattern="/*" access="hasRole('ROLE_USER')"/>
</http>

SpEL Voter
o.s.s.web.access.expression.WebExpressionVoter SpEL
WebExpressionVoter o.s.s.web.access.expression.WebSecurityExpressionHandler
WebSecurityExpressionHandler

o.s.s.web.access.expression.WebSecurityExpressionRoot

SpEL pseudo-property WebSecurityExpessionRoot

pseudo-property JavaBeans getters


SpEL is get isAnonymous() anonymous

Spring Security 3 SpEL web only

<intercept-url> access

Web only?

hasIpAddress

Yes

42 / 350

IP

access="hasIpAddress('

http://lengyun3566.iteye.com

1.8 Spring Security3doc

162.79.8.30')"
(ipAddress)

access="hasIpAddress('
162.0.0.0/224')"

hasRole(role)

No

GrantedAuthority
RoleVoter

hasAnyRole(role)

No

access="hasRole('ROLE

GrantedAuthority

USER')"

access="hasRole('ROLE_
USER','ROLE_ADMIN')"

SpEL

Web only?

permitAll

No

access="permitAll"

denyAll

NO

anonymous

NO

authenticated

NO

access="denyAll"

access="anonymous"

access="authenticated"

rememberMe

No

remember me

43 / 350

access="rememberMe"

http://lengyun3566.iteye.com

1.8 Spring Security3doc

fullyAuthenticated

No

access="fullyAuthenticated"

voter
hasRole Boolean SpEL Boolean
true false
Boolean
org.springframework.expression.spel.SpelException:
EL1001E:Type conversion problem, cannot convert from
class java.lang.Integer to java.lang.Boolean
SpEL

SpEL

l
l Spring Security
l Spring Security servlet
l Authentication UserDetails
l SpEL

:
Spring_Security3.zip (687.5 KB)
44 / 350

http://lengyun3566.iteye.com

1.8 Spring Security3doc

dl.iteye.com/topics/download/6bd4937f-26e3-3418-a4df-78d26c8812a5

45 / 350

http://lengyun3566.iteye.com

1.9 Spring Security3

1.9 Spring Security3


: 2011-06-29 : Spring, Security, JSP, MVC,

JBCP Pets

l Spring web MVC


l remember me
l

Spring Securitysecurity

l JBCP Pets
l
l

46 / 350

http://lengyun3566.iteye.com

1.9 Spring Security3

Spring Security

controller
Spring MVCJBCP PetsSpring
MVC
com.packtpub.springsecurity.web.controllerLoginLogoutControllercontroller

// imports omitted
@Controller
public class LoginLogoutController extends BaseController{
@RequestMapping(method=RequestMethod.GET,value="/login.do")
public void home() {
}
}

controller/login.doURL
Spring Security
BaseControllerSpring Security
controller

JSP
/login.doWEB-INF/dogstore-servlet.xmlSpring MVC view resolver/WEBINF/viewslogin.jspJSPformJSPSpring
Securityform

l Form actionUsernamePasswordAuthenticationFilteractionform
actionj_spring_security_check
l servletj_usernamej_password

47 / 350

http://lengyun3566.iteye.com

1.9 Spring Security3

JSP
JSP
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<jsp:include page="common/header.jsp">
<jsp:param name="pageTitle" value="Login"/>
</jsp:include>
<h1>Please Log In to Your Account</h1>
<p>
Please use the form below to log in to your account.
</p>
<form action="j_spring_security_check" method="post">
<label for="j_username">Login</label>:
<input id="j_username" name="j_username" size="20" maxlength="50"
type="text"/>
<br />
<label for="j_password">Password</label>:
<input id="j_password" name="j_password" size="20" maxlength="50"
type="password"/>
<br />
<input type="submit" value="Login"/>
</form>
<jsp:include page="common/footer.jsp"/>

postformUsernamePasswordAuthenticationFilter

Spring Security

http://localhost:8080/JBCPPets/login.do
Spring Securityspring_security_login
formSpring SecurityDefaultLoginPageGeneratingFilter

form

Spring SecuritySpring MVC


Spring Security<form-login>login-page

48 / 350

http://lengyun3566.iteye.com

1.9 Spring Security3

<http auto-config="true" use-expressions="true">


<intercept-url pattern="/*" access="hasRole('ROLE_USER')"/>
<form-login login-page="/login.do" />
</http>

http://localhost:8080/JBCPPets/home.doIE
Mozilla Firefox
Firefox

URL
<intercept-url pattern="/*" access="hasRole('ROLE_USER')"/>

/*URLROLE_USER

URLSpring SecurityURL

<intercept-url pattern="/login.do" access="permitAll"/>


<intercept-url pattern="/*" access="hasRole('ROLE_USER')"/>

49 / 350

http://lengyun3566.iteye.com

1.10 Spring Security3

1.10 Spring Security3


: 2011-07-04 : Spring Security, ,

Logoutsession
Log Out

Log Out
Spring SecurityURLURL
URL/j_spring_security_logoutheader.jsp
ahref

<c:url value="/j_spring_security_logout" var="logoutUrl"/>


<li><a href="${logoutUrl}">Log Out</a></li>

Log Outform

JSTL URLURLJSTLurlURLweb
urlURL/
JSP(<%= request.getContextPath() %>)JSTLurl

50 / 350

http://lengyun3566.iteye.com

1.10 Spring Security3

URLservletSpring Security
/j_spring_security_logoutURLJSPJSPSpring MVC
URLURL

/j_spring_security_logoutURLo.s.s.web.authentication.logout.LogoutFilter
Spring SecurityLogoutFilterURL

Spring Securitysecurity

<http auto-config="true" use-expressions="true">


<logout invalidate-session="true"
logout-success-url="/"
logout-url="/j_spring_security_logout"/>
</http>

logout-urlURL

1.

HTTP sessioninvalidate-sessiontrue

2.

SecurityContex

3.

logout-success-urlURL

o.s.s.web.authentication.logout.LogoutHandlerLogoutFilter
LogoutHandlerLogoutFilter
LogoutFilterLogoutHandlersessionremember mesession
o.s.s.web.
51 / 350

http://lengyun3566.iteye.com

1.10 Spring Security3

authentication.logout.LogoutSuccessHandlerURL
URL/
session

logout URL
logout URLlogout URL
/logout
dogstore-security.xml<logout>

<http auto-config="true" use-expressions="true">


...
..<logout invalidate-session="true"
logout-success-url="/"
logout-url="/logout"/>
</http>

/common/header.jsplogoutherfURL:

<c:url value="/logout" var="logoutUrl"/>


<li><a href="${logoutUrl}">Log Out</a></li>

52 / 350

http://lengyun3566.iteye.com

1.10 Spring Security3

/logout URL/j_spring_security_logout
/j_spring_security_logoutPage not Found(404)
URLservlet

Logout
<logout>

invalidate-

trueHTTP session

session

logout-success-

URL/

url

HttpServletResponse.redirect

logout-url

successhandler-ref

53 / 350

LogoutFilterURL

LogoutSuccessHandler

http://lengyun3566.iteye.com

1.11 Spring Security3Remember me

1.11 Spring Security3Remember me


: 2011-07-04 : Java, Spring Security, , remember me

Remember me
remember me
cookieSpring Security
remember me cookie

remember mesecurity

remember me
pet store

dogstore-security.xml<remember-me>keyjbcpPetStore

<http auto-config="true" use-expressions="true" access-decisionmanager-ref="affirmativeBased">

<remember-me key="jbcpPetStore"/>
<logout invalidate-session="true" logout-success-url="/" logout-url="/logout"/>
</http>

form
login.jspcheckbox

54 / 350

http://lengyun3566.iteye.com

1.11 Spring Security3Remember me

<input id="j_username" name="j_username" size="20" maxlength="50" type="text"/>


<br />
<input id="_spring_security_remember_me" name="_spring_security_
remember_me" type="checkbox" value="true"/>
<label for="_spring_security_remember_me">Remember Me?</label>
<br />
<label for="j_password">Password</label>:

Remember MeRemember Mecookie


JBCP Pets
Remember Me

Firecookiehttp://www.
softwareishard.com/blog/firecookie/session

Remember me
Remember mecookieBase64
l
l /
l MD5/
l key<remember-me>key
cookie

55 / 350

http://lengyun3566.iteye.com

1.11 Spring Security3Remember me

MD5
hash

MD5
encryption algorithms
fingerprint,

MD5
rainbow table attacks
hash

remember mecookiecookie
cookieremember me

Cookiecookie
cookiecookie

remember me cookie
o.s.s.web.authentication.rememberme.RememberMeAuthenticationFiltercookie
remember me cookieRemember me
<remember-me>

remember me cookie

56 / 350

http://lengyun3566.iteye.com

1.11 Spring Security3Remember me

RememberMeAuthenticationFilterSecurityContextHolderAwareRequestFilter
AnonymousProcessingFilterRememberMeAuthenticationFilter
request
remember me cookie
remember meBase64MD5cookie
MD5cookie
cookie

remember me token
remember me

RememberMeAuthenticationFiltero.s.s.web.authentication.RememberMeServices
cookierequest_spring_security_remember_me form
formcookieBase64
MD5

remember me
remember me

Remember me
RememberMeServicessession
remember meremember me service

57 / 350

http://lengyun3566.iteye.com

1.11 Spring Security3Remember me

remember me cookieform

cookie

cookie

RememberMeServices
RememberMeServices

Remember me
remember me

Key

remember mecookiekey

tokenvalidityseconds

Remember mecookie
cookie

cookieKeyremember me
key

keyremember me
key36googleonline
password generator
remember me key

58 / 350

http://lengyun3566.iteye.com

1.11 Spring Security3Remember me

remember me cookie
remember me cookie

key
jbcpPets-rmkey-paLLwApsifs24THosE62scabWow78PEaCh99Jus

token-validity-secondsremember me tokentoken
cookie

remember mecookietoken-validity-seconds-1cookie
cookieToken2
cookiesession IDcookie

remember me

59 / 350

http://lengyun3566.iteye.com

1.12 Spring Security3Remember me

1.12 Spring Security3Remember me


: 2011-07-08 : Spring Security, java, ,

Remember me

Remember mecookie

SSL
XSSremembered user session
remembered session

XSSOWASP Top
Tenhttp://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
web

SpELfullyAuthenticatedSpEL

Remember me
session
remembered

60 / 350

http://lengyun3566.iteye.com

1.12 Spring Security3Remember me

remembered sessionwish list

remembered

<intercept-url
pattern="/login.do" access="permitAll"/>
<intercept-url pattern="/account/*.do"
access="hasRole('ROLE_USER') and fullyAuthenticated"/>
<intercept-url pattern="/*" access="hasRole('ROLE_USER')"/>

ROLE_USERGrantedAuthority
ROLE_USERsession
SpELSpELandornot
SpEL&&XML

remember meMy Account


403
AccessDeniedHandlerAccessDeniedException
AccessDeniedException

SpEL
IS_AUTHENTICATED_FULLYaccess="
IS_AUTHENTICATED_FULLY"SpEL
boolean

remember me

61 / 350

http://lengyun3566.iteye.com

1.12 Spring Security3Remember me

IPRemember me Service
remember meIPcookie
RememberMeServices

o.s.s.web.authentication.rememberme.TokenBasedRememberMeServices
IPcookieMD5

HttpServletRequestIPThreadLocal
HttpServletRequest
TokenBasedRememberMeServices

TokenBasedRememberMeServices

com.packtpub.springsecurity.security

public class IPTokenBasedRememberMeServices extends


TokenBasedRememberMeServices {

ThreadLocal HttpServletRequest

private static final ThreadLocal<HttpServletRequest> requestHolder =


new ThreadLocal<HttpServletRequest>();
public HttpServletRequest getContext() {
return requestHolder.get();
}
public void setContext(HttpServletRequest context) {

62 / 350

http://lengyun3566.iteye.com

1.12 Spring Security3Remember me

requestHolder.set(context);
}

HttpServletRequestIP

protected String getUserIPAddress(HttpServletRequest request) {


return request.getRemoteAddr();
}

onLoginSuccessremember mecookie
ThreadLocal
cookie

@Override
public void onLoginSuccess(HttpServletRequest request,
HttpServletResponse response,
Authentication successfulAuthentication) {
try
{
setContext(request);
super.onLoginSuccess(request, response, successfulAuthentication
}
finally
{

setContext(null);

}
}

onLoginSuccessmakeTokenSignatureMD5
requestIPSpringcookie
remember mecookieIP
MD5

63 / 350

http://lengyun3566.iteye.com

1.12 Spring Security3Remember me

@Override
protected String makeTokenSignature(long tokenExpiryTime,
String username, String password) {
return DigestUtils.md5DigestAsHex((username + ":" +
tokenExpiryTime + ":" + password + ":" + getKey() + ":" + getUserIPAdd
ress(getContext())).getBytes());
}

setCookieIP

@Override
protected void setCookie(String[] tokens, int maxAge,
HttpServletRequest request, HttpServletResponse response) {
// append the IP adddress to the cookie
String[] tokensWithIPAddress =
Arrays.copyOf(tokens, tokens.length+1);
tokensWithIPAddress[tokensWithIPAddress.length-1] =
getUserIPAddress(request);
super.setCookie(tokensWithIPAddress, maxAge,
request, response);
}

cookie

processAutoLoginCookieremember me cookie

IP

@Override
protected UserDetails processAutoLoginCookie(
String[] cookieTokens,

64 / 350

http://lengyun3566.iteye.com

1.12 Spring Security3Remember me

HttpServletRequest request, HttpServletResponse response)


{
try
{
setContext(request);
// take off the last token
String ipAddressToken = cookieTokens[cookieTokens.length-1];
if(!getUserIPAddress(request).equals(ipAddressToken))
{
throw new InvalidCookieException("Cookie IP Address did not
contain a matching IP (contained '" + ipAddressToken + "')");
}

return super.processAutoLoginCookie(Arrays.copyOf(cookieTokens,
cookieTokens.length-1), request, response);
}
finally
{
setContext(null);
}
}

RememberMeServices

RememberMeServices

RememberMeServicesdogstore-base.xml Spring
Spring Bean

<bean class="com.packtpub.springsecurity.security.IPTokenBasedRememberMeServices" id="ipTokenBasedR


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

65 / 350

http://lengyun3566.iteye.com

1.12 Spring Security3Remember me

<property name="userDetailsService" ref="userService"/>


</bean>

Spring SecurityXML<remember-me>Spring
Bean

<remember-me key="jbcpPetStore"
services-ref="ipTokenBasedRememberMeServicesBean"/>

<user-service>id

<user-service

id="userService">

webIP

remember me cookieBase64Base64cookie

SPRING_SECURITY_REMEMBER_ME_COOKIEcookie

guest:1251695034322:776f8ad44034f77d13218a5c431b7b34:127.0.0.1

IPcookieIP
MD5

remember me cookieremember mecookie


Spring Securitycookie
Mozilla FirefoxChris Pederick's Web Developerhttp://chrispederick.com/work/webdeveloper/cookie
cookieBase64cookie
=Base64
66 / 350

http://lengyun3566.iteye.com

1.12 Spring Security3Remember me

multi-WANIPremember me tokens
IPremember me

Remember me
remember me formcheckbox_spring_security_remember_mecookie
SPRING_SECURITY_REMEMBER_ME_COOKIE<remember-me>
Spring BeanRememberMeServices
checkboxcookie

<bean class="com.packtpub.springsecurity.web.custom.
IPTokenBasedRememberMeServices" id="ipTokenBasedRememberMeServicesBean">
<property name="key"><value>jbcpPetStore</value></property>
<property name="userDetailsService" ref="userService"/>
<property name="parameter" value="_remember_me"/>
<property name="cookieName" value="REMEMBER_ME"/>
</bean>

login.jspcheckbox formparameter

Spring Security

67 / 350

http://lengyun3566.iteye.com

1.13 Spring Security3

1.13 Spring Security3


: 2011-07-09 : Java, , Spring Security,

UserDetailsService
o.s.s.core.userdetails.memory.InMemoryDaoImpl

Spring SecurityInMemoryDaoImplmap
UserDetailsInMemoryDaoImplUserDetailso.s.s.core.userdetails.User
Spring Security API

InMemoryChangePasswordDaoImplInMemoryDaoImpl
InMemoryDaoImpl
copyUser

package com.packtpub.springsecurity.security;
// imports omitted
public interface IChangePassword extends UserDetailsService {
void changePassword(String username, String password);
}

68 / 350

http://lengyun3566.iteye.com

1.13 Spring Security3

package com.packtpub.springsecurity.security;
public class InMemoryChangePasswordDaoImpl extends InMemoryDaoImpl
implements IChangePassword {
@Override
public void changePassword(String username,
String password) {
// get the UserDetails
User userDetails =
(User) getUserMap().getUser(username);
// create a new UserDetails with the new password
User newUserDetails =
new User(userDetails.getUsername(),password,
userDetails.isEnabled(),
userDetails.isAccountNonExpired(),
userDetails.isCredentialsNonExpired(),
userDetails.isAccountNonLocked(),
userDetails.getAuthorities());
// add to the map
getUserMap().addUser(newUserDetails);
}
}

UserDetailsServicepet store

Spring SecurityInMemoryChangePasswordDaoImpl
Spring SecurityXMLUserDetailsService
<user-service>Spring Security
bean<user-service>

<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service id="userService">
<user authorities="ROLE_USER" name="guest" password="guest"/>
</user-service>
69 / 350

http://lengyun3566.iteye.com

1.13 Spring Security3

</authentication-provider>
</authentication-manager>

<authentication-provider user-service-ref="userService"/>

user-service-refiduserServiceSpring Beandogstorebase.xml Spring Beansbean

<bean id="userService" class="com.packtpub.springsecurity.security.


InMemoryChangePasswordDaoImpl">
<property name="userProperties">
<props>
<prop key="guest">guest,ROLE_USER</prop>
</props>
</property>
</bean>

<user-service><user><user>
InMemoryDaoImplUserDetailsService

Spring Security 36.2


UserDetailsServiceUserDetailsService

UserDetailsServiceGrantedAuthority

JBCP Pets
UI

70 / 350

http://lengyun3566.iteye.com

1.13 Spring Security3

My Account/account/home.jsp

<p>
Please find account functions below...
</p>
<ul>
<li><a href="changePassword.do">Change Password</a></li>
</ul>

/account/ changePassword.jspChange Password

<?xml version="1.0" encoding="ISO-8859-1" ?>


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<jsp:include page="../common/header.jsp">
<jsp:param name="pageTitle" value="Change Password"/>
</jsp:include>
<h1>Change Password</h1>
<form method="post">
<label for="password">New Password</label>:
<input id="password" name="password" size="20" maxlength="50"
type="password"/>
<br />
<input type="submit" value="Change Password"/>
</form>
<jsp:include page="../common/footer.jsp"/>

71 / 350

http://lengyun3566.iteye.com

1.13 Spring Security3

Spring MVCAccountController
AccountController

AccountController
UserDetailsService
com.packtpub.springsecurity.web.controller.AccountController
Spring@Autowired

@Autowired
private IChangePassword changePasswordDao;

formPOSTform

@RequestMapping(value="/account/changePassword.
do",method=RequestMethod.GET)
public void showChangePasswordPage() {
}
@RequestMapping(value="/account/changePassword.
do",method=RequestMethod.POST)
public String submitChangePasswordPage(@RequestParam("password")
String newPassword) {
Object principal = SecurityContextHolder.getContext().
getAuthentication().getPrincipal();
String username = principal.toString();
if (principal instanceof UserDetails) {
username = ((UserDetails)principal).getUsername();
}
changePasswordDao.changePassword(username, newPassword);
SecurityContextHolder.clearContext();
return "redirect:home.do";
}

72 / 350

http://lengyun3566.iteye.com

1.13 Spring Security3

My AccountChange Password

form

l
l remember me

SecurityContextHolder.clearContext()
SecurityContext

JBCP Pet Store

l Spring MVC
l Spring Security
l remember me
l IPremember me
l
l UserDetailsServiceInMemoryDaoImpl

73 / 350

http://lengyun3566.iteye.com

1.14 Spring Security3

1.14 Spring Security3


: 2011-07-17 : Java, , Spring Security,


JBCP Pets
remember me

Spring SecurityschemaJDBC

l Spring SecurityJDBC
l HSQLDBJDBC
l Spring SecurityJDBCschema
l
l
l salting
l remember me tokentoken
l SSL/TLS

74 / 350

http://lengyun3566.iteye.com

1.14 Spring Security3

Spring Security
JBCP Pets
JBCP
PetsSpring Security
JDBCSpring
Security

JavaHyperSQL DBHSQLSpring
SecurityschemaSpring SecurityHSQL

HSQL

Spring Securityschema
SQLsecurity-schema.sqlSpring SecurityHSQL
schemaSQL
classpathWEB-INF/classes

HSQL
HSQLdogstore-security.xmlSQL
Spring Securityjdbc XML

<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
75 / 350

http://lengyun3566.iteye.com

1.14 Spring Security3

http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/
spring-security3.0.xsd"
>

<embedded-database>SQL

<jdbc:embedded-database id="dataSource" type="HSQL">


<jdbc:script location="classpath:security-schema.sql"/>
</jdbc:embedded-database>

HSQL<embedded-database>

JdbcDaoImpl
dogstore-security.xmlJDBCUserDetailsService
Spring SecuritySpring SecurityUserDetailsService
<authentication-manager>

<authentication-manager alias="authenticationManager">
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"/>
</authentication-provider>
</authentication-manager>

data-source-ref<embedded-database>bean

schema
SQLSQL
adminguestGrantedAuthority
test-data.sqlsecurity-schema.sqlWEB-INF/classes

76 / 350

http://lengyun3566.iteye.com

1.14 Spring Security3

insert into users(username, password, enabled) values


('admin','admin',true);
insert into authorities(username,authority) values
('admin','ROLE_USER');
insert into authorities(username,authority) values
('admin','ROLE_ADMIN');
insert into users(username, password, enabled) values
('guest','guest',true);
insert into authorities(username,authority) values
('guest','ROLE_USER');
commit;

SQL

<jdbc:embedded-database id="dataSource" type="HSQL">


<jdbc:script location="classpath:security-schema.sql"/>
<jdbc:script location="classpath:test-data.sql"/>
</jdbc:embedded-database>

SQLSpring Security
GrantedAuthority

AuthenticationManagerAuthenticationProvider
AuthenticationProvider
DaoAuthenticationProviderproviderUserDetailsService

77 / 350

http://lengyun3566.iteye.com

1.14 Spring Security3

UserDetailsService
o.s.s.core.userdetails.jdbc.JdbcDaoImplUserDetailsServiceSpring
SecurityJdbcDaoImpl

Spring Security<jdbc-userservice>JdbcDaoImplAuthenticationProvider
Spring SecurityJdbcDaoImpl
InMemoryDaoImpl
JdbcDaoImpl

78 / 350

http://lengyun3566.iteye.com

1.15 Spring Security3


UserDetailsService

1.15 Spring Security3


UserDetailsService
: 2011-07-19 : Java, , Spring Security,

JDBC UserDetailsService

JdbcDaoImpl

JDBC UserDetailsService
com.packtpub.springsecurity.security

public class CustomJdbcDaoImpl extends JdbcDaoImpl implements


IChangePassword {
public void changePassword(String username, String password) {
getJdbcTemplate()
update("UPDATE USERS SET PASSWORD = ? WHERE USERNAME = ?",
password, username);
}
}

JdbcDaoImpl
Spring JDBC

JDBC UserDetailsServiceSpring bean


dogstore-base.xmlSpring Bean

<bean id="jdbcUserService"
class="com.packtpub.springsecurity.security.CustomJdbcDaoImpl">

79 / 350

http://lengyun3566.iteye.com

1.15 Spring Security3


UserDetailsService

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


</bean>

dataSource Bean<embedded-database>HSQL

UserDetailsService
UserDetailsServiceSpring Security
JDBC

JdbcDaoImpl
online store

JDBCSpring Security

o.s.s.provisioning.JdbcUserDetailsManagerJdbcDaoImpl
o.s.s.provisioning.UserDetailsManager

UserDetails
void createUser(UserDetails user)

GrantedAuthority

void updateUser(final UserDetails


user)

80 / 350

UserDetails
GrantedAuthority

1.15 Spring Security3


UserDetailsService

http://lengyun3566.iteye.com

void deleteUser(String username)

boolean userExists(String username)

void changePassword(String
oldPassword, String newPassword)

JdbcUserDetailsManagerchangePasswordCustomJdbcDaoImpl
CustomJdbcDaoImpl
JdbcUserDetailsManager

dogstore-base.xmlJdbcUserDetailsManager bean

<bean id="jdbcUserService"
class="org.springframework.security
.provisioning.JdbcUserDetailsManager">
<property name="dataSource" ref="dataSource"/>
<property name="authenticationManager"
ref="authenticationManager"/>
</bean>

AuthenticationManagerdogstore-security.xml<authenticationmanager>aliasCustomJdbcDaoImpl

changePassword.jsp

81 / 350

http://lengyun3566.iteye.com

1.15 Spring Security3


UserDetailsService

<h1>Change Password</h1>
<form method="post">
<label for="oldpassword">Old Password</label>:
<input id="oldpassword" name="oldpassword"
size="20" maxlength="50" type="password"/>
<br />
<label for="password">New Password</label>:
<input id="password" name="password" size="20"
maxlength="50" type="password"/>
<br />

AccountController@AutowiredIChangePassword

@Autowired
private UserDetailsManager userDetailsManager;

submitChangePasswordPage
JdbcUserDetailsManager

public String submitChangePasswordPage(@RequestParam("oldpassword")


String oldPassword,
@RequestParam("password") String newPassword) {
userDetailsManager.changePassword(oldPassword, newPassword);
SecurityContextHolder.clearContext();
return "redirect:home.do";
}

82 / 350

http://lengyun3566.iteye.com

1.15 Spring Security3


UserDetailsService

JdbcUserDetailsManagerJSP

83 / 350

http://lengyun3566.iteye.com 1.16 Spring Security3JdbcDaoImpl

1.16 Spring Security3JdbcDaoImpl


: 2011-07-25 : Java, , Spring Security,

JdbcDaoImpl
JdbcDaoImplschema
UserDetailsService

UserGrantedAuthoritya level of
indirectionGrantedAuthoritygroup
GrantedAuthority

GrantedAuthority

l
l

84 / 350

http://lengyun3566.iteye.com 1.16 Spring Security3JdbcDaoImpl

GroupBased Access Control GBAC


Active
DirectoryAD)GBACADGBAC
AD

JBCP Pets

Users
AdministratorsSQLguestadmin

JdbcDaoImpl
JdbcDaoImpl
dogstore-base.xmlbean

<bean id="jdbcUserService"
class="com.packtpub.springsecurity.security.CustomJdbcDaoImpl">
<property name="dataSource" ref="dataSource"/>
<property name="enableGroups" value="true"/>
<property name="enableAuthorities" value="false"/>
</bean>

JdbcUserManager
CustomJdbcDaoImpl

SQL
SQL
l
85 / 350

http://lengyun3566.iteye.com 1.16 Spring Security3JdbcDaoImpl

l GrantedAuthority
l

test-users-groups-data.sqlSQL

insert into groups(group_name) values ('Users');


insert into groups(group_name) values ('Administrators');

insert into group_authorities(group_id, authority) select id,'ROLE_


USER' from groups where group_name='Users';
insert into group_authorities(group_id, authority) select id,'ROLE_
USER' from groups where group_name='Administrators';
insert into group_authorities(group_id, authority) select id,'ROLE_
ADMIN' from groups where group_name='Administrators';

insert into users(username, password, enabled) values


('admin','admin',true);
insert into users(username, password, enabled) values
('guest','guest',true);

86 / 350

http://lengyun3566.iteye.com 1.16 Spring Security3JdbcDaoImpl

insert into group_members(group_id, username) select id,'guest' from


groups where group_name='Users';
insert into group_members(group_id, username) select id,'admin' from
groups where group_name='Administrators';

HSQLtest-data.sql

<jdbc:embedded-database id="dataSource" type="HSQL">


<jdbc:script location="classpath:security-schema.sql"/>
<jdbc:script location="classpath:test-users-groups-data.sql"/>
</jdbc:embedded-database>

security-schema.sql

JBCP Pets

JBCP Pets
schame

Spring Securityschema
Spring SecurityschemaJdbcDaoImpl
schemaSpring Security

JdbcDaoImplschemaJBCP PetsSpring
Security

87 / 350

http://lengyun3566.iteye.com 1.16 Spring Security3JdbcDaoImpl

JDBC SQL
JdbcDaoImplSQL
SQLJdbcDaoImplSQL

usersByUsernameQuery

authoritiesByUsernameQuery

GBAC

SQL

Username (string)
Password (string)
Enabled (Boolean)

Username (string)
Granted Authority
(string)

Group Primary Key

groupAuthoritiesByUsernameQuery

GBAC

(any)
Group Name (any)
Granted Authority
(string)

JdbcDaoImpl

JdbcDaoImplSQL
SQLSpring BeanJdbcDaoImpl
JdbcDaoImplJDBC<jdbc-user-service>
beanJdbcDaoImpl

88 / 350

http://lengyun3566.iteye.com 1.16 Spring Security3JdbcDaoImpl

<bean id="jdbcUserService"
class="com.packtpub.springsecurity.security.CustomJdbcDaoImpl">
<property name="dataSource" ref="dataSource"/>
<property name="enableGroups" value="true"/>
<property name="enableAuthorities" value="false"/>
<property name="usersByUsernameQuery">
<value>SELECT LOGIN, PASSWORD,
1 FROM USER_INFO WHERE LOGIN = ?
</value>
</property>
<property name="groupAuthoritiesByUsernameQuery">
<value>SELECT G.GROUP_ID, G.GROUP_NAME, P.NAME
FROM USER_INFO U
JOIN USER_GROUP UG on U.USER_INFO_ID = UG.USER_INFO_ID
JOIN GROUP G ON UG.GROUP_ID = G.GROUP_ID
JOIN GROUP_PERMISSION GP ON G.GROUP_ID = GP.GROUP_ID
JOIN PERMISSION P ON GP.PERMISSION_ID = P.PERMISSION_ID
WHERE U.LOGIN = ?
</value>
</property>
</bean>

Spring Securityschema
schemaJdbcDaoImpl

JdbcUserDetailsManager20SQL
JavadocJdbcUserDetailsManager

89 / 350

http://lengyun3566.iteye.com

1.17 Spring Security3

1.17 Spring Security3


: 2011-07-31 : java, Spring Security, ,

l
l
l

ID
email

16
XXXX XXXX XXXX 1234

SQLHSQL
HSQL
bootstrapSQLJava

90 / 350

1.17 Spring Security3

http://lengyun3566.iteye.com

JBCP PetsSQLJava

Spring Securityo.s.s.authentication.encoding.PasswordEncoder
<authentication-provider><password-encoder>

<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="jdbcUserService">
<password-encoder hash="sha"/>
</authentication-provider>
</authentication-manager>

Spring SecurityPasswordEncoder
<password-encoder>hash
o.s.s.authentication.
Encoding

hash

PlaintextPasswordEncoder

DaoAuthenticationProvider

plaintext

PasswordEncoderMD4 hashMD4
Md4PasswordEncoder

md4

Md5PasswordEncoder

91 / 350

PasswordEncoderMD5

md5

1.17 Spring Security3

http://lengyun3566.iteye.com

ShaPasswordEncoder

PasswordEncoderSHA

LDAPLDAP
LdapShaPasswordEncoder

SHALDAP SSHA
LDAPLDAP

sha
sha-256

{sha}
{ssha}

Spring SecurityPasswordEncoder
PasswordEncoderbeanJBCP Petsbean

JBCP Pet

SQL
DaoAuthenticationProviderPasswordEncoder

PasswordEncoder
Spring beanPasswordEncoder

<bean class="org.springframework.security.authentication.
encoding.ShaPasswordEncoder" id="passwordEncoder"/>

SHA-1PasswordEncoder

AuthenticationProvider
DaoAuthenticationProviderPasswordEncoder
<password-encoder>beanID

92 / 350

1.17 Spring Security3

http://lengyun3566.iteye.com

<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="jdbcUserService">
<password-encoder ref="passwordEncoder"/>
</authentication-provider>
</authentication-manager>

test-users-groups-data.sqljava

SQLSpring beanembeddeddatabase beanbean


com.packtpub.springsecurity.security.DatabasePasswordSecurerBean

public class DatabasePasswordSecurerBean extends JdbcDaoSupport {


@Autowired
private PasswordEncoder passwordEncoder;

public void secureDatabase() {


getJdbcTemplate().query("select username, password from users",
new RowCallbackHandler(){
@Override
public void processRow(ResultSet rs) throws SQLException {
String username = rs.getString(1);
String password = rs.getString(2);
String encodedPassword =
passwordEncoder.encodePassword(password, null);
getJdbcTemplate().update("update users set password = ?
where username = ?", encodedPassword,username);
logger.debug("Updating password for username:
"+username+" to: "+encodedPassword);
}
});

93 / 350

http://lengyun3566.iteye.com

1.17 Spring Security3

}
}

JdbcTemplatePasswordEncoder

Spring beanweb<embedded-database>
Spring beanDatabasePasswordSecurerBean

<bean class="com.packtpub.springsecurity.security.
DatabasePasswordSecurerBean"
init-method="secureDatabase" depends-on="dataSource">
<property name="dataSource" ref="dataSource"/>
</bean>

JBCP Pets

94 / 350

http://lengyun3566.iteye.com

1.18 Spring Security3salt

1.18 Spring Security3salt


: 2011-08-05 : Java, Spring Security, ,

salt

adminguest

admin

admin

7b2e9f54cdff413fcde01f330af6896c3cd7e6cd

guest

guest

2ac15cab107096305d0274cd4eb86c74bb35a4b4

admin

fakeadmin

admin

7b2e9f54cdff413fcde01f330af6896c3cd7e6cd

fakeadminadmin
admin

passwordSHA-1password

95 / 350

http://lengyun3566.iteye.com

1.18 Spring Security3salt

salt
Salt
salt

salt
l
l twoway encrypte
salt

saltsalt
salt
Spring Securityo.s.s.authentication.dao.SaltSource
UserDetailssalt
l SystemWideSaltSourcesaltsalt

l ReflectionSaltSourceUserDetailsbeansalt
saltReflectionSaltSource

salted

96 / 350

http://lengyun3566.iteye.com

1.18 Spring Security3salt

salted
DaoAuthenticationProvidersalted

ReflectionSaltSourcesalt

SaltSource Spring bean


dogstore-base.xmlSaltSourcebean

<bean class="org.springframework.security.authentication.dao.ReflectionSaltSource" id="saltSource">


<property name="userPropertyToUse" value="username"/>
</bean>

salt sourceusername
salt

SaltSourcePasswordEncoder
SaltSourcePasswordEncoder
salteddogstore-security.xml

<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="jdbcUserService">
<password-encoder ref="passwordEncoder">
<salt-source ref="saltSource"/>
</password-encoder>
</authentication-provider>
</authentication-manager>

SaltSource

97 / 350

1.18 Spring Security3salt

http://lengyun3566.iteye.com

DatabasePasswordSecurerBean
UserDetailsServiceDatabasePasswordSecurerBeanbean
SaltSourcesalt

public class DatabasePasswordSecurerBean extends JdbcDaoSupport {


@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private SaltSource saltSource;
@Autowired
private UserDetailsService userDetailsService;

public void secureDatabase() {


getJdbcTemplate().query("select username, password from users",
new RowCallbackHandler(){
@Override
public void processRow(ResultSet rs) throws SQLException {
String username = rs.getString(1);
String password = rs.getString(2);
UserDetails user =
userDetailsService.loadUserByUsername(username);
String encodedPassword =
passwordEncoder.encodePassword(password,
saltSource.getSalt(user));
getJdbcTemplate().update("update users set password = ?
where username = ?",
encodedPassword,
username);
logger.debug("Updating password for username:
"+username+" to: "+encodedPassword);
}
});
}
}

98 / 350

http://lengyun3566.iteye.com

1.18 Spring Security3salt

SaltSourceUserDetailssaltUserDetails
UserDetailsServiceCustomJdbcDaoImplSQL
UserDetails
admin
salt

salt

CustomJdbcDaoImpl
beanchangePassword

public class CustomJdbcDaoImpl extends JdbcDaoImpl {


@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private SaltSource saltSource;
public void changePassword(String username, String password) {
UserDetails user = loadUserByUsername(username);
String encodedPassword = passwordEncoder.encodePassword
(password, saltSource.getSalt(user));
getJdbcTemplate().update(
"UPDATE USERS SET PASSWORD = ? WHERE USERNAME = ?",
encodedPassword, username);
}

PasswordEncoderSaltSourcesalt
JdbcUserDetailsManagerPasswordEncoderSaltSource
JdbcUserDetailsManager

salt source
saltsaltusername
usernamesalt
99 / 350

http://lengyun3566.iteye.com

1.18 Spring Security3salt

salt

UserDetails
UserDetailssalt

scheama
saltSpring Securityschema
security-schema.sql

create table users(


username varchar_ignorecase(50) not null primary key,
password varchar_ignorecase(50) not null,
enabled boolean not null,
salt varchar_ignorecase(25) not null
);

salttest-users-groups-data.sql

insert into users(username, password, enabled, salt) values ('admin','


admin',true,CAST(RAND()*1000000000 AS varchar));
insert into users(username, password, enabled, salt) values ('guest','
guest',true,CAST(RAND()*1000000000 AS varchar));

insertsalt
salt

CustomJdbcDaoImpl UserDetails service

saltdogstore-security.xmlCustomJdbcDaoImpl

100 / 350

http://lengyun3566.iteye.com

1.18 Spring Security3salt

<beans:bean id="jdbcUserService"
class="com.packtpub.springsecurity.security.CustomJdbcDaoImpl">
<beans:property name="dataSource" ref="dataSource"/>
<beans:property name="enableGroups" value="true"/>
<beans:property name="enableAuthorities" value="false"/>
<beans:property name="usersByUsernameQuery">
<beans:value>select username,password,enabled,
salt from users where username = ?
</beans:value>
</beans:property>
</beans:bean>

UserDetails
UserDetailssalt
SpringUsersaltgettersetter
ReflectionSaltSourcesalter

package com.packtpub.springsecurity.security;
// imports
public class SaltedUser extends User {
private String salt;
public SaltedUser(String username, String password,
boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired,
boolean accountNonLocked, List<GrantedAuthority>
authorities, String salt) {
super(username, password, enabled,
accountNonExpired, credentialsNonExpired,
accountNonLocked, authorities);
this.salt = salt;
}

101 / 350

http://lengyun3566.iteye.com

1.18 Spring Security3salt

public String getSalt() {


return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
}

UserDetailssalt
UserDetailsAuthenticationProvider

CustomJdbcDaoImpl
JdbcDaoImplUserDetailsUser
UserUserUserDetailsService

public class CustomJdbcDaoImpl extends JdbcDaoImpl {


public void changePassword(String username, String password) {
getJdbcTemplate().update(
"UPDATE USERS SET PASSWORD = ? WHERE USERNAME = ?"
password, username);
}
@Override
protected UserDetails createUserDetails(String username,
UserDetails userFromUserQuery,
List<GrantedAuthority> combinedAuthorities) {
String returnUsername = userFromUserQuery.getUsername();
if (!isUsernameBasedPrimaryKey()) {
returnUsername = username;
}
return new SaltedUser(returnUsername,
userFromUserQuery.getPassword(),userFromUserQuery.isEnabled(),
true, true, true, combinedAuthorities,

102 / 350

1.18 Spring Security3salt

http://lengyun3566.iteye.com

((SaltedUser) userFromUserQuery).getSalt());
}
@Override
protected List<UserDetails> loadUsersByUsername(String username) {
return getJdbcTemplate().
query(getUsersByUsernameQuery(),
new String[] {username},
new RowMapper<UserDetails>() {
public UserDetails mapRow(ResultSet rs, int rowNum)
throws SQLException {
String username = rs.getString(1);
String password = rs.getString(2);
boolean enabled = rs.getBoolean(3);
String salt = rs.getString(4);
return new SaltedUser(username, password,
enabled, true, true, true,
AuthorityUtils.NO_AUTHORITIES, salt);
}
});
}
}

createUserDetailsloadUsersByUsername
salt

UserDetails
UserDetailsJBCP Pets

103 / 350

http://lengyun3566.iteye.com

1.19 Spring Security3Remember me


SSLdoc

1.19 Spring Security3Remember me


SSLdoc
: 2011-08-05

Remember me
remember mesession
JBCP Pets
Spring Securityrememberme token
o.s.s.web.authentication.rememberme.PersistentTokenRepositoryJDBC

remember me tokens
remember meSpring Security<rememberme>data-source-refRememberMeServices

SQLremember me schema

schemaSQLclasspathWEB-INF/classesSQL
SQLremember-me-schema.sql

create table persistent_logins (


username varchar_ignorecase(50) not null,
series varchar(64) primary key,
token varchar(64) not null,
last_used timestamp not null);

SQL

dogstore-security.xml<embedded-database>SQL

104 / 350

http://lengyun3566.iteye.com

1.19 Spring Security3Remember me


SSLdoc

<jdbc:embedded-database id="dataSource" type="HSQL">


<jdbc:script location="classpath:security-schema.sql"/>
<jdbc:script location="classpath:remember-me-schema.sql"/>
<jdbc:script location="classpath:test-users-groups-data.sql"/>
</jdbc:embedded-database>

remember me

<remember-me>data source

<http auto-config="true" use-expressions="true"


access-decision-manager-ref="affirmativeBased">
<intercept-url pattern="/login.do" access="permitAll"/>
<intercept-url pattern="/account/*.do"
access="hasRole('ROLE_USER') and fullyAuthenticated"/>
<intercept-url pattern="/*" access="hasRole('ROLE_USER')"/>
<form-login login-page="/login.do" />
<remember-me key="jbcpPetStore" token-validity-seconds="3600"
data-source-ref="dataSource"/>
<logout invalidate-session="true" logout-success-url=""
logout-url="/logout"/>
</http>
remember me cookie

tokens
TokenBasedRememberMeServicesMD5
cookie
o.s.s.web.authentication.rememberme.PersistentTokenBasedRememberMeServicestokenstoken

105 / 350

http://lengyun3566.iteye.com

1.19 Spring Security3Remember me


SSLdoc

PersistentTokenBasedRememberMeServices
tokenstokencookietokentoken

TokenBasedRememberMeServicestokencookieman-in-the-middle
tokenIPtoken

SSL
SSLSSLTLS
HTTPHTTPHTTPS
SSLTLSHTTPweb
SSLSpring SecuritySSLweb

SSLTLSTLSSSL
SSLTLS
SSLRFC
5246TLSVersion1.2http://tools.ietf.org/html/rfc5246

Apache TomcatSSL
SSLSSLApache Tomcat

server key store

Javakeytoolkey store

keytool -genkeypair -alias jbcpserver -keyalg RSA -validity 365


-keystore tomcat.keystore -storetype JKS

passwordkey store

What is your first and last name?


[Unknown]:

JBCP Pets Admin

What is the name of your organizational unit?


[Unknown]:
106 / 350

JBCP Pets

http://lengyun3566.iteye.com

1.19 Spring Security3Remember me


SSLdoc

What is the name of your organization?


[Unknown]:

JBCP Pets

What is the name of your City or Locality?


[Unknown]:

Anywhere

What is the name of your State or Province?


[Unknown]:

NH

What is the two-letter country code for this unit?


[Unknown]:

US

Is CN=JBCP Pets Admin, OU=JBCP Pets, O=JBCP Pets, L=Anywhere, ST=NH, C=US
correct?
[no]:

yes

tomcat.keystoreTomcat SSLkey store

genkeypairjava 6keytoolgenkey

TomcatSSL Connector

Apache TomcatconfXMLEclipseserver.xmlSSL Connector

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"


maxThreads="150" scheme="https" secure="true"
sslProtocol="TLS"
keystoreFile="conf/tomcat.keystore"
keystorePass="password"/>
tomcat.keystorecopyTomcatconfTomcat
JBCP Petshttps://localhost:8443/JBCPPets/

httpshttp
JBCP Pets

107 / 350

http://lengyun3566.iteye.com

1.19 Spring Security3Remember me


SSLdoc

SSLSSLSpring Security
<intercept-url>
requires-channel<intercept-url>URLHTTPHTTPS
JBCP Pets

<http auto-config="true" use-expressions="true">


<intercept-url pattern="/login.do" access="permitAll"
requires-channel="https"/>
<intercept-url pattern="/account/*.do"
access="hasRole('ROLE_USER') and fullyAuthenticated"
requires-channel="https"/>
<intercept-url pattern="/*" access="permitAll"
requires-channel="any"/>
<!-- ... -->
</http>

l HTTPSHTTPURLURL
http://localhost:8080/JBCPPets/login.dohttps://localhost:8443/JBCPPets/login.do
l HTTPS URLHTTPSURLHTTPS

securesessioncookie
sessionsessioncookiesession
SSL
HTTPHTTPSSpring Securityservlet
SecurityContextPersistenceFilterURLrequires-channel
o.s.s.web.access.channel.ChannelProcessingFilter
ChannelProcessingFilter

ChannelProcessingFilter
SecureChannelProcessorRetryWithHttpsEntryPointHTTPURL
108 / 350

http://lengyun3566.iteye.com

1.19 Spring Security3Remember me


SSLdoc

ChannelEntryPointHTTP 302URLPOSTURLPOST

HTTPHTTPS80/4438080/8443
ChannelEntryPointURL
<port-mappings>HTTP HTTPS

<port-mappings>
<port-mapping http="9080" https="9443"/>
</port-mappings>

l JDBC
l JBCP Petssalting
l JDBC
l
l Spring Securityschema
l HTTPS
Spring SecuritySpring SecurityJSP

:
Spring_Security3.zip (1.5 MB)
dl.iteye.com/topics/download/ecbe1861-5607-34ef-92b6-566261d3668d

109 / 350

http://lengyun3566.iteye.com 1.20 Spring Security3

1.20 Spring Security3


: 2011-08-25


JBCP Pets
remember me

/
Spring SecurityAOP

l webcritical thinking
l
l pre-authorization
l
l CollectionsArrays

Spring Security

110 / 350

http://lengyun3566.iteye.com 1.20 Spring Security3

JBCP Pets

JBCP Pets

JBCP PetsSpring SecurityGrantedAuthority

Guest

None (anonymous)

ROLE_CUSTOMER

Consumer / Customer

Customer w/
Completed Purchase

Administrator

Supplier

111 / 350

ROLE_USER

ROLE_PURCHASER
ROLE_USER

ROLE_ADMIN
ROLE_USER

ROLE_SUPPLIER
ROLE_USER

http://lengyun3566.iteye.com 1.20 Spring Security3

l Microsoft VisioSpring Security

jsp:includeJBCP PetsApache Tiles 2

Microsoft VisioAdobe
DreamweaverAxure RP
UI
UI

UIVisio
http://www.guuui.com/issues/02_07.ph Visio
Visio
Dia (http://projects.gnome.org/dia/)OpenOffice Draw (http://www.openoffice.org/
product/draw.html)
Visio

112 / 350

http://lengyun3566.iteye.com 1.20 Spring Security3

113 / 350

http://lengyun3566.iteye.com

1.21 Spring Security3

1.21 Spring Security3

: 2011-09-11 : Spring Security, java EE,

Spring Security

Spring Security
l Spring SecurityJSPJSP
l MVC
JSTLSpring Security JSP
webMVC
webJBCP Pets

ROLE_USERROLE_CUSTOMER
ROLE_USERSpring
SecurityJSP

Spring Security
Spring SecurityAuthentication
Spring Security
<authorize>JSTL<if>
<authorize>
114 / 350

http://lengyun3566.iteye.com

1.21 Spring Security3

URL
Spring SecurityURLURL
<authorize><url>
My Account

<intercept-url pattern="/account/*.do"
access="hasRole('ROLE_USER') and fullyAuthenticated"/>

JSPMy Account

<sec:authorize url="/account/home.do">
<c:url value="/account/home.do" var="accountUrl"/>
<li><a href="${accountUrl}">My Account</a></li>
</sec:authorize>

URLtagHTTP
method

<sec:authorize url="/account/home.do"

method="GET">

<c:url value="/account/home.do" var="accountUrl"/>


<li><a href="${accountUrl}">My Account</a> (with 'url' attr)</li>
</sec:authorize>

urlJSP

HTTP<intercept-url>
URLwebURL

115 / 350

http://lengyun3566.iteye.com

1.21 Spring Security3

<authorize>action
form
form

Spring

<authorize>SpringSpELJSP
SpELSpring Security
SpEL<authorize>
My Account

<sec:authorize access="hasRole('ROLE_USER') and fullyAuthenticated">


<c:url value="/account/home.do" var="accountUrl"/>
<li><a href="${accountUrl}">My Account</a> (with 'access' attr)</li>
</sec:authorize>

SpEL<intercept-url>
<authorize>
<authorize>

Spring Security2
Spring SecuritySpring Security3
<authorize>

Log InROLE_USER<authorize>
ifNotGranted

116 / 350

http://lengyun3566.iteye.com

1.21 Spring Security3

<sec:authorize ifNotGranted="ROLE_USER">
<c:url value="/login.do" var="loginUrl"/>
<li><a href="${loginUrl}">Log In</a></li>
</sec:authorize>

form

Log OutifAnyGranted
Log Out

<sec:authorize ifAnyGranted="ROLE_USER">
<c:url value="/logout" var="logoutUrl"/>
<li><a href="${logoutUrl}">Log Out</a></li>
</sec:authorize>

ifAnyGranted

ifAllGranted

<sec:authorize ifAllGranted="ROLE_USER,ROLE_CUSTOMER">
<c:url value="/account/orders.do" var="ordersUrl"/>
<li><a href="${ordersUrl}">My Orders</a></li>
</sec:authorize>

authorize
ifNotGrantedifAnyGrantedBoolean

117 / 350

http://lengyun3566.iteye.com

1.21 Spring Security3

JSP

(ifNotGrantedifAnyGrantedifAllGrantedJSP EL
GrantedAuthority

118 / 350

http://lengyun3566.iteye.com

1.22 Spring Security3

1.22 Spring Security3

: 2011-09-11 : Spring Security, java EE,

<authorize>java

Log In
Spring Security<authorize>Boolean
Log inMVC
Java Standard Tag Library (JSTL)ifJSP EL

<c:if test="${showLoginLink}">
<c:url value="/login.do" var="loginUrl"/>
<li><a href="${loginUrl}">Log In</a></li>
</c:if>

Spring MVC
com.packtpub.springsecurity.web.controller.BaseController
BaseControllerrequest
Authentication

119 / 350

http://lengyun3566.iteye.com

1.22 Spring Security3

protected Authentication getAuthentication() {


return SecurityContextHolder.getContext().getAuthentication();
}

showLoginLinkSpring MVC

@ModelAttribute("showLoginLink")
public boolean getShowLoginLink() {
for (GrantedAuthority authority : getAuthentication().
getAuthorities()) {
if(authority.getAuthority().equals("ROLE_USER")) {
return false;
}
}
return true;
}

@ModelAttributeBaseControllerSpring MVC
authorize/

Spring Security 3 <authorize>


urlJSPurl

lurl
lURL
url

Spring Securitysping
if...Grantedaccess

120 / 350

http://lengyun3566.iteye.com

1.22 Spring Security3

l TagUserDetails
IP<authorize>
JSPSpELJSP

l <authorize>

JSPJSP

l javaJSP tag

Java

JSP

121 / 350

http://lengyun3566.iteye.com

1.23 Spring Security3

1.23 Spring Security3


: 2011-09-11

JBCP Pets web

Spring SecuritySpringbean
web
UIweb service

Spring Security
l Pre-authorization
GrantedAuthorityROLE_ADMIN
lPost-authorization

preconditions and
postconditions

API

JBCP Pets

122 / 350

http://lengyun3566.iteye.com

1.23 Spring Security3

JBCP Pets
web MVCJDBC DAO

com.packtpub.springsecurity.service.IuserService

@PreAuthorize

public interface IUserService {


@PreAuthorize("hasRole('ROLE_USER')")
public void changePassword(String username, String password);
}

Spring Security
aspect oriented programming (AOP) pointcutbefore advice
AccessDeniedException

Spring Security
dogstore-security.xmlSpring
Security<http>

<global-method-security pre-post-annotations="enabled"/>

123 / 350

http://lengyun3566.iteye.com

1.23 Spring Security3

ROLE_USERROLE_ADMINguestguest

Tomcat

DEBUG - Could not complete request


o.s.s.access.AccessDeniedException: Access is denied
at o.s.s.access.vote.AffirmativeBased.decide
at o.s.s.access.intercept.AbstractSecurityInterceptor.beforeInvocation
...
at $Proxy12.changePassword(Unknown Source)
at com.packtpub.springsecurity.web.controller.AccountController.
submitChangePasswordPage

changePassword
ROLE_ADMINGrantedAuthority

Tomcat 403

@PreAuthorize

124 / 350

http://lengyun3566.iteye.com

1.23 Spring Security3

JSR-250
JSR-250, Common Annotations for the Java Platform
JSR-250SpringSpring 2.xJSR-250
Spring Security
JSR-250SpringJava EE
GlassfishApache Tuscany

dogstore-security.xml

<global-method-security jsr250-annotations="enabled"/>

@PreAuthorize@RolesAllowed@RolesAllowed
SpELURLIuserService

@RolesAllowed("ROLE_USER")
public void changePassword(String username, String password);

ROLE_USER ROLE_ADMIN

GrantedAuthorityJava 5

@RolesAllowed({"ROLE_USER","ROLE_ADMIN"})
public void changePassword(String username, String password);

JSR-250@PermitAll @DenyAll

125 / 350

http://lengyun3566.iteye.com

1.23 Spring Security3

JSR-250Spring Security

@Secured
SpringJSR-250 @RolesAllowed@Secured
@RolesAllowed<global-methodsecurity>

<global-method-security secured-annotations="enabled"/>

@SecuredJSR@RolesAllowed
Spring

Aspect Oriented Programming AOP

pointcutadvice
AOPSpring SecurityXML
service

<global-method-security>
<protect-pointcut access="ROLE_ADMIN"
expression="execution(* com.packtpub.springsecurity.service.I*Service.*(..))"/>
</global-method-security>

Spring AOPAspectJSpring AspectJ AOPAspectJ


Spring AOPSpring AOP

DAO

126 / 350

1.23 Spring Security3

http://lengyun3566.iteye.com

<global-method-security>
<protect-pointcut access="ROLE_USER"
expression="execution(* com.packtpub.springsecurity.dao.IProductDao.getCategories(..)) &amp;&amp;
args()"/>
<protect-pointcut access="ROLE_ADMIN" expression="execution(* com.
packtpub.springsecurity.service.I*Service.*(..))"/>
</global-method-security>

AspectJBoolean

Spring SecurityAOP

AOPAOP
Spring AOPAOP

JSR

SpEL

No

Yes

Yes

NO

@PreAuthorize
@PostAuthorize

@RolesAllowed
@PermitAll
@DenyAll

127 / 350

http://lengyun3566.iteye.com

1.23 Spring Security3

@Secure

No

No

protect-pointcut

XML

No

No

Java 5Spring SecurityJSR-250IT


Spring Security

Java 1.4Spring Security


AOP

web
AccessDecisionManagerAccessDecisionVoters
AccessDecisionManager

WebServletFilters
Spring SecuritySpring
SecuritySpringAOP

Spring Securityo.s.s.access.intercept.aopalliance.MethodSecurityInterceptor
Spring AOP

MethodSecurityInterceptor
AOP
AOPSpringbean<global-method-security>
Spring SecuritySpring AOP o.s.beans.factory.config.BeanPostProcessor
AOPAOPadvisorsSpring
AOPAOPSpring SecurityBeanPostProcessorsspring
ApplicationContextSpring Bean
128 / 350

http://lengyun3566.iteye.com

1.23 Spring Security3

SpringAOPPointcutAdvisorsAOP
AOPadviceSpring Security
o.s.s.access.intercept.aopalliance.MethodSecurityMetadataSourceAdvisor
AOPAOP
AOPSpring
CGLIB
AOP
MethodSecurityMetadataSourceAdvisorAOP
o.s.s.access.method.MethodSecurityMetadataSource
MethodSecurityMetadataSourceadvice

Sprin Bean
ApplicationContextbean

129 / 350

http://lengyun3566.iteye.com

1.24 Spring Security3

1.24 Spring Security3


: 2011-09-11

Spring
SpELURL
Boolean
bean

XMLSpring Bean

XML
XMLchangePassword
beanXML
XMLdogstore-base.xml
schemaSpring Bean

<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.
springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/jdbc

130 / 350

http://www.

http://lengyun3566.iteye.com

1.24 Spring Security3

springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/context http://www.
springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/security http://www.
springframework.org/schema/security/spring-security-3.0.xsd
">

IUserService.changePassword

Spring XMLbeanchangePassword
ROLE_USER

<bean id="userService" class="com.packtpub.springsecurity.service.UserServiceImpl">


<security:intercept-methods>
<security:protect access="ROLE_USER" method="changePassword"/>
</security:intercept-methods>
</bean>

ROLE_USER ROLE_ADMIN
guest
MethodSecurityInterceptor
MapBasedMethodSecurityMetadataSourceConfigAttributes
SpEL@PreAuthorize<protect>access
JSR-250 @RolesAllowed
beanset

131 / 350

http://lengyun3566.iteye.com

1.24 Spring Security3

<security:intercept-methods>
<security:protect access="ROLE_USER" method="set*"/>
</security:intercept-methods>

*
?[
Java

changePassword
l
l

Spring SecuritySpEL

@PreAuthorize("#username == principal.username and hasRole('ROLE_USER')")


public void changePassword(String username, String password);

@PreAuthorize("#username == principal.username or
hasRole('ROLE_USER')")
SpEL
#username#

132 / 350

http://lengyun3566.iteye.com

1.24 Spring Security3

<intercept-url>
o.s.s.access.expression.method.MethodSecurityExpressionHandlerSpEL
MethodSecurityExpressionHandler
o.s.s.access.expression.method.MethodSecurityExpressionRoot
WebSecurityExpressionRootURLSpEL

hasRole

webprincipal
principalAuthenticationprincipal
UserDetailsUserDetails

SpEL#

ljavacclass-g
lant<javac>debug="true"
lMavenPOMmaven.compiler.debug=on
IDE

Spring Security@PreFilter@PostFilterCollectionsArrays
@PostFiltersecurity
trimming or security pruning
SpEL
JBCP Pets
Customer Appreciation SpecialsCategorycustomersOnly

133 / 350

http://lengyun3566.iteye.com

1.24 Spring Security3

Spring MVCweb
com.packtpub.springsecurity.web.controller.HomeController
CategoryCollection

@Controller
public class HomeController extends BaseController {
@Autowired
private IProductService productService;
@ModelAttribute("categories")
public Collection<Category> getCategories() {
return productService.getCategories();
}

@RequestMapping(method=RequestMethod.GET,value="/home.do")
public void home() {
}
}

IProductServiceIProductDaoIProductDao
Category

@PostFilter
@PostFilter

@PostFilter("(!filterObject.customersOnly) or (filterObject.customersOnly and hasRole('ROLE_USER'))


Collection<Category> getCategories();

@PostFilter

Spring AOPafterAOP
134 / 350

http://lengyun3566.iteye.com

1.24 Spring Security3

o.s.s.access.expression.method.ExpressionBasedPostInvocationAdviceadvice
CollectionArray@PreAuthorize
DefaultMethodSecurityExpressionHandlerSpEL
guestJBCP Pets
Customer Appreciation Specials

SpEL
Collection@PostFilterCollectionArray

lfilterObjectCollectionSpEL
100CollectionSpEL
lSpELBooleantrueCollection
false
Collection
@PostFilter@PreAuthorize@PostFilter
@PostFilter

CollectionCollection
CollectionCollection
ORMORM
Spring SecurityCollections

@PreFilter
@PreFilterCollection
Collection@PostFilter
l @PreFilterCollectionArray
l @PreFilterfilterTarget

135 / 350

http://lengyun3566.iteye.com

1.24 Spring Security3

@PostFilterCollection
Collection
@PostFiltergetCategories
getCategories

@Override
public Collection<Category> getCategories() {
Collection<Category> unfilteredCategories = productDao.getCategories();
return productDao.filterCategories(unfilteredCategories);
}

filterCategoriesIProductDao@PreFilter

@PreFilter("(!filterObject.customersOnly) or (filterObject.customersOnly and hasRole('ROLE_USER'))"


public Collection<Category> filterCategories(Collection<Category> categories);

@PreFilter
ProductDao

@Override
public Collection<Category> filterCategories(Collection<Category>

categories) {

return categories;
}

IProductService@PostFilter

@PreFilter
@PreFilter@PostFilter

136 / 350

http://lengyun3566.iteye.com

1.24 Spring Security3

@PreFilter@PostFilter

@PreFilter
@PreFilter

@PreFilter

Collections

AOP
Spring 3 Reference DocumentationSpring

Spring SecurityJBCP Pets

l/
lSpring SecurityJSP
Spring MVC
l
webSpring Security

137 / 350

http://lengyun3566.iteye.com

1.24 Spring Security3

Spring Security
Spring Security

138 / 350

http://lengyun3566.iteye.com

1.25 Spring Security3

1.25 Spring Security3


: 2011-09-18 : Spring Security, Java


Spring SecurityJBCP Pets
web

l IP
l AuthenticationProvider
l sessionsession fixation protectionsession
l sessionsession
l
l Spring beanSpring Security<http>
Spring Security
l Spring beansession
l <http>Spring bean
l AuthenticationEvent
l SpELSpEL<intercept-url>

servlet

servletIP

139 / 350

http://lengyun3566.iteye.com

1.25 Spring Security3

JBCP Pets

ROLE_ADMINIP
IP
IP
<intercept-url>
Network
Address Translation NATIPIP

servlet
IP
com.packtpub.springsecurity.security.IPRoleAuthenticationFilter

package com.packtpub.springsecurity.security;
// imports omitted
public class IPRoleAuthenticationFilter extends OncePerRequestFilter
{}

Spring webo.s.web.filter.OncePerRequestFilter

private String targetRole;


private List<String> allowedIPAddresses;

ROLE_ADMINIP
Spring beanbeandoFilterInternal

@Override
public void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)

140 / 350

http://lengyun3566.iteye.com

1.25 Spring Security3

// before we allow the request to proceed, we'll first get the user's role
// and see if it's an administrator
final Authentication authentication = SecurityContextHolder.
getContext().getAuthentication();
if (authentication != null && targetRole != null) {
boolean shouldCheck = false;
// look if the user is the target role
for (GrantedAuthority authority : authentication.getAuthorities()) {
if(authority.getAuthority().equals(targetRole)) {
shouldCheck = true;
break;
}
}
// if we should check IP, then check
if(shouldCheck && allowedIPAddresses.size() > 0) {
boolean shouldAllow = false;
for (String ipAddress : allowedIPAddresses) {
if(req.getRemoteAddr().equals(ipAddress)) {
shouldAllow = true;
break;
}
}

if(!shouldAllow) {
// fail the request
throw new AccessDeniedException(Access has been
denied for your IP address: +req.getRemoteAddr());
}
}
} else {
logger.warn(The IPRoleAuthenticationFilter should be placed
after the user has been authenticated in the filter chain.);
}
chain.doFilter(req, res);
}
// accessors (getters and setters) omitted
}
141 / 350

http://lengyun3566.iteye.com

1.25 Spring Security3

SecurityContextAuthentication
Spring Security
GrantedAuthorityAccessDeniedException
Spring bean

IP servlet
Spring beandogstore-base.xml

<bean id="ipFilter" class="com.packtpub.springsecurity .security.IPRoleAuthenticationFilter">


<property name="targetRole" value="ROLE_ADMIN"/>
<property name="allowedIPAddresses">
<list>
<value>1.2.3.4</value>
</list>
</property>
</bean>

Spring beanIP1.2.3.4IP
127.0.0.1IP

Spring Security

IP servletSpring Security
Spring SecurityServlet
<http>benaIP servlet

<http>
<custom-filter ref="ipFilter" before="FILTER_SECURITY_INTERCEPTOR"/>
</http>

SecurityContext Authentication
GrantedAuthorityFilterSecurityInterceptor

142 / 350

http://lengyun3566.iteye.com

1.25 Spring Security3

Spring Security

IPadmin

IPIPIP
javaIP

IP

143 / 350

http://lengyun3566.iteye.com

1.26 Spring Security3


AuthenticationProvider

1.26 Spring Security3


AuthenticationProvider
: 2011-09-18 : Spring Security, java

AuthenticationProvider
Spring Security
AuthenticationProviderAuthenticationProvider
Authenticationauthentication token
AuthenticationProvider

HTTPj_username
j_passwordj_signature

AuthenticationProviderSSO
Spring SecuritySSOCASSiteMinder
Spring Security
SiteMindero.s.s.web.authentication.preauth.RequestHeaderAuthenticationFilter

admin

j_username

admin

j_password

admin

j_signature

admin|+|admin

144 / 350

http://lengyun3566.iteye.com

1.26 Spring Security3


AuthenticationProvider

AuthenticationProviderAuthenticationToken
servlet filterAuthenticationManager

AuthenticationTokenAuthenticationProvider
AuthenticationProviderservlet
AuthenticationToken

token
Spring Security
UsernamePasswordAuthenticationToken
com.packtpub.springsecurity.security.SignedUsernamePasswordAuthenticationToken

package com.packtpub.springsecurity.security;
// imports omitted
public class SignedUsernamePasswordAuthenticationToken
extends UsernamePasswordAuthenticationToken {
private String requestSignature;
private static final long serialVersionUID =
3145548673810647886L;
/**
* Construct a new token instance with the given principal,
credentials, and signature.
*
* @param principal the principal to use
* @param credentials the credentials to use
* @param signature the signature to use
*/
public SignedUsernamePasswordAuthenticationToken(String principal,
String credentials, String signature) {
super(principal, credentials);

145 / 350

http://lengyun3566.iteye.com

1.26 Spring Security3


AuthenticationProvider

this.requestSignature = signature;
}
public void setRequestSignature(String requestSignature) {
this.requestSignature = requestSignature;
}
public String getRequestSignature() {
return requestSignature;
}
}

SignedUsernamePasswordAuthenticationTokenPOJO
UsernamePasswordAuthenticationTokenTokens

servlet
servlettoken
Spring Securityo.s.s.web.authentication.
AbstractAuthenticationProcessingFilter
AbstractAuthenticationProcessingFilterSpring Security
OpenIDform
RememberMeServicesApplicationEventPublisher

// imports omitted
public class RequestHeaderProcessingFilter extends
AbstractAuthenticationProcessingFilter {
private String usernameHeader = "j_username";
private String passwordHeader = "j_password";
private String signatureHeader = "j_signature";
protected RequestHeaderProcessingFilter() {
super("/j_spring_security_filter");
}
@Override

146 / 350

http://lengyun3566.iteye.com

1.26 Spring Security3


AuthenticationProvider

public Authentication attemptAuthentication


(HttpServletRequest request,HttpServletResponse response)
throws AuthenticationException,
IOException, ServletException {
String username = request.getHeader(usernameHeader);
String password = request.getHeader(passwordHeader);
String signature = request.getHeader(signatureHeader);
SignedUsernamePasswordAuthenticationToken authRequest =
new SignedUsernamePasswordAuthenticationToken
(username, password, signature);
return this.getAuthenticationManager().authenticate(authRequest);
}
// getters and setters omitted below
}

beanURL /j_spring_security_filterSpring
SecurityURLAbstractAuthenticationProcessingFilter
Authentication token
token
tokeno.s.s.core.AuthenticationAuthenticationToken
Spring Security

<http auto-config="true" ...>


<custom-filter ref="requestHeaderFilter"
before="FORM_LOGIN_FILTER"/>
</http>

AuthenticationManager
AuthenticationProviderSignedUsernamePasswordAuthenticationToken
AuthenticationProvider
147 / 350

http://lengyun3566.iteye.com

1.26 Spring Security3


AuthenticationProvider

AuthenticationProvider
AuthenticationProvider
com.packtpub.springsecurity.security.SignedUsernamePasswordAuthenticationProvider
Authentication token

package com.packtpub.springsecurity.security;
// imports omitted
public class SignedUsernamePasswordAuthenticationProvider
extends DaoAuthenticationProvider {
@Override
public boolean supports(Class<? extends Object> authentication) {
return (SignedUsernamePasswordAuthenticationToken .class.isAssignableFrom(authentication));
}
@Override
protected void additionalAuthenticationChecks
(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
super.additionalAuthenticationChecks
(userDetails, authentication);
SignedUsernamePasswordAuthenticationToken signedToken =
(SignedUsernamePasswordAuthenticationToken) authentication;
if(signedToken.getRequestSignature() == null) {
throw new BadCredentialsException(messages.getMessage(
"SignedUsernamePasswordAuthenticationProvider
.missingSignature", "Missing request signature"),
isIncludeDetailsObject() ? userDetails : null);
}
// calculate expected signature
if(!signedToken.getRequestSignature()
.equals(calculateExpectedSignature(signedToken))) {
throw new BadCredentialsException(messages.getMessage
("SignedUsernamePasswordAuthenticationProvider
.badSignature", "Invalid request signature"),

148 / 350

http://lengyun3566.iteye.com

1.26 Spring Security3


AuthenticationProvider

isIncludeDetailsObject() ? userDetails : null);


}
}
private String calculateExpectedSignature
(SignedUsernamePasswordAuthenticationToken signedToken) {
return signedToken.getPrincipal() + "|+|" +
signedToken.getCredentials();
}
}

DaoAuthenticationProvider
UserDetailsServiceUserDetails

SupportsAuthenticationManagerAuthenticationProvider
Authentication token
additionalAuthenticationCheckstoken
tokenSSO

AuthenticationProvider

AuthenticationProvider

AuthenticationProvider
formSSO
AuthenticationProviderAuthenticationProvider
AuthenticationTokentokentoken

AuthenticationProviderdogstore-security.xml
authentication-provider

<authentication-manager alias="authenticationManager">
<authentication-provider ref= "signedRequestAuthenticationProvider"/>

149 / 350

http://lengyun3566.iteye.com

1.26 Spring Security3


AuthenticationProvider

<authentication-provider user-service-ref="jdbcUserService">
<password-encoder ref="passwordEncoder" >
<salt-source ref="saltSource"/>
</password-encoder>
</authentication-provider>
</authentication-manager>

Spring beansignedRequestAuthenticationProvider
AuthenticationProviderdogstore-base.xmlSpring bean

<bean id="signedRequestAuthenticationProvider"

class="com.packtpub.springsecurity.security

.SignedUsernamePasswordAuthenticationProvider">
<property name="passwordEncoder" ref="passwordEncoder"/>
<property name="saltSource" ref="saltSource"/>
<property name="userDetailsService" ref="jdbcUserService"/>
</bean>

AuthenticationProviderbean
AuthenticationManagerauthentication-providerbean

httpSSO

HTTP
CANetegritySiteMinder
SSOSSO provider
provider
SSO
Mozilla FirefoxModify Headers
http://modifyheaders.mozdev.orgHTTP
SSO

150 / 350

http://lengyun3566.iteye.com

1.26 Spring Security3


AuthenticationProvider

EnabledURLhttp://localhost:8080/JBCPPets/j_spring_security_filter
form
AuthenticationProvider
AuthenticationProvider
AuthenticationProviderSpring Security
CasAuthenticationProvider
AuthenticationProviders

AuthenticationProvider
AuthenticationProvider
l Authentication

l AuthenticationAuthenticationProvider
AuthenticationProvider
l sessionAuthenticationEntryPoint
CAS
AuthenticationEntryPoint
AuthenticationProvider

151 / 350

http://lengyun3566.iteye.com

1.27 Spring Security3Session

1.27 Spring Security3Session


: 2011-10-17 : Spring Security, , Java

Session
Spring Securitysession
concurrency controlsessionsession management
Sping Security
Spring Securitysessionsession
session fixation protectionsession
session
session fixation

securitysession

<http auto-config="true" use-expressions="true">


<!-- ... -->
<session-management session-fixation-protection="migrateSession"/>
</http>

Session
sessionsession

session fixation
Sessionsession
sessionJSESSIONIDJSESSIONIDcookie
URLsession

session
session

152 / 350

http://lengyun3566.iteye.com

1.27 Spring Security3Session

session
OWASPhttp://www.owasp.org/

session

Spring Security

Spring Securitysession fixation


sessionsession ID
Spring Securitysession
sessionsession

o.s.s.web.session.SessionManagementFilter

o.s.s.web.authentication.session.SessionAuthenticationStrategy
o.s.s.web.authentication.session.SessionAuthenticationStrategysession
sessionsession
session ID

session fixation
session
dogstore-security.xmlsession

<session-management session-fixation-protection="none"/>

IEsession
sessionFirefoxInternet Explorer Developer Tools IE 8Firefox
Web Developer Add-OnURLcookie
153 / 350

http://lengyun3566.iteye.com

1.27 Spring Security3Session

IEJBCP PetsF12
CookielocalhostJSESSIONIDcookie

session cookieJBCP PetsCookie


JSESSIONIDsession
FirefoxJBCP Petssession cookieCookie
Cookie

Edit CookieIEJSESSIONID

sessionFirefoxIE

sessionJSESSIONID
session

session cookieXSS
sessionOWASP

session-fixation-protection
session-fixation-protection

none

154 / 350

session
SessionManagementFilter

http://lengyun3566.iteye.com

1.27 Spring Security3Session

<session-management>

sessionsession
migrateSession

session
bean

session
newSession

session
session

migrateSession

session
sessionsession
sessionsession
session

session
session
ConcurrentSessionFilterdogstore-security.xml

<http auto-config="true" use-expressions="true">


<!-- ... -->
<session-management>
<concurrency-control max-sessions="1"/>
</session-management>
</http>

155 / 350

http://lengyun3566.iteye.com

1.27 Spring Security3Session

web.xmlo.s.s.web.session.HttpSessionEventPublisher
serveltSpring Security sessionHttpSessionEventPublisher

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.security.web.session
.HttpSessionEventPublisher
</listener-class>
</listener>
<servlet>
<servlet-name>dogstore</servlet-name>

session
session

session
sessionsessionsession
sessionsession

Sessiono.s.s.core.session.SessionRegistryHTTP session
sessionHttpSessionEventPublisher
sessionsession

SessionAuthenticationStrategy
o.s.s.web.authentication.session.ConcurrentSessionControlStrategysession
156 / 350

http://lengyun3566.iteye.com

1.27 Spring Security3Session

sessionSessionManagementFilter
SessionRegistrysessionsessionSessionRegistrysession
session
sessiono.s.s.web.session.ConcurrentSessionFilter
sessionsessionservlet
ConcurrentSessionControlStrategysession
session

session
sessionweb
1.

IEguest

2.

Firefoxguest

3.

IEsession

session
JBCP Pets

sessionSpring Security

session
session
expired-url

157 / 350

http://lengyun3566.iteye.com

1.27 Spring Security3Session

<http auto-config="true" use-expressions="true">


<!-- ... -->
<session-management>
<concurrency-control max-sessions="1" expired-url= "/login.do?error=expired"/>
</session-management>
</http>

form
sessionURL

Session
SessionSessionRegistrysessionsession

sessionmax-sessions-1
sessionsession

sessionsession

BaseControllerbean@Autowired
SessionRegistry sessionRegistry;
@ModelAttribute("numUsers")
public int getNumberOfUsers() {
return sessionRegistry.getAllPrincipals().size();
}

Spring MVC JSPfooter.jsp


JBCP Pets

158 / 350

http://lengyun3566.iteye.com

1.27 Spring Security3Session

<div id="footer">
${numUsers} user(s) are logged in!
</div>
</body>
</html>

Spring Securitysession

SessionRegistry

SessionRegistrysession

AccountController
JBCP PetsSessionRegistry
session

@RequestMapping("/account/listActiveUsers.do")
public void listActiveUsers(Model model) {
Map<Object,Date> lastActivityDates = new HashMap<Object, Date>();
for(Object principal: sessionRegistry.getAllPrincipals()) {
// a principal may have multiple active sessions
for(SessionInformation session : sessionRegistry.getAllSessions(principal, false))
{
// no last activity stored
if(lastActivityDates.get(principal) == null) {
lastActivityDates.put(principal, session.getLastRequest());
} else {
// check to see if this session is newer than the last stored

159 / 350

http://lengyun3566.iteye.com

1.27 Spring Security3Session

Date prevLastRequest = lastActivityDates.get(principal);


if(session.getLastRequest().after(prevLastRequest)) {
// update if so
lastActivityDates.put(principal, session.getLastRequest());
}
}
}
}
model.addAttribute("activeUsers", lastActivityDates);
}

SessionRegistryAPI
l getAllPrincipalssessionPrincipalUserDetailsList
l getAllSessions(principal, includeExpired)PrincipalSessionInformationList
sessionsession
SessionRegistry APIlistActiveUsers
sessionPrincipalMapUI
UIJSTLWEB-INF/views/accountlistActiveUsers.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


<h1>Active Users</h1>
<ul>
<c:forEach items="${activeUsers}" var="uinfo">
<li><strong>${uinfo.key.username}</strong>
/ Last Active: <strong>${uinfo.value}</strong></li>
</c:forEach>
</ul>

http://localhost:8080/JBCPPets/account/listActiveUsers.do

160 / 350

http://lengyun3566.iteye.com

1.27 Spring Security3Session

SessionRegistrySessionRegistry
Spring Security

161 / 350

http://lengyun3566.iteye.com

1.28 Spring Security3

1.28 Spring Security3


: 2011-10-18 : spring, security, java

Spring Security
Spring Security
o.s.s.web.access.ExceptionTranslationFilter
FilterSecurityInterceptor
ExceptionTranslationFilter

ExceptionTranslationFilter
l AuthenticationException
AuthenticationEntryPoint
l AccessDeniedException
l AccessDeniedException
HTTP 403
AccessDeniedHandler
Access Denied
GrantedAuthority
servletHTTP 403
o.s.s.web.access.AccessDeniedHandlerExceptionTranslationFilter
AccessDeniedException

URLSpring Security
URL<form-login> login-page

162 / 350

http://lengyun3566.iteye.com

1.28 Spring Security3

Access Denied
<http><accessdenied-handler>URL

<http auto-config="true" ...>


<access-denied-handler error-page="/accessDenied.do"/>
</http>

URLSpring MVC
LoginLogoutControllerURLmodelview

AccessDeniedException
actionURL
AccessDeniedException

@Controller
public class LoginLogoutController extends BaseController{
// Ch 6 Access Denied
@RequestMapping(method=RequestMethod.GET, value="/accessDenied.do").
public void accessDenied(ModelMap model, HttpServletRequest request) {
AccessDeniedException ex = (AccessDeniedException)
request.getAttribute(AccessDeniedHandlerImpl
.SPRING_SECURITY_ACCESS_DENIED_EXCEPTION_KEY);
StringWriter sw = new StringWriter();
model.addAttribute("errorDetails", ex.getMessage());
ex.printStackTrace(new PrintWriter(sw));
model.addAttribute("errorTrace", sw.toString());
}
}

AccessDeniedHandlerImplrequest
request
163 / 350

http://lengyun3566.iteye.com

1.28 Spring Security3

AccessDeniedExceptionmessage
Spring SecurityAccessDeniedException

Access Denied

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<jsp:include page="common/header.jsp">
<jsp:param name="pageTitle" value="Access Denied"/>
</jsp:include>
<h1>Access Denied</h1>
<p>
Access to the specified resource has been denied for
the following reason: <strong>${errorDetails}</strong>.
</p>
<em>Error Details (for Support Purposes only):</em><br />
<blockquote>
<pre>${errorTrace}</pre>
</blockquote>
<jsp:include page="common/footer.jsp"/>

errorDetailserrorTrace

AccessDeniedException

Spring Security
AccessDeniedExceptionHTTP 403AuthenticationException

164 / 350

http://lengyun3566.iteye.com

1.28 Spring Security3

AuthenticationProvider

DaoAuthenticationProvider
DAO
AuthenticationException
RememberMeServicesremember
me cookie
CASNTLM

AccessDecisionManager
AccessDeniedException

Voter

ExceptionTranslationFilter

ExceptionTranslationFilterExceptionTranslationFilter

AuthenticationEntryPoint

AuthenticationEntryPointExceptionTranslationFilter
ExceptionTranslationFilter
AuthenticationEntryPointform
o.s.s.web.authentication.LoginUrlAuthenticationEntryPointform
AuthenticationEntryPoint
CASAuthenticationEntryPointCAS

165 / 350

http://lengyun3566.iteye.com

1.28 Spring Security3

Spring Securityweb
AuthenticationEntryPoint

166 / 350

http://lengyun3566.iteye.com

1.29 Spring Security3Spring Security


bean

1.29 Spring Security3Spring Security


bean
: 2011-10-19 : Spring Security, java,

Spring Securitybean
Spring Security
Spring SecuritySpring Security
Spring Security
alternate universe
beansecurity
<http>
beanbean25
beanbeanbean
XMLSpring SecuritySecurity XML

beanbean
Spring Security
bean
dogstore-explicit-base.xml

Spring Security bean


beanSpring Security bean
bean

bean
beansecurity

167 / 350

http://lengyun3566.iteye.com

1.29 Spring Security3Spring Security


bean

web
XML

SpringApplicationContext
dogstore-explicit-base.xmlweb.xml<web-app
...>
<display-name>Dog Store</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/dogstore-explicit-base.xml
</param-value>
</context-param>

dogstore-security.xmlXML security
Springbeansecurity

Spring Security
remember melogout
Spring Security
Spring Securityservlet

<bean id="springSecurityFilterChain"
class="org.springframework.security.web.FilterChainProxy">
<security:filter-chain-map path-type="ant">
<security:filter-chain pattern="/**" filters="
securityContextPersistenceFilter,
usernamePasswordAuthenticationFilter,
anonymousAuthenticationFilter,
filterSecurityInterceptor" />
</security:filter-chain-map>
</bean>

168 / 350

http://lengyun3566.iteye.com

1.29 Spring Security3Spring Security


bean

securitybean
securityfilter-chain-map
<http>
l <http>security
<custom-filter>
FilterChainProxy
l URL<http>

Springweb.xml
contextConfigLocation

<filter-chain>bean definitions

servlet

servletweb
security
servletbean
bean

169 / 350

http://lengyun3566.iteye.com

1.29 Spring Security3Spring Security


bean

SecurityContextPersistenceFilter

SecurityContextPersistenceFilterSecurityContextrequest
Spring MVCPrincipa
SecurityContext
web sessionSecurityContextPersistenceFilter

<bean id="securityContextPersistenceFilter"
class="org.springframework.security.web.context .SecurityContextPersistenceFilter/>

HTTP session
session
UsernamePasswordAuthenticationFilter

UsernamePasswordAuthenticationFilterform
security

<bean id="UsernamePasswordAuthenticationFilter"
class="org.springframework.security.web
.authentication.UsernamePasswordAuthenticationFilter">
<property name="authenticationManager" ref="customAuthenticationManager"/>
</bean>

patternurl

customAuthenticationManagerbeansecurity
<authentication-manager>AuthenticationManagerbean

170 / 350

http://lengyun3566.iteye.com

1.29 Spring Security3Spring Security


bean

AnonymousAuthenticationFilter

AnonymousAuthenticationFilter

AnonymousAuthenticationFiltersecurity

<bean id="anonymousAuthenticationFilter"
class="org.springframework.security.web
.authentication.AnonymousAuthenticationFilter">
<property name="userAttribute"
value="anonymousUser,ROLE_ANONYMOUS"/>
<property name="key" value="BF93JFJ091N00Q7HF"/>
</bean>

userAttributeGrantedAuthority
GrantedAuthorityKey
beano.s.s.authentication.AnonymousAuthenticationProvider

FilterSecurityInterceptor

Authentication

security

<bean id="filterSecurityInterceptor"
class="org.springframework.security.web.access .intercept.FilterSecurityInterceptor">
<property name="authenticationManager"

ref="customAuthenticationManager"/>

<property name="accessDecisionManager" ref="affirmativeBased"/>


<property name="securityMetadataSource">
<security:filter-security-metadata-source>
<security:intercept-url pattern="/login.do"

171 / 350

http://lengyun3566.iteye.com

1.29 Spring Security3Spring Security


bean

access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<security:intercept-url pattern="/
home.do" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<security:intercept-url pattern="/
account/*.do" access="ROLE_USER"/>
<security:intercept-url pattern="/*" access="ROLE_USER"/>
</security:filter-security-metadata-source>
</property>
</bean>

security<http><intercepturl>
Spring bean
<filter-security-metadata-source>FilterSecurityInterceptor
SecurityMetadataSourceURL
XMLSpring
Spring XMLXML
:<security:intercept-url>
intercept-urlsecurityXMLXMLXML
URIsecurity
xmlns:security=http://www.springframework.org/schema/security
XMLxmlnsdogstore-explicitbase.xmlxmlns="http://www.springframework.org/schema/beans"
XML
SpringSpring Security

Spring bean

bean

172 / 350

http://lengyun3566.iteye.com

1.29 Spring Security3Spring Security


bean

<bean class="org.springframework.security.access.vote.AffirmativeBased" id="affirmativeBased">


<property name="decisionVoters">
<list>
<ref bean="roleVoter"/>
<ref bean="authenticatedVoter"/>
</list>
</property>
</bean>
<bean class="org.springframework.security.access .vote.RoleVoter" id="roleVoter"/>
<bean class="org.springframework.security.access.vote.AuthenticatedVoter"
id="authenticatedVoter"/>
<bean id="daoAuthenticationProvider"
class="org.springframework .security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="jdbcUserService"/>
</bean>
<bean id=anonymousAuthenticationProvider
class=org.springframework.security.authentication.AnonymousAuthenticationProvider>
<property name=key value=BF93JFJ091N00Q7HF/>
</bean>

jdbcUserServicedataSource beansbean
AnonymousAuthenticationProviderkeyAnonymousAuthenticationFilter
key
beansecurity
AuthenticationManagerbean

<bean id="customAuthenticationManager"
class="org.springframework .security.authentication.ProviderManager">
<property name="providers">
<list>
<ref local="daoAuthenticationProvider"/>
<ref local=anonymousAuthenticationProvider/>
</list>

173 / 350

http://lengyun3566.iteye.com

1.29 Spring Security3Spring Security


bean

</property>
</bean>

AuthenticationManagerbean

beansecurity
saltingremember me

174 / 350

http://lengyun3566.iteye.com

1.30 Spring Security3Spring Securitybean

1.30 Spring Security3Spring Securitybean

: 2011-11-22 : Spring Security, , , Java EE

Spring Securitybean

beanSpring Security
security XML

JavadocSpring Security

Session
Spring SecurityHttpSessionSpring
beansessionbean

Class

true

AbstractAuthentication ProcessingFilter
UsernamePasswordAuthenticationFilter

allowSessionCreation

true

session

true

UsernamePasswordAuthenticationFilter

allowSessionCreation

true

session

175 / 350

http://lengyun3566.iteye.com

1.30 Spring Security3Spring Securitybean

true
HttpSession

SecurityContextLogoutHandler

invalidateHttpSession

true

Servlet
session

true

SecurityContextPersistenceFilter

forceEagerSessionCreation

false

session

true

session
HttpSessionSecurityContextRepository

allowSessionCreation

true

SecurityContext

SecurityContext
session

sessionsession

security

remember me

176 / 350

http://lengyun3566.iteye.com

1.30 Spring Security3Spring Securitybean

<bean id="springSecurityFilterChain"
class="org.springframework.security.web.FilterChainProxy">
<security:filter-chain-map path-type="ant">
<security:filter-chain pattern="/**" filters="
securityContextPersistenceFilter,
logoutFilter,
usernamePasswordAuthenticationFilter,
rememberMeAuthenticationFilter,
anonymousAuthenticationFilter,
exceptionTranslationFilter,
filterSecurityInterceptor" />
</security:filter-chain-map>
</bean>

Spring beanbean

LogoutFilter
LogoutFilterURL /j_spring_security_logout

<bean id="logoutFilter" class="org.springframework.security


.web.authentication.logout.LogoutFilter">
<!-- the post-logout destination -->
<constructor-arg value="/"/>
<constructor-arg>
<array>
<ref local="logoutHandler"/>
</array>
</constructor-arg>
<property name="filterProcessesUrl" value="/logout"/>
</bean>
177 / 350

http://lengyun3566.iteye.com

1.30 Spring Security3Spring Securitybean

LogoutFilterbean
URLLogoutHandler
Spring
setterSpring
SpringSpring
Security

LogoutHandler

<bean id="logoutHandler" class="org.springframework.security


.web.authentication.logout.SecurityContextLogoutHandler"/>

LogoutHandlersessionlogout
sessionLog Out

securitySpring Security
URLsecuritybeanbean
filterProcessesUrl

RememberMeAuthenticationFilter
remember mebean
remember mebeanbean

<bean id="rememberMeAuthenticationFilter"
class="org.springframework.security.web
.authentication.rememberme.RememberMeAuthenticationFilter">
<property name="rememberMeServices" ref="rememberMeServices"/>
<property name="authenticationManager"

ref="customAuthenticationManager" />

</bean>

rememberMeServicesbean
178 / 350

http://lengyun3566.iteye.com

1.30 Spring Security3Spring Securitybean

<bean id="rememberMeServices"
class="org.springframework.security.web.authentication
.rememberme.PersistentTokenBasedRememberMeServices">
<property name="key" value="jbcpPetStore"/>
<property name="tokenValiditySeconds" value="3600"/>
<property name="tokenRepository" ref="jdbcRememberMeTokenRepository"/>
<property name="userDetailsService" ref="jdbcUserService"/>
</bean>

RememberMeServicessecurity
RememberMeServicessecurity
beanbeanremember mebean
remember me
beanremember metokenbean

<bean id="jdbcRememberMeTokenRepository"
class="org.springframework.security.web
.authentication.rememberme.JdbcTokenRepositoryImpl">
<property name="dataSource" ref="dataSource"/>
</bean>

AuthenticationProviderremember me

<bean id="rememberMeAuthenticationProvider"
class="org.springframework.security .authentication.RememberMeAuthenticationProvider">
<property name="key" value="jbcpPetStore"/>
</bean>

keyAuthenticationProvidertokenRememberMeServices
tokenproperties
PropertyPlaceholderConfigurer
AuthenticationProviderAuthenticationManager
179 / 350

http://lengyun3566.iteye.com

1.30 Spring Security3Spring Securitybean

<bean id="customAuthenticationManager"
class="org.springframework.security .authentication.ProviderManager">
<property name="providers">
<list>
<ref local="daoAuthenticationProvider"/>
<ref local=anonymousAuthenticationProvider/>
<ref local="rememberMeAuthenticationProvider"/>
</list>
</property>
</bean>

RememberMeServicesUsernamePasswordAuthenticationFilterRememberMeServices
remember me cookieremember me
cookie

<bean id="usernamePasswordAuthenticationFilter"
class="org.springframework.security.web
.authentication.UsernamePasswordAuthenticationFilter">
<property name="authenticationManager"
ref="customAuthenticationManager"/>
<property name="rememberMeServices" ref="rememberMeServices"/>
</bean>

Spring Security beanRememberMeServices


LogoutHandlercookie

<bean id="logoutFilter"
class="org.springframework.security.web .authentication.logout.LogoutFilter">
<constructor-arg value="/"/>
<constructor-arg>
<array>
<ref local="logoutHandler"/>

180 / 350

http://lengyun3566.iteye.com

1.30 Spring Security3Spring Securitybean

<ref local="rememberMeServices"/>
</array>
</constructor-arg>
<property name="filterProcessesUrl" value="/logout"/>
</bean>

remember me<remember-me>

ExceptionTranslationFilter
Spring SecurityservletExceptionTranslationFilter

bean

<bean id="exceptionTranslationFilter"
class="org.springframework.security.web .access.ExceptionTranslationFilter">
<property name="authenticationEntryPoint" ref="authenticationEntryPoint"/>
<property name="accessDeniedHandler" ref="accessDeniedHandler"/>
</bean>

bean

<bean id="authenticationEntryPoint"
class="org.springframework.security.web
.authentication.LoginUrlAuthenticationEntryPoint">
<property name="loginFormUrl" value="/login.do"/>
</bean>
<bean id="accessDeniedHandler"
class="org.springframework.security.web .access.AccessDeniedHandlerImpl">
<property name="errorPage" value="/accessDenied.do"/>
</bean>

errorPageAccess Denied
loginFormUrlsecuritylogin-page
181 / 350

http://lengyun3566.iteye.com

1.30 Spring Security3Spring Securitybean

SpEL
securityuse-expressions="true"Spring bean

<bean class="org.springframework.security
.web.access.expression.DefaultWebSecurityExpressionHandler"
id="expressionHandler"/>

Voter

<bean class="org.springframework.security.web.access
.expression.WebExpressionVoter" id="expressionVoter">
<property name="expressionHandler" ref="expressionHandler"/>
</bean>

AccessDecisionManager bean

<bean

class="org.springframework.security.access.vote.AffirmativeBased"

id="affirmativeBased">
<property name="decisionVoters">
<list>
<ref bean="expressionVoter"/>
</list>
</property>
</bean>

use-expressions="true"
use-expressions="true"

182 / 350

http://lengyun3566.iteye.com

1.30 Spring Security3Spring Securitybean

bean
security<global-method-security>
bean<global-method-security>

bean
dogstoreexplicit-base.xml

beanSpring security
securitybeanweb.xmlSpring

l securityweb.xmldogstore-base.xmldogstore-security.xml
l beanweb.xmldogstore-explicit-base.xml
securitybean
bean

Spring Security

l web

security

l security

183 / 350

http://lengyun3566.iteye.com

1.30 Spring Security3Spring Securitybean

l Spring Security

l URL<filter-chain>
patternweb service
bean

REST
l Spring Security
l
l security

security
beanbean
Spring Security

184 / 350

http://lengyun3566.iteye.com

1.31 Spring Security3

1.31 Spring Security3


: 2011-11-22 : Spring Security, Java EE, ,

beanSpring
o.s.context.ApplicationEventSpring

-Spring
Spring
ApplicationContextSpringbean
o.s.context.ApplicationListenerbean
o.s.context.event.ApplicationEventMulticastero.s.context.ApplicationEventPublisher
Spring1.1Spring

Spring Security
session

securitySpring bean
ApplicationEventPublisherAuthenticationManager

bean
ApplicationEventPublisher

185 / 350

http://lengyun3566.iteye.com

1.31 Spring Security3

<bean id="defaultAuthEventPublisher"
class="org.springframework.security.authentication .DefaultAuthenticationEventPublisher"/>

AuthenticationManager

<bean id="customAuthenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<property name="authenticationEventPublisher" ref="defaultAuthEventPublisher"/>
<property name="providers">
<list>
<ref local="daoAuthenticationProvider"/>
<ref local="rememberMeAuthenticationProvider"/>
</list>
</property>
</bean>

bean

ApplicationListenerSpring 3Java
ApplicationListener

ApplicationListener

package com.packtpub.springsecurity.security;
// imports omitted
@Component
public class CustomAuthenticationEventListener implements
ApplicationListener<AbstractAuthenticationEvent> {
@Override
public void onApplicationEvent(AbstractAuthenticationEvent event) {
System.out.println("Received event of type:
186 / 350

http://lengyun3566.iteye.com

1.31 Spring Security3

"+event.getClass().getName()+": "+event.toString());
}
}

@ComponentXMLSpring
bean
ApplicationListenerSpring 3
ApplicationListenerSpringApplicationEventMulticaster

Spring
o.s.context.event.GenericApplicationListenerAdapterApplicationEvent
Java

ApplicationListener
implements

ApplicationListeners
Spring SecurityApplicationListenerSpring Security
Apache Commons LoggingApplicationListener

<bean id="authenticationListener"
class="org.springframework.security .authentication.event.LoggerListener"/>
<bean id="authorizationListener"
class="org.springframework.security .access.event.LoggerListener"/>

Commons Logging
AbstractAuthenticationFailureEvent

187 / 350

http://lengyun3566.iteye.com

1.31 Spring Security3

WARN - Authentication event


AuthenticationFailureBadCredentialsEvent: adb; details: org.
springframework.security.web.authentication.WebAuthenticationDetails@2
55f8: RemoteIpAddress: 127.0.0.1; SessionId: B20510F25464B109CE3AE94D9
FBF981E; exception: Bad credentials

ApplicationListener

Spring Security

l DefaultAuthenticationEventPublisher
exceptionMappings
l HttpSessionweb.xml
Spring
Spring Security

SpEL
SpEL
SpEL
com.packtpub.springsecurity.security.CustomWebSecurityExpressionRoot
WebSecurityExpressionRoot

public class CustomWebSecurityExpressionRoot extends WebSecurityExpressionRoot {


public CustomWebSecurityExpressionRoot (Authentication a, FilterInvocation fi) {
super(a, fi);
}
public boolean isEvenMinute() {
return (Calendar.getInstance().get(Calendar.MINUTE) % 2) == 0;

188 / 350

http://lengyun3566.iteye.com

1.31 Spring Security3

}
}

WebSecurityExpressionHandler
DefaultWebSecurityExpressionHandler
com.packtpub.springsecurity.security.CustomWebSecurityExpressionHandler
CustomWebSecurityExpressionRoot

public class CustomWebSecurityExpressionHandler


extends DefaultWebSecurityExpressionHandler {
public EvaluationContext createEvaluationContext(Authentication authentication, FilterInvocation
StandardEvaluationContext ctx = (StandardEvaluationContext)
super.createEvaluationContext(authentication, fi);
SecurityExpressionRoot root = new CustomWebSecurityExpressionRoot(authentication, fi);
ctx.setRootObject(root);
return ctx;
}
}

Voterbean

<bean class="com.packtpub.springsecurity.security.CustomWebSecurityExpressionHandler"
id="customExpressionHandler"/>
<bean class="org.springframework.security.web.access.expression.WebExpressionVoter"
id="expressionVoter">
<property name="expressionHandler" ref="customExpressionHandler"/>
</bean>

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

189 / 350

http://lengyun3566.iteye.com

1.31 Spring Security3

SpEL

SpEL Votersecurityaccess-decisionmanager-refAccessDecisionManager

Spring Security

l servletIPHTTPSSO
l AuthenticationProviderHTTPSSO
l sessionsessionsession
l AccessDeniedException

l Spring SecuritySping bean XML

l Spring beansession
l ApplicationListenerSpring Security
l SpELURL
Spring Security

190 / 350

http://lengyun3566.iteye.com

1.32 Spring Security3ACL

1.32 Spring Security3ACL


: 2011-12-30 : Spring Security, java, ,

ACL

Spring Security

l
l Spring Security ACL
l Spring ACL
l JBCP PetsSpring beanACL
l ACLJSPACL
l ACL

permissionentryaccess control entry

web
access control listACLACLACL

JBCP PetsACL

191 / 350

http://lengyun3566.iteye.com

1.32 Spring Security3ACL

Profile123

readwrite

ROLE_USER

Profile123

read

ANONYMOUS

Any Profile

none

amy

ACLAmyProfile123
AmyACL
ACLACL

ACL
Microsoft WindowsUnix/LinuxACL
ACL
Microsoft Windows|
ACL

ACL
Spring Security
Spring SecurityACLOS
Spring Security ACL

Spring Security ACL


ACLSpring Securitybean

Spring SecurityACL
Spring SecurityACL

Spring Security ACL

192 / 350

http://lengyun3566.iteye.com

1.32 Spring Security3ACL

Spring ACLsecurity identitySIDSID


GrantedAuthorityACLSID

SIDACL
object identitySpring ACLACL

access control entriesACEsACE

l SID
l
l SID
l SID

Spring ACLACE
ACE
Spring Security ACLSpring Security

Spring Security

ACL

Java

SID

o.s.s.acls.model.Sid

Object Identity

o.s.s.acls.model.ObjectIdentity

ACL

o.s.s.acls.model.Acl

193 / 350

http://lengyun3566.iteye.com

ACE

1.32 Spring Security3ACL

o.s.s.acls.model.AccessControlEntry

JBCP Pets storeSpring Security ACL

Spring Security ACL


SpringSecurityACLbean
ACLsecurity XMLACLbean
securityweb.xmlsecurity
dogstore-base.xmldogstore-security.xml

ROLE_ADMIN GrantedAuthority
Pet ApparelACL
ACL
ACLACL
IProductService.getItemsByCategory

@Secured("VOTE_CATEGORY_READ")
public Collection<Item> getItemsByCategory(Category cat);

JBCP Pets

ACLHSQL
ACLHSQL
SQL DDLdogstore-security.xml

194 / 350

http://lengyun3566.iteye.com

1.32 Spring Security3ACL

<jdbc:embedded-database id="dataSource" type="HSQL">


<jdbc:script location="classpath:security-schema.sql"/>
<jdbc:script location="classpath:test-data.sql"/>
<jdbc:script location="classpath:remember-me-schema.sql"/>
<jdbc:script location="classpath:test-users-groups-data.sql"/>
<jdbc:script location="classpath:acl-schema.sql"/>
</jdbc:embedded-database>

acl-schema.sqlWEB-INF/classes

create table acl_sid (


id bigint generated by default as identity(start with 100) not null
primary key,
principal boolean not null,
sid varchar_ignorecase(100) not null,
constraint uk_acl_sid unique(sid,principal) );
create table acl_class (
id bigint generated by default as identity(start with 100) not null
primary key,
class varchar_ignorecase(500) not null,
constraint uk_acl_class unique(class) );
create table acl_object_identity (
id bigint generated by default as identity(start with 100) not null
primary key,
object_id_class bigint not null,
object_id_identity bigint not null,
parent_object bigint,
owner_sid bigint not null,
entries_inheriting boolean not null,
constraint uk_acl_objid unique(object_id_class,object_id_identity),
constraint fk_acl_obj_parent foreign key(parent_object)references
acl_object_identity(id),
constraint fk_acl_obj_class foreign key(object_id_class)references
acl_class(id),
195 / 350

http://lengyun3566.iteye.com

1.32 Spring Security3ACL

constraint fk_acl_obj_owner foreign key(owner_sid)references acl_


sid(id) );
create table acl_entry (
id bigint generated by default as identity(start with 100) not null
primary key,
acl_object_identity bigint not null,
ace_order int not null,
sid bigint not null,
mask integer not null,
granting boolean not null,
audit_success boolean not null,
audit_failure boolean not null,
constraint uk_acl_entry unique(acl_object_identity,ace_order),
constraint fk_acl_entry_obj_id foreign key(acl_object_identity)
references acl_object_identity(id),
constraint fk_acl_entry_sid foreign key(sid) references acl_sid(id)
);

SIDACE
ACL
Spring SecurityHSQL

l ACL_CLASS.CLASS100500100
l
oracleDDL
ACLACEACL

196 / 350

http://lengyun3566.iteye.com

1.32 Spring Security3ACL

<global-method-security>ACL
access decision manager
ACLweb URL
voterweb

security

dogstore-security.xml

<global-method-security secured-annotations="enabled"
access-decision-manager-ref="aclDecisionManager"/>

beandogstore-base.xml

<bean class="org.springframework.security.access.vote.AffirmativeBased"
id="aclDecisionManager">
<property name="decisionVoters">
<list>
<ref bean="categoryReadVoter"/>
</list>
</property>
</bean>

AccessDecisionManager
web
ACLbean
ACL
Spring Security ACLACL

197 / 350

http://lengyun3566.iteye.com

1.32 Spring Security3ACL

ACLSpring Security
constructor injectionproperty injection
beanSpring Security
ACL
categoryReadVoterAccessDecisionVoterACL

<bean class="org.springframework.security.acls.AclEntryVoter"
id="categoryReadVoter">
<constructor-arg ref="aclService"/>
<constructor-arg value="VOTE_CATEGORY_READ"/>
<constructor-arg>
<array>
<util:constant static-field="org.springframework.security.acls.
domain.BasePermission.READ"/>
</array>
</constructor-arg>
<property name="processDomainObjectClass"
value="com.packtpub.springsecurity.data.Category"/>
</bean>

bean
VOTE_CATEGORY_READACL
@Secured
ACL
VOTE_CATEGORY_READACL
com.packtpub.springsecurity.data.CategoryREAD
ACLACL SID

aclServicebeano.s.s.acls.model.AclServiceACL
ACE

198 / 350

http://lengyun3566.iteye.com

1.32 Spring Security3ACL

<bean class="org.springframework.security.acls.jdbc.JdbcAclService"

id="aclService">

<constructor-arg ref="dataSource"/>
<constructor-arg ref="lookupStrategy"/>
</bean>

o.s.s.acls.jdbc.JdbcAclServiceAclService
JdbcAclServiceSQLSID
AclEntryVoter
JdbcAclServiceJDBC dataSource
o.s.s.acls.jdbc.LookupStrategyACLSpring
SecurityLookupStrategyo.s.s.acls.jdbc.BasicLookupStrategy

<bean class="org.springframework.security.acls.jdbc.BasicLookupStrategy" id="lookupStrategy">


<constructor-arg ref="dataSource"/>
<constructor-arg ref="aclCache"/>
<constructor-arg ref="aclAuthzStrategy"/>
<constructor-arg ref="aclAuditLogger"/>
</bean>

BasicLookupStrategybeast
ObjectIdentityACEObjectIdentity
SQL
BasicLookupStrategy
ANSI SQL[]left[outer]joinsOracle 8i
SQL
SQLOracleCONNECT BY
PostgreSQLMicrosoft SQL ServerCommon Table ExpressionCTE
JdbcDaoImpl UserDetailsServiceBasicLookupStrategy
SQLJavadoc

LookupStrategyAclServiceJDBC dataSoure

199 / 350

1.32 Spring Security3ACL

http://lengyun3566.iteye.com

o.s.s.acls.model.AclCacheObjectIdentityACL
Spring SecurityAclCacheEhcache
Ehcache
AclCachecom.packtpub.springsecurity.security.NullAclCache

package com.packtpub.springsecurity.security;
// imports omitted
public class NullAclCache implements AclCache {
@Override
public void clearCache() {

@Override
public void evictFromCache(Serializable arg0) { }
@Override
public void evictFromCache(ObjectIdentity arg0) {

@Override
public MutableAcl getFromCache(ObjectIdentity arg0) {
return null;
}
@Override
public MutableAcl getFromCache(Serializable arg0) {
return null;
}
@Override
public void putInCache(MutableAcl arg0) {

bean

<bean class="com.packtpub.springsecurity.security.NullAclCache"
id="aclCache"/>

EhcacheACL

200 / 350

http://lengyun3566.iteye.com

1.32 Spring Security3ACL

BasicLookupStrategyo.s.s.acls.domain.AuditLogger
BasicLookupStrategyACLACEAclCacheSpring Security
logbean

<bean class="org.springframework.security.acls.domain.ConsoleAuditLogger"
id="aclAuditLogger"/>

o.s.s.acls.domain.AclAuthorizationStrategyACL
ACLACE
ACL

<bean class="org.springframework.security.acls.domain.AclAuthorizationStrategyImpl"
id="aclAuthzStrategy">
<constructor-arg>
<array>
<ref local="aclAdminAuthority"/>
<ref local="aclAdminAuthority"/>
<ref local="aclAdminAuthority"/>
</array>
</constructor-arg>
</bean>
<bean class="org.springframework.security.core.authority.GrantedAuthorityImpl"
id="aclAdminAuthority">
<constructor-arg value="ROLE_ADMIN"/>
</bean>

aclAdminAuthorityAclAuthorizationStrategyImpl
GrantedAuthorityACL
Spring Security ACL
ACLACEHSQL
ACL entry

201 / 350

http://lengyun3566.iteye.com

1.32 Spring Security3ACL

JBCP Pets storeROLE_ADMIN

WEB-INFtest-acl-data.sqlJBCP PetsSQL
SQLSQL

ACL_CLASSACL
Category

insert into acl_class (class) values ('com.packtpub.springsecurity.


data.Category');

ACL_SIDSIDACESID
principal

insert into acl_sid (principal, sid) values (false, 'ROLE_USER');


insert into acl_sid (principal, sid) values (false, 'ROLE_ADMIN');

ACL_OBJECT_IDENTITY
SID
l CategoryOBJECT_ID_CLASSACL_CLASS
l PK1OBJECT_ID_IDENTITY
l SIDROLE_ADMINOWNER_SID columnACL_SID
1CategorySQL

insert into acl_object_identity (object_id_class,object_id_


identity,parent_object,owner_sid,entries_inheriting)
select cl.id, 1, null, sid.id, false
from acl_class cl, acl_sid sid

202 / 350

http://lengyun3566.iteye.com

1.32 Spring Security3ACL

where cl.class='com.packtpub.springsecurity.data.Category' and sid.


sid='ROLE_ADMIN';

SIDACL

ROLE_ADMINACE

insert into acl_entry (acl_object_identity, ace_order, sid, mask, granting, audit_success, audit_fa
from acl_object_identity oi, acl_sid si
where si.sid = 'ROLE_ADMIN';

MASKSID

SQL<embedded-database>ACL

<jdbc:embedded-database id="dataSource" type="HSQL">


<!--additional SQL files omitted -->
<jdbc:script location="classpath:acl-schema.sql"/>
<jdbc:script location="classpath:test-acl-data.sql"/>
</jdbc:embedded-database>

Pet
Apparel
AccessDeniedException
ACL
Spring ACL

203 / 350

http://lengyun3566.iteye.com

1.33 Spring Security3ACL

1.33 Spring Security3ACL


: 2012-01-10

ACL
ACLACEGrantedAuthority
ACL

Permission
permission
SID
Permissiono.s.s.acls.domain.BasePermissionACL
BasePermission. WRITE1
1

2 2

3ReadWrite
BasePermission
ACLo.s.s.acls.AclEntryVoter
BasePermission.READ
BasePermissionSpring Security
ACL

Spring ACL

204 / 350

http://lengyun3566.iteye.com

1.33 Spring Security3ACL

AclEntryVoter
@SecuredACLSpring ACL
ACE

AclEntryVotero.s.s.acls.model.ObjectIdentityRetrievalStrategy
o.s.s.acls.model.SidRetrievalStrategyObjectIdentitySids
ObjectIdentity
Sids
ObjectIdentitytypeidentifier
ACEObjectIdentityRetrievalStrategytypeidentifier
Serializable getId()ACLgetId

ACL
Spring Security ACL
205 / 350

http://lengyun3566.iteye.com

1.33 Spring Security3ACL

ObjectRetrievalStrategy

AclImplPermissionAclEntryVoterPermission
ACESpring Security
AclEntryVoter
ACEpermissionACE
ROLE_ADMIN SIDReadRead
Write3test-acl-data.sql

insert into acl_entry (acl_object_identity, ace_order, sid, mask, granting, audit_success, audit_fa
select oi.id, 1, si.id, 3, true, true, true
from acl_object_identity oi, acl_sid si
where si.sid = 'ROLE_ADMIN';

ACLACERead
WriteSpring Security ACL
ACL permission

permission
BasePermissionACL
ADMIN_READ
JBCP Pets
PII

com.packtpub.springsecurity.security.CustomPermissionBasePermission

package com.packtpub.springsecurity.security;
// imports omitted
public class CustomPermission extends BasePermission {
protected CustomPermission(int mask, char code) {
super(mask, code);
}

206 / 350

http://lengyun3566.iteye.com

1.33 Spring Security3ACL

protected CustomPermission(int mask) {


super(mask);
}
public static final Permission ADMIN_READ = new CustomPermission(1 << 5, 'M'); // 32
}

o.s.s.acls.domain.PermissionFactory
o.s.s.acls.domain.DefaultPermissionFactoryPermissionFactory

ADMIN_READPermissionFactory
com.packtpub.springsecurity.security.CustomPermissionFactory class

package com.packtpub.springsecurity.security;
// imports omitted
public class CustomPermissionFactory extends DefaultPermissionFactory
{
public CustomPermissionFactory() {
super();
registerPublicPermissions(CustomPermission.class);
}
public CustomPermissionFactory(Class<? extends Permission> permissionClass) {
super(permissionClass);
}
public CustomPermissionFactory(
Map<String, ? extends Permission> namedPermissions) {
super(namedPermissions);
}
}

CustomPermission
ACL
buildFromNameACLJSP tag

207 / 350

http://lengyun3566.iteye.com

1.33 Spring Security3ACL

CustomPermissionFactoryBasicLookupStrategydogstorebase.xml
<bean class="org.springframework.security.acls.jdbc.BasicLookupStrategy" id="lookupStrategy">
<constructor-arg ref="dataSource"/>
<constructor-arg ref="aclCache"/>
<constructor-arg ref="aclAuthzStrategy"/>
<constructor-arg ref="aclAuditLogger"/>
<property name="permissionFactory" ref="customPermissionFactory"/>
</bean>
<bean class="com.packtpub.springsecurity.security.CustomPermissionFactory"
id="customPermissionFactory"/>

ACLACL
Dog Foodtest-acl-data.sql

-- User SID
insert into acl_sid (principal, sid) values (true, 'admin2');
-- Category #2
insert into acl_object_identity (object_id_class,object_id_
identity,parent_object,owner_sid,entries_inheriting)
select cl.id, 2, null, sid.id, false
from acl_class cl, acl_sid sid
where cl.class='com.packtpub.springsecurity.data.Category' and sid.sid='admin2';
-- Give user 'admin2' access to category 2
-- "32" == 1 << 5
insert into acl_entry (acl_object_identity, ace_order, sid, mask,
granting, audit_success, audit_failure)
select oi.id, 2, si.id, 32, true, true, true
from acl_object_identity oi, acl_sid si
where si.sid = 'admin2' and oi.object_id_identity = 2;
commit;

32ACE
ADMIN_READACL_OBJECT_IDENTITYDog Foodobject_id_identity
2

208 / 350

http://lengyun3566.iteye.com

1.33 Spring Security3ACL

dogstore-base.xmlAclEntryVoter
<bean class="org.springframework.security.acls.AclEntryVoter" id="adminResourceReadVoter">
<constructor-arg ref="aclService"/>
<constructor-arg value="VOTE_ADMIN_READ"/>
<constructor-arg>
<array>

<util:constant static-field="com.packtpub.springsecurity.security.CustomPermission.ADMIN_READ
</array>
</constructor-arg>
<property name="processDomainObjectClass"
value="com.packtpub.springsecurity.data.Category"/>
</bean>

ACL

<bean class="org.springframework.security.access.vote.AffirmativeBased"
id="aclDecisionManager">
<property name="decisionVoters">
<list>
<ref bean="categoryReadVoter"/>
<ref bean="adminResourceReadVoter"/>
</list>
</property>
</bean>

IProductService
public interface IProductService {
// other methods omitted
@Secured({"VOTE_CATEGORY_READ","VOTE_ADMIN_READ"})
public Collection<Item> getItemsByCategory(Category cat);
}

209 / 350

http://lengyun3566.iteye.com

1.33 Spring Security3ACL

ACL

admin

admin2

guest

Pet apparel (1)

ROLE_ADMIN
SID ACEREAD

ROLE_ADMIN
SID ACEREAD

Dog Food ( 2)

SID
ACEADMIN_READ

Spring ACL
GrantedAuthority

JSPSpring Security JSP tagACL


Spring SecurityJSP tag

tagACL
ACL
<accesscontrollist>tag

<accesscontrollist>tag

210 / 350

http://lengyun3566.iteye.com

1.33 Spring Security3ACL

<c:forEach var="category" items="${categories}">


<security:accesscontrollist hasPermission="READ,ADMIN_READ" domainObject="${category}">
<li><a href="category.do?id=${category.name}">${category.name}
</a></li>
</security:accesscontrollist>
</c:forEach>

READADMIN_READ
JSP EL
${category}
tagSidRetrievalStrategy
ObjectIdentityRetrievalStrategyACL

211 / 350

http://lengyun3566.iteye.com

1.34 Spring Security3ACL

1.34 Spring Security3ACL


: 2012-01-17 : Spring Security, , , java ee

ACLSpring

SpELACLhasPermission SpEL
@PreAuthorize@PostAuthorize

ACLSpring Bean
<global-method-security>
ACL
hasPermission

<bean class="org.springframework.security.access.expression.method.
DefaultMethodSecurityExpressionHandler" id="methodExprHandler">
<property name="permissionEvaluator" ref="aclPermissionEvaluator"/>
</bean>
<bean class="org.springframework.security.acls.AclPermissionEvaluator"
id="aclPermissionEvaluator">
<constructor-arg ref="aclService"/>
<property name="permissionFactory" ref="customPermissionFactory"/>
</bean>

methodExprHandlerbeano.s.s.access.PermissionEvaluator
PermissionEvaluatoro.s.s.acls.AclPermissionEvaluator
AclServiceSpEL

tag
hasPermission<accesscontrollist> JSP tag
SpEL

212 / 350

http://lengyun3566.iteye.com

1.34 Spring Security3ACL

IProductService

@PostFilter("hasPermission(filterObject, 'READ') or hasPermission(filterObject, 'ADMIN_READ')")


Collection<Category> getCategories();

adminadmin2
ACLSpELhasPermissionACL

ACLMutable ACLs
JBCP Pets
SQL
Spring SecuritySpring ACL
ACLACL
Spring ACLACLo.s.s.acls.model.MutableAcl
AclMutableAclACLACL
ACEACE
Spring ACLACLJDBC
o.s.s.acls.jdbc.JdbcMutableAclServiceMutableAcl
ACLSIDObjectIdentity
JdbcMutableAclServiceJdbcAclService
serviceACLbean

<bean class="org.springframework.security.acls.jdbc.JdbcMutableAclService"
id="mutableAclService">
<constructor-arg ref="dataSource"/>
<constructor-arg ref="lookupStrategy"/>
<constructor-arg ref="aclCache"/>
</bean>

213 / 350

http://lengyun3566.iteye.com

1.34 Spring Security3ACL

AclAuthorizationStrategyImplACL
bean

ACL

ACL

ACL

JdbcMutableAclServiceACLACE
createAclupdateAcldeleteAclJdbcMutableAclServiceSpring
Security
ACLACLACE
ObjectIdentitySid

Spring
JdbcMutableAclServiceSpringJdbcTemplateJDBC DataSource
Spring JDBC PlatformTransactionManager

SpringJBCP Pets
dogstore-base.xml

214 / 350

http://lengyun3566.iteye.com

1.34 Spring Security3ACL

<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>

<bean class="com.packtpub.springsecurity.security.AclBootstrapBean"
init-method="aclBootstrap"/>

DatabasePasswordSecurerBeanbeanSpring
ApplicationContextaclBootstrapACL

JdbcMutableAclService
beancom.packtpub.springsecurity.security.AclBootstrapBean
@Autowired
package com.packtpub.springsecurity.security;
// imports omitted
public class AclBootstrapBean {
@Autowired
MutableAclService mutableAclService;
@Autowired
IProductDao productDao;
@Autowired
PlatformTransactionManager transactionManager;

ACL

public void aclBootstrap() {


// domain data to set up
Collection<Category> categories = productDao.getCategories();
Iterator<Category> iterator = categories.iterator();
final Category category1 = iterator.next();
final Category category2 = iterator.next();

215 / 350

http://lengyun3566.iteye.com

1.34 Spring Security3ACL

ACLACLSQL
ProductDAO
JdbcMutableAclServiceObjectIdentityMutableAcl
ObjectIdentity

// needed because MutableAclService requires a current authenticated principal


GrantedAuthorityImpl roleUser = new GrantedAuthorityImpl("ROLE_USER");
GrantedAuthorityImpl roleAdmin = new GrantedAuthorityImpl("ROLE_ADMIN");

UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("admin","admin"


SecurityContextHolder.getContext().setAuthentication(token);

JdbcMutableAclServiceMutableAcl
ACL
JdbcMutableAclServiceadmin

// sids
final Sid userRole = new GrantedAuthoritySid("ROLE_USER");
final Sid adminRole = new GrantedAuthoritySid("ROLE_ADMIN");
// users
final Sid adminUser = new PrincipalSid("admin");
final Sid admin2User = new PrincipalSid("admin2");

SidACLACE
ACLUI

// all interaction with JdbcMutableAclService must be within a


transaction
TransactionTemplate tt = new TransactionTemplate(transactionManager);
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus arg0)

216 / 350

http://lengyun3566.iteye.com

1.34 Spring Security3ACL

{
// category 1 ACL
MutableAcl createAclCategory1 = mutableAclService.createAcl(new Obje
ctIdentityImpl(category1));
createAclCategory1.setOwner(adminRole);
createAclCategory1.insertAce(0, BasePermission.READ, adminRole,
true);
mutableAclService.updateAcl(createAclCategory1);
// category 2 ACL
MutableAcl createAclCategory2 = mutableAclService.createAcl(new Obje
ctIdentityImpl(category2));
createAclCategory2.setOwner(admin2User);
createAclCategory2.insertAce(0, CustomPermission.ADMIN_READ,
admin2User, true);
mutableAclService.updateAcl(createAclCategory2);
}});
SecurityContextHolder.clearContext();
}
}

JdbcMutableAclServicecreateAcl
MutableAclObjectIdentitySidMutableAcl
ACLACEACE-SIDMutableAcl
updateAcl
JdbcMutableAclServiceMutableAclAclCache
ACLJdbcMutableAclService
ACL

Ehcache ACL
EhcacheJava
Spring SecurityACLEhcache
ACLACL
EhcacheSpring ACLcache

217 / 350

http://lengyun3566.iteye.com

1.34 Spring Security3ACL

Ehcache ACL
EhcacheSpring CorebeanEhcache

<bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
id="ehCacheManagerBean"/>
<bean class="org.springframework.cache.ehcache.EhCacheFactoryBean"
id="ehCacheFactoryBean">
<property name="cacheManager" ref="ehCacheManagerBean"/>
</bean>

Ehcache ACLbean

<bean class="org.springframework.security.acls.domain.EhCacheBasedAclCache"
id="ehCacheAclCache">
<constructor-arg ref="ehCacheFactoryBean"/>
</bean>

NullAclCacheEhcache

<bean class="org.springframework.security.acls.jdbc.BasicLookupStrategy" id="lookupStrategy">


<constructor-arg ref="dataSource"/>
<constructor-arg ref="ehCacheAclCache"/>
<constructor-arg ref="aclAuthzStrategy"/>
<constructor-arg ref="aclAuditLogger"/>
</bean>

EhcacheJARclasspathACLEhcache

218 / 350

http://lengyun3566.iteye.com

1.34 Spring Security3ACL

Spring ACLEhcache
Ehcache
EhcacheSpring ACL

ACLSpring ACLo.s.s.acls.domain
key
l ObjectIdentityObjectIdentityImpl
l SidGrantedAuthoritySidPrincipalSid
l AclAclImplAccessControlEntry AccessControlEntryImpl
l SerializableLongSpring ACL
BasicLookupStrategyMutableAclServiceACL

HibernateORMEhcache
ORMACLSpring ACL
EhCacheFactoryBeancache

<bean class="org.springframework.cache.ehcache.EhCacheFactoryBean"
id="ehCacheFactoryBean">
<property name="cacheManager" ref="ehCacheManagerBean"/>
<property name="cacheName" value="springAclCacheRegion"/>
</bean>

JavadocSpring CoreEhcacheSpring
ACLEhcache

219 / 350

1.35 Spring Security3ACL

http://lengyun3566.iteye.com

1.35 Spring Security3ACL


: 2012-01-17 : Spring Security, , , java ee

ACL
Spring ACLSpring ACL
Spring ACL
ACL
ACL
ACLACE
DBA
ACLJBCP PetsJBCP
Pets
l
l 10%2
l read-onlyread/write
l 10%20
l read-writeread-only
ACL

ACL_CLASS

NO

ACL_SID

YesUser

GrantedAuthority

220 / 350

1.35 Spring Security3ACL

http://lengyun3566.iteye.com

ACL_OBJECT_IDENTITY

ACL_ENTRY

Yes*

Yes*

ACE

ACE

ACL_CLASS1000ACL_SID

ACL_OBJECT_IDENTITYACL_ENTRY

ACL

ACL

ACL_OBJECT_IDENTITY

SIDread

SID

SID

ACL_ENTRY

ACL

221 / 350

1.35 Spring Security3ACL

http://lengyun3566.iteye.com

Users

Orders

ForumPosts

ACL_SID

ACL_OBJECT_IDENTITY

ACL_ENTRY

10,000

1,000,000

# Users * 0.1 * 2

2,000

200,000

# Users * 0.1 * 20

20,000

2,000,000

# Users

10,000

1,000,000

22,000

2,200,000

86,000

8,600,000

# Orders + #
Posts

(# Orders * 3) +
(# Posts * 4)

ACLACL
ACL
ACL

Spring ACL
ACL
l SID
l
l ACL
Spring ACLACL
ACEACLACE
hook

222 / 350

http://lengyun3566.iteye.com

1.35 Spring Security3ACL

ACL
hook
Spring ACLAcegi 1.x
Spring Security JIRA
http://jira.springframework.org/SEC-479
Spring Security3

l ACLGUIDUUID

l JIRASEC-1140ACLPermission

l Spring ACLSpring Security


DI
l Permissioninteger32

32

Spring SecurityACL
Spring SecuritySpring ACL
ACLSpring ACL
Spring ACLSpring ACL

223 / 350

http://lengyun3566.iteye.com

1.35 Spring Security3ACL

Spring Security ACL

l
l Spring ACLSID
l ACL
l Spring BeanSpring ACL
ACE
l Spring ACL
l SpringSecurity JSPSpELACL
l ACLACL
l ACL
l EhcacheSpring ACL
l Spring ACL

Spring SecuritySpring
SecurityOpenIDLDAP

224 / 350

http://lengyun3566.iteye.com

1.36 Spring Security3OpenIDSpring


Security

1.36 Spring Security3OpenIDSpring Security


: 2012-01-17 : Spring Security, Java EE, ,

OpenID
OpenIDprovider
OpenID
OpenIDOpenID

l OpenID
l OpenIDJBCP Pets
l OpenID
l OpenID
l OpenID
l OpenID

OpenID
OpenIDweb

Microsoft
PassportOpenIDOpenIDOpenID Provider
OpenIDOpenID

OpenIDOpenID

225 / 350

http://lengyun3566.iteye.com

1.36 Spring Security3OpenIDSpring


Security

Uniform Resource
IdentifierURIOpenIDOpenID
OpenIDURIhttps://jamesgosling.myopenid.
com/OpenIDURIhttps://me.yahoo.com/jamesgosling
URLOpenID
OpenIDOpenID
James Gosling
OpenIDOpenID
James GoslingID
OpenIDOpenIDOpenID

OpenIDOpenIDJBCP Pets
OpenID
OpenID
OpenIDhttp://openid.net/get-an-openid/OpenID
Yahoo!AOL FlickrMySpaceGoogleOpenID

226 / 350

http://lengyun3566.iteye.com

1.36 Spring Security3OpenIDSpring


Security

Sign In with Google

l myOpenID
l Google

Spring SecurityOpenID
Spring
Spring Security
openid4javahttp://code.google.com/p/openid4java/Spring SecurityOpenID
OpenID/negotiation
OpenID
OpenID
JBCP Pets

OpenIDform

<h1>Or, Log Into Your Account with OpenID</h1>


<p>
Please use the form below to log into your account with OpenID.
</p>

227 / 350

http://lengyun3566.iteye.com

1.36 Spring Security3OpenIDSpring


Security

<form action="j_spring_openid_security_check" method="post">


<label for="openid_identifier">Login</label>:
<input id="openid_identifier" name="openid_identifier" size="20" maxlength="100" type="text"/>
<img src="images/openid.png" alt="OpenID"/>
<br />
<input type="submit" value="Login"/>
</form>

Formopenid_identifierOpenIDOpenID
Verisign's OpenID
SeatBelt (https://pip.verisignlabs.com/seatbelt.do)
OpenIDOpenID
OpenIDremember me
remember meremember me
OpenIDOpenID
Spring SecurityOpenID
OpenIDservletdogstore-security.xml
<http>

<http auto-config="true" ...>


<!-- Omitting content... -->
<openid-login/>
</http>

OpenIDformOpenID
OpenIDJBCP Pets

OpenID
OpenID
test-users-groups-data.sql
myOpenIDYahoo!OpenID
https://jamesgosling.myopenid.com/SQL

228 / 350

http://lengyun3566.iteye.com

1.36 Spring Security3OpenIDSpring


Security

insert into users(username, password, enabled, salt) values ('https://jamesgosling.myopenid.com/','

insert into group_members(group_id, username) select id,'https://jamesgosling.myopenid.com/' from g

adminunused
OpenID
OpenID

OpenID

OpenIDJBCP PetsOpenID
OpenID

229 / 350

http://lengyun3566.iteye.com

1.37 Spring Security3OpenID

1.37 Spring Security3OpenID


: 2012-01-18 : Spring Security, java EE, ,

OpenID
Yahoo! OpenIDhttps://me.yahoo.com/pmularien
OpenIDOpenID
OpenID
OpenID
Yahoo!OpenIDhttps://me.yahoo.com/pmularien#9a466OpenID
user-supplied identifier
claimed identifier
OpenID
OpenID Provider
OpenIDOpenIDOpenID
OpenIDwww.yahoo.comOpenID
OpenIDOpenIDOpenID
OpenIDhttp://openid.net/developers/
OpenID
OpenIDOpenID Provider Local IdentifierOP-Local Identifier
OpenIDOpenIDJBCP
Pets
Spring SecurityOpenID

230 / 350

http://lengyun3566.iteye.com

1.37 Spring Security3OpenID

o.s.s.openid.OpenIDAuthenticationFilter/j_spring_openid_security_checkURL
UsernamePasswordAuthenticationFilter/j_spring_security_check URL
o.s.s.openid.OpenID4JavaConsumeropenid4javaOpenID
URLopenid4javaorg.openid4java.consumer.ConsumerManager

OpenIDOpenID
OpenIDGETopenid4java

openid.op_endpoint

OpenIDURL

openid.claimed_id

OpenID

231 / 350

http://lengyun3566.iteye.com

1.37 Spring Security3OpenID

openid.response_nonce

openid.sig

OpenID

openid.association

openid.identifier

OP-Local identifier

OpenID

232 / 350

http://lengyun3566.iteye.com

1.37 Spring Security3OpenID

OpenID/j_spring_openid_security_check
OpenIDAuthenticationFilterOpenIDJBCP Pets
OpenID
OpenIDIs
OpenID secure?OpenID4JavaConsumer
o.s.s.openid.OpenIDAuthenticationToken
tokenAuthenticationManagerAuthenticationManagerAuthentication

o.s.s.openid.OpenIDAuthenticationProviderJdbcDaoImpl
OP-Local Identifier
OpenID/
UserDetailsService
OpenID
OpenIDJBCP Pets
OpenID
RegistrationOpenID

OpenID
OpenID
registration.jsp

<h1>Or, Register with OpenID</h1>


<p>
Please use the form below to register your account with OpenID.
</p>
<form action="j_spring_openid_security_check" method="post">
<label for="openid_identifier">Login</label>:
<input id="openid_identifier" name="openid_identifier" size="50"
maxlength="100" type="text"/>
233 / 350

http://lengyun3566.iteye.com

1.37 Spring Security3OpenID

<img src="images/openid.png" alt="OpenID"/>


<br />
<input type="submit" value="Login"/>
</form>

OpenID

AuthenticationFailureHandler
com.packtpub.springsecurity.security.OpenIDAuthenticationFailureHandler

package com.packtpub.springsecurity.security;
// imports omitted
public class OpenIDAuthenticationFailureHandler extends
SimpleUrlAuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response, AuthenticationException exception)
throws IOException, ServletException {
if(exception instanceof UsernameNotFoundException && exception.getAuthentication() instanceof
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

request.getSession(true).setAttribute("USER_OPENID_CREDENTIAL", ((UsernameNotFoundException)excep
// redirect to create account page
redirectStrategy.sendRedirect(request, response, "/registrationOpenid.do");
} else {
super.onAuthenticationFailure(request, response, exception);
}
}
}

registrationOpenid.do

234 / 350

http://lengyun3566.iteye.com

1.37 Spring Security3OpenID

l UsernameNotFoundException
l OpenIDOpenIDAuthenticationToken
OpenIDAuthenticationStatus
OpenIDOP-Local IdentifiersessionOpenID
URL

dogstore-security.xml<openid-login>

<openid-login authentication-failure-handler-ref="openIdAuthFailureHandler">
<!-- The corresponding bean can be declared in dogstore-base.xml:-->
<bean id="openIdAuthFailureHandler"
class="com.packtpub.springsecurity.security.OpenIDAuthenticationFailureHandler">
<property name="defaultFailureUrl" value="/login.do"/>
</bean>

defaultFailureUrl

OpenID
OpenIDLoginLogoutController

@RequestMapping(method=RequestMethod.GET,value="/registrationOpenid.do")
public String registrationOpenId(HttpServletRequest request) {
String userId = (String) request.getSession().getAttribute("USER_OPENID_CREDENTIAL");
if(userId != null) {
userService.createUser(userId, "unused", null);
setMessage(request, "Your account has been created. Please log in using your OpenID.");
return "redirect:login.do";
} else {
setMessage(request, "Please register using your OpenID.");
return "redirect:registration.do";
235 / 350

http://lengyun3566.iteye.com

1.37 Spring Security3OpenID

}
}

IuserServiceUserServiceImplcreateUser

@Service
public class UserServiceImpl implements IUserService {
@Autowired
CustomJdbcDaoImpl jdbcDao;
// existing code omitted
@Override
public void createUser(String username, String password, String
email) {
jdbcDao.createUser(username, password, email);
}
}

@AutowiredCustomJdbcDaoImpl
createUser

@Transactional
public void createUser(String username, String password, String email)
{

getJdbcTemplate().update("insert into users(username, password, enabled, salt) values (?,?,true,C

getJdbcTemplate().update("insert into group_members(group_id, username) select id,? from groups w


}

SQL
DatabasePasswordSecurerBeansaltcreateUserSQL
Java

236 / 350

http://lengyun3566.iteye.com

1.37 Spring Security3OpenID

saltuserCustomJdbcDaoImpl
JdbcUserDetailsManagercreateUser

public class CustomJdbcDaoImpl


extends JdbcUserDetailsManager
implements IChangePassword {

UserServiceImpl

@Override
public void createUser(String username, String password, String email)
{
GrantedAuthority roleUser = new GrantedAuthorityImpl("ROLE_USER");

UserDetails user = new User(username, password, true, true, true, true, Arrays.asList(roleUser));
jdbcDao.createUser(user);
}

OpenID

IuserService
OpenIDAuthenticationToken

OP-Local identifiersOpenID 2.0OP-Local identifier


Spring SecurityJDBC
100
OpenIDOpenIDAuthenticationProviderUserDetailsService
URLURL
OpenIDOpenID
OpenIDOpenID

237 / 350

http://lengyun3566.iteye.com

1.37 Spring Security3OpenID

OpenIDOpenID
OpenIDOpenID

OpenID

238 / 350

http://lengyun3566.iteye.com

1.38 Spring Security3

1.38 Spring Security3


: 2012-01-18 : Spring Security, , , Java EE

Attribute Exchange
OpenIDOpenIDOpenID provider
e-mailAttribute ExchangeAX
OpenID

AXproviderOpenID
o.s.s.openid.OpenIDAttributelistOpenIDAuthenticationToken
AXOpenIDURI
http://www.axschema.org/types/

239 / 350

http://lengyun3566.iteye.com

1.38 Spring Security3

http://axschema.org/contact/email

e-mail

http://axschema.org/namePerson

axschema.org30URI
schema.openid.netaxschema.org
Spring Security
Spring Security OpenIDAX
Spring Security OpenIDAXAX
e-mail

<openid-login authentication-failure-handler-ref="openIdAuthFailureHandler">
<attribute-exchange>
<openid-attribute name="email" type="http://schema.openid.net/contact/email" required="true"/>
</attribute-exchange>
</openid-login>

myOpenID
JBCP PetsAX

240 / 350

http://lengyun3566.iteye.com

1.38 Spring Security3

OpenIDAuthenticationToken
<openid-attribute>

OpenIDAuthenticationFailureHandler

request.getSession(true).setAttribute("USER_OPENID_CREDENTIAL", ((UsernameNotFoundException)excepti
OpenIDAuthenticationToken openIdAuth = (OpenIDAuthenticationToken)exception.getAuthentication();
for(OpenIDAttribute attr : openIdAuth.getAttributes()) {

System.out.printf("AX Attribute: %s, Type: %s, Count: %d\n", attr.getName(), attr.getType(), attr
for(String value : attr.getValues()) {
System.out.printf(" Value: %s\n", value);
}
}
redirectStrategy.sendRedirect(request, response, "/registrationOpenid.
do");

241 / 350

http://lengyun3566.iteye.com

1.38 Spring Security3

AX Attribute: email, Type: http://schema.openid.net/contact/email,


Count: 1
Value: peter@mularien.com
AX Attribute: birthDate, Type: http://schema.openid.net/birthDate,
Count: 1
Value: 1968-04-13
AX Attribute: namePerson, Type: http://schema.openid.net/namePerson,
Count: 1
Value: Peter Mularien
AX Attribute: nickname, Type: http://schema.openid.net/namePerson/
friendly, Count: 1
Value: pmularien
AX Attribute: country, Type: http://schema.openid.net/contact/country/
home, Count: 1
Value: US

AXOpenIDAPI
AXOpenID

AX
AXOpenIDAX
myOpenIDGoogle
e-mailAX

myOpenID

242 / 350

AX

http://schema.openid.net/contact/
email

http://lengyun3566.iteye.com

Google

1.38 Spring Security3

http://axschema.org/contact/email

OpenIDOpenID

AXSimple Registration SRegopenid4java


Spring Security OpenIDSReg
AXAXSReg
Google OpenID
GoogleOpenIDOpenID
GoogleOpenIDGoogleURLGoogle
Sign in with GoogleGoogle OpenID

<form action="j_spring_openid_security_check" method="post">


<input name="openid_identifier" size="50" maxlength="100"
type="hidden" value="https://www.google.com/accounts/o8/id"/>
<input type="submit" value="Sign in with Google"/>
</form>

Google URL

243 / 350

http://lengyun3566.iteye.com

1.38 Spring Security3

GoogleOP-Local Identifier/OpenID

OpenID
OpenIDOpenIDOpenID

OpenID

l Response forgeryOpenID
hash

l Replay attacksnoncekey
OpenIDURL
nonce
man-in-the-middle attack
OpenIDOpenID
OpenID

openid4javaJDBCnonceSpring Security
OpenID
JVM

OpenIDOpenIDweb
web
OpenIDJBCP Pets

l OpenID
l JBCP PetsOpenID
l Attribute Exchange AXOpenID

244 / 350

http://lengyun3566.iteye.com

1.38 Spring Security3

l OpenID
web
LDAP

245 / 350

http://lengyun3566.iteye.com 1.39 Spring Security3LDAPLDAP

1.39 Spring Security3LDAPLDAP


: 2012-01-19 : Spring Security, java EE, ,

LDAP
Lightweight Directory Access ProtocolLDAP
Spring Security

l LDAP
l Spring SecurityLDAP
l LDAP
l LDAP
l LDAP
l LDAP
l Spring BeanSpring Security LDAP
l LDAPMicrosoft Active Directory

LDAP
LDAP
LDAP

LDAPLDAP

LDAP

246 / 350

http://lengyun3566.iteye.com 1.39 Spring Security3LDAPLDAP

LDAP
LDAPApache Directory Server
1.5LDAP

Albert EinsteinMr. Einstein


einsteinorganizational unitouusers
example.comdcdomain
componentLDAPDITRoot DSE
aeinsteinLDAP

Mr. Einstein

uid=aeinstein,ou=users,dc=example,dc=com

distinguished nameDN
DNSpring Security LDAP

Mr. Einstein
Mr. EinsteinLDAP

Spring Security LDAPSpring LDAPhttp://www.springsource.org/ldap


SpringSpring SecurityJava LDAP

247 / 350

http://lengyun3566.iteye.com 1.39 Spring Security3LDAPLDAP

LDAP
object class
personLDAP

LDAPschemaLDAP
LDAPZytrax OpenLDAP
http://www.zytrax.com/books/ldap/ape/ Internet2
http://middleware.internet2.edu/eduperson/
LDAPDN
DNDNLDAP
LDAPDN

LDAPLDAP

dc

ou

cn

248 / 350

Domain Component
LDAP

CountryLDAP

Organization name
LDAP

Organizational unit

Common name

dc=jbcppets,dc=com

c=US

o=Sun Microsystems

ou=Product Development

cn=Super Visor
cn=Jim Bob

http://lengyun3566.iteye.com 1.39 Spring Security3LDAPLDAP

LDAP

IDUser ID
uid

Spring

uid=svisor

uid

User password
userPassword

userPassword=plaintext

SHA

userPassword={SHA}cryptval

LDAPLDAP
Spring SecurityLDAP

LDAP
Spring SecurityLDAP
LDAP
LDAP
LDAPApache Directory Server (DS) 1.5Java
LDAPApache DS
DependenciesLDAPJAR
Mavenhttp://directory.apache.org/ Apache
DS
HSQLSQLLDAPLDAP
LDAP Data Interchange Format LDIFLDIF
LDAP
LDIF

LDAP
JBCP PetsLDAPLDAPLDIF
LDIFLDAP

249 / 350

http://lengyun3566.iteye.com 1.39 Spring Security3LDAPLDAP

Spring SecurityLDIFApache DS 1.5


SpringSecurity
LDAP
dogstore-security.xmlLDAPLDAP<http>
<authentication-manager>

<ldap-server ldif="classpath:JBCPPets.ldif" id="ldapLocal" root="dc=jb


cppets,dc=com"/>

classpathJBCPPets.ldifLDAPHSQL
WEB-INF/classesJBCPPets.ldifrootDNLDAP
LDIFDN
LDAProotXML
Apache DS server
Spring SecurityLDAPbean
IDLDAP<ldap-server>
LDAP AuthenticationProvider
AuthenticationProviderLDAP
AuthenticationProvider

<authentication-manager alias="authenticationManager">
<!-- Other authentication providers are here -->
<ldap-authentication-provider server-ref="ldapLocal"
user-search-filter="(uid={0})"
group-search-base="ou=Groups"
/>
</authentication-manager>

ldapguestpassword

250 / 350

http://lengyun3566.iteye.com 1.39 Spring Security3LDAPLDAP

LDAP
LDAPApache DS
SpringSecurity
l Apache DSJARwebclasspath

l <ldap-server>rootLDIFroot
rootLDIF
l LDAPLDIF
Apache DSERRORLDIFLDIF

l Windows
%TEMP%
LDAPHSQL
LDAP
LDAPApache Directory StudioEclipse
http://directory.apache.org/studio/

Spring LDAP
LDIFLDAPLDAP
LDAP
l LDAP
l LDAPGrantedAuthority
l LDAPUserDetails

AuthenticationManagerLDAP
o.s.s.ldap.authentication.LdapAuthenticationProviderLDAP

251 / 350

http://lengyun3566.iteye.com 1.39 Spring Security3LDAPLDAP

o.s.s.ldap.authentication.LdapAuthenticator
o.s.s.ldap.authentication.BindAuthenticator
LDAP
LDAPLDAP

<ldap-server>manager-dnLDAP
managerdnLDAP
manager-dnmanager-dnDN

252 / 350

http://lengyun3566.iteye.com 1.39 Spring Security3LDAPLDAP

LDAP
LDAP

LDAPLdapAuthenticationProvider
LdapAuthoritiesPopulatorDefaultLdapAuthoritiesPopulatorLDAP
DNLDAP

DNgroup-search-base
group-search-base="ou=Groups"DNgroup-search-base DN
DN
groupSearchBase
group-search-baseXML
XMLJava
Spring SecurityLDAPJBCP Pets
DefaultLdapAuthoritiesPopulator<ldap-authenticationprovider>
l group-search-baseDNLDAP
LDAP

253 / 350

http://lengyun3566.iteye.com 1.39 Spring Security3LDAPLDAP

l group-search-filterLDAPDNgroup-search-base
{0}DN{1}
uniqueMember={0}
l group-role-attributeGrantedAuthoritycn
l role-prefixgroup-role-attributeSpring SecurityGrantedAuthority
ROLE_
JDBCUserDetailsService
JBCP Pets LDAPldapguest
DNuid=ldapguest,ou=Users,dc=jbcppets,dc=comgroup-search-base
ou=GroupsouLDAP

ou=Groupscn=Admincn=UserobjectClass:
groupOfUniqueNamesLDAP
DNcn=User

cn=UseruniqueMemberLDAP
uniqueMemberDN

254 / 350

http://lengyun3566.iteye.com 1.39 Spring Security3LDAPLDAP

ou=Groups (group-search-base)Spring Security


uniqueMemberDNgroup-search-filter
cngroup-role-attributeUserROLE_ (role-prefix)
GrantedAuthority
Spring LDAPLDAPSpring Security
LDAPSpring SecuritySpring
SecurityLDAPSpringLDAP

Apache Directory Studio


LDAPSpring
Security LDAP
UserDetails
LDAPGrantedAuthority
o.s.s.ldap.userdetails.LdapUserDetailsMappero.s.s.ldap.userdetails.UserDetailsContextMapper
UserDetails
<ldap-authentication-provider>LdapUserDetailsMapper
LDAPUserDetails

255 / 350

http://lengyun3566.iteye.com 1.39 Spring Security3LDAPLDAP

UserDetailsContextMapperLDAP personinetOrgPerson
LdapUserDetailsMapperGrantedAuthority
LDAPJDBC
GrantedAuthoritysJDBCLDAP

256 / 350

http://lengyun3566.iteye.com 1.40 Spring Security3LDAPLDAP

1.40 Spring Security3LDAPLDAP


: 2012-01-19 : Spring Security, , , Java EE

LDAP
LDAPsecurity XMLSpring
Security LDAPLDAP
UserDetailsServiceDaoAuthenticationProvider
JBCP LDAP
JBCP Pets LDIF
userwithphonepassword

ldapguest

ROLE_USER

Plaintext

anotherldapuser

ROLE_USER

Plaintext

ldapadmin

ROLE_USER
ROLE_ADMIN

Plaintext

shapassworduser

ROLE_USER

{sha}

sshapassworduser

ROLE_USER

{ssha}

userwithphone

ROLE_USER

257 / 350

Plaintext
telephoneNumber

http://lengyun3566.iteye.com 1.40 Spring Security3LDAPLDAP

LDAP

Spring Securiry LDAP


o.s.s.ldap.authentication.PasswordComparisonAuthenticatorBindAuthenticator

PasswordComparisonAuthenticatorLDAPDN
LDAPuserPassword
BindAuthenticator

<ldap-authentication-provider>

258 / 350

http://lengyun3566.iteye.com 1.40 Spring Security3LDAPLDAP

<ldap-authentication-provider server-ref="ldapLocal"
user-search-filter="(uid={0})" group-search-base="ou=Groups">
<password-compare/>
</ldap-authentication-provider>

PasswordComparisonAuthenticatorLDAPSHA
SHA-1shapassworduser
password

LDAP
LDAP
LDAPSHASHA-1SSHAsalt
LDAPRFC 2307, An Approach for Using
LDAP as a Network Information Service (http://tools.ietf.org/html/rfc2307)
RFC 2307
SHALDAP
SHA

{SHA}5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8

{SHA}
SSHASHA-1salting
salthashhashsalthash
{SSHA}LDAP
LDAPSSHA

LDAPPasswordComparisonAuthenticator
sshapassworduserSSHA

SHA

259 / 350

http://lengyun3566.iteye.com 1.40 Spring Security3LDAPLDAP

LDAP
Spring Security LDAP

PasswordComparisonAuthenticatorLDAP
Spring Securitysshapassworduser
PasswordComparisonAuthenticatorSHA
SSHA
PasswordComparisonAuthenticatorhashSSHA

<password-compare hash="{ssha}"/>

SSHAsaltedsalt
LDAPPasswordComparisonAuthenticatorLDAP
PasswordComparisonAuthenticatorhash
salt
PasswordComparisonAuthenticator

UserDetailsContextMapper
o.s.s.ldap.userdetails.UserDetailsContextMapper
UserDetailsUserDetailsContextMapperJdbcDaoImpl
UserDetails
LDAPSpring Security
LDAPpersoninetOrgPerson

UserDetailsContextMapper
UserDetailsContextMapper
LdapAuthenticationProviderLdapUserDetailssecurity
LdapUserDetailsUserDetailsContextMapper
inetOrgPerson

260 / 350

http://lengyun3566.iteye.com 1.40 Spring Security3LDAPLDAP

<ldap-authentication-provider server-ref="ldapLocal"
user-search-filter="(uid={0})" group-search-base="ou=Groups"
user-details-class="inetOrgPerson">

LDAPUserDetailsContextMapper
inetOrgPerson

JBCP PetsView LDAP User Profile


personinetOrgPerson LDAPLDAP

AccountController

@RequestMapping(value="/account/viewLdapUserProfile.
do",method=RequestMethod.GET)
public void showViewLdapUserProfilePage(ModelMap model) {
final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
model.addAttribute("user", principal);
if(principal instanceof LdapUserDetailsImpl) {
model.addAttribute("isLdapUserDetails", Boolean.TRUE);
}
if(principal instanceof Person) {
model.addAttribute("isLdapPerson", Boolean.TRUE);
}
if(principal instanceof InetOrgPerson) {
model.addAttribute("isLdapInetOrgPerson", Boolean.TRUE);
}
}

LdapAuthenticationProviderAuthenticationUserDetails (principal)
LdapUserDetailsImplUserDetails
JSPJSPWebContent/WEB-INF/views/account/
viewLdapUserProfile.jsp

261 / 350

http://lengyun3566.iteye.com 1.40 Spring Security3LDAPLDAP

<!-- Common Header and Footer Omitted -->


<h1>View Profile</h1>
<p>
Some information about you, from LDAP:
</p>
<ul>
<li><strong>Username:</strong> ${user.username}</li>
<li><strong>DN:</strong> ${user.dn}</li>
<c:if test="${isLdapPerson}">
<li><strong>Description:</strong> ${user.description}</li>
<li><strong>Telephone:</strong> ${user.telephoneNumber}</li>
<li><strong>Full Name(s):</strong>
<c:forEach items="${user.cn}" var="cn">
${cn}<br />
</c:forEach>
</li>
</c:if>
<c:if test="${isLdapInetOrgPerson}">
<li><strong>Email:</strong> ${user.mail}</li>
<li><strong>Street:</strong> ${user.street}</li>
</c:if>
</ul>

WebContent/WEB-INF/views/account/home.jsp

<li><a href="viewLdapUserProfile.do">View LDAP User Profile</a></li>

shapasswordpersonshapasswordinetorgperson
View LDAP User Profile
personpersoninetOrgPersonuser-details-classinetOrgPerson
o.s.s.ldap.userdetails.InetOrgPerson

inetOrgPerson
RFC 2798, Definition of the inetOrgPerson LDAP Object Class (http://tools.ietf.org/html/rfc2798)

262 / 350

http://lengyun3566.iteye.com 1.40 Spring Security3LDAPLDAP

UserDetailsContextMappersuser-context-mapper-ref
UserDetailsContextMapper

LDAPuserPassword
LDAP

PasswordComparisonAuthenticatorLDAP
userPassword
telephoneNumber

<ldap-authentication-provider server-ref="ldapLocal"
user-search-filter="(uid={0})" group-search-base="ou=Groups"
user-details-class="inetOrgPerson">
<password-compare hash="plaintext" password-attribute="telephoneNumber"/>
</ldap-authentication-provider>

userwithphone1112223333
PasswordComparisonAuthenticator
LDAP
LDAPUserDetailsService
LDAPUserDetailsServiceUserDetailsServiceSpring
Securityremember meOpenID
LDAPUserDetailsServiceLDAP AuthenticationProviderJDBC
UserDetailsServiceLDAP UserDetailsService<http>

<ldap-user-service id="ldapUserService" server-ref="ldapLocal"


user-search-filter="(uid={0})" group-search-base="ou=Groups"/>

263 / 350

http://lengyun3566.iteye.com 1.40 Spring Security3LDAPLDAP

o.s.s.ldap.userdetails.LdapUserDetailsServiceLdapAuthenticationProvider
LDAP<ldap-server>

LDAPuser-details-service-ref
LdapUserDetailsService<authentication-provider>
LdapUserDetailsService<ldap-server>manager-dn
LDAPLdapUserDetailsService
OpenIDremember me

LDAP UserDetailsServiceremember me

More than one UserDetailsService registered. Please use a specific Id


reference in <remember-me/> <openid-login/> or <x509 /> elements.

remember me
remember meUserDetailsServiceremember me cookie
AbstractRememberMeServicesUserDetailsService
remember meUserDetailsService
LDAPJDBCremember me<remember-me>
UserDetailsServiceSpring Bean IDSpring Security

remember me
LDAPremember meLDAPremember me
JDBCtoken remember me
remember me cookieremember me
InMemoryTokenRepositoryImplUserDetailsLDAP
userPasswordPasswordComparisonAuthenticator
LdapUserDetailsMapperUserDetailspassword
remember me cookiecookie

264 / 350

http://lengyun3566.iteye.com 1.40 Spring Security3LDAPLDAP

JDBCremember me cookie
cookie
LDAP
LDAPLDAP
LDAP <ldap-server>
10389LDAP

<ldap-server url="ldap://localhost:10389/dc=jbcppets,dc=com"
id="ldapLocal"

manager-dn="uid=admin,ou=system" manager-password="secret"/>

LDAP URLDN
LDAPURL
LDAP
LDAPSSLLDAPLDAPSSpring LDAP
LDAPURLldaps://LDAPS636TCP
LDAPGrantedAuthoritys
LDAPMicrosoft Active
Directory

265 / 350

http://lengyun3566.iteye.com 1.41 Spring Security3LDAPLDAP

1.41 Spring Security3LDAPLDAP


: 2012-01-19

LDAP bean
beanLDAP
LdapAuthenticationProviderbeansecurity

LDAP
10389LDAP<ldapserver>beandogstore-base.xml

<bean class="org.springframework.security.ldap.DefaultSpringSecurityContextSource"
id="ldapServer">
<constructor-arg value="ldap://localhost:10389/dc=jbcppets,dc=com"/>
<property name="userDn" value="uid=admin,ou=system"/>
<property name="password" value="secret"/>
</bean>

LdapAuthenticationProvider

LdapAuthenticationProvider

Spring Security LDAPbean


LdapAuthenticationProvider
l
l UserDetailsContextMapperInetOrgPerson
LdapAuthenticationProvider

266 / 350

http://lengyun3566.iteye.com 1.41 Spring Security3LDAPLDAP

<bean class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider" id="ldapA


<constructor-arg ref="ldapBindAuthenticator"/>
<constructor-arg ref="ldapAuthoritiesPopulator"/>
<property name="userDetailsContextMapper" ref="ldapUserDetailsConte
xtMapper"/>
</bean>

BindAuthenticatorFilterBasedLdapUserSearch beanLDAP
DN

<bean class="org.springframework.security.ldap.authentication.BindAuthenticator" id="ldapBindAuthen


<constructor-arg ref="ldapServer"/>
<property name="userSearch" ref="ldapSearchBean"/>
</bean>
<bean class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch"
id="ldapSearchBean">
<constructor-arg value=""/> <!-- user-search-base -->
<constructor-arg value="(uid={0})"/> <!-- user-search-filter -->
<constructor-arg ref="ldapServer"/>
</bean>

LdapAuthoritiesPopulatorUserDetailsContextMapper

<bean class="org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator"
id="ldapAuthoritiesPopulator">
<constructor-arg ref="ldapServer"/>
<constructor-arg value="ou=Groups"/>
<property name="groupSearchFilter" value="(uniqueMember={0})"/>
</bean>

267 / 350

http://lengyun3566.iteye.com 1.41 Spring Security3LDAPLDAP

<bean class="org.springframework.security.ldap.userdetails.InetOrgPersonContextMapper"
id="ldapUserDetailsContextMapper"/>

LdapAuthenticationProviderdogstoresecurity.xml

<authentication-manager alias="authenticationManager">
<authentication-provider ref="ldapAuthProvider"/>
</authentication-manager>

Spring beanLDAP
beanLDAPsecurity

LDAPMicrosoft Active Directory

LDAPMicrosoft Active Directory


Microsoft Active DirectoryMicrosoft Windows
LDAPActive DirectoryWindows
LDAPActive Directory
Microsoft Active DirectorySpring Security LDAP
Active DirectorySpring Security
GrantedAuthority
JBCP PetsActive Directory LDAPLDAP

268 / 350

http://lengyun3566.iteye.com 1.41 Spring Security3LDAPLDAP

LDAPou=GroupsActive Directory
Spring SecurityActive Directory LDAP
LdapAuthoritiesPopulator
beanLdapAuthoritiesPopulator
LDAPROLE_USER
com.packtpub.springsecurity.security.SimpleRoleGrantingLdapAuthoritiesPopulator

public class SimpleRoleGrantingLdapAuthoritiesPopulator implements


LdapAuthoritiesPopulator {
protected String role = "ROLE_USER";
public Collection<GrantedAuthority> getGrantedAuthorities(
DirContextOperations userData, String username) {
GrantedAuthority ga = new GrantedAuthorityImpl(role);
return Arrays.asList(ga);

269 / 350

http://lengyun3566.iteye.com 1.41 Spring Security3LDAPLDAP

}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}

o.s.ldap.core.DirContextOperations
LDAP
beanActive Directory

<bean class="org.springframework.security.ldap.
DefaultSpringSecurityContextSource" id="ldapServer">
<constructor-arg value="ldap://corp.jbcppets.com/dc=corp,dc=jbcppets,dc=com"/>
<property name="userDn"
value="CN=Administrator,CN=Users,DC=corp,DC=jbcppets,DC=com"/>
<property name="password" value="admin123!"/>
</bean>
<bean class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch"
id="ldapSearchBean">
<constructor-arg value="CN=Users"/>
<constructor-arg value="(sAMAccountName={0})"/>
<constructor-arg ref="ldapServer"/>
</bean>

<bean class="com.packtpub.springsecurity.security.SimpleRoleGrantingLdapAuthoritiesPopulator" id="l

sAMAccountNameActive DirectoryLDAPuid
Active Directory
Active Directory LDAPSpring
Security LDAP

270 / 350

http://lengyun3566.iteye.com 1.41 Spring Security3LDAPLDAP

Active DirectoryKerberosSpring Security


Spring Security
Active DirectoryLDAPKerberos
UserDetailsService
beanUserDetailsService
GrantedAuthoritybeanUserDetailsServiceJDBC

<bean class="org.springframework.security.ldap.authentication.UserDetailsServiceLdapAuthoritiesPopu
<constructor-arg ref="jdbcUserServiceCustom"/>
</bean>

LDAPUserDetailsService

LDAP
LDAP

LDAP

l LDAPLDAP Spring Security


l Spring SecurityLDAP
l LDAPSpring Security
l LDAPSpring Security
l LDAPUserDetailsLDAPSpring
l LDAPbean

271 / 350

http://lengyun3566.iteye.com 1.41 Spring Security3LDAPLDAP

272 / 350

http://lengyun3566.iteye.com

1.42 Spring Security3CASCAS

1.42 Spring Security3CASCAS


: 2012-01-19 : Spring Security, , , Java EE

CAS
Central Authentication ServiceCASSpring
Securitysingle sign-on portal

l CAS
l Spring SecurityCAS
l JBCP PetsCAS
l CASLDAPCASLDAPSpring Security
l CAS 2.0SAML1.1

CAS
Central Authentication ServiceCAS
webCAS
l
l
l CASwebwebJava
l CASCAS

CASCAS
CASintranetSony Online
Entertainment's Dun and Bradstreet's
273 / 350

http://lengyun3566.iteye.com

1.42 Spring Security3CASCAS

CAS
CAS
l
l CAS
l CASCAS
CAS ticket
l CASticketCAS
assertionticket

CAS
274 / 350

http://lengyun3566.iteye.com

1.42 Spring Security3CASCAS

SSL
CASSpring Security
SpringCAS
Spring SecurityCASOpenIDLDAP
securitybeansecurity
bean
CAS
l AuthenticationEntryPointCAS

l CASticket
CASCAS
Spring SecurityCASCAS
CASSpring
SecurityLDAP
UserDetails
CASSpring SecurityLog In
CAS

CAS
CAS
CASGet StartedCAS
http://localhost:8080/cas/
CASJBCP PetsTomcatJBCP Pets
CASCAS8080JBCP Pets8081
CAS3.3.5
CAS3.xCAS

CAS
275 / 350

http://lengyun3566.iteye.com

1.42 Spring Security3CASCAS

CAS
CASJBCP PetsSpring Security
bean

CasAuthenticationEntryPoint
AuthenticationEntryPoint

CAS
o.s.s.cas.web.CasAuthenticationEntryPoint
dogstore-base.xmlbean

276 / 350

http://lengyun3566.iteye.com

1.42 Spring Security3CASCAS

<bean id="casAuthEntryPoint"
class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
<property name="loginUrl" value="http://localhost:8080/cas/"/>
<property name="serviceProperties" ref="casService"/>
</bean>

dogstore-security.xmlsecuritybean

<http auto-config="true"
entry-point-ref="casAuthEntryPoint">

CasAuthenticationEntryPointserviceProperties
o.s.s.cas.ServicePropertiesCAS
URL

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


<property name="service"
value="http://localhost:8081/JBCPPets/j_spring_cas_security_check"/>
</bean>

ServicePropertiesCAS
Spring CASCAS
CASURLCAS
CAS
CAS
serviceCASCAS
URLURL
CAS
My AccountROLE_USERCAS
adminadminguest/guest

277 / 350

http://lengyun3566.iteye.com

1.42 Spring Security3CASCAS

CAS
ticketCASAccessDeniedExceptionticket
CAS
CAS Spring Security
FilterSecurityInterceptorCAS
CasAuthenticationEntryPointCAS
CAS
OpenID
OpenIDCASOpenID
CASCAS
OpenIDnoncekeyOpenID
OpenIDCASCAS
ticketOpenIDOpenID
CASCASCAS
URLticketCAS
OpenIDCASdogstorebase.xmlSpring bean

<bean id="casAuthenticationFilter"
class="org.springframework.security.cas.web.CasAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager"/>
</bean>

dogstore-security.xmlsecurity

<http auto-config="true" ...>


...
<custom-filter ref="casAuthenticationFilter" position="CAS_FILTER"/>
</http>

CasAuthenticationFilterAuthenticationManagerdogstoresecurity.xml<authentication-manager>alias
278 / 350

http://lengyun3566.iteye.com

<authentication-manager

1.42 Spring Security3CASCAS

alias="authenticationManager">

ServicePropertiesCASURL
http://localhost:8081/JBCPPets/j_spring_cas_security_check
/j_spring_cas_security_check URLCasAuthenticationFilterURLCAS

CASURLCASURL /j_spring_cas_security_check
CasAuthenticationFilterfilterProcessesUrlURLURL
Spring Security/CAS

CasAuthenticationFilterAuthentication
UsernamePasswordAuthenticationTokenCAS
CasAuthenticationProvider
Spring SecurityAuthentication
tokenAuthenticationProviderCAS
o.s.s.cas.authentication.CasAuthenticationProviderAuthenticationManager
dogstore-base.xmlSpring bean

<bean id="casAuthenticationProvider"
class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
<property name="ticketValidator" ref="casTicketValidator"/>
<property name="serviceProperties" ref="casService"/>
<property name="key" value="jbcp-pets-dogstore-cas"/>
<property name="authenticationUserDetailsService" ref="authenticationUserDetailsService"/>
</bean>

dogstore-security.xmlAuthenticationProvider<authenticationmanager>

279 / 350

http://lengyun3566.iteye.com

1.42 Spring Security3CASCAS

<authentication-manager alias="authenticationManager">
<authentication-provider ref="casAuthenticationProvider"/>
</authentication-manager>

AuthenticationProviderCAS
CasAuthenticationProviderbean
ticketValidatororg.jasig.cas.client.validation.TicketValidator
CAS 2.0org.jasig.cas.client.validation.Cas20ServiceTicketValidator

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


<constructor-arg value="http://localhost:8080/cas/"/>
</bean>

CASURL
org.springframework.securityorg.jasigCASJAR
TicketValidatorCASCASJARSAML
URLCASSpring
URLURLpropertiesSpring
PropertyPlaceholderConfigurerproperties
Spring
keyUsernamePasswordAuthenticationToken

authenticationUserDetailsService
o.s.s.core.userdetails.AuthenticationUserDetailsServiceAuthentication
UserDetailsAuthentication
UserDetailsService JdbcDaoImpl

<bean id="authenticationUserDetailsService"
class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<property name="userDetailsService" ref="jdbcUserService"/>
</bean>
280 / 350

http://lengyun3566.iteye.com

1.42 Spring Security3CASCAS

UserDetailsServiceCAS
UserDetails
CASJBCP Pets

281 / 350

http://lengyun3566.iteye.com

1.43 Spring Security3CASCAS

1.43 Spring Security3CASCAS


: 2012-01-19 : Spring Security, , , Java EE

CAS
CASCASCAS
CASCAS

CAS assertion
CASticketCASCAS
CAS
GrantedAuthority

CAS
CASCASCASLDAP

282 / 350

http://lengyun3566.iteye.com

1.43 Spring Security3CASCAS

CASSpring SecurityCASCAS
CAS
CASorg.jasig.cas.authentication.AuthenticationManagerSpringSecurity
Spring Security
org.jasig.cas.authentication.handler.AuthenticationHandlerSpring Security
AuthenticationProvider
org.jasig.cas.authentication.principal.CredentialsToPrincipalResolver
org.jasig.cas.authentication.principal.PrincipalSpring Security
UserDetailsService

283 / 350

http://lengyun3566.iteye.com

1.43 Spring Security3CASCAS

CAS
CASJA-SIG CAS wiki http://www.ja-sig.org/
wiki/display/CAS

CASLDAP
CAS
org.jasig.cas.authentication.principal.UsernamePasswordCredentialsToPrincipalResolver
Spring Security CAS
LDAP
org.jasig.cas.authentication.handler.AuthenticationHandlerLDAP
CASLDAP
CASCASWEB-INF/deployerConfigContext.xml

CASSpringJBCP Pets
IDECAS
WEB-INF/deployerConfigContext.xmlCASJBCP Pets
AuthenticationHandler
SimpleTestUsernamePasswordAuthenticationHandlerLDAP
LDAPAuthenticationHandlerauthenticationManager bean
authenticationHandlers

<property name="authenticationHandlers">
<list>
<!-- ... -->
<bean class="org.jasig.cas.adaptors.ldap.BindLdapAuthenticationHandler">
<property name="filter" value="uid=%u" />
<property name="searchBase" value="ou=Users,dc=jbcppets,dc=com" />
<property name="contextSource" ref="contextSource" />
</bean>

SimpleTestUsernamePasswordAuthenticationHandler
BindLdapAuthenticationHandlerCASLDAP

284 / 350

http://lengyun3566.iteye.com

1.43 Spring Security3CASCAS

beancontextSource bean
org.springframework.ldap.core.ContextSourceCASLDAPCAS
Spring LDAP

<bean id="contextSource" class="org.springframework.ldap.core.support.LdapContextSource">


<property name="urls">
<list>
<value>ldap://127.0.0.1:33389</value>
</list>
</property>
<property name="userDn"
value="uid=ldapadmin,ou=Administrators,ou=Users,dc=jbcppets,dc=com"/>
<property name="password" value="password"/>
<property name="baseEnvironmentProperties">
<map>
<entry>
<key>
<value>java.naming.security.authentication</value>
</key>
<value>simple</value>
</entry>
</map>
</property>
</bean>

Spring SecurityLDAPCASDN
LDAPJBCPPets.ldif
URL ldap://127.0.0.1:3338933389Spring SecurityLDAP
LDAPSCAS LDAP

org.jasig.cas.authentication.principal.CredentialsToPrincipalResolverCAS
BindLdapAuthenticationHandler
org.jasig.cas.authentication.principal.Principal
CAS

285 / 350

http://lengyun3566.iteye.com

1.43 Spring Security3CASCAS

CAS authenticationManager beancredentialsToPrincipalResolvers


bean

<property name="credentialsToPrincipalResolvers">
<list>

<bean class="org.jasig.cas.authentication.principal.CredentialsToLDAPAttributePrincipalResolver
<property name="credentialsToPrincipalResolver">

<bean class="org.jasig.cas.authentication.principal.UsernamePasswordCredentialsToPrincipalR
</property>
<property name="filter" value="(uid=%u)" />
<property name="principalAttributeName" value="uid" />
<property name="searchBase" value="ou=Users,dc=jbcppets,dc=com" />
<property name="contextSource" ref="contextSource" />
<property name="attributeRepository" ref bean="attributeRepository" />
</bean>

Spring Security LDAPCASDN

attributeRepository
org.jasig.services.persondir.IpersonAttributeDaoCAS
org.jasig.services.persondir.support.StubPersonAttributeDaoLDAP

CASLDAPCASJBCP Pets
LDAPldapguestpassword
403AuthenticationUserDetailsService
LDAP

CAS assertionUserDetails
CASSpring SecurityUserDetailsByNameServiceWrapper
CASUserDetailsUserDetailsService
JdbcDaoImplCASLDAPLdapUserDetailsService

286 / 350

http://lengyun3566.iteye.com

1.43 Spring Security3CASCAS

Spring Security CASCAS assertion


UserDetailsAuthenticationUserDetailsService
o.s.s.cas.userdetails.GrantedAuthorityFromAssertionAttributesUserDetailsService
CAS assertionGrantedAuthorityassertion
roledogstore-base.xml
authenticationUserDetailsService bean

<bean id="authenticationUserDetailsService"

class="org.springframework.security.cas.userdetails.GrantedAuthorityFromAssertionAttributesUserDet
<constructor-arg>
<array>
<value>role</value>
</array>
</constructor-arg>
</bean>

assertion

CAS assertion
CASJBCP PetsAccountControllerCAS
CASURLAccountController

@RequestMapping(value="/account/viewCasUserProfile.do",method=RequestMethod.GET)
public void showViewCasUserProfilePage(ModelMap model) {
final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
model.addAttribute("auth", auth);
if(auth instanceof CasAuthenticationToken) {
model.addAttribute("isCasAuthentication", Boolean.TRUE);
}
}

JSPCasAuthenticationTokenCAS
WEB-INF/views/account/viewCasUserProfile.jsp

287 / 350

http://lengyun3566.iteye.com

1.43 Spring Security3CASCAS

<!-- Common Header and Footer Omitted -->


<h1>View Profile</h1>
<p>
Some information about you, from CAS:
</p>
<ul>
<li><strong>Auth:</strong> ${auth}</li>
<li><strong>Username:</strong> ${auth.principal}</li>
<li><strong>Credentials:</strong> ${auth.credentials}</li>
<c:if test="${isCasAuthentication}">
<li><strong>Assertion:</strong> ${auth.assertion}</li>
<li><strong>Assertion Attributes:</strong>
<c:forEach items="${auth.assertion.attributes}" var="attr">
${attr.key}:${attr.value}<br />
</c:forEach>
</li>
<li><strong>Assertion Attribute Principal:</strong> ${auth.assertion.principal}</li>
<li><strong>Assertion Principal Attributes:</strong>
<c:forEach items="${auth.assertion.principal.attributes}" var="attr">
${attr.key}:${attr.value}<br />
</c:forEach>
</li>
</c:if>
</ul>

WEB-INF/views/account/home.jsp

<h1>Welcome to Your Account</h1>


<!-- omitted -->
<ul>
<li><a href="viewCasUserProfile.do">View CAS User Profile</a></li>

assertionFinally, we'll have to


(temporarily) disable authorization checks for this page, until we get assertion attribute-based authorization
288 / 350

http://lengyun3566.iteye.com

1.43 Spring Security3CASCAS

working. dogstore-security.xmlGrantedAuthority

My Account

<intercept-url pattern="/home.do" access="permitAll"/>


<intercept-url pattern="/account/home.do" access="!anonymous"/>
<intercept-url pattern="/account/view*Profile.do"
access="!anonymous"/>
<intercept-url pattern="/account/*.do" access="hasRole('ROLE_USER')"/>

UIJBCP Pets
assertion

LDAPCAS
LDAPCAS assertionGrantedAuthority
role
CAS deployerConfigContext.xmlCAS
CAS PrincipalCAS IPersonAttributesticket
beanbeanattributeRepository

<bean id="attributeRepository"
class="org.jasig.services.persondir.support.ldap.LdapPersonAttributeDao">
<property name="contextSource" ref="contextSource" />
<property name="requireAllQueryAttributes" value="true" />
<property name="baseDN" value="ou=Users,dc=jbcppets,dc=com" />
<property name="queryAttributeMapping">
<map>
<entry key="username" value="uid" />
</map>
</property>
<property name="resultAttributeMapping">
<map>
<entry key="cn" value="FullName" />
<entry key="sn" value="LastName" />
289 / 350

http://lengyun3566.iteye.com

1.43 Spring Security3CASCAS

<entry key="description" value="role" />


</map>
</property>
</bean>

PrincipalLDAP
queryAttributeMappingPrincipalusernameLDAPuidbaseDN
LDAPuid=ldapguest Principal
resultAttributeMappingLDAPcnsn
descriptionrolerole
GrantedAuthorityFromAssertionAttributesUserDetailsService
Person
Directoryhttp://www.ja-sig.org/wiki/display/PD/Home
Person DirectoryCAS
CAS
CASLDAPSpring Security LDAPLDAP
PrincipalLDAPDNuniqueMember
groupOfUniqueNamesCAS LDAPLDAP
CAS
LDAPCAS
CASwikihttp://www.ja-sig.org/wiki/display/CASUM/Home

CAS assertion
CAS 2.0CASJIRA
CAS2.0
CASCASticket
JSPCASCas20ServiceTicketValidator
CASWEB-INF/view/jsp/protocol/2.0/casServiceValidationSuccess.jsp

290 / 350

http://lengyun3566.iteye.com

1.43 Spring Security3CASCAS

<cas:authenticationSuccess>

<cas:user>${fn:escapeXml(assertion.chainedAuthentications[fn:length(assertion.chainedAuthenticati
<cas:attributes>

<c:forEach var="attr" items="${assertion.chainedAuthentications[fn:length(assertion.chainedAuthen


varStatus="loopStatus" begin="0"

end="${fn:length(assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].
<cas:${fn:escapeXml(attr.key)}>${fn:escapeXml(attr.value)}</cas:${fn:escapeXml(attr.key)}>
</c:forEach>
</cas:attributes>

CAS

<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
<cas:authenticationSuccess>
<cas:user>ldapguest</cas:user>
<cas:attributes>
<cas:FullName>LDAP Guest</cas:FullName>
<cas:role>ROLE_USER</cas:role>
<cas:LastName>Guest</cas:LastName>
</cas:attributes>
</cas:authenticationSuccess>
</cas:serviceResponse>

CASJBCP PetsldapguestROLE_USER
View CAS ProfileCAS assertion
LdapPersonAttributeDao.resultAttributeMappingCAS
XMLXML
JSP

CASCas20ServiceTicketValidatorSpring Security
CAS

291 / 350

http://lengyun3566.iteye.com

1.43 Spring Security3CASCAS

SAML 1.1
SAMLXML assertionSAML
CASSpring SecuritySAML
SAMLassertion XMLCAS
CAS ticketSAML ticketdogstore-base.xmlTicketValidator
bean

<bean id="samlTicketValidator" class="org.jasig.cas.client.validation.Saml11TicketValidator">


<constructor-arg value="http://localhost:8080/cas/"/>
</bean>

CasAuthenticationProviderTicketValidator

<bean id="casAuthenticationProvider"
class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
<property name="ticketValidator" ref="samlTicketValidator"/>
<property name="serviceProperties" ref="casService"/>

JBCP PetsSAMLticketCAS ticketSpring


SecurityJA-SIG CASlog4jorg.jasig

SAML ticketCAS 2.0 ticket

CAS
CAS

CASLDAP
CASCAS

292 / 350

http://lengyun3566.iteye.com

1.43 Spring Security3CASCAS

CASCAS
CAS
Spring Security CASCAS
AuthenticationCAS
session
CAS
Spring Security CASCAS
l CASCAS
TicketValidatorrenewtrueCAS

l CASticketCASticketweb
ticketCAShttp://www.jasig.org/cas/proxyauthentication
l CAS sessionSpring SecurityCAS
HttpSessionListenerservlet
CASJA-SIG

CASSpring Security

CASCAS
CAS
JBCP PetsCAS
CASLDAPLDAPCAS
CAS 2.0SAMLCAS

CASSSO

293 / 350

http://lengyun3566.iteye.com

1.43 Spring Security3CASCAS

294 / 350

http://lengyun3566.iteye.com

1.44 Spring Security3

1.44 Spring Security3


: 2012-02-13 : Spring Security, ,

Client Certificate
Authentication
Spring Security
formSpring Security
form

l
l Spring Security
l Spring Security
l
l

certificates
servlet

mutual authenticationsocketSecure Sockets


LayerSSLTransport Layer SecurityTLS
295 / 350

http://lengyun3566.iteye.com

1.44 Spring Security3

SSLTLSHTTPSSSLTLS
Spring SecuritySSL/TLSSSL/TLS
TomcatSSL/TLS
SSLSSL/TLS
webSSL

SSLSSLTLS
RFC 5246, The Transport Layer Security (TLS) Protocol
V1.2 (http://tools.ietf.org/html/rfc5246)
Eric RescorlaSSL and TLS: Designing and Building Secure Systems

296 / 350

http://lengyun3566.iteye.com

1.44 Spring Security3

X.509X.509X.509ITU-T
X.500LDAPLDAP

Spring SecurityX.509X.509

Spring Security

Apache Tomcat
CA
SSL
TomcatSpring SecuritySSL

Spring Security

web
S/MIMEPKCS 11In addition to being
used for web application authentication, certificates or hardware devices in these environments can
be used for secure, non-repudiated email (using S/MIME), network authentication, and even physical
building access (using PKCS 11-based hardware devices)
IT

keytool
webkey storetrust store

297 / 350

http://lengyun3566.iteye.com

1.44 Spring Security3

keytool -genkeypair -alias jbcpclient -keyalg RSA -validity 365 -keystore


jbcppets_clientauth.p12 -storetype PKCS12

common nameDNDN
Spring Security JDBCadmin

What is your first and last name?


[Unknown]: admin
... etc
Is CN=admin, OU=JBCP Pets, O=JBCP Pets, L=Anywhere, ST=NH, C=US
correct?
[no]: yes

Spring SecurityTomcat

Tomcattrust store
SSL

keytooljava

Tomcat
Tomcattrust store
jbcppets_clientauth.cer

298 / 350

http://lengyun3566.iteye.com

1.44 Spring Security3

keytool -exportcert -alias jbcpclient -keystore jbcppets_clientauth.p12 storetype PKCS12 -storepass password -file jbcppets_clientauth.cer

trust storetrust store


trust store

keytool -importcert -alias jbcpclient -keystore tomcat.truststore -file


jbcppets_clientauth.cer

tomcat.truststoretrust store

Owner: CN=admin, OU=JBCP Pets, O=JBCP Pets, L=Anywhere, ST=NH,


C=US
Issuer: CN=admin, OU=JBCP Pets, O=JBCP Pets, L=Anywhere, ST=NH, C=US
Serial number: 4b3fb3d9
Valid from: Sat Jan 02 16:00:09 EST 2010 until: Sun Jan 02 16:00:09
EST 2011
Certificate fingerprints:
MD5: 02:69:16:3B:D7:C2:74:9E:F7:FD:18:C9:C5:E4:C8:94
SHA1: 65:57:94:6D:D2:83:7E:51:19:CF:58:94:ED:43:11:F6:AC:D0:FB:EC
Signature algorithm name: SHA1withRSA
Version: 3
Trust this certificate? [no]: yes

tomcat.truststoreTomcatconf

Key StoreTrust StoreJava Secure Socket Extension (JSSE)key store


key storetrust store
299 / 350

http://lengyun3566.iteye.com

1.44 Spring Security3

trust store
key storetrust storeTomcat
ConnectorkeystoreFiletruststoreFile
JSSEkeystoreJava Key Store / JKS, PKCS 12
Tomcattrust storeTomcat server.xml
SSL Connector

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"


maxThreads="150" scheme="https" secure="true"
sslProtocol="TLS"
keystoreFile="conf/tomcat.keystore"
keystorePass="password"
truststoreFile="conf/tomcat.truststore"
truststorePass="password"
clientAuth="true"
/>

SSLTomcatTomcat
Tomcat
Tomcat

FirefoxIE

Firefox
key
1.

2.

3.

300 / 350

http://lengyun3566.iteye.com

1.44 Spring Security3

4.

tab

5.

6.

tab

7.

8.

jbcppets_clientauth.p12

9.

IE
IEWindowskey
1.

Windows Explorerjbcppets_clientauth.p12

2.

3.

4.

5.

1.

IE

2.

internet

3.

tab

4.

5.

tab

301 / 350

http://lengyun3566.iteye.com

1.44 Spring Security3

JBCP Pets
Firefox

My Account
Spring SecurityTomcat

web

Spring SecurityTomcat

302 / 350

http://lengyun3566.iteye.com

1.44 Spring Security3

u SSL8443URLhttps
SSL

u clientAuthTomcat
u Wireshark (http://www.wireshark.org/)
Fiddler2 (http://www.fiddler2.com/) SSL
l trust storeCA
JVMCACAtrust store
l IEFirefox

303 / 350

http://lengyun3566.iteye.com

1.45 Spring Security3

1.45 Spring Security3


: 2012-02-13 : Spring Security, ,

Spring Security

pre-authenticatedTomcatSpring
Securityassertion
Spring Security
Spring SecurityHTTP sessionTomcat
Spring SecurityUserDetailsService
UserDetailsServiceSpring SecuritySpring
SecurityGrantedAuthority

security
LDAPOpenIDsecurity
<http>

<http auto-config="true" ...>


<!-- Other content omitted -->
<x509 user-service-ref="jdbcUserServiceCustom"/>
<!-- Other content omitted -->
</http>

admin
Spring Security
Spring Security
<x509>
LDAP DNdistinguished name DN
304 / 350

http://lengyun3566.iteye.com

1.45 Spring Security3

Owner: CN=admin, OU=JBCP Pets, O=JBCP Pets, L=Anywhere, ST=NH,


C=US

Spring SecurityDNUserDetailsService
DNDN
<x509>

<x509
subject-principal-regex="CN=(.*?),"
user-service-ref="jdbcUserService"/>

admin
DNemailuserid

Spring Securit
Spring Securitysession

305 / 350

http://lengyun3566.iteye.com

1.45 Spring Security3

o.s.s.web.authentication.preauth.x509. X509AuthenticationFilter

o.s.s.web.authentication.preauth.x509.SubjectDnX509PrincipalExtractor
DN

/Authentication token
AuthenticationManager
o.s.s.web.authentication.preauth.PreAuthenticatedAuthenticationProvidertoken

306 / 350

http://lengyun3566.iteye.com

1.45 Spring Security3

CASCASCAS
Spring Security
Java EESite Minder

AuthenticationEntryPointCASform
LoginUrlAuthenticationEntryPoint
Tomcat
Spring Securityformform
entry pointo.s.s.web.authentication.Http403ForbiddenEntryPointHTTP 403
dogstore-base.xmlbeanSpring bean

307 / 350

http://lengyun3566.iteye.com

1.45 Spring Security3

<bean id="forbiddenAuthEntryPoint"
class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint"/>

<http>entry point

<http ... entry-point-ref="forbiddenAuthEntryPoint">

AccessDeniedHandlerHttp403ForbiddenEntryPoint
SpringURLweb<error-page>
Java EE servletHttp403ForbiddenEntryPoint

l form
l Log out
l
l
Dual-Mode authentication

308 / 350

http://lengyun3566.iteye.com

1.45 Spring Security3

form
Spring Security3AuthenticationEntryPointform
form
TomcatSSL
clientAuthwanttrue

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"


maxThreads="150" scheme="https" secure="true"
sslProtocol="TLS"
keystoreFile="conf/tomcat.keystore"
keystorePass="password"
truststoreFile="conf/tomcat.truststore"
truststorePass="password"
clientAuth="want"
/>

entry-point-ref
form
form

JDBC UserDetailsService
formUserDetailsService
PreAuthenticatedAuthenticationProvider
form
l
l JDBCform
JdbcDaoImplSQL
l form

309 / 350

http://lengyun3566.iteye.com

1.45 Spring Security3

Spring bean
bean
dogstore-explicit-base.xmlbean
bean

<bean id="x509Filter"
class="org.springframework.security.web.authentication.preauth.x509.X509AuthenticationFilter>
<property name="authenticationManager" ref="customAuthenticationManager"/>
</bean>

<bean id="preauthAuthenticationProvider" class="org.springframework.security.web.authentication.pre


<property name="preAuthenticatedUserDetailsService"
ref="authenticationUserDetailsService"/>
</bean>
<bean id="forbiddenAuthEntryPoint"
class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint"/>
<bean id="authenticationUserDetailsService"
class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<property name="userDetailsService" ref="jdbcUserService"/>
</bean>

<bean id="springSecurityFilterChain"
class="org.springframework.security.web.FilterChainProxy">
<security:filter-chain-map path-type="ant">
<security:filter-chain pattern="/**" filters="
securityContextPersistenceFilter,
x509Filter,
anonymousProcessingFilter,
exceptionTranslationFilter,
filterSecurityInterceptor" />
</security:filter-chain-map>
</bean>

310 / 350

http://lengyun3566.iteye.com

1.45 Spring Security3

AuthenticationProviderProviderManager

<bean id="customAuthenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<property name="providers">
<list>
<ref local="preauthAuthenticationProvider"/>
</list>
</property>
</bean>

beanweb.xml
bean
bean
Springbeanbeansecurity

X509AuthenticationFilter

false

continueFilterChainOnUnsuccessfulAuthentication

true

true

true
checkForPrincipalChanges

311 / 350

false

http://lengyun3566.iteye.com

1.45 Spring Security3

HTTP session

false

true

HTTP session
invalidateSessionOn PrincipalChange

true

falsesession

PreAuthenticatedAuthenticationProvider

preAuthenticated

UserDetailsService

UserDetails

None

truetoken

throwExceptionWhenTokenRejected

BadCredentialsException

false

true

312 / 350

http://lengyun3566.iteye.com

1.45 Spring Security3

l form
l

web

IT

non-repudiation

Spring Security

l
l Apache TomcatSSL
l Spring Security
l Spring Security

313 / 350

http://lengyun3566.iteye.com

1.45 Spring Security3

l Spring bean
l

314 / 350

http://lengyun3566.iteye.com

1.46 Spring Security3Spring Security

1.46 Spring Security3Spring Security


: 2012-02-13 : Spring Security, ,

Spring Security
Spring SecurityWindows
Active DirectoryKerberosSpring SecurityIntranet

l Kerberosweb
l KerberoswebKerberos
l JBCP PetsActive DirectoryWindows
l Active DirectoryLDAP UserDetailsService

Spring Security
Spring SecuritySpring Security Extensions
http://static.springsource.org/spring-security/site/extensions.html Spring Security
Spring Security
Kerberos authenticationSpring Security 2NTLMSecurity Assertion Markup Language 2.0
Portlet
Kerberos SPNEGOSpring
SecurityKerberos
Spring Security

KerberosSPNEGO
Kerberos
KDCkey distribution centerKDC
RFC 4120, The Kerberos Network Authentication Service V5
http://tools.ietf.org/html/rfc4120

315 / 350

http://lengyun3566.iteye.com

1.46 Spring Security3Spring Security

KerberosKerberosKerberos
principal
KerberosMITKerberos
Kerberos
KerberosGeneric Security Service Application Program Interface GSSAPIRFCRFC 2078, Generic Security Service Application Program Interface, Version
2, http://tools.ietf.org/html/rfc2078GSS-API
Kerberos

GSS-APIJavaRFCRFC 2853, Generic Security Service API


Version 2: Java Bindings, http://tools.ietf.org/html/rfc2853Sun JVMorg.ietf.jgss
javaKerberosGSS-APIAPIAPIJRE
Sunhttp://java.sun.com/javase/6/docs/technotes/
guides/security/jgss/tutorials/index.htmlSun JVMJVM
Sun JVM
GSS-APIwebSimple and Protected GSS-API Negotiation
Mechanism (SPNEGO)SPNEGOGSS-API
Kerberos SPNEGO
Kerberos
SPNEGOGSS-APIweb
webMicrosoftRFC 4559 SPNEGO-based Kerberos and
NTLM HTTP Authentication in Microsoft Windows, http://tools.ietf.org/html/rfc4559
HTTPSPNEGOGSS-APISPNEGO
MicrosoftWindowsGSSAPINT LAN Manager (NTLM)KerberosWindow
KerberosSPNEGO
Mozilla FirefoxApple Safari
web

SPNEGO Kerberos

316 / 350

http://lengyun3566.iteye.com

1.46 Spring Security3Spring Security

Spring SecurityKerberosSPNEGO
HTTP
l WWW-Authenticate: Negotiate HTTP
SPNEGO
l
HTTP Authorize
Spring Security
SPNEGOSSLSSOweb

Kerberos KDCMIT
KerberosKerberos

317 / 350

http://lengyun3566.iteye.com

1.46 Spring Security3Spring Security

Microsoft Active Directory ADWindowsActive DirectoryKerberos KDC


ADKerberos

Spring SecurityKerberos
CASKerberosKerberos Single SignOn (SSO)form
Spring SecurityKerberosKerberos

Kerberos Spring Security


SPNEGO
Spring Security's Kerberos Extension
CASCAS
servletAuthenticationProvider

Spring SecuritySPNEGO

318 / 350

http://lengyun3566.iteye.com

1.46 Spring Security3Spring Security

o.s.s.extensions.kerberos.KerberosServiceAuthenticationProvider
SPNEGOSpring Bean

KerberosMicrosoft Active DirectoryKerberos


Kerberos

Microsoft Active DirectoryAD


Spring SecurityKerberosKerberos
Kerberos principalAD

319 / 350

http://lengyun3566.iteye.com

1.46 Spring Security3Spring Security

webKerberos

webKerberosKerberos authentication
realmWindowsADAD domain
webweb
Kerberos SSOintranetADKerberos Realm
web

Kerberos

Domain Name

jbcppets.com

ADAD domain

corp.jbcppets.com

Web
Website principal

CORP\website

Active DirectoryKerberos
CORP

webAD

keytab
keytabKDCweb
keytabKerberosKerberos

webSPNEGO KerberosRFCRFC 4559keytab


HTTP/fully.qualified.web.server.name
JBCP Petsweb.jbcppets.comKerberoscorp.jbcppets.com
keytabHTTP/web.jbcppets.com@CORP.JBCPPETS.COM

320 / 350

http://lengyun3566.iteye.com

1.46 Spring Security3Spring Security

ADKerberos KDCADCORP\website
MicrosoftktpassAD

ktpass -princ HTTP/web.jbcppets.com@CORP.JBCPPETS.COM -mapuser


CORP\website -out website.keytab

l HTTP/web.jbcppets.com@CORP.JBCPPETS.COMKerberosHTTP/
web.jbcppets.comCORP.JBCPPETS.COM
l CORP\websiteKerberos
KerberosKerberos

website.keytabweb
Spring SecurityKerberosJBCP Pets webWEB-INF/classes
Spring Security Kerberos bean
keytabKerberos

Kerberosweb
ktpassWindows 2008 ServerWindows Server
Kerberos
KerberosSpring bean
KerberosSun JVMSpring Security Kerberos

AuthenticationEntryPointWWW-Authenticate
Kerberosdogstore-base.xmlbean

<bean id="kerbEntryPoint"
class="org.springframework.security.extensions.kerberos.web.SpnegoEntryPoint" />

321 / 350

http://lengyun3566.iteye.com

1.46 Spring Security3Spring Security

Authorization HTTPSPNEGO

<bean id="kerbAuthenticationProcessingFilter"
class="org.springframework.security.extensions.kerberos.web.SpnegoAuthenticationProcessingFilter">
<property name="authenticationManager" ref="authenticationManager" />
</bean>

SSOSSO
SpnegoAuthenticationProcessingFilterHTTP Authorization
o.s.s.extensions.kerberos.KerberosServiceRequestToken
AuthenticationProviderKerberosServiceRequestToken
CASKerberos AuthenticationProvidertoken
ticket

<bean

id="kerberosServiceAuthenticationProvider"

class="org.springframework.security.extensions.kerberos.KerberosServiceAuthenticationProvider">
<property name="ticketValidator" ref="ticketValidator"/>
<property name="userDetailsService" ref="jdbcUserService" />
</bean>
<bean id="ticketValidator"
class="org.springframework.security.extensions.kerberos.SunJaasKerberosTicketValidator">
<property name="servicePrincipal" value="HTTP/web.jbcppets.com@CORP.JBCPPETS.COM" />
<property name="keyTabLocation" value="classpath:website.keytab"/>
</bean>

KerberosServiceAuthenticationProvidero.s.s.extensions.kerberos.KerberosTicketValidator
tokenKerberos ticketSpring Security Kerberos Extension
Sun JVM's GSS-APIkeytabKerberos ticket
servicePrincipalkeyTabLocationKerberos server
keytabkeytab
classpathweb
Springfile:

322 / 350

http://lengyun3566.iteye.com

1.46 Spring Security3Spring Security

JDBC UserDetailsServiceJDBCSQL
Kerberoskerbuser
Kerberoskerbuser@CORP.JBCPPETS.COMWEBINF/classes/test-users-groups-data.sql

insert into users(username, password, enabled, salt) values ('kerbuser@CORP.JBCPPETS.COM','unused',

insert into group_members(group_id, username) select id,'kerbuser@CORP.JBCPPETS.COM' from groups wh

Active DirectoryLDAP UserDetailsService

SPNEGOsecurity
beansecurity
AuthenticationEntryPointCAS

<http ...
entry-point-ref="kerbEntryPoint">

SPNEGOSpring SecuritySPNEGO
form

<custom-filter ref="kerbAuthenticationProcessingFilter"

position="FORM_LOGIN_FILTER" />

<authentication-provider>AuthenticationProviderSPNEGO
tickets

<authentication-manager alias="authenticationManager">
<authentication-provider ref="kerberosServiceAuthenticationProvider"/>
</authentication-manager>

SPNEGO SSO

323 / 350

http://lengyun3566.iteye.com

1.46 Spring Security3Spring Security

Kerberosweb

IEIESPNEGO
My Account

My Account
webKerberos
IEIESPNEGO SSO

l IntranetInternettab

l intranetIE
l tabwindows
IESPNEGO

Kerberos

324 / 350

1.46 Spring Security3Spring Security

http://lengyun3566.iteye.com

KerberosSun GSSAPIKerberos KDCkrb5.ini


Windowsc:\Windows
KDC
corp.jbcppets.com

[domain_realm]
.jbcppets.com = CORP.JBCPPETS.COM
[libdefaults]
default_realm = CORP.JBCPPETS.COM
[logging]
[realms]
CORP.JBCPPETS.COM = {
kdc = corp.jbcppets.com
}

krb5.iniJVMKDC

Djava.security.krb5.realm

-Djava.security.krb5.kdc

CORP.JBCPPETS.COM

KDC

corp.jbcppets.com

krb5.iniKerberos
Firefox

325 / 350

http://lengyun3566.iteye.com

1.46 Spring Security3Spring Security

FirefoxKerberos
WWW-Authenticate: Negotiatefirefox
Firefoxabout:config
network.negotiate-auth.trusted-uris

FirefoxWindows
FirefoxSPNEGOIE

KerberosKerberos
web

KerberosKerberos
kinitktabMIT Kerberos for WindowsKfW
http://web.mit.edu/Kerberos/
kinitktabJDKktab

ktab -a kerbuser@CORP.JBCPPETS.COM -k kerbuser.keytab

326 / 350

http://lengyun3566.iteye.com

1.46 Spring Security3Spring Security

Password for kerbuser@CORP.JBCPPETS.COM:xxxxx Done!


Service key for kerbuser@CORP.JBCPPETS.COM is saved in kerbuser.keytab

MIT Kerberos

Java GSS-API
Java GSS-APIKerberos
JVM-Dsun.security.krb5.debug=true
SunJaasKerberosTicketValidator beandebug

<bean id="ticketValidator"
class="org.springframework.security.extensions.kerberos.SunJaasKerberosTicketValidator">
<property name="servicePrincipal" value="HTTP/web.jbcppets.com@corp.jbcppets.com" />
<property name="keyTabLocation" value="classpath:website.keytab"/>
<property name="debug" value="true"/>
</bean>

Spring Security Kerberos ExtensionkerberizingKerberosweb

l Spring Securitythe org.springframework.security.extensions.kerberos


WARNticketSpring

l KDC

l Windows
WindowsNTLMNTLMrequest/response
NegotiateSpring
TlRMNTLMSPNEGOSPNEGOYII

327 / 350

http://lengyun3566.iteye.com

1.46 Spring Security3Spring Security

l WindowsWindowsNTLM
l DNSKerberos
SPNEGOKerberos

LDAP UserDetailsServiceKerberos
JDBC UserDetailsServiceKerberosIDKerberos
Active DirectoryLDAPADKerberos
Microsoft ADLDAP UserDetailsServiceSpring SecurityLDAP
LDAPLDAPLDAP
AD
authentication providerLDAP UserDetailsService
dogstore-security.xml

<ldap-server url="ldaps://corp.jbcppets.com/DC=corp,DC=jbcppets,DC=com" id="ldapCorp" manager-dn="C


<ldap-user-service id="ldapUserService" server-ref="ldapCorp"
user-search-filter="(userPrincipalName={0})" user-search-base="CN=Users"
group-search-base="CN=Groups"/>

user-search-filteruserPrincipalName LDAPSPNEGO
Kerberosmanager-dnAD

KerberosServiceAuthenticationProviderUserDetailsServicedogstorebase.xml

<bean id="kerberosServiceAuthenticationProvider"
class="org.springframework.security.extensions.kerberos.KerberosServiceAuthenticationProvider">
<property name="ticketValidator" ref="ticketValidator"/>
<property name="userDetailsService" ref="ldapUserService" />
</bean>

328 / 350

http://lengyun3566.iteye.com

1.46 Spring Security3Spring Security

Spring Security LDAP


LDAPADLDAP
LdapAuthoritiesPopulator
Active Directory
Active DirectoryIT

Kerberosform
SPNEGOSSOKerberosSpring Security
KerberosAuthenticationProviderLDAP

KerberosKerberos
AuthenticationProvidersLDAPJDBC
SpnegoEntryPoint
formSPNEGO
dogstore-base.xmlSpring BeanSPNEGO
bean
SPNEGOform
bean

<bean id="kerberosAuthenticationProvider"
class="org.springframework.security.extensions.kerberos.KerberosAuthenticationProvider">
<property name="kerberosClient" ref="kerbJaasClient"/>
<property name="userDetailsService" ref="jdbcUserServiceCustom"/>
</bean>
<bean id="kerbJaasClient"
class="org.springframework.security.extensions.kerberos.SunJaasKerberosClient">
<property name="debug" value="true"/>
</bean>
<bean id="kerbGlobalJaasConfig"
class="org.springframework.security.extensions.kerberos.GlobalSunJaasKerberosConfig">

329 / 350

http://lengyun3566.iteye.com

1.46 Spring Security3Spring Security

<property name="debug" value="true"/>


<property name="krbConfLocation" value="/path/to/krb5.conf" />
</bean>

krbConfLocationKerberos V5
krb5.iniKerberos V5
http://web.mit.edu/kerberos/krb5-1.5/krb5-1.5.1/doc/krb5-admin/krb5.conf.html
Kerberos keytab
c:\spring\krb5.confSpringfile:classpath:
Sun JVMKerberosSpring beanSunJaasKerberosTicketValidator
JVMJVM
Kerberos
default_realm
kerbuser@jbcppets.comKerberos KDCKerberos
Kerberosform
AuthenticationProviderKerberosAuthenticationProvidersecurity
dogstore-security.xml

<authentication-manager alias="authenticationManager">
<authentication-provider ref="kerberosAuthenticationProvider"/>
</authentication-manager>

formKerberos
UserDetailsServiceGrantedAuthority
AuthenticationProviderbasic

KerberosWindows DomainMicrosoft Active


DirectoryWindows

l Kerberos SPNEGO
l Kerberosweb
330 / 350

http://lengyun3566.iteye.com

1.46 Spring Security3Spring Security

l JBCP PetsKerberosSPNEGO
l Kerberos web
l ADLDAP
l formKerberos
Spring Security

331 / 350

http://lengyun3566.iteye.com

1.47 Spring Security3Spring Security 3

1.47 Spring Security3Spring Security 3


: 2012-02-13 : Spring Security, ,

Spring Security 3
Spring Security2Spring Security3

l Spring Security 3
l Spring Security 2Spring Security 3
l Spring Security 3
Spring Security 2Spring Security 3

Spring Security2
Spring Security 2Spring Security 3Spring Security 2

Spring Security 2Spring Security 3


Spring Security 3Spring
Security 2
Spring Security 3Spring3Java51.5
Spring Security

Spring Security3
Spring Security 3Spring Security 2
l SpringSpring Expression LanguageSpELURL
Spring Security
l

332 / 350

http://lengyun3566.iteye.com

1.47 Spring Security3Spring Security 3

l security
bean
l securitysession
l ACLo.s.s.aclACLACL

l OpenIDOpenIDOpenID
l Spring Security ExtensionKerberosSAMLSpring
Security

Spring SecurityURL
Spring Security2
Spring Security2

Spring Security
Spring Security 3security
Spring Security3
AuthenticationManager
Spring Security 3AuthenticationManagerAuthenticationProvider
Spring Security 2AuthenticationManagerAuthenticationProvider
AuthenticationProviderAuthenticationManager

<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"/>
</authentication-provider>

Spring Security 2<authentication-manager>AuthenticationProvider

333 / 350

http://lengyun3566.iteye.com

1.47 Spring Security3Spring Security 3

<authentication-manager alias="authManager"/>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"/>
</authentication-provider>
<ldap-authentication-provider server-ref="ldap://localhost:10389/"/>

Spring Security 3AuthenticationProvider<authentication-manager>

<authentication-manager alias="authManager">
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"/>
</authentication-provider>
<ldap-authentication-provider server-ref=
"ldap://localhost:10389/"/>
</authentication-manager>

<authentication-manager>security
Spring Security 2AuthenticationProviderbean
<custom-authentication-provider>
AuthenticationProvider

<bean id="signedRequestAuthenticationProvider"
class="com.packtpub.springsecurity.security .SignedUsernamePasswordAuthenticationProvider">
<security:custom-authentication-provider/>
<property name="userDetailsService" ref="userDetailsService"/>
<!-- ... -->
</bean>

AuthenticationProviderSpring Security 3
<authentication-provider>refAuthenticationProvider

334 / 350

http://lengyun3566.iteye.com

1.47 Spring Security3Spring Security 3

<authentication-manager alias="authenticationManager">
<authentication-provider ref= "signedRequestAuthenticationProvider"/>
</authentication-manager>

providerSpring Security 3

Session
sessionSpring Security 3URLsession

sessionsession<http><session-management>

Spring Security 2

<http ... session-fixation-protection="none">


<!-- ... -->
<concurrent-session-control exception-if-maximum-exceeded="true" max-sessions="1"/>
</http>

Spring Security 3<http>session-fixation-protection

<http ...>
<session-management session-fixation-protection="none">
<concurrency-control error-if-maximum-exceeded="true" max-sessions="1"/>
</session-management>
</http>

Spring Security 2
provider<custom-filter>bean
Spring Security

335 / 350

http://lengyun3566.iteye.com

1.47 Spring Security3Spring Security 3

Spring Security 2

<bean id="requestHeaderFilter"
class="com.packtpub .springsecurity.security.RequestHeaderProcessingFilter">
<security:custom-filter after="AUTHENTICATION_PROCESSING_FILTER"/>
<property name="authenticationManager"
ref="authenticationManager"/>
</bean>

Spring Security 3bean


<http>

<http ...>
<!-- ... -->
<custom-filter ref="requestHeaderFilter"
before="FORM_LOGIN_FILTER"/>
<!-- ... -->
</http>

beanSpring Security 2
Spring Security 2Spring Security 3

Spring Security 3

Spring Security 2

Spring Security 3

SESSION_CONTEXT_INTEGRATION_FILTER

SECURITY_CONTEXT_FILTER

CAS_PROCESSING_FILTER

CAS_FILTER

AUTHENTICATION_PROCESSING_FILTER

FORM_LOGIN_FILTER

336 / 350

http://lengyun3566.iteye.com

1.47 Spring Security3Spring Security 3

OPENID_PROCESSING_FILTER

OPENID_FILTER

BASIC_PROCESSING_FILTER

BASIC_AUTH_FILTER

NTLM_FILTER

Spring Security

<custom-filter>

CustomAfterInvocationProvider
Spring Security 2bean<custom-afterinvocation-provider>CustomAfterInvocationProvider

<bean id="customAfterInvocationProvider"
class="com.packtpub.springsecurity.security .CustomAfterInvocationProvider">
<security:custom-after-invocation-provider/>
</bean>

Spring Security 2 beanSpring Security 3<globalmethod-security>bean

<global-method-security ...>
<after-invocation-provider ref="customAfterInvocationProvider"/>
</global-method-security>

Spring Security 3

Spring Security 2 3
l Spring Security 3auto-configremember me<http>
<remember-me>
337 / 350

http://lengyun3566.iteye.com

1.47 Spring Security3Spring Security 3

l LDAPSpring Security 3group-search-base-attributeLDAP


ou=GroupsLDAPLDAP
l Spring Security 3<filter-invocation-definition-source>
<filter-security-metadata-source>bean
l Spring Security 3<concurrent-session-control>exception-if-maximum-exceeded
<concurrency-control>error-if-maximum-exceeded
l Spring Security 3DAO UserDetailsServicepassword

l NTLMSpring Security 3Kerberos


KerberosSpring Security
Spring Security 3NTLMSpring SecuritySpring
Security 3NTLM
Spring Security 3securityXML

Spring Security 2Spring Security


Spring Security 2 3

Spring Security 2Spring Security 3

Spring 2

Spring 3

13

o.s.s

o.s.s.authentication

13

o.s.s.acls

o.s.s.acls.model

13

o.s.s.event.authentication

o.s.s.authentication.event

338 / 350

http://lengyun3566.iteye.com

1.47 Spring Security3Spring Security 3

12

o.s.s.vote

o.s.s.access.vote

11

o.s.s.ui.rememberme

o.s.s.web.authentication.rememberme

10

o.s.s.providers.jaas

o.s.s.authentication.jaas

10

o.s.s.securechannel

o.s.s.web.access.channel

10

o.s.s.userdetails.ldap

o.s.s.ldap.userdetails

o.s.s.providers.encoding

o.s.s.authentication.encoding

o.s.s.config

o.s.s.config.authentication

o.s.s.util

o.s.s.web.util

o.s.s.config

o.s.s.config.http

o.s.s.context

o.s.s.core.context

o.s.s.userdetails

o.s.s.core.userdetails

o.s.s

o.s.s.access

o.s.s.afterinvocation

o.s.s.acls.afterinvocation

o.s.s.event.authorization

o.s.s.access.event

o.s.s.util

o.s.s.web

o.s.s.annotation

o.s.s.access.annotation

339 / 350

http://lengyun3566.iteye.com

1.47 Spring Security3Spring Security 3

o.s.s.authoritymapping

o.s.s.core.authority.mapping

o.s.s.providers

o.s.s.authentication

o.s.s.token

o.s.s.core.token

o.s.s.ui

o.s.s.web.authentication

Spring Security 3

JAR
nnn

JAR

spring-security-acl-nnn.jar

ACL

spring-security-cas-client-nnn.jar

CAS

spring-security-config-nnn.jar

spring-security-core-nnn.jar

spring-security-ldap-nnn.jar

LDAP

spring-security-openid-nnn.jar

OpenID

spring-security-taglibs-nnn.jar

JSP

340 / 350

http://lengyun3566.iteye.com

spring-security-web-nnn.jar

1.47 Spring Security3Spring Security 3

web

Spring Securitywebweb
spring-security-configspring-security-core

Spring Security 2Spring Security 3

l
l
l Spring Security
Spring Security 3

341 / 350

http://lengyun3566.iteye.com

1.48 Spring Security3

1.48 Spring Security3


: 2012-02-13 : Spring Security, ,

JBCP Pets
Eclipse 3.4
3.5IDEWeb Tools PackageWTPZIP
ZIP
Spring Security
Eclipse
Dependencies
l FileImportGeneralExisting Projects into
WorkspaceNext
l Select root directoryBrowse...
Dependencies.zipOK
l DependenciesFinish
ZIPSpring Security

l FileImportGeneralExisting Projects into


WorkspaceNext
l Select root directoryBrowseZIP
OK
l JBCPPetsServersFinish
JBCP Pets webTomcat
342 / 350

1.48 Spring Security3

http://lengyun3566.iteye.com

l JBCPPetsRun AsRun on Server


l web
JBCP Pets
l EclipseJavaclasspath
Spring IDE
l Eclipseweb
classpathclasspathJBCPPets Java EE Module
DependenciesEclipse

Spring Security

o.s.s.authentication.evento.s.s.access.event

AbstractAuthenticationEvent

AbstractAuthenticationFailureEvent

AuthenticationFailureBadCredentialsEvent

UsernameNotFoundException

343 / 350

BadCredentialsExceptio

UsernameNotFoundExc

1.48 Spring Security3

http://lengyun3566.iteye.com

AuthenticationFailureConcurrentLoginEvent

AuthenticationFailureCredentialsExpiredEvent

AuthenticationFailureDisabledEvent

AuthenticationFailureExpiredEvent

AuthenticationFailureLockedEvent

session

UserDetails

UserDetails

UserDetails

UserDetails

ConcurrentLoginExcept

CredentialsExpiredExcep

DisabledException

AccountExpiredExceptio

LockedException

AuthenticationFailureProviderNotFoundEvent

Authentication Provider

ProviderNotFoundExcep

AuthenticationFailureProxyUntrustedEvent

AuthenticationFailureServiceExceptionEvent

CASticket

DAO Provider

AuthenticationSuccessEvent

AuthenticationSwitchUserEvent

InteractiveAuthenticationSuccess
Event

AbstractAuthorizationEvent

344 / 350

IS_FULLY_AUTHENTICATED
GrantedAuthority

AuthenticationServiceEx

http://lengyun3566.iteye.com

AuthenticationCredentialsNot
FoundEvent

1.48 Spring Security3

AuthorizationFailureEvent

AuthorizedEvent

PublicInvocationEvent

SessionCreationEvent

HttpSession

SessionDestroyedEvent

HttpSession

Spring SecurityURL
URLSpring SecurityURLservelt
URLweb
l /j_spring_security_checkUsernamePasswordAuthenticationFilter/form

l /j_spring_openid_security_checkOpenIDAuthenticationFilterOpenID
OpenID provider
l /j_spring_cas_security_checkCAS SSOCAS
l /spring_security_loginDefaultLoginPageGeneratingFilterURL
l /j_spring_security_logoutLogoutFilter
l /saml/SSOSpring Security SAML SSO extension SAMLProcessingFilterSAML SSO

l /saml/logoutSpring Security SAML SSO extension SAMLLogoutFilterSAML SSO

345 / 350

http://lengyun3566.iteye.com

1.48 Spring Security3

l /j_spring_security_switch_userSwitchUserFilter
l /j_spring_security_exit_user

bean
dogstore-explicit-base.xmlbean
bean
Spring bean

<!-- ************************************************** -->


<!-- Method Authorization

-->

<!-- ************************************************** -->


<bean class="org.springframework.security.access.intercept.
aopalliance.MethodSecurityInterceptor" id="methodSecurityInterceptor">
<property name="accessDecisionManager" ref="methodAccessDecisionMan
ager"/>
<property name="authenticationManager" ref="customAuthenticationMan
ager"/>
<property name="securityMetadataSource" ref="delegatingMetadataSour
ce"/>
<property name="afterInvocationManager" ref="afterInvocationManager
"/>
</bean>
<bean class="org.springframework.security.access.intercept.
aopalliance.MethodSecurityMetadataSourceAdvisor" id="methodSecurityMet
adataSourceAdvisor">
<constructor-arg value="methodSecurityInterceptor"/>
<constructor-arg ref="delegatingMetadataSource"/>
</bean>
<bean class="org.springframework.aop.framework.autoproxy.
DefaultAdvisorAutoProxyCreator" id="defaultAdvisorAutoProxyCreator">
<property name="beanName" value="methodSecurityMetadataSourceAdviso
r"/>
346 / 350

http://lengyun3566.iteye.com

1.48 Spring Security3

</bean>
<bean class="org.springframework.security.access.intercept.
AfterInvocationProviderManager" id="afterInvocationManager">
<property name="providers">
<list>
<ref local="postAdviceProvider"/>
</list>
</property>
</bean>
<bean class="org.springframework.security.access.vote.
AffirmativeBased" id="methodAccessDecisionManager">
<property name="decisionVoters">
<list>
<ref bean="preAdviceVoter"/>
<ref bean="roleVoter"/>
<ref bean="authenticatedVoter"/>
<ref bean="jsr250Voter"/> <!-- For JSR 250 Method Annotations
-->
</list>
</property>
</bean>
<!-- Overall Delegating Metadata Source -->
<bean class="org.springframework.security.access.method.
DelegatingMethodSecurityMetadataSource" id="delegatingMetadataSource">
<property name="methodSecurityMetadataSources">
<list>
<ref local="prePostMetadataSource"/>
<ref local="securedMetadataSource"/>
<ref local="jsr250MetadataSource"/>
</list>
</property>
</bean>
<!-- JSR 250 Method Voters -->
<bean class="org.springframework.security.access.annotation.
Jsr250MethodSecurityMetadataSource" id="jsr250MetadataSource"/>
<bean class="org.springframework.security.access.annotation.
Jsr250Voter" id="jsr250Voter"/>
347 / 350

http://lengyun3566.iteye.com

1.48 Spring Security3

<!-- Spring @Secured Beans -->


<bean class="org.springframework.security.access.annotation.
SecuredAnnotationSecurityMetadataSource" id="securedMetadataSource"/>
<!-- @Pre/@Post Method Advice Voters -->
<bean class="org.springframework.security.access.prepost.
PreInvocationAuthorizationAdviceVoter" id="preAdviceVoter">
<constructor-arg ref="exprPreInvocationAdvice"/>
</bean>
<bean class="org.springframework.security.access.prepost.
PostInvocationAdviceProvider" id="postAdviceProvider">
<constructor-arg ref="exprPostInvocationAdvice"/>
</bean>
<bean class="org.springframework.security.access.prepost.
PrePostAnnotationSecurityMetadataSource" id="prePostMetadataSource">
<constructor-arg ref="exprAnnotationAttrFactory"/>
</bean>
<!-- @Pre/@Post Method Expression Handler -->
<bean class="org.springframework.security.access.expression.method.
DefaultMethodSecurityExpressionHandler" id="methodExprHandler"/>
<bean class="org.springframework.security.access.expression.method.
ExpressionBasedPreInvocationAdvice" id="exprPreInvocationAdvice">
<property name="expressionHandler" ref="methodExprHandler"/>
</bean>
<bean class="org.springframework.security.access.expression.method.
ExpressionBasedPostInvocationAdvice" id="exprPostInvocationAdvice">
<constructor-arg ref="methodExprHandler"/>
</bean>
<bean class="org.springframework.security.access.expression.method.
ExpressionBasedAnnotationAttributeFactory" id="exprAnnotationAttrFact
ory">
<constructor-arg ref="methodExprHandler"/>
</bean>

beanSpring Security
Spring Securitybean
o.s.s.config.method.GlobalMethodSecurityBeanDefinitionParser

348 / 350

1.48 Spring Security3

http://lengyun3566.iteye.com

JSR-250@Secured@Pre/@Post
bean@SecuredSecurityMetadataSourceAccessDecisionVoter

Spring Security 3<custom-filter>


Spring Security 2Spring Security 3Spring
Security 2 3

Spring Security 2

Spring Security 3

CHANNEL_FILTER

CHANNEL_FILTER

CONCURRENT_SESSION_FILTER

CONCURRENT_SESSION_FILTER

SESSION_CONTEXT_INTEGRATION_
SECURITY_CONTEXT_FILTER
FILTER

LOGOUT_FILTER

LOGOUT_FILTER

PRE_AUTH_FILTER

PRE_AUTH_FILTER

CAS_PROCESSING_FILTER

CAS_FILTER

AUTHENTICATION_PROCESSING_FILTER

FORM_LOGIN_FILTER

OPENID_PROCESSING_FILTER

OPENID_FILTER

Spring Security 2
LOGIN_PAGE_FILTER

Spring Security 2
DIGEST_AUTH_FILTER

349 / 350

LOGIN_PAGE_FILTER

DIGEST_AUTH_FILTER

http://lengyun3566.iteye.com

BASIC_PROCESSING_FILTER

Spring Security 2
REQUEST_CACHE_FILTER

1.48 Spring Security3

BASIC_AUTH_FILTER

REQUEST_CACHE_FILTER

SERVLET_API_SUPPORT_FILTER

SERVLET_API_SUPPORT_FILTER

REMEMBER_ME_FILTER

REMEMBER_ME_FILTER

ANONYMOUS_FILTER

ANONYMOUS_FILTER

Spring Security 2

SESSION_MANAGEMENT_FILTER

SESSION_MANAGEMENT_FILTER

EXCEPTION_TRANSLATION_FILTER

NTLM_FILTER

EXCEPTION_TRANSLATION_FILTER

Spring Security 3
NTLM_FILTER

FILTER_SECURITY_INTERCEPTOR

FILTER_SECURITY_INTERCEPTOR

SWITCH_USER_FILTER

SWITCH_USER_FILTER

350 / 350

You might also like