SlideShare a Scribd company logo
1 of 96
Download to read offline
From 0 to Spring Security 4.0 
Rob Winch 
@rob_winch 
© 2014 SpringOne 2GX. All rights reserved. Do not distribute without permission.
Agenda 
• Introductions 
• Hello Spring Security (Java Config) 
• Custom Authentication 
• Spring Data Integration 
• Testing Support 
• WebSocket Support 
• White Hat Hacker 
2
About Me 
• Open Source fanatic 
• Spring Security & Spring 
Project Lead 
• Committer on Spring 
Framework 
• Co-author of Spring Security 
3.1 book 
• Twitter @rob_winch 
3
What is Spring Security? 
• Comprehensive support for Authentication And Authorization 
• Protection against common attacks 
• Servlet API Integration 
• Optional integration with Spring MVC 
• Optional Spring Data Integration 
• WebSocket Support 
4
Demo 
Message 
Application 
Unless otherwise indicated, these slides are 
© 2013-2014 Pivotal Software, Inc. and licensed under a 
Creative Commons Attribution-NonCommercial license: 
http://creativecommons.org/licenses/by-nc/3.0/ 
SPRING SECURITY
Spring Security
web.xml 
<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>
Hello Java Configuration – Replaces web.xml 
public class SecurityWebInitializer 
extends AbstractSecurityWebApplicationInitializer { 
// optionally override methods 
}
Hello Java Configuration – WebSecurityConfig 
@Configuration 
@EnableWebMvcSecurity 
public class WebSecurityConfig 
extends WebSecurityConfigurerAdapter { 
... 
}
Hello Java Configuration – WebSecurityConfig 
@Autowired 
public void configureGlobal( 
AuthenticationManagerBuilder auth) throws Exception { 
auth 
.inMemoryAuthentication() 
.withUser("admin”) 
.password("password”) 
.roles("ADMIN","USER") 
.and() 
.withUser("user") 
.password("password") 
.roles("USER"); 
}
Hello Java Configuration
Hello Java Configuration
Hello Java Configuration 
<div th:with="currentUser=$ 
{#httpServletRequest.userPrincipal?.name}"> 
<div th:if="${currentUser != null}"> 
<form th:action="@{/logout}" method="post”> 
<input type="submit" value="Log out" /> 
</form> 
<p th:text="${currentUser}”> 
sample_user 
</p> 
</div>
Hello Java Configuration 
<div th:with="currentUser=$ 
{#httpServletRequest.userPrincipal?.name}"> 
<div th:if="${currentUser != null}"> 
<form th:action="@{/logout}" method="post”> 
<input type="submit" value="Log out" /> 
</form> 
<p th:text="${currentUser}”> 
sample_user 
</p> 
</div> 
public interface HttpServletRequest … { 
Principal getUserPrincipal(); 
... 
}
Hello Java Configuration 
<div th:with="currentUser=$ 
{#httpServletRequest.userPrincipal?.name}"> 
<div th:if="${currentUser != null}"> 
<form th:action="@{/logout}" method="post”> 
<input type="submit" value="Log out" /> 
</form> 
<p th:text="${currentUser}”> 
sample_user 
</p> 
</div> 
public interface Principal … { 
String getName(); 
... 
}
Hello Java Configuration 
<div th:with="currentUser=$ 
{#httpServletRequest.userPrincipal?.name}"> 
<div th:if="${currentUser != null}"> 
<form th:action="@{/logout}" method="post”> 
<input type="submit" value="Log out" /> 
</form> 
<p th:text="${currentUser}”> 
sample_user 
</p> 
</div> 
</div>
Custom Log in Form
Java Configuration 
@Override 
protected void configure(HttpSecurity http) 
throws Exception { 
http 
.authorizeRequests() 
.anyRequest().authenticated() 
.and() 
.formLogin().and() 
.httpBasic(); 
}
Java Configuration 
http 
.authorizeRequests() 
.anyRequest().authenticated() 
.and() 
.formLogin().and() 
.httpBasic(); 
<http use-expressions="true"> 
<intercept-url pattern="/**" access="authenticated"/> 
<form-login /> 
<http-basic /> 
</http>
Java Configuration 
http 
.authorizeRequests() 
.anyRequest().authenticated() 
.and() 
.formLogin() 
.loginPage("/login”) 
.permitAll() 
.and() 
.logout() 
.permitAll();
Java Configuration 
http 
.authorizeRequests() 
.antMatchers("/resources/**”).permitAll() 
.anyRequest().authenticated() 
.and() 
.formLogin() 
.loginPage("/login”) 
.permitAll() 
.and() 
.logout() 
.permitAll();
Java Configuration 
<form th:action="@{/login}" method="post"> 
<label for="username">Username</label> 
<input type="text" id="username" 
name="username"/> 
<label for="password">Password</label> 
<input type="password" id="password" 
name="password"/> 
<button type="submit">Log in</button> 
</form>
Java Configuration 
<form th:action="@{/login}" method="post"> 
<label for="username">Username</label> 
<input type="text" id="username" 
name="username"/> 
<label for="password">Password</label> 
<input type="password" id="password" 
name="password"/> 
<button type="submit">Log in</button> 
</form>
Java Configuration 
<form th:action="@{/login}" method="post"> 
<label for="username">Username</label> 
<input type="text" id="username" 
name="username"/> 
<label for="password">Password</label> 
<input type="password" id="password" 
name="password"/> 
<button type="submit">Log in</button> 
</form> 
http 
…. 
.formLogin() 
.loginPage("/login”)
Custom Authentication
Java Configuration – Custom Authentication 
public interface UserDetailsService { 
UserDetails loadUserByUsername(String username) 
throws UsernameNotFoundException; 
}
Java Configuration – Custom Authentication 
public interface UserDetails extends Serializable { 
Collection<? extends GrantedAuthority> 
getAuthorities(); 
String getPassword(); 
String getUsername(); 
boolean isAccountNonExpired(); 
boolean isAccountNonLocked(); 
boolean isCredentialsNonExpired(); 
boolean isEnabled(); 
}
Java Configuration – Custom Authentication 
@Entity 
public class User implements Serializable { 
@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
private Long id; 
private String firstName; 
private String lastName; 
private String email; 
private String password; 
... 
}
Java Configuration – Custom Authentication 
pubic class CustomUserDetails extends User 
implements UserDetails { 
public CustomUserDetails(User u) { 
super(user); 
} 
public Collection getAuthorities() { 
return AuthorityUtils.createAuthorityList("ROLE_USER"); 
} 
public String getUsername() { 
return getEmail(); 
} 
public boolean isEnabled() { return true; } 
...
Java Configuration – Custom Authentication 
public UserDetails loadUserByUsername(String username) 
throws UsernameNotFoundException { 
User user = userRepository.findByEmail(username); 
if(user == null) { 
throw new UsernameNotFoundException(…); 
} 
return new CustomUserDetails(user); 
}
Java Configuration – Custom Authentication 
@Autowired 
public void configureGlobal( 
AuthenticationManagerBuilder auth, 
UserDetailsService userDetailsService) 
throws Exception { 
auth 
.userDetailsService(userDetailsService); 
}
Java Configuration – Custom Authentication 
<div th:with="currentUser=$ 
{#httpServletRequest.userPrincipal?.name}"> 
<div th:if="${currentUser != null}"> 
<form th:action="@{/logout}" method="post”> 
<input type="submit" value="Log out" /> 
</form> 
<p th:text="${currentUser}”> 
sample_user 
</p> 
</div>
Java Configuration – Custom Authentication 
<div th:with="currentUser=$ 
{#httpServletRequest.userPrincipal?.name}"> 
<div th:if="${currentUser != null}"> 
<form th:action="@{/logout}" method="post”> 
<input type="submit" value="Log out" /> 
</form> 
<p th:text="${currentUser}”> 
sample_user 
</p> 
</div> 
public interface HttpServletRequest … { 
Principal getUserPrincipal(); 
... 
}
Java Configuration – Custom Authentication 
<div th:with="currentUser=$ 
{#httpServletRequest.userPrincipal?.name}"> 
<div th:if="${currentUser != null}"> 
<form th:action="@{/logout}" method="post”> 
<input type="submit" value="Log out" /> 
</form> 
<p th:text="${currentUser}”> 
sample_user 
</p> 
</div> 
public interface HttpServletRequest … { 
(Authentication) Principal getUserPrincipal(); 
... 
}
Java Configuration – Custom Authentication 
<div th:with="currentUser=$ 
{#httpServletRequest.userPrincipal?.principal}"> 
<div th:if="${currentUser != null}"> 
<form th:action="@{/logout}" method="post”> 
<input type="submit" value="Log out" /> 
</form> 
<p th:text="${currentUser}”> 
sample_user 
</p> 
</div> 
public interface Authentication … { 
Object getPrincipal(); 
... 
}
Java Configuration – Custom Authentication 
<div th:with="currentUser=$ 
{#httpServletRequest.userPrincipal?.principal}"> 
<div th:if="${currentUser != null}"> 
<form th:action="@{/logout}" method="post”> 
<input type="submit" value="Log out" /> 
</form> 
<p th:text="${currentUser}”> 
sample_user 
</p> 
</div> 
public interface Authentication … { 
(UserDetails) Object getPrincipal(); 
... 
}
Java Configuration – Custom Authentication 
<div th:with="currentUser=$ 
{#httpServletRequest.userPrincipal?.principal}"> 
<div th:if="${currentUser != null}"> 
<form th:action="@{/logout}" method="post”> 
<input type="submit" value="Log out" /> 
</form> 
<p th:text="${currentUser}”> 
sample_user 
</p> 
</div> 
public interface Authentication … { 
(CustomUserDetails) Object getPrincipal(); 
... 
}
Java Configuration – Custom Authentication 
<div th:with="currentUser=$ 
{#httpServletRequest.userPrincipal?.principal}"> 
<div th:if="${currentUser != null}"> 
<form th:action="@{/logout}" method="post”> 
<input type="submit" value="Log out" /> 
</form> 
<p th:text="${currentUser.firstName}”> 
sample_user 
</p> 
</div> 
public class CustomUserDetails … { 
String getFirstName(); 
... 
}
Java Configuration – Custom Authentication 
@RequestMapping(method=RequestMethod.GET) 
public ModelAndView list() { 
SecurityContext ctx = 
SecurityContextHolder.getContext(); 
Authentication authentication = 
ctx.getAuthentication(); 
User custom = authentication == null ? 
null : (User) authentication.getPrincipal(); 
... 
}
Java Configuration – Custom Authentication 
@RequestMapping(method=RequestMethod.GET) 
public ModelAndView list(Authentication 
authentication) { 
User custom = authentication == null ? 
null : (User) 
authentication.getPrincipal(); 
... 
}
Java Configuration – Custom Authentication 
@RequestMapping(method=RequestMethod.GET) 
public ModelAndView list( 
@AuthenticationPrincipal User 
currentUser) { 
... 
}
Java Configuration – Custom Authentication 
@Target(ElementType.PARAMETER) 
@Retention(RetentionPolicy.RUNTIME) 
@Documented 
@AuthenticationPrincipal 
public @interface CurrentUser { }
Java Configuration – Custom Authentication 
@RequestMapping(method=RequestMethod.GET) 
public ModelAndView list( 
@CurrentUser User currentUser) { 
Iterable<Message> messages = 
messageRepository.findByToId(currentUser.getId()) 
; 
... 
}
Spring Security / Spring Data 
SpEL Support
Spring Security / Spring Data 
@Bean 
public SecurityEvaluationContextExtension 
securityEvaluationContextExtension() { 
return new SecurityEvaluationContextExtension(); 
}
Spring Security / Spring Data 
public interface MessageRepository 
extends CrudRepository<Message, Long> { 
@Query("select m from Message m where m.to.id = " + 
"?#{principal.id}”) 
Iterable<Message> findAllToCurrentUser(); 
}
Spring Security / Spring Data 
public interface MessageRepository 
extends CrudRepository<Message, Long> { 
@Query("select m from Message m where m.to.id = " + 
"?#{hasRole('ROLE_ADMIN') ? '%' : 
principal.id}”) 
Iterable<Message> findAll(); 
}
Spring Security / Spring Data
In the year 2000…. 
@EnableAclSecurity 
public interface SecuredMessageRepository 
extends MessageRepository {}
Password Storage
Password Storage 
auth 
.userDetailsService(userDetailsService) 
.passwordEncoder(new BCryptPasswordEncoder());
CSRF Protection
Demo 
CSRF Protection 
Unless otherwise indicated, these slides are 
© 2013-2014 Pivotal Software, Inc. and licensed under a 
Creative Commons Attribution-NonCommercial license: 
http://creativecommons.org/licenses/by-nc/3.0/ 
SPRING SECURITY
CSRF Protection
CSRF Protection
CSRF Protection 
“When do I use CSRF protection?
CSRF Protection 
“... but my application uses JSON
CSRF Protection 
<form ... method="post" enctype="text/plain"> 
<input type='hidden' 
name=’{"summary":"Hi", … "ignore_me":"' 
value='test"}' 
/> 
</form>
CSRF Protection 
{ 
"summary": "Hi", 
"message": "New Message", 
"to": "luke@example.com", 
"ignore_me": "=test" 
}
CSRF Protection 
“… but my application is stateless
CSRF Protection
CSRF Protection 
“…and I use a custom header for 
authentication and ignore cookies
CSRF Protection 
• Use proper HTTP Verbs 
• Configure CSRF Protection 
• Include the CSRF Token
CSRF Protection – Providing the Token 
<form ... method="post"> 
... 
<input type="hidden" 
name="${_csrf.parameterName}" 
value="${_csrf.token}"/> 
</form>
CSRF Protection – Providing the Token 
<form ... method="post"> 
... 
<sec:csrfInput /> 
</form>
CSRF Protection – Providing the Token 
<form:form … method="post”> 
... 
</form:form>
CSRF Protection – Providing the Token 
<form ... method="post"> 
... 
<input type="hidden" name="_csrf" 
value="f81d4fae-…"/> 
</form>
Security HTTP Response Headers
Demo 
Click Jacking 
Unless otherwise indicated, these slides are 
© 2013-2014 Pivotal Software, Inc. and licensed under a 
Creative Commons Attribution-NonCommercial license: 
http://creativecommons.org/licenses/by-nc/3.0/ 
SPRING SECURITY
Security HTTP Response Headers
Security HTTP Response Headers
Test Support
Testing Support 
@Before 
public void setup() { 
Authentication auth = 
new TestingAuthenticationToken("user",”pass","ROLE_USER"); 
SecurityContext ctx = 
SecurityContextHolder.getContext(); 
ctx.setAuthentication(auth); 
SecurityContextHolder.setContext(ctx); 
} 
@After 
public void cleanup() { 
SecurityContextHolder.clearContext(); 
}
Testing Support 
UserDetails user = ... 
List<GrantedAuthority> roles = 
AuthorityUtils.createAuthorityList("ROLE_USER"); 
Authentication auth = 
new UsernamePasswordAuthenticationToken(user,”pass", 
roles); 
SecurityContext ctx = 
SecurityContextHolder.getContext(); 
ctx.setAuthentication(auth);
Testing Support 
User user = ... 
List<GrantedAuthority> roles = 
AuthorityUtils.createAuthorityList("ROLE_USER"); 
Authentication auth = 
new UsernamePasswordAuthenticationToken(user,”pass", 
roles); 
SecurityContext ctx = 
SecurityContextHolder.getContext(); 
ctx.setAuthentication(auth);
Testing Support 
... 
@WithMockUser 
public class SecurityMethodTests { 
... 
}
Testing Support 
... 
public class SecurityMethodTests { 
@Test 
@WithMockUser 
public void findAllMessages() { 
... 
} 
}
Testing Support 
... 
public class SecurityMethodTests { 
@Test 
@WithMockUser(username="admin",roles="ADMIN”) 
public void findAllMessages() { 
repository.findAll(); 
} 
}
Testing Support 
... 
public class SecurityMethodTests { 
@Test 
@WithUserDetails(”rob@example.com") 
public void findAllMessages() { 
repository.findAll(); 
} 
}
Testing Support 
@Target({ ElementType.METHOD, ElementType.TYPE }) 
@Retention(RetentionPolicy.RUNTIME) 
@Inherited 
@Documented 
@WithSecurityContext(factory = 
WithCustomUserSecurityContextFactory.class) 
public @interface WithCustomUser { 
String email() default "rob@example.com"; 
String firstName() default "Rob"; 
String lastName() default "Winch"; 
long id() default 0L; 
}
Testing Support 
public class WithCustomUserSecurityContextFactory 
implements WithSecurityContextFactory<WithCustomUser> { 
public SecurityContext 
createSecurityContext(WithCustomUser customUser) { 
User principal = new User(); 
principal.setEmail(customUser.email()); 
... 
return ctx; 
} 
}
Testing Support 
... 
public class SecurityMethodTests { 
@Test 
@WithCustomUser 
public void findAllMessages() { 
repository.findAll(); 
} 
}
Testing Support 
... 
public class SecurityMethodTests { 
@Test 
@WithCustomUser(id=1,email=”luke@example.com") 
public void findAllMessages() { 
repository.findAll(); 
} 
}
Testing Support 
“…what about Spring Test MVC?
Testing Support 
... 
public class SecurityMockMvcTests { 
@Before 
public void setup() { 
mvc = MockMvcBuilders 
.webAppContextSetup(context) 
.apply(springSecurity()) 
.build(); 
}
Testing Support 
@Test 
@WithCustomUser 
public void inboxShowsOnlyTo() throws Exception { 
... 
}
Testing Support 
@Test 
@WithCustomUser(id=1,email=”luke@example.com") 
public void inboxShowsOnlyTo() throws Exception { 
... 
}
Testing Support 
@Test 
@WithCustomUser 
public void compose() throws Exception { 
MockHttpServletRequestBuilder compose = post("/”) 
.param("summary", "Hello Luke”) 
.param("message", "This is my message”) 
.with(csrf()); 
mvc 
.perform(compose) 
.andExpect(status().is2xxSuccessful()); 
}
WebSocket Security
Demo 
Web Socket 
Authorization 
Unless otherwise indicated, these slides are 
© 2013-2014 Pivotal Software, Inc. and licensed under a 
Creative Commons Attribution-NonCommercial license: 
http://creativecommons.org/licenses/by-nc/3.0/ 
SPRING SECURITY
WebSocket Authorization 
@MessageMapping("/im") 
/app/im 
/queue/messages-user<id> 
Client (Web Browser) 
Browser
WebSocket Authorization 
@Configuration 
public class WebSocketSecurityConfig extends 
AbstractSecurityWebSocketMessageBrokerConfigurer {
WebSocket Authorization 
protected void configure( 
MessageSecurityMetadataSourceRegistry messages) { 
messages 
.matchers(message("/topic/**","/queue/**")).denyAll() 
.anyMessage().hasRole("USER"); 
}
WebSocket Authorization 
// avoid processing outbound channel 
public void configureClientOutboundChannel( 
ChannelRegistration registration) {}
WebSocket Security 
Spring Session
Learn More. Stay Connected. 
• Source http://github.com/rwinch/spring-security-0-to-4.0 
• http://spring.io/spring-security 
• Twitter: @rob_winch 
Security for Microservices with Spring & OAuth2 – 4:30 Today

More Related Content

What's hot

Rest Security with JAX-RS
Rest Security with JAX-RSRest Security with JAX-RS
Rest Security with JAX-RS
Frank Kim
 
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Hermann Burgmeier
 
Avoiding Cross Site Scripting - Not as easy as you might think
Avoiding Cross Site Scripting - Not as easy as you might thinkAvoiding Cross Site Scripting - Not as easy as you might think
Avoiding Cross Site Scripting - Not as easy as you might think
Erlend Oftedal
 
Authentication: Cookies vs JWTs and why you’re doing it wrong
Authentication: Cookies vs JWTs and why you’re doing it wrongAuthentication: Cookies vs JWTs and why you’re doing it wrong
Authentication: Cookies vs JWTs and why you’re doing it wrong
Derek Perkins
 

What's hot (20)

JavaOne 2014 - Securing RESTful Resources with OAuth2
JavaOne 2014 - Securing RESTful Resources with OAuth2JavaOne 2014 - Securing RESTful Resources with OAuth2
JavaOne 2014 - Securing RESTful Resources with OAuth2
 
JWT Authentication with AngularJS
JWT Authentication with AngularJSJWT Authentication with AngularJS
JWT Authentication with AngularJS
 
Rest Security with JAX-RS
Rest Security with JAX-RSRest Security with JAX-RS
Rest Security with JAX-RS
 
ConFoo 2015 - Securing RESTful resources with OAuth2
ConFoo 2015 - Securing RESTful resources with OAuth2ConFoo 2015 - Securing RESTful resources with OAuth2
ConFoo 2015 - Securing RESTful resources with OAuth2
 
Java EE Application Security With PicketLink
Java EE Application Security With PicketLinkJava EE Application Security With PicketLink
Java EE Application Security With PicketLink
 
Securing RESTful APIs using OAuth 2 and OpenID Connect
Securing RESTful APIs using OAuth 2 and OpenID ConnectSecuring RESTful APIs using OAuth 2 and OpenID Connect
Securing RESTful APIs using OAuth 2 and OpenID Connect
 
Securing REST APIs
Securing REST APIsSecuring REST APIs
Securing REST APIs
 
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry BuzdinModern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
 
Security in java ee platform: what is included, what is missing
Security in java ee platform: what is included, what is missingSecurity in java ee platform: what is included, what is missing
Security in java ee platform: what is included, what is missing
 
Introduction to PicketLink
Introduction to PicketLinkIntroduction to PicketLink
Introduction to PicketLink
 
Token Authentication for Java Applications
Token Authentication for Java ApplicationsToken Authentication for Java Applications
Token Authentication for Java Applications
 
An Introduction to OAuth2
An Introduction to OAuth2An Introduction to OAuth2
An Introduction to OAuth2
 
Secure Your REST API (The Right Way)
Secure Your REST API (The Right Way)Secure Your REST API (The Right Way)
Secure Your REST API (The Right Way)
 
Octopus framework; Permission based security framework for Java EE
Octopus framework; Permission based security framework for Java EEOctopus framework; Permission based security framework for Java EE
Octopus framework; Permission based security framework for Java EE
 
JavaEE Security
JavaEE SecurityJavaEE Security
JavaEE Security
 
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
 
Avoiding Cross Site Scripting - Not as easy as you might think
Avoiding Cross Site Scripting - Not as easy as you might thinkAvoiding Cross Site Scripting - Not as easy as you might think
Avoiding Cross Site Scripting - Not as easy as you might think
 
API Security & Federation Patterns - Francois Lascelles, Chief Architect, Lay...
API Security & Federation Patterns - Francois Lascelles, Chief Architect, Lay...API Security & Federation Patterns - Francois Lascelles, Chief Architect, Lay...
API Security & Federation Patterns - Francois Lascelles, Chief Architect, Lay...
 
Stateless authentication for microservices - GR8Conf 2015
Stateless authentication for microservices - GR8Conf 2015Stateless authentication for microservices - GR8Conf 2015
Stateless authentication for microservices - GR8Conf 2015
 
Authentication: Cookies vs JWTs and why you’re doing it wrong
Authentication: Cookies vs JWTs and why you’re doing it wrongAuthentication: Cookies vs JWTs and why you’re doing it wrong
Authentication: Cookies vs JWTs and why you’re doing it wrong
 

Viewers also liked

Seo terminology
Seo terminologySeo terminology
Seo terminology
denise2228
 
Deliver Certification Exams Online Conveniently and Securely Anytime. Anywhere
Deliver Certification Exams Online Conveniently and Securely Anytime. AnywhereDeliver Certification Exams Online Conveniently and Securely Anytime. Anywhere
Deliver Certification Exams Online Conveniently and Securely Anytime. Anywhere
Software Secure, Inc.
 
Occupy the Curriculum
Occupy the CurriculumOccupy the Curriculum
Occupy the Curriculum
jrharshman
 

Viewers also liked (20)

Apiworld
ApiworldApiworld
Apiworld
 
IO State In Distributed API Architecture
IO State In Distributed API ArchitectureIO State In Distributed API Architecture
IO State In Distributed API Architecture
 
Api Abstraction & Api Chaining
Api Abstraction & Api ChainingApi Abstraction & Api Chaining
Api Abstraction & Api Chaining
 
API Security and Management Best Practices
API Security and Management Best PracticesAPI Security and Management Best Practices
API Security and Management Best Practices
 
Startups - How to start - The Idea
Startups - How to start - The Idea Startups - How to start - The Idea
Startups - How to start - The Idea
 
06 Carlyle Guide
06 Carlyle Guide06 Carlyle Guide
06 Carlyle Guide
 
Seo terminology
Seo terminologySeo terminology
Seo terminology
 
Trickbetrug
TrickbetrugTrickbetrug
Trickbetrug
 
Avis delpéréesyfel
Avis delpéréesyfelAvis delpéréesyfel
Avis delpéréesyfel
 
Deliver Certification Exams Online Conveniently and Securely Anytime. Anywhere
Deliver Certification Exams Online Conveniently and Securely Anytime. AnywhereDeliver Certification Exams Online Conveniently and Securely Anytime. Anywhere
Deliver Certification Exams Online Conveniently and Securely Anytime. Anywhere
 
Caesarea Philippi - Ehab Isaac - Palestinian Christians (c)
Caesarea Philippi - Ehab Isaac - Palestinian Christians (c)Caesarea Philippi - Ehab Isaac - Palestinian Christians (c)
Caesarea Philippi - Ehab Isaac - Palestinian Christians (c)
 
SACSCOC 2012 -Protecting Academic Integrity in Online Exam Environments
SACSCOC 2012 -Protecting Academic Integrity in Online Exam EnvironmentsSACSCOC 2012 -Protecting Academic Integrity in Online Exam Environments
SACSCOC 2012 -Protecting Academic Integrity in Online Exam Environments
 
Non-Profit 2013 Financial Outlook Survey Report
Non-Profit 2013 Financial Outlook Survey ReportNon-Profit 2013 Financial Outlook Survey Report
Non-Profit 2013 Financial Outlook Survey Report
 
How to make spaghetti
How to make spaghettiHow to make spaghetti
How to make spaghetti
 
Tìm hiểu thế giới Sôcôla tại Bỉ
Tìm hiểu thế giới Sôcôla tại BỉTìm hiểu thế giới Sôcôla tại Bỉ
Tìm hiểu thế giới Sôcôla tại Bỉ
 
Lễ hội Sôcôla các nước trên thế giới
Lễ hội Sôcôla các nước trên thế giớiLễ hội Sôcôla các nước trên thế giới
Lễ hội Sôcôla các nước trên thế giới
 
Occupy the Curriculum
Occupy the CurriculumOccupy the Curriculum
Occupy the Curriculum
 
Món quà đặc biệt tri ân thầy cô ngày 20/11
Món quà đặc biệt tri ân thầy cô ngày 20/11Món quà đặc biệt tri ân thầy cô ngày 20/11
Món quà đặc biệt tri ân thầy cô ngày 20/11
 
Igaa 1
Igaa 1Igaa 1
Igaa 1
 
Ekmm
EkmmEkmm
Ekmm
 

Similar to From 0 to Spring Security 4.0

Simple blog wall creation on Java
Simple blog wall creation on JavaSimple blog wall creation on Java
Simple blog wall creation on Java
Max Titov
 
ASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin Lau
Spiffy
 
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
Tieturi Oy
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
Aren Zomorodian
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)
Luka Zakrajšek
 

Similar to From 0 to Spring Security 4.0 (20)

Javatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparisonJavatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparison
 
JavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
JavaCro'14 - Building interactive web applications with Vaadin – Peter LehtoJavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
JavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
 
Simple blog wall creation on Java
Simple blog wall creation on JavaSimple blog wall creation on Java
Simple blog wall creation on Java
 
Mashing up JavaScript
Mashing up JavaScriptMashing up JavaScript
Mashing up JavaScript
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web Apps
 
ASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin Lau
 
JSP
JSPJSP
JSP
 
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2
 
AnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFacesAnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFaces
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
UA Testing with Selenium and PHPUnit - ZendCon 2013
UA Testing with Selenium and PHPUnit - ZendCon 2013UA Testing with Selenium and PHPUnit - ZendCon 2013
UA Testing with Selenium and PHPUnit - ZendCon 2013
 
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortal
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
Stripes Framework
Stripes FrameworkStripes Framework
Stripes Framework
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)
 
Java Training Ahmedabad , how to Insert Data in Servlet, iOS Classes Ahmedabad
Java Training Ahmedabad , how to Insert Data in Servlet, iOS Classes AhmedabadJava Training Ahmedabad , how to Insert Data in Servlet, iOS Classes Ahmedabad
Java Training Ahmedabad , how to Insert Data in Servlet, iOS Classes Ahmedabad
 
Building iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoBuilding iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" Domino
 

Recently uploaded

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Recently uploaded (20)

Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 

From 0 to Spring Security 4.0

  • 1. From 0 to Spring Security 4.0 Rob Winch @rob_winch © 2014 SpringOne 2GX. All rights reserved. Do not distribute without permission.
  • 2. Agenda • Introductions • Hello Spring Security (Java Config) • Custom Authentication • Spring Data Integration • Testing Support • WebSocket Support • White Hat Hacker 2
  • 3. About Me • Open Source fanatic • Spring Security & Spring Project Lead • Committer on Spring Framework • Co-author of Spring Security 3.1 book • Twitter @rob_winch 3
  • 4. What is Spring Security? • Comprehensive support for Authentication And Authorization • Protection against common attacks • Servlet API Integration • Optional integration with Spring MVC • Optional Spring Data Integration • WebSocket Support 4
  • 5. Demo Message Application Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software, Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ SPRING SECURITY
  • 7. web.xml <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>
  • 8. Hello Java Configuration – Replaces web.xml public class SecurityWebInitializer extends AbstractSecurityWebApplicationInitializer { // optionally override methods }
  • 9. Hello Java Configuration – WebSecurityConfig @Configuration @EnableWebMvcSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { ... }
  • 10. Hello Java Configuration – WebSecurityConfig @Autowired public void configureGlobal( AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("admin”) .password("password”) .roles("ADMIN","USER") .and() .withUser("user") .password("password") .roles("USER"); }
  • 13. Hello Java Configuration <div th:with="currentUser=$ {#httpServletRequest.userPrincipal?.name}"> <div th:if="${currentUser != null}"> <form th:action="@{/logout}" method="post”> <input type="submit" value="Log out" /> </form> <p th:text="${currentUser}”> sample_user </p> </div>
  • 14. Hello Java Configuration <div th:with="currentUser=$ {#httpServletRequest.userPrincipal?.name}"> <div th:if="${currentUser != null}"> <form th:action="@{/logout}" method="post”> <input type="submit" value="Log out" /> </form> <p th:text="${currentUser}”> sample_user </p> </div> public interface HttpServletRequest … { Principal getUserPrincipal(); ... }
  • 15. Hello Java Configuration <div th:with="currentUser=$ {#httpServletRequest.userPrincipal?.name}"> <div th:if="${currentUser != null}"> <form th:action="@{/logout}" method="post”> <input type="submit" value="Log out" /> </form> <p th:text="${currentUser}”> sample_user </p> </div> public interface Principal … { String getName(); ... }
  • 16. Hello Java Configuration <div th:with="currentUser=$ {#httpServletRequest.userPrincipal?.name}"> <div th:if="${currentUser != null}"> <form th:action="@{/logout}" method="post”> <input type="submit" value="Log out" /> </form> <p th:text="${currentUser}”> sample_user </p> </div> </div>
  • 18. Java Configuration @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin().and() .httpBasic(); }
  • 19. Java Configuration http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin().and() .httpBasic(); <http use-expressions="true"> <intercept-url pattern="/**" access="authenticated"/> <form-login /> <http-basic /> </http>
  • 20. Java Configuration http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login”) .permitAll() .and() .logout() .permitAll();
  • 21. Java Configuration http .authorizeRequests() .antMatchers("/resources/**”).permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login”) .permitAll() .and() .logout() .permitAll();
  • 22. Java Configuration <form th:action="@{/login}" method="post"> <label for="username">Username</label> <input type="text" id="username" name="username"/> <label for="password">Password</label> <input type="password" id="password" name="password"/> <button type="submit">Log in</button> </form>
  • 23. Java Configuration <form th:action="@{/login}" method="post"> <label for="username">Username</label> <input type="text" id="username" name="username"/> <label for="password">Password</label> <input type="password" id="password" name="password"/> <button type="submit">Log in</button> </form>
  • 24. Java Configuration <form th:action="@{/login}" method="post"> <label for="username">Username</label> <input type="text" id="username" name="username"/> <label for="password">Password</label> <input type="password" id="password" name="password"/> <button type="submit">Log in</button> </form> http …. .formLogin() .loginPage("/login”)
  • 26. Java Configuration – Custom Authentication public interface UserDetailsService { UserDetails loadUserByUsername(String username) throws UsernameNotFoundException; }
  • 27. Java Configuration – Custom Authentication public interface UserDetails extends Serializable { Collection<? extends GrantedAuthority> getAuthorities(); String getPassword(); String getUsername(); boolean isAccountNonExpired(); boolean isAccountNonLocked(); boolean isCredentialsNonExpired(); boolean isEnabled(); }
  • 28. Java Configuration – Custom Authentication @Entity public class User implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; private String email; private String password; ... }
  • 29. Java Configuration – Custom Authentication pubic class CustomUserDetails extends User implements UserDetails { public CustomUserDetails(User u) { super(user); } public Collection getAuthorities() { return AuthorityUtils.createAuthorityList("ROLE_USER"); } public String getUsername() { return getEmail(); } public boolean isEnabled() { return true; } ...
  • 30. Java Configuration – Custom Authentication public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByEmail(username); if(user == null) { throw new UsernameNotFoundException(…); } return new CustomUserDetails(user); }
  • 31. Java Configuration – Custom Authentication @Autowired public void configureGlobal( AuthenticationManagerBuilder auth, UserDetailsService userDetailsService) throws Exception { auth .userDetailsService(userDetailsService); }
  • 32. Java Configuration – Custom Authentication <div th:with="currentUser=$ {#httpServletRequest.userPrincipal?.name}"> <div th:if="${currentUser != null}"> <form th:action="@{/logout}" method="post”> <input type="submit" value="Log out" /> </form> <p th:text="${currentUser}”> sample_user </p> </div>
  • 33. Java Configuration – Custom Authentication <div th:with="currentUser=$ {#httpServletRequest.userPrincipal?.name}"> <div th:if="${currentUser != null}"> <form th:action="@{/logout}" method="post”> <input type="submit" value="Log out" /> </form> <p th:text="${currentUser}”> sample_user </p> </div> public interface HttpServletRequest … { Principal getUserPrincipal(); ... }
  • 34. Java Configuration – Custom Authentication <div th:with="currentUser=$ {#httpServletRequest.userPrincipal?.name}"> <div th:if="${currentUser != null}"> <form th:action="@{/logout}" method="post”> <input type="submit" value="Log out" /> </form> <p th:text="${currentUser}”> sample_user </p> </div> public interface HttpServletRequest … { (Authentication) Principal getUserPrincipal(); ... }
  • 35. Java Configuration – Custom Authentication <div th:with="currentUser=$ {#httpServletRequest.userPrincipal?.principal}"> <div th:if="${currentUser != null}"> <form th:action="@{/logout}" method="post”> <input type="submit" value="Log out" /> </form> <p th:text="${currentUser}”> sample_user </p> </div> public interface Authentication … { Object getPrincipal(); ... }
  • 36. Java Configuration – Custom Authentication <div th:with="currentUser=$ {#httpServletRequest.userPrincipal?.principal}"> <div th:if="${currentUser != null}"> <form th:action="@{/logout}" method="post”> <input type="submit" value="Log out" /> </form> <p th:text="${currentUser}”> sample_user </p> </div> public interface Authentication … { (UserDetails) Object getPrincipal(); ... }
  • 37. Java Configuration – Custom Authentication <div th:with="currentUser=$ {#httpServletRequest.userPrincipal?.principal}"> <div th:if="${currentUser != null}"> <form th:action="@{/logout}" method="post”> <input type="submit" value="Log out" /> </form> <p th:text="${currentUser}”> sample_user </p> </div> public interface Authentication … { (CustomUserDetails) Object getPrincipal(); ... }
  • 38. Java Configuration – Custom Authentication <div th:with="currentUser=$ {#httpServletRequest.userPrincipal?.principal}"> <div th:if="${currentUser != null}"> <form th:action="@{/logout}" method="post”> <input type="submit" value="Log out" /> </form> <p th:text="${currentUser.firstName}”> sample_user </p> </div> public class CustomUserDetails … { String getFirstName(); ... }
  • 39. Java Configuration – Custom Authentication @RequestMapping(method=RequestMethod.GET) public ModelAndView list() { SecurityContext ctx = SecurityContextHolder.getContext(); Authentication authentication = ctx.getAuthentication(); User custom = authentication == null ? null : (User) authentication.getPrincipal(); ... }
  • 40. Java Configuration – Custom Authentication @RequestMapping(method=RequestMethod.GET) public ModelAndView list(Authentication authentication) { User custom = authentication == null ? null : (User) authentication.getPrincipal(); ... }
  • 41. Java Configuration – Custom Authentication @RequestMapping(method=RequestMethod.GET) public ModelAndView list( @AuthenticationPrincipal User currentUser) { ... }
  • 42. Java Configuration – Custom Authentication @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @Documented @AuthenticationPrincipal public @interface CurrentUser { }
  • 43. Java Configuration – Custom Authentication @RequestMapping(method=RequestMethod.GET) public ModelAndView list( @CurrentUser User currentUser) { Iterable<Message> messages = messageRepository.findByToId(currentUser.getId()) ; ... }
  • 44. Spring Security / Spring Data SpEL Support
  • 45. Spring Security / Spring Data @Bean public SecurityEvaluationContextExtension securityEvaluationContextExtension() { return new SecurityEvaluationContextExtension(); }
  • 46. Spring Security / Spring Data public interface MessageRepository extends CrudRepository<Message, Long> { @Query("select m from Message m where m.to.id = " + "?#{principal.id}”) Iterable<Message> findAllToCurrentUser(); }
  • 47. Spring Security / Spring Data public interface MessageRepository extends CrudRepository<Message, Long> { @Query("select m from Message m where m.to.id = " + "?#{hasRole('ROLE_ADMIN') ? '%' : principal.id}”) Iterable<Message> findAll(); }
  • 48. Spring Security / Spring Data
  • 49. In the year 2000…. @EnableAclSecurity public interface SecuredMessageRepository extends MessageRepository {}
  • 51. Password Storage auth .userDetailsService(userDetailsService) .passwordEncoder(new BCryptPasswordEncoder());
  • 53. Demo CSRF Protection Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software, Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ SPRING SECURITY
  • 56. CSRF Protection “When do I use CSRF protection?
  • 57. CSRF Protection “... but my application uses JSON
  • 58. CSRF Protection <form ... method="post" enctype="text/plain"> <input type='hidden' name=’{"summary":"Hi", … "ignore_me":"' value='test"}' /> </form>
  • 59. CSRF Protection { "summary": "Hi", "message": "New Message", "to": "luke@example.com", "ignore_me": "=test" }
  • 60. CSRF Protection “… but my application is stateless
  • 62. CSRF Protection “…and I use a custom header for authentication and ignore cookies
  • 63. CSRF Protection • Use proper HTTP Verbs • Configure CSRF Protection • Include the CSRF Token
  • 64. CSRF Protection – Providing the Token <form ... method="post"> ... <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> </form>
  • 65. CSRF Protection – Providing the Token <form ... method="post"> ... <sec:csrfInput /> </form>
  • 66. CSRF Protection – Providing the Token <form:form … method="post”> ... </form:form>
  • 67. CSRF Protection – Providing the Token <form ... method="post"> ... <input type="hidden" name="_csrf" value="f81d4fae-…"/> </form>
  • 69. Demo Click Jacking Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software, Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ SPRING SECURITY
  • 73. Testing Support @Before public void setup() { Authentication auth = new TestingAuthenticationToken("user",”pass","ROLE_USER"); SecurityContext ctx = SecurityContextHolder.getContext(); ctx.setAuthentication(auth); SecurityContextHolder.setContext(ctx); } @After public void cleanup() { SecurityContextHolder.clearContext(); }
  • 74. Testing Support UserDetails user = ... List<GrantedAuthority> roles = AuthorityUtils.createAuthorityList("ROLE_USER"); Authentication auth = new UsernamePasswordAuthenticationToken(user,”pass", roles); SecurityContext ctx = SecurityContextHolder.getContext(); ctx.setAuthentication(auth);
  • 75. Testing Support User user = ... List<GrantedAuthority> roles = AuthorityUtils.createAuthorityList("ROLE_USER"); Authentication auth = new UsernamePasswordAuthenticationToken(user,”pass", roles); SecurityContext ctx = SecurityContextHolder.getContext(); ctx.setAuthentication(auth);
  • 76. Testing Support ... @WithMockUser public class SecurityMethodTests { ... }
  • 77. Testing Support ... public class SecurityMethodTests { @Test @WithMockUser public void findAllMessages() { ... } }
  • 78. Testing Support ... public class SecurityMethodTests { @Test @WithMockUser(username="admin",roles="ADMIN”) public void findAllMessages() { repository.findAll(); } }
  • 79. Testing Support ... public class SecurityMethodTests { @Test @WithUserDetails(”rob@example.com") public void findAllMessages() { repository.findAll(); } }
  • 80. Testing Support @Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented @WithSecurityContext(factory = WithCustomUserSecurityContextFactory.class) public @interface WithCustomUser { String email() default "rob@example.com"; String firstName() default "Rob"; String lastName() default "Winch"; long id() default 0L; }
  • 81. Testing Support public class WithCustomUserSecurityContextFactory implements WithSecurityContextFactory<WithCustomUser> { public SecurityContext createSecurityContext(WithCustomUser customUser) { User principal = new User(); principal.setEmail(customUser.email()); ... return ctx; } }
  • 82. Testing Support ... public class SecurityMethodTests { @Test @WithCustomUser public void findAllMessages() { repository.findAll(); } }
  • 83. Testing Support ... public class SecurityMethodTests { @Test @WithCustomUser(id=1,email=”luke@example.com") public void findAllMessages() { repository.findAll(); } }
  • 84. Testing Support “…what about Spring Test MVC?
  • 85. Testing Support ... public class SecurityMockMvcTests { @Before public void setup() { mvc = MockMvcBuilders .webAppContextSetup(context) .apply(springSecurity()) .build(); }
  • 86. Testing Support @Test @WithCustomUser public void inboxShowsOnlyTo() throws Exception { ... }
  • 87. Testing Support @Test @WithCustomUser(id=1,email=”luke@example.com") public void inboxShowsOnlyTo() throws Exception { ... }
  • 88. Testing Support @Test @WithCustomUser public void compose() throws Exception { MockHttpServletRequestBuilder compose = post("/”) .param("summary", "Hello Luke”) .param("message", "This is my message”) .with(csrf()); mvc .perform(compose) .andExpect(status().is2xxSuccessful()); }
  • 90. Demo Web Socket Authorization Unless otherwise indicated, these slides are © 2013-2014 Pivotal Software, Inc. and licensed under a Creative Commons Attribution-NonCommercial license: http://creativecommons.org/licenses/by-nc/3.0/ SPRING SECURITY
  • 91. WebSocket Authorization @MessageMapping("/im") /app/im /queue/messages-user<id> Client (Web Browser) Browser
  • 92. WebSocket Authorization @Configuration public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
  • 93. WebSocket Authorization protected void configure( MessageSecurityMetadataSourceRegistry messages) { messages .matchers(message("/topic/**","/queue/**")).denyAll() .anyMessage().hasRole("USER"); }
  • 94. WebSocket Authorization // avoid processing outbound channel public void configureClientOutboundChannel( ChannelRegistration registration) {}
  • 96. Learn More. Stay Connected. • Source http://github.com/rwinch/spring-security-0-to-4.0 • http://spring.io/spring-security • Twitter: @rob_winch Security for Microservices with Spring & OAuth2 – 4:30 Today