Java Training-Spring Core
Java Training-Spring Core
SPRING FRAMEWORK
Dmitry Noskov
Application security
Dmitry Noskov
Dmitry Noskov
Fundamentals (1)
principal
authentication
authorization
Dmitry Noskov
Fundamentals (2)
Authentication
GrantedAuthority
SecurityContext
SecurityContextHolder
Dmitry Noskov
SecurityContextHolder
Dmitry Noskov
Getting started
SecurityContext context = SecurityContextHolder.getContext();
Object principal = context.getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
} else {
String username = principal.toString();
}
Dmitry Noskov
Use case
Dmitry Noskov
Namespace
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:sec="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema
/beans
http://www.springframework.org/schema/
beans/spring-beans-3.0.xsd
http://www.springframework.org/schema
/security
http://www.springframework.org/schema
/security/spring-security-3.0.xsd">
Dmitry Noskov
Filters
Dmitry Noskov
Security filter
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Dmitry Noskov
Filter chain
Dmitry Noskov
<sec:filter-chain-map path-type="ant">
<sec:filter-chain pattern="/login.do*" filters="none"/>
<sec:filter-chain pattern="/**.do*"
filters="
securityContextPersistenceFilter,
logoutFilter,
usernamePasswordAuthenticationFilter,
rememberMeAuthenticationFilter,
exceptionTranslationFilter,
filterSecurityInterceptor" />
</sec:filter-chain-map>
</bean>
Spring Framework - Security
Dmitry Noskov
Basic filters
Filter
Description
ChannelProcessingFilter
SecurityContextPersistentFilter
LogoutFilter
UsernamePasswordAuthenticationFilter
BasicAuthenticationFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
http://static.springsource.org/spring-security/site/docs/3.0.x/reference/nsconfig.html#ns-custom-filters
Spring Framework - Security
Dmitry Noskov
Authentication
Dmitry Noskov
Authentication variants
credential-based
two-factor
hardware
other
Dmitry Noskov
Authentication mechanisms
basic
form
x.509
JAAS
etc.
Dmitry Noskov
Authentication storage
RDMBS
LDAP
custom storage
etc.
Dmitry Noskov
Fundamentals
Filter
Manager
Provider
Authentication
UserDetails
Dmitry Noskov
HTML form
Dmitry Noskov
Username-password filter
<bean id="..." class="...security.web.authentication.UsernamePasswordAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager"/>
<property name="filterProcessesUrl" value="/j_spring_security_check"/>
<property name="usernameParameter" value="login"/>
<property name="passwordParameter" value="password"/>
<property name="authenticationSuccessHandler">
<bean class="...security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<property name="defaultTargetUrl" value="/index.do"/>
</bean>
</property>
<property name="authenticationFailureHandler">
<bean class="...security.web.authentication.SimpleUrlAuthenticationFailureHandler">
<property name="defaultFailureUrl" value="/login.do"/>
</bean>
</property>
Dmitry Noskov
AuthenticationManager
AuthenticationProvider
performs authentication
UserDetailsService
UerDetails
Dmitry Noskov
AuthenticationManager
public interface AuthenticationManager {
/* Attempts to authenticate the passed Authentication object,
* returning a fully populated Authentication object (including
* granted authorities) if successful.
* @param authentication the authentication request object
Dmitry Noskov
AuthenticationProvider
public interface AuthenticationProvider {
/* Performs authentication.
* @param authentication the authentication request object.
* @return a fully authenticated object including credentials.
* @throws AuthenticationException if authentication fails.*/
Dmitry Noskov
UserDetailsService
/*Core interface which loads user-specific data.*/
public interface UserDetailsService {
/* Locates the user based on the username.
* @param username the username identifying the user
* @return a fully populated user record (never null)
* @throws UsernameNotFoundException if the user could not be
Dmitry Noskov
UserDetails
/* Provides core user information.*/
public interface UserDetails extends Serializable {
Collection<GrantedAuthority> getAuthorities();
String getPassword();
String getUsername();
boolean isAccountNonExpired();
boolean isAccountNonLocked();
boolean isCredentialsNonExpired();
boolean isEnabled();
}
Dmitry Noskov
Authentication manager
<bean id="..." class="...security.authentication.ProviderManager">
<property name="providers">
<list>
<ref local="casAuthenticationProvider"/>
<ref local="daoAuthenticationProvider"/>
<ref local="ldapAuthenticationProvider"/>
</list>
</property>
</bean>
Dmitry Noskov
Authentication provider
<bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService"/>
<property name="saltSource" ref bean="saltSource"/>
<property name="passwordEncoder" ref="passwordEncoder"/>
</bean>
<bean id="userDetailsService"
class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
Dmitry Noskov
Authentication DB schema
Dmitry Noskov
Password encoding
PasswordEncoder
MD5
SHA
SaltSource
SystemWide
reflection
Dmitry Noskov
Session management
<bean id="sessionManagementFilter"
class="org.springframework.security.web.session.SessionManagementFilter">
<property name="invalidSessionUrl" value="/timeout.do"/>
<property name="sessionAuthenticationStrategy" ref="strategy"/>
</bean>
<bean id="strategy"
class="SessionFixationProtectionStrategy">
<property name="alwaysCreateSession" value="true"/>
<property name="migrateSessionAttributes" value="true"/>
</bean>
Dmitry Noskov
Logout
<bean id="logoutFilter"
class="org.springframework.security.web.authentication.logout.LogoutFilter">
<constructor-arg>
<bean class="SimpleUrlLogoutSuccessHandler">
<property name="defaultTargetUrl" value="/login"/>
</bean>
</constructor-arg>
<constructor-arg>
<bean class="SecurityContextLogoutHandler"/>
</constructor-arg>
<property name="filterProcessesUrl" value="/logout"/>
</bean>
Dmitry Noskov
Remember Me authentication
RememberMeAuthenticationFilter
RememberMeServices
RememberMeAuthenticationProvider
Dmitry Noskov
RememberMe service
public interface RememberMeServices {
Authentication autoLogin(HttpServletRequest request,
HttpServletResponse response);
void loginFail(HttpServletRequest request,
HttpServletResponse response);
void loginSuccess(HttpServletRequest request,
HttpServletResponse response,
Authentication successfulAuthentication);
}
Dmitry Noskov
Remember Me shema
Dmitry Noskov
Anonymous authentication
<bean id="anonymousAuthenticationFilter"
class="...web.authentication.AnonymousAuthenticationFilter">
<property name="key" value="foobar"/>
<property name="userAttribute" value="anonymous,ROLE_ANONYMOUS"/>
</bean>
<bean id="anonymousAuthenticationProvider"
class="...authentication.AnonymousAuthenticationProvider">
<property name="key" value="foobar"/>
</bean>
Dmitry Noskov
<sec:remember-me services-ref=""/>
</sec:http>
Dmitry Noskov
Authorization
Dmitry Noskov
Use case
Dmitry Noskov
Authorization
handling
pre-invocation
after invocation
implementations
voting based
expression based
Dmitry Noskov
Security layers
WEB (URLs)
Servlet Filter
methods
Spring AOP
AspectJ
content
JSP tag
Dmitry Noskov
Dmitry Noskov
Authentication
Manager
Access Decision
Manager
Run-As
Manager
After-Invocation
Manager
Dmitry Noskov
Voting based
DecisionManager
DecisionVoter
ConfigAttribute
Dmitry Noskov
Decision managers
Decision manager
Description
AffirmativeBased
ConsensusBased
UnanimousBased
Dmitry Noskov
Decision voter
public interface AccessDecisionVoter {
int ACCESS_GRANTED = 1;
int ACCESS_ABSTAIN = 0;
int ACCESS_DENIED = -1;
boolean supports(ConfigAttribute attribute);
boolean supports(Class<?> clazz);
int vote(Authentication authentication,
Object object,
Collection<ConfigAttribute> attributes);
}
Spring Framework - Security
Dmitry Noskov
Basic expressions
Expression
Description
hasRole(ROLE_USER)
hasAnyRole(ROLE_USER, ROLE_ADMIN)
principal
authentication
permitAll
denyAll
isAnonymous()
isRememberMe()
Dmitry Noskov
WEB authorization
Dmitry Noskov
Web authorization
<bean id="..." class="web.access.intercept.FilterSecurityInterceptor">
<property name="authenticationManager" ref="authManager"/>
<sec:intercept-url pattern="/**"
access="ROLE_USER"
filters="none"
method="GET"
requires-channel="https"/>
</sec:filter-security-metadata-source>
</property>
</bean>
Spring Framework - Security
Dmitry Noskov
access="hasRole('ROLE_USER')"
filters="none"
method="GET"
requires-channel="https"/>
</sec:http>
Dmitry Noskov
WEB authorization
<bean id="webExpressionHandler"
class="DefaultWebSecurityExpressionHandler"/>
<bean id="webExpressionVoter" class="WebExpressionVoter">
<property name="expressionHandler" ref="webExpressionHandler"/>
</bean>
<bean class="org.springframework.security.access.vote.AffirmativeBased">
<property name="decisionVoters">
<list>
<ref bean="webExpressionVoter"/>
</list>
</property>
</bean>
Spring Framework - Security
Dmitry Noskov
super(a, fi);
}
public boolean hasAllRoles(String... roles) {
return false;
}
}
Spring Framework - Security
Dmitry Noskov
extends DefaultWebSecurityExpressionHandler {
@Override
public EvaluationContext createEvaluationContext(Authentication a,
FilterInvocation fi) {
StandardEvaluationContext ctx =
(StandardEvaluationContext)super.createEvaluationContext(a, fi);
SecurityExpressionRoot root =
new CustomWebSecurityExpressionRoot(a, fi);
ctx.setRootObject(root);
return ctx;
}
}
Spring Framework - Security
Dmitry Noskov
Method authorization
Dmitry Noskov
Method authorization
annotation driven
voting based - @Secured
expression based - @Pre/@Post
JSR-250 - @RolesAllowed
xml driven
Dmitry Noskov
Configuration
<sec:global-method-security>
access-decision-manager-ref="accessDecisionManager"
jsr250-annotations="disabled"
pre-post-annotations="disabled"
secured-annotations="enabled"
</sec:global-method-security>
Dmitry Noskov
voting
@Secured({"ROLE_USER"})
void create(Customer customer);
jsr-250
@RolesAllowed({"ROLE_USER"})
Dmitry Noskov
1
@PreAuthorize("hasRole('ROLE_USER')")
void create(Customer customer);
2
@PreAuthorize("hasRole('ROLE_USER') and hasRole('ROLE_ADMIN')")
3
@PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')")
void create(Customer customer);
Dmitry Noskov
org.training.AccountService.createAccount=ROLE_USER
org.training.AccountService.delete*=ROLE_ADMIN
</value>
</property>
</bean>
Dmitry Noskov
Dmitry Noskov
Dmitry Noskov
ACL DB scheme
Dmitry Noskov
ACL_CLASS
ACL_SID
ACL_OBJECT_IDENTITY
ACL_ENTRY
Dmitry Noskov
Basic classes
Acl
AccessControlEntry
Permission
Sid
ObjectIdentity
Dmitry Noskov
AclService
MutableAclService
LookupStrategy
ObjectIdentityRetrievalStrategy
SidRetrievalStrategy
Dmitry Noskov
Permissions
base permissions
read (1)
write (2)
create (4)
delete (8)
administration (16)
custom permissions
Dmitry Noskov
Dmitry Noskov
Configuration (voting)
<sec:global-method-security
access-decision-manager-ref="accessDecisionManager"
secured-annotations="enabled">
</sec:global-method-security>
<bean id="accessDecisionManager" class="AffirmativeBased">
<property name="decisionVoters">
<list>
<ref bean="voter1"/>
<ref bean="voter2"/>
</list>
</property>
</bean>
Spring Framework - Security
Dmitry Noskov
@Secured
annotation
@Secured("ACL_CUSTOMER_READ")
public Customer getProjectsByCustomer(Customer customer) {}
voter
<constructor-arg value="ACL_CUSTOMER_READ"/>
<constructor-arg>
<array>
<util:constant static-field="BasePermission.READ"/>
</array>
</constructor-arg>
<property name="processDomainObjectClass" value="Customer"/>
</bean>
Spring Framework - Security
Dmitry Noskov
Configuration (expressions)
<sec:global-method-security pre-post-annotations="enabled">
<sec:expression-handler ref="expressionHandler"/>
</sec:global-method-security>
<bean id="expressionHandler"
class="DefaultMethodSecurityExpressionHandler">
<property name="permissionEvaluator" ref="permissionEvaluator"/>
</bean>
<bean id="permissionEvaluator" class="AclPermissionEvaluator">
<constructor-arg ref="aclService"/>
</bean>
Spring Framework - Security
Dmitry Noskov
Permission evaluator
public interface PermissionEvaluator {
boolean hasPermission(Authentication authentication,
Object targetDomainObject,
Object permission);
boolean hasPermission(Authentication authentication,
Serializable targetId,
String targetType,
Object permission);
}
Dmitry Noskov
@PreAuthorize
by domain object
@PreAuthorize("hasPermission(#customer, 'delete')")
public void delete(Customer customer);
by identifier
@PreAuthorize(
hardcode
@PreAuthorize("#customer.owner.id == principal.id")
public void create(Customer customer);
Dmitry Noskov
@PreFilter
single parameter
@PreFilter("hasPermission(filterObject, 'read')")
public List<Customer> filterCustomers(List<Customer> customers) {
return customers;
}
multiple parameters
@PreFilter(filterTarget = "customers",
value = "hasPermission(filterObject, 'update')")
public void updateCustomers(List<Customer> customers, State st) {
}
Dmitry Noskov
Additional features
Dmitry Noskov
RunAsManager
/*Creates a new temporary Authentication object.*/
public interface RunAsManager {
/ *Returns a replacement Authentication object for the current
*secure object, or null if replacement not required*/
Authentication buildRunAs(Authentication authentication,
Object object,
Collection<ConfigAttribute> attr);
boolean supports(ConfigAttribute attribute);
boolean supports(Class<?> clazz);
}
Spring Framework - Security
Dmitry Noskov
<bean class="RunAsImplAuthenticationProvider">
<property name="key" value="someKey"/>
</bean>
Dmitry Noskov
magic tag
<sec:global-method-security run-as-manager-ref="runAsManager">
</sec:global-method-security>
interceptor bean
<bean class="MethodSecurityInterceptor">
Dmitry Noskov
After invocation
Dmitry Noskov
Basic services
public interface AfterInvocationManager {
Object decide(Authentication authentication, Object object,
Collection<ConfigAttribute> attributes,
Object returnedObject) throws AccessDeniedException;
boolean supports(ConfigAttribute attribute);
boolean supports(Class<?> clazz);
}
Dmitry Noskov
Configuration
custom provider
<sec:global-method-security>
<sec:after-invocation-provider ref="myProvider"/>
</sec:global-method-security>
custom manager
<bean class="MethodSecurityInterceptor">
<property name="afterInvocationManager" ref="myManager"/>
</bean>
Dmitry Noskov
@Post
@PostAuthorize
@PreAuthorize("hasRole('ROLE_USER')")
@PostAuthorize("hasPermission(returnObject, 'read')")
public Employee getEmployeeByName(String name) {
}
@PostFilter
@PreAuthorize("hasRole('ROLE_USER')")
@PostFilter("hasPermission(filterObject, 'read')")
public List<Employee> getEmployees() {
}
Dmitry Noskov
Dmitry Noskov
Authentication
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags" %>
<sec:authentication property="principal" var="user"/>
<div class="links"><div>Logged in: ${user.name}</div></div>
<div class="links">
<div><sec:authentication property="principal.name"/></div>
</div>
Dmitry Noskov
Authorize (1)
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags" %>
<sec:authorize ifAllGranted="ROLE_ADMIN, ROLE_SUPERVISOR">
</sec:authorize>
Dmitry Noskov
Authorize (2)
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags" %>
<sec:authorize access="hasRole('supervisor')">
This content will only be visible to users who have
the "supervisor" authority in their list of
<tt>GrantedAuthority</tt>s.
</sec:authorize>
Dmitry Noskov
Authorize (3)
JSP
security interceptor
</sec:filter-security-metadata-source>
</property>
</bean>
Spring Framework - Security
Dmitry Noskov
ACL
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags" %>
<sec:accesscontrollist hasPermission="1,2" domainObject="object">
This will be shown if the user has either of the permissions
Dmitry Noskov
Summary
Dmitry Noskov
Separation of concerns
Dmitry Noskov
Flexibility
authentication mechanisms
based on Spring
Dmitry Noskov
Portability
Dmitry Noskov
Books
Dmitry Noskov
Links
main features
http://static.springsource.org/spring-security/site/features.html
articles
http://static.springsource.org/spring-security/site/articles.html
reference
http://static.springsource.org/springsecurity/site/docs/3.0.x/reference/springsecurity.html
blog
http://blog.springsource.com/category/security/
refcardz
http://refcardz.dzone.com/refcardz/expression-basedauthorization
Spring Framework - Security
Dmitry Noskov
Questions
Dmitry Noskov
The end
http://www.linkedin.com/in/noskovd
http://www.slideshare.net/analizator/presentations