Professional Documents
Culture Documents
Spring Security3
Spring Security3
Spring Security3
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
3 / 350
http://lengyun3566.iteye.com
4 / 350
http://lengyun3566.iteye.com
http://weibo.com/1920428940
http://www.packtpub.com/support?nid=4435
5 / 350
http://lengyun3566.iteye.com
21web
Spring3webSpring Security3
Spring Security
l
l web
l
Spring Security
6 / 350
http://lengyun3566.iteye.com
Super Visor
Spring
ORMUI
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
faade
webBO
SpringORM
hibernateJPAAPIJDBC
HSQL
webORM
8 / 350
http://lengyun3566.iteye.com
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
9 / 350
http://lengyun3566.iteye.com
Super Visor
10 / 350
http://lengyun3566.iteye.com
URL
{}Spring Security
11 / 350
http://lengyun3566.iteye.com
Spring Security
OpenID
Spring Security
web
Spring Security
JDBC
PCI
Spring SecurityAOP
12 / 350
http://lengyun3566.iteye.com
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
14 / 350
http://lengyun3566.iteye.com
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
l e-mailE-mail
e-mailJBCP
Pete-mail
Microsoft Active Directory
l
ATM
RSASecurId
Spring Security
Spring Security
Spring Securityjavaprincipaljava.security.Principal
authorities
16 / 350
http://lengyun3566.iteye.com
web
<!--[endif]-->
17 / 350
http://lengyun3566.iteye.com
Spring Security
18 / 350
http://lengyun3566.iteye.com
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
</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
<url-pattern>/*</url-pattern>
</filter-mapping>
ServletRequestURL/*
URL
Spring Securitydogstore-security.xml
XMLwebweb.xml
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
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
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
Spring Security
23 / 350
http://lengyun3566.iteye.com
Spring SecurityXML
schameXMLXML
<!--[if !supportLists]-->l <!--[endif]-->SpringSpring Security
Spring jar
24 / 350
http://lengyun3566.iteye.com
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
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
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
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
http://lengyun3566.iteye.com
<http>
form
form
form
CASLDAP
form
web
AbstractAuthenticationProcessingFilter
form POSTSSO
Authentication
AuthenticationManager
Authentication
AuthenticationProvider
29 / 350
AuthenticationManager
AuthenticationProvider
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
web
UsernamePasswordAuthenticationFilterUsernamePasswordAuthenticationToken
AuthenticationHttpServletRequet
spring_security_login
JBCP Petshttp://localhost:8080/
JBCPPets/spring_security_login
URLspring_security_login
DefaultLoginPageGeneratingFilter
URLSpring
SecuritySpring SecuritySpring Security
springURL
formHTMLUsernamePasswordAuthenticationFilter
31 / 350
http://lengyun3566.iteye.com
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
http://lengyun3566.iteye.com
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
<user-service>o.s.s.core.userdetails.memory.InMemoryDaoImpl
UserDetailsServiceXML
service
33 / 350
http://lengyun3566.iteye.com
DaoAuthenticationProviderAuthenticationManager
Spring Security
JDBCJBCP Pets
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
request
HTTPHTTP 403
35 / 350
http://lengyun3566.iteye.com
Spring SecurityserveltFilterSecurityInterceptor
FilterSecurityInterceptor
Authentication
(List<GrantedAuthority>
getAuthorities()
Spring Security
access decision manager
Spring Securityo.s.s.access.AccessDecisionManager
AuthenticationException
o.s.s.access.AccessDeniedException
AccessDecisionManagerSpring bean
AccessDecisionManagerAccessDecisionVoter
36 / 350
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
Spring Security
o.s.s.access.AccessDecisionVoter
Grant (ACCESS_GRANTED)
Deny (ACCESS_DENIED)
Abstain (ACCESS_ABSTAIN)
37 / 350
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
<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
decisionVotersAccessDecisionManager
AccessDecisionManager
security
Spring SecurityAccessDecisionVoter
o.s.s.access.
vote.RoleVoter
GrantedAuthorityaccess
GrantedAuthority
access="ROLE_USER,ROLE_ADMI
ROLE_
o.s.s.access.
vote.AuthenticatedVoter
access="
>IS_AUTHENTICATED_REMEMBERED
IS_AUTHENTICATED_ANONYMO
remember me
40 / 350
http://lengyun3566.iteye.com
Spring
RoleVoter
Spring SpEL <http> use-expressions
<http auto-config="true"
use-expressions="true">
use-expressions SpEL
RoleVoter
41 / 350
http://lengyun3566.iteye.com
SpEL hasRole
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
<intercept-url> access
Web only?
hasIpAddress
Yes
42 / 350
IP
access="hasIpAddress('
http://lengyun3566.iteye.com
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
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
dl.iteye.com/topics/download/6bd4937f-26e3-3418-a4df-78d26c8812a5
45 / 350
http://lengyun3566.iteye.com
JBCP Pets
Spring Securitysecurity
l JBCP Pets
l
l
46 / 350
http://lengyun3566.iteye.com
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
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
48 / 350
http://lengyun3566.iteye.com
http://localhost:8080/JBCPPets/home.doIE
Mozilla Firefox
Firefox
URL
<intercept-url pattern="/*" access="hasRole('ROLE_USER')"/>
/*URLROLE_USER
URLSpring SecurityURL
49 / 350
http://lengyun3566.iteye.com
Logoutsession
Log Out
Log Out
Spring SecurityURLURL
URL/j_spring_security_logoutheader.jsp
ahref
Log Outform
JSTL URLURLJSTLurlURLweb
urlURL/
JSP(<%= request.getContextPath() %>)JSTLurl
50 / 350
http://lengyun3566.iteye.com
URLservletSpring Security
/j_spring_security_logoutURLJSPJSPSpring MVC
URLURL
/j_spring_security_logoutURLo.s.s.web.authentication.logout.LogoutFilter
Spring SecurityLogoutFilterURL
Spring Securitysecurity
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
authentication.logout.LogoutSuccessHandlerURL
URL/
session
logout URL
logout URLlogout URL
/logout
dogstore-security.xml<logout>
/common/header.jsplogoutherfURL:
52 / 350
http://lengyun3566.iteye.com
/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
Remember me
remember me
cookieSpring Security
remember me cookie
remember mesecurity
remember me
pet store
dogstore-security.xml<remember-me>keyjbcpPetStore
<remember-me key="jbcpPetStore"/>
<logout invalidate-session="true" logout-success-url="/" logout-url="/logout"/>
</http>
form
login.jspcheckbox
54 / 350
http://lengyun3566.iteye.com
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
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
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
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
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
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
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
SpEL
IS_AUTHENTICATED_FULLYaccess="
IS_AUTHENTICATED_FULLY"SpEL
boolean
remember me
61 / 350
http://lengyun3566.iteye.com
IPRemember me Service
remember meIPcookie
RememberMeServices
o.s.s.web.authentication.rememberme.TokenBasedRememberMeServices
IPcookieMD5
HttpServletRequestIPThreadLocal
HttpServletRequest
TokenBasedRememberMeServices
TokenBasedRememberMeServices
com.packtpub.springsecurity.security
ThreadLocal HttpServletRequest
62 / 350
http://lengyun3566.iteye.com
requestHolder.set(context);
}
HttpServletRequestIP
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
@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
return super.processAutoLoginCookie(Arrays.copyOf(cookieTokens,
cookieTokens.length-1), request, response);
}
finally
{
setContext(null);
}
}
RememberMeServices
RememberMeServices
RememberMeServicesdogstore-base.xml Spring
Spring Bean
65 / 350
http://lengyun3566.iteye.com
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
http://lengyun3566.iteye.com
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
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
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
</authentication-provider>
</authentication-manager>
<authentication-provider user-service-ref="userService"/>
<user-service><user><user>
InMemoryDaoImplUserDetailsService
UserDetailsServiceGrantedAuthority
JBCP Pets
UI
70 / 350
http://lengyun3566.iteye.com
My Account/account/home.jsp
<p>
Please find account functions below...
</p>
<ul>
<li><a href="changePassword.do">Change Password</a></li>
</ul>
71 / 350
http://lengyun3566.iteye.com
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
My AccountChange Password
form
l
l remember me
SecurityContextHolder.clearContext()
SecurityContext
l Spring MVC
l Spring Security
l remember me
l IPremember me
l
l UserDetailsServiceInMemoryDaoImpl
73 / 350
http://lengyun3566.iteye.com
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
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
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
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
SQL
SQLSpring Security
GrantedAuthority
AuthenticationManagerAuthenticationProvider
AuthenticationProvider
DaoAuthenticationProviderproviderUserDetailsService
77 / 350
http://lengyun3566.iteye.com
UserDetailsService
o.s.s.core.userdetails.jdbc.JdbcDaoImplUserDetailsServiceSpring
SecurityJdbcDaoImpl
Spring Security<jdbc-userservice>JdbcDaoImplAuthenticationProvider
Spring SecurityJdbcDaoImpl
InMemoryDaoImpl
JdbcDaoImpl
78 / 350
http://lengyun3566.iteye.com
JDBC UserDetailsService
JdbcDaoImpl
JDBC UserDetailsService
com.packtpub.springsecurity.security
JdbcDaoImpl
Spring JDBC
<bean id="jdbcUserService"
class="com.packtpub.springsecurity.security.CustomJdbcDaoImpl">
79 / 350
http://lengyun3566.iteye.com
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
80 / 350
UserDetails
GrantedAuthority
http://lengyun3566.iteye.com
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
<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
82 / 350
http://lengyun3566.iteye.com
JdbcUserDetailsManagerJSP
83 / 350
JdbcDaoImpl
JdbcDaoImplschema
UserDetailsService
UserGrantedAuthoritya level of
indirectionGrantedAuthoritygroup
GrantedAuthority
GrantedAuthority
l
l
84 / 350
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
l GrantedAuthority
l
test-users-groups-data.sqlSQL
86 / 350
HSQLtest-data.sql
security-schema.sql
JBCP Pets
JBCP Pets
schame
Spring Securityschema
Spring SecurityschemaJdbcDaoImpl
schemaSpring Security
JdbcDaoImplschemaJBCP PetsSpring
Security
87 / 350
JDBC SQL
JdbcDaoImplSQL
SQLJdbcDaoImplSQL
usersByUsernameQuery
authoritiesByUsernameQuery
GBAC
SQL
Username (string)
Password (string)
Enabled (Boolean)
Username (string)
Granted Authority
(string)
groupAuthoritiesByUsernameQuery
GBAC
(any)
Group Name (any)
Granted Authority
(string)
JdbcDaoImpl
JdbcDaoImplSQL
SQLSpring BeanJdbcDaoImpl
JdbcDaoImplJDBC<jdbc-user-service>
beanJdbcDaoImpl
88 / 350
<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
l
l
l
ID
email
16
XXXX XXXX XXXX 1234
SQLHSQL
HSQL
bootstrapSQLJava
90 / 350
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
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
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
93 / 350
http://lengyun3566.iteye.com
}
}
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
salt
adminguest
admin
admin
7b2e9f54cdff413fcde01f330af6896c3cd7e6cd
guest
guest
2ac15cab107096305d0274cd4eb86c74bb35a4b4
admin
fakeadmin
admin
7b2e9f54cdff413fcde01f330af6896c3cd7e6cd
fakeadminadmin
admin
passwordSHA-1password
95 / 350
http://lengyun3566.iteye.com
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
salted
DaoAuthenticationProvidersalted
ReflectionSaltSourcesalt
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
http://lengyun3566.iteye.com
DatabasePasswordSecurerBean
UserDetailsServiceDatabasePasswordSecurerBeanbean
SaltSourcesalt
98 / 350
http://lengyun3566.iteye.com
SaltSourceUserDetailssaltUserDetails
UserDetailsServiceCustomJdbcDaoImplSQL
UserDetails
admin
salt
salt
CustomJdbcDaoImpl
beanchangePassword
PasswordEncoderSaltSourcesalt
JdbcUserDetailsManagerPasswordEncoderSaltSource
JdbcUserDetailsManager
salt source
saltsaltusername
usernamesalt
99 / 350
http://lengyun3566.iteye.com
salt
UserDetails
UserDetailssalt
scheama
saltSpring Securityschema
security-schema.sql
salttest-users-groups-data.sql
insertsalt
salt
saltdogstore-security.xmlCustomJdbcDaoImpl
100 / 350
http://lengyun3566.iteye.com
<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
UserDetailssalt
UserDetailsAuthenticationProvider
CustomJdbcDaoImpl
JdbcDaoImplUserDetailsUser
UserUserUserDetailsService
102 / 350
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
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
SQL
dogstore-security.xml<embedded-database>SQL
104 / 350
http://lengyun3566.iteye.com
remember me
<remember-me>data source
tokens
TokenBasedRememberMeServicesMD5
cookie
o.s.s.web.authentication.rememberme.PersistentTokenBasedRememberMeServicestokenstoken
105 / 350
http://lengyun3566.iteye.com
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
Javakeytoolkey store
passwordkey store
JBCP Pets
http://lengyun3566.iteye.com
JBCP Pets
Anywhere
NH
US
Is CN=JBCP Pets Admin, OU=JBCP Pets, O=JBCP Pets, L=Anywhere, ST=NH, C=US
correct?
[no]:
yes
genkeypairjava 6keytoolgenkey
TomcatSSL Connector
httpshttp
JBCP Pets
107 / 350
http://lengyun3566.iteye.com
SSLSSLSpring Security
<intercept-url>
requires-channel<intercept-url>URLHTTPHTTPS
JBCP Pets
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
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
JBCP Pets
remember me
/
Spring SecurityAOP
l webcritical thinking
l
l pre-authorization
l
l CollectionsArrays
Spring Security
110 / 350
JBCP Pets
JBCP Pets
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
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
113 / 350
http://lengyun3566.iteye.com
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
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">
urlJSP
HTTP<intercept-url>
URLwebURL
115 / 350
http://lengyun3566.iteye.com
<authorize>action
form
form
Spring
<authorize>SpringSpELJSP
SpELSpring Security
SpEL<authorize>
My Account
SpEL<intercept-url>
<authorize>
<authorize>
Spring Security2
Spring SecuritySpring Security3
<authorize>
Log InROLE_USER<authorize>
ifNotGranted
116 / 350
http://lengyun3566.iteye.com
<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
JSP
(ifNotGrantedifAnyGrantedifAllGrantedJSP EL
GrantedAuthority
118 / 350
http://lengyun3566.iteye.com
<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
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/
lurl
lURL
url
Spring Securitysping
if...Grantedaccess
120 / 350
http://lengyun3566.iteye.com
l TagUserDetails
IP<authorize>
JSPSpELJSP
l <authorize>
JSPJSP
l javaJSP tag
Java
JSP
121 / 350
http://lengyun3566.iteye.com
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
JBCP Pets
web MVCJDBC DAO
com.packtpub.springsecurity.service.IuserService
@PreAuthorize
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
ROLE_USERROLE_ADMINguestguest
Tomcat
changePassword
ROLE_ADMINGrantedAuthority
Tomcat 403
@PreAuthorize
124 / 350
http://lengyun3566.iteye.com
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
JSR-250Spring Security
@Secured
SpringJSR-250 @RolesAllowed@Secured
@RolesAllowed<global-methodsecurity>
<global-method-security secured-annotations="enabled"/>
@SecuredJSR@RolesAllowed
Spring
pointcutadvice
AOPSpring SecurityXML
service
<global-method-security>
<protect-pointcut access="ROLE_ADMIN"
expression="execution(* com.packtpub.springsecurity.service.I*Service.*(..))"/>
</global-method-security>
DAO
126 / 350
http://lengyun3566.iteye.com
<global-method-security>
<protect-pointcut access="ROLE_USER"
expression="execution(* com.packtpub.springsecurity.dao.IProductDao.getCategories(..)) &&
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
@Secure
No
No
protect-pointcut
XML
No
No
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
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
Spring
SpELURL
Boolean
bean
XMLSpring Bean
XML
XMLchangePassword
beanXML
XMLdogstore-base.xml
schemaSpring Bean
130 / 350
http://www.
http://lengyun3566.iteye.com
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
ROLE_USER ROLE_ADMIN
guest
MethodSecurityInterceptor
MapBasedMethodSecurityMetadataSourceConfigAttributes
SpEL@PreAuthorize<protect>access
JSR-250 @RolesAllowed
beanset
131 / 350
http://lengyun3566.iteye.com
<security:intercept-methods>
<security:protect access="ROLE_USER" method="set*"/>
</security:intercept-methods>
*
?[
Java
changePassword
l
l
Spring SecuritySpEL
@PreAuthorize("#username == principal.username or
hasRole('ROLE_USER')")
SpEL
#username#
132 / 350
http://lengyun3566.iteye.com
<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
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
Spring AOPafterAOP
134 / 350
http://lengyun3566.iteye.com
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
@PostFilterCollection
Collection
@PostFiltergetCategories
getCategories
@Override
public Collection<Category> getCategories() {
Collection<Category> unfilteredCategories = productDao.getCategories();
return productDao.filterCategories(unfilteredCategories);
}
filterCategoriesIProductDao@PreFilter
@PreFilter
ProductDao
@Override
public Collection<Category> filterCategories(Collection<Category>
categories) {
return categories;
}
IProductService@PostFilter
@PreFilter
@PreFilter@PostFilter
136 / 350
http://lengyun3566.iteye.com
@PreFilter@PostFilter
@PreFilter
@PreFilter
@PreFilter
Collections
AOP
Spring 3 Reference DocumentationSpring
l/
lSpring SecurityJSP
Spring MVC
l
webSpring Security
137 / 350
http://lengyun3566.iteye.com
Spring Security
Spring Security
138 / 350
http://lengyun3566.iteye.com
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
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
ROLE_ADMINIP
Spring beanbeandoFilterInternal
@Override
public void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
140 / 350
http://lengyun3566.iteye.com
// 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
SecurityContextAuthentication
Spring Security
GrantedAuthorityAccessDeniedException
Spring bean
IP servlet
Spring beandogstore-base.xml
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
Spring Security
IPadmin
IPIPIP
javaIP
IP
143 / 350
http://lengyun3566.iteye.com
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
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
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
beanURL /j_spring_security_filterSpring
SecurityURLAbstractAuthenticationProcessingFilter
Authentication token
token
tokeno.s.s.core.AuthenticationAuthenticationToken
Spring Security
AuthenticationManager
AuthenticationProviderSignedUsernamePasswordAuthenticationToken
AuthenticationProvider
147 / 350
http://lengyun3566.iteye.com
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
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
<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
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
Session
Spring Securitysession
concurrency controlsessionsession management
Sping Security
Spring Securitysessionsession
session fixation protectionsession
session
session fixation
securitysession
Session
sessionsession
session fixation
Sessionsession
sessionJSESSIONIDJSESSIONIDcookie
URLsession
session
session
152 / 350
http://lengyun3566.iteye.com
session
OWASPhttp://www.owasp.org/
session
Spring Security
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
IEJBCP PetsF12
CookielocalhostJSESSIONIDcookie
Edit CookieIEJSESSIONID
sessionFirefoxIE
sessionJSESSIONID
session
session cookieXSS
sessionOWASP
session-fixation-protection
session-fixation-protection
none
154 / 350
session
SessionManagementFilter
http://lengyun3566.iteye.com
<session-management>
sessionsession
migrateSession
session
bean
session
newSession
session
session
migrateSession
session
sessionsession
sessionsession
session
session
session
ConcurrentSessionFilterdogstore-security.xml
155 / 350
http://lengyun3566.iteye.com
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
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
form
sessionURL
Session
SessionSessionRegistrysessionsession
sessionmax-sessions-1
sessionsession
sessionsession
BaseControllerbean@Autowired
SessionRegistry sessionRegistry;
@ModelAttribute("numUsers")
public int getNumberOfUsers() {
return sessionRegistry.getAllPrincipals().size();
}
158 / 350
http://lengyun3566.iteye.com
<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
SessionRegistryAPI
l getAllPrincipalssessionPrincipalUserDetailsList
l getAllSessions(principal, includeExpired)PrincipalSessionInformationList
sessionsession
SessionRegistry APIlistActiveUsers
sessionPrincipalMapUI
UIJSTLWEB-INF/views/accountlistActiveUsers.jsp
http://localhost:8080/JBCPPets/account/listActiveUsers.do
160 / 350
http://lengyun3566.iteye.com
SessionRegistrySessionRegistry
Spring Security
161 / 350
http://lengyun3566.iteye.com
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
Access Denied
<http><accessdenied-handler>URL
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
AccessDeniedExceptionmessage
Spring SecurityAccessDeniedException
Access Denied
errorDetailserrorTrace
AccessDeniedException
Spring Security
AccessDeniedExceptionHTTP 403AuthenticationException
164 / 350
http://lengyun3566.iteye.com
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
Spring Securityweb
AuthenticationEntryPoint
166 / 350
http://lengyun3566.iteye.com
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
bean
beansecurity
167 / 350
http://lengyun3566.iteye.com
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
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
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
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"/>
171 / 350
http://lengyun3566.iteye.com
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
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
</property>
</bean>
AuthenticationManagerbean
beansecurity
saltingremember me
174 / 350
http://lengyun3566.iteye.com
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
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
<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
http://lengyun3566.iteye.com
LogoutFilterbean
URLLogoutHandler
Spring
setterSpring
SpringSpring
Security
LogoutHandler
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
<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
<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>
<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
<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
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
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
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
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
<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
"+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
ApplicationListener
Spring Security
l DefaultAuthenticationEventPublisher
exceptionMappings
l HttpSessionweb.xml
Spring
Spring Security
SpEL
SpEL
SpEL
com.packtpub.springsecurity.security.CustomWebSecurityExpressionRoot
WebSecurityExpressionRoot
188 / 350
http://lengyun3566.iteye.com
}
}
WebSecurityExpressionHandler
DefaultWebSecurityExpressionHandler
com.packtpub.springsecurity.security.CustomWebSecurityExpressionHandler
CustomWebSecurityExpressionRoot
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>
189 / 350
http://lengyun3566.iteye.com
SpEL
SpEL Votersecurityaccess-decisionmanager-refAccessDecisionManager
Spring Security
l servletIPHTTPSSO
l AuthenticationProviderHTTPSSO
l sessionsessionsession
l AccessDeniedException
l Spring beansession
l ApplicationListenerSpring Security
l SpELURL
Spring Security
190 / 350
http://lengyun3566.iteye.com
ACL
Spring Security
l
l Spring Security ACL
l Spring ACL
l JBCP PetsSpring beanACL
l ACLJSPACL
l ACL
web
access control listACLACLACL
JBCP PetsACL
191 / 350
http://lengyun3566.iteye.com
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 SecurityACL
Spring SecurityACL
192 / 350
http://lengyun3566.iteye.com
SIDACL
object identitySpring ACLACL
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
o.s.s.acls.model.AccessControlEntry
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
acl-schema.sqlWEB-INF/classes
http://lengyun3566.iteye.com
SIDACE
ACL
Spring SecurityHSQL
l ACL_CLASS.CLASS100500100
l
oracleDDL
ACLACEACL
196 / 350
http://lengyun3566.iteye.com
<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
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
<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
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
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
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
WEB-INFtest-acl-data.sqlJBCP PetsSQL
SQLSQL
ACL_CLASSACL
Category
ACL_SIDSIDACESID
principal
ACL_OBJECT_IDENTITY
SID
l CategoryOBJECT_ID_CLASSACL_CLASS
l PK1OBJECT_ID_IDENTITY
l SIDROLE_ADMINOWNER_SID columnACL_SID
1CategorySQL
202 / 350
http://lengyun3566.iteye.com
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
Pet
Apparel
AccessDeniedException
ACL
Spring ACL
203 / 350
http://lengyun3566.iteye.com
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
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
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
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
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
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
ACL
admin
admin2
guest
ROLE_ADMIN
SID ACEREAD
ROLE_ADMIN
SID ACEREAD
Dog Food ( 2)
SID
ACEADMIN_READ
Spring ACL
GrantedAuthority
tagACL
ACL
<accesscontrollist>tag
<accesscontrollist>tag
210 / 350
http://lengyun3566.iteye.com
READADMIN_READ
JSP EL
${category}
tagSidRetrievalStrategy
ObjectIdentityRetrievalStrategyACL
211 / 350
http://lengyun3566.iteye.com
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
IProductService
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
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
<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
215 / 350
http://lengyun3566.iteye.com
ACLACLSQL
ProductDAO
JdbcMutableAclServiceObjectIdentityMutableAcl
ObjectIdentity
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
216 / 350
http://lengyun3566.iteye.com
{
// 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
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
EhcacheJARclasspathACLEhcache
218 / 350
http://lengyun3566.iteye.com
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
http://lengyun3566.iteye.com
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
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
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
ACL
hook
Spring ACLAcegi 1.x
Spring Security JIRA
http://jira.springframework.org/SEC-479
Spring Security3
l ACLGUIDUUID
l JIRASEC-1140ACLPermission
32
Spring SecurityACL
Spring SecuritySpring ACL
ACLSpring ACL
Spring ACLSpring ACL
223 / 350
http://lengyun3566.iteye.com
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
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
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
l myOpenID
l Google
Spring SecurityOpenID
Spring
Spring Security
openid4javahttp://code.google.com/p/openid4java/Spring SecurityOpenID
OpenID/negotiation
OpenID
OpenID
JBCP Pets
OpenIDform
227 / 350
http://lengyun3566.iteye.com
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>
OpenIDformOpenID
OpenIDJBCP Pets
OpenID
OpenID
test-users-groups-data.sql
myOpenIDYahoo!OpenID
https://jamesgosling.myopenid.com/SQL
228 / 350
http://lengyun3566.iteye.com
adminunused
OpenID
OpenID
OpenID
OpenIDJBCP PetsOpenID
OpenID
229 / 350
http://lengyun3566.iteye.com
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
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
openid.response_nonce
openid.sig
OpenID
openid.association
openid.identifier
OP-Local identifier
OpenID
232 / 350
http://lengyun3566.iteye.com
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
http://lengyun3566.iteye.com
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
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
}
}
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)
{
SQL
DatabasePasswordSecurerBeansaltcreateUserSQL
Java
236 / 350
http://lengyun3566.iteye.com
saltuserCustomJdbcDaoImpl
JdbcUserDetailsManagercreateUser
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
237 / 350
http://lengyun3566.iteye.com
OpenIDOpenID
OpenIDOpenID
OpenID
238 / 350
http://lengyun3566.iteye.com
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
http://axschema.org/contact/email
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
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
AXOpenIDAPI
AXOpenID
AX
AXOpenIDAX
myOpenIDGoogle
e-mailAX
myOpenID
242 / 350
AX
http://schema.openid.net/contact/
email
http://lengyun3566.iteye.com
http://axschema.org/contact/email
OpenIDOpenID
Google URL
243 / 350
http://lengyun3566.iteye.com
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
l OpenID
web
LDAP
245 / 350
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
LDAP
LDAPApache Directory Server
1.5LDAP
Mr. Einstein
uid=aeinstein,ou=users,dc=example,dc=com
distinguished nameDN
DNSpring Security LDAP
Mr. Einstein
Mr. EinsteinLDAP
247 / 350
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
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
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
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
o.s.s.ldap.authentication.LdapAuthenticator
o.s.s.ldap.authentication.BindAuthenticator
LDAP
LDAPLDAP
<ldap-server>manager-dnLDAP
managerdnLDAP
manager-dnmanager-dnDN
252 / 350
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
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
255 / 350
UserDetailsContextMapperLDAP personinetOrgPerson
LdapUserDetailsMapperGrantedAuthority
LDAPJDBC
GrantedAuthoritysJDBCLDAP
256 / 350
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
LDAP
PasswordComparisonAuthenticatorLDAPDN
LDAPuserPassword
BindAuthenticator
<ldap-authentication-provider>
258 / 350
<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
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
<ldap-authentication-provider server-ref="ldapLocal"
user-search-filter="(uid={0})" group-search-base="ou=Groups"
user-details-class="inetOrgPerson">
LDAPUserDetailsContextMapper
inetOrgPerson
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
WebContent/WEB-INF/views/account/home.jsp
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
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>
263 / 350
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
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
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
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
266 / 350
BindAuthenticatorFilterBasedLdapUserSearch beanLDAP
DN
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
<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
268 / 350
LDAPou=GroupsActive Directory
Spring SecurityActive Directory LDAP
LdapAuthoritiesPopulator
beanLdapAuthoritiesPopulator
LDAPROLE_USER
com.packtpub.springsecurity.security.SimpleRoleGrantingLdapAuthoritiesPopulator
269 / 350
}
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>
sAMAccountNameActive DirectoryLDAPuid
Active Directory
Active Directory LDAPSpring
Security LDAP
270 / 350
<bean class="org.springframework.security.ldap.authentication.UserDetailsServiceLdapAuthoritiesPopu
<constructor-arg ref="jdbcUserServiceCustom"/>
</bean>
LDAPUserDetailsService
LDAP
LDAP
LDAP
271 / 350
272 / 350
http://lengyun3566.iteye.com
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
CAS
CAS
l
l CAS
l CASCAS
CAS ticket
l CASticketCAS
assertionticket
CAS
274 / 350
http://lengyun3566.iteye.com
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
CAS
CASJBCP PetsSpring Security
bean
CasAuthenticationEntryPoint
AuthenticationEntryPoint
CAS
o.s.s.cas.web.CasAuthenticationEntryPoint
dogstore-base.xmlbean
276 / 350
http://lengyun3566.iteye.com
<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
ServicePropertiesCAS
Spring CASCAS
CASURLCAS
CAS
CAS
serviceCASCAS
URLURL
CAS
My AccountROLE_USERCAS
adminadminguest/guest
277 / 350
http://lengyun3566.iteye.com
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
CasAuthenticationFilterAuthenticationManagerdogstoresecurity.xml<authentication-manager>alias
278 / 350
http://lengyun3566.iteye.com
<authentication-manager
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
<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
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
UserDetailsServiceCAS
UserDetails
CASJBCP Pets
281 / 350
http://lengyun3566.iteye.com
CAS
CASCASCAS
CASCAS
CAS assertion
CASticketCASCAS
CAS
GrantedAuthority
CAS
CASCASCASLDAP
282 / 350
http://lengyun3566.iteye.com
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
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
beancontextSource bean
org.springframework.ldap.core.ContextSourceCASLDAPCAS
Spring LDAP
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
<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>
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
<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
WEB-INF/views/account/home.jsp
http://lengyun3566.iteye.com
working. dogstore-security.xmlGrantedAuthority
My Account
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
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
<cas:authenticationSuccess>
<cas:user>${fn:escapeXml(assertion.chainedAuthentications[fn:length(assertion.chainedAuthenticati
<cas:attributes>
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
SAML 1.1
SAMLXML assertionSAML
CASSpring SecuritySAML
SAMLassertion XMLCAS
CAS ticketSAML ticketdogstore-base.xmlTicketValidator
bean
CasAuthenticationProviderTicketValidator
<bean id="casAuthenticationProvider"
class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
<property name="ticketValidator" ref="samlTicketValidator"/>
<property name="serviceProperties" ref="casService"/>
CAS
CAS
CASLDAP
CASCAS
292 / 350
http://lengyun3566.iteye.com
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
294 / 350
http://lengyun3566.iteye.com
Client Certificate
Authentication
Spring Security
formSpring Security
form
l
l Spring Security
l Spring Security
l
l
certificates
servlet
http://lengyun3566.iteye.com
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
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
common nameDNDN
Spring Security JDBCadmin
Spring SecurityTomcat
Tomcattrust store
SSL
keytooljava
Tomcat
Tomcattrust store
jbcppets_clientauth.cer
298 / 350
http://lengyun3566.iteye.com
keytool -exportcert -alias jbcpclient -keystore jbcppets_clientauth.p12 storetype PKCS12 -storepass password -file jbcppets_clientauth.cer
tomcat.truststoretrust store
tomcat.truststoreTomcatconf
http://lengyun3566.iteye.com
trust store
key storetrust storeTomcat
ConnectorkeystoreFiletruststoreFile
JSSEkeystoreJava Key Store / JKS, PKCS 12
Tomcattrust storeTomcat server.xml
SSL Connector
SSLTomcatTomcat
Tomcat
Tomcat
FirefoxIE
Firefox
key
1.
2.
3.
300 / 350
http://lengyun3566.iteye.com
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
JBCP Pets
Firefox
My Account
Spring SecurityTomcat
web
Spring SecurityTomcat
302 / 350
http://lengyun3566.iteye.com
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
Spring Security
pre-authenticatedTomcatSpring
Securityassertion
Spring Security
Spring SecurityHTTP sessionTomcat
Spring SecurityUserDetailsService
UserDetailsServiceSpring SecuritySpring
SecurityGrantedAuthority
security
LDAPOpenIDsecurity
<http>
admin
Spring Security
Spring Security
<x509>
LDAP DNdistinguished name DN
304 / 350
http://lengyun3566.iteye.com
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
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
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
<bean id="forbiddenAuthEntryPoint"
class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint"/>
<http>entry point
AccessDeniedHandlerHttp403ForbiddenEntryPoint
SpringURLweb<error-page>
Java EE servletHttp403ForbiddenEntryPoint
l form
l Log out
l
l
Dual-Mode authentication
308 / 350
http://lengyun3566.iteye.com
form
Spring Security3AuthenticationEntryPointform
form
TomcatSSL
clientAuthwanttrue
entry-point-ref
form
form
JDBC UserDetailsService
formUserDetailsService
PreAuthenticatedAuthenticationProvider
form
l
l JDBCform
JdbcDaoImplSQL
l form
309 / 350
http://lengyun3566.iteye.com
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="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
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
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
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
l Spring bean
l
314 / 350
http://lengyun3566.iteye.com
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
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
SPNEGO Kerberos
316 / 350
http://lengyun3566.iteye.com
Spring SecurityKerberosSPNEGO
HTTP
l WWW-Authenticate: Negotiate HTTP
SPNEGO
l
HTTP Authorize
Spring Security
SPNEGOSSLSSOweb
Kerberos KDCMIT
KerberosKerberos
317 / 350
http://lengyun3566.iteye.com
Spring SecurityKerberos
CASKerberosKerberos Single SignOn (SSO)form
Spring SecurityKerberosKerberos
Spring SecuritySPNEGO
318 / 350
http://lengyun3566.iteye.com
o.s.s.extensions.kerberos.KerberosServiceAuthenticationProvider
SPNEGOSpring Bean
319 / 350
http://lengyun3566.iteye.com
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
320 / 350
http://lengyun3566.iteye.com
ADKerberos KDCADCORP\website
MicrosoftktpassAD
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
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
JDBC UserDetailsServiceJDBCSQL
Kerberoskerbuser
Kerberoskerbuser@CORP.JBCPPETS.COMWEBINF/classes/test-users-groups-data.sql
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
Kerberosweb
IEIESPNEGO
My Account
My Account
webKerberos
IEIESPNEGO SSO
l IntranetInternettab
l intranetIE
l tabwindows
IESPNEGO
Kerberos
324 / 350
http://lengyun3566.iteye.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
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
326 / 350
http://lengyun3566.iteye.com
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>
l KDC
l Windows
WindowsNTLMNTLMrequest/response
NegotiateSpring
TlRMNTLMSPNEGOSPNEGOYII
327 / 350
http://lengyun3566.iteye.com
l WindowsWindowsNTLM
l DNSKerberos
SPNEGOKerberos
LDAP UserDetailsServiceKerberos
JDBC UserDetailsServiceKerberosIDKerberos
Active DirectoryLDAPADKerberos
Microsoft ADLDAP UserDetailsServiceSpring SecurityLDAP
LDAPLDAPLDAP
AD
authentication providerLDAP UserDetailsService
dogstore-security.xml
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
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
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
l Kerberos SPNEGO
l Kerberosweb
330 / 350
http://lengyun3566.iteye.com
l JBCP PetsKerberosSPNEGO
l Kerberos web
l ADLDAP
l formKerberos
Spring Security
331 / 350
http://lengyun3566.iteye.com
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 Security3
Spring Security 3Spring Security 2
l SpringSpring Expression LanguageSpELURL
Spring Security
l
332 / 350
http://lengyun3566.iteye.com
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>
333 / 350
http://lengyun3566.iteye.com
<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 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
<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-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
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>
<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
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>
<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
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
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
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
web
Spring Securitywebweb
spring-security-configspring-security-core
l
l
l Spring Security
Spring Security 3
341 / 350
http://lengyun3566.iteye.com
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
http://lengyun3566.iteye.com
Spring Security
o.s.s.authentication.evento.s.s.access.event
AbstractAuthenticationEvent
AbstractAuthenticationFailureEvent
AuthenticationFailureBadCredentialsEvent
UsernameNotFoundException
343 / 350
BadCredentialsExceptio
UsernameNotFoundExc
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
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
345 / 350
http://lengyun3566.iteye.com
l /j_spring_security_switch_userSwitchUserFilter
l /j_spring_security_exit_user
bean
dogstore-explicit-base.xmlbean
bean
Spring bean
-->
http://lengyun3566.iteye.com
</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
beanSpring Security
Spring Securitybean
o.s.s.config.method.GlobalMethodSecurityBeanDefinitionParser
348 / 350
http://lengyun3566.iteye.com
JSR-250@Secured@Pre/@Post
bean@SecuredSecurityMetadataSourceAccessDecisionVoter
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
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