SlideShare a Scribd company logo
Building Layers of Defense
with Spring Security
“We have to distrust each other.
It is our only defense against betrayal.”
― Tennessee Williams
About Me
 Joris Kuipers ( @jkuipers)
 Hands-on architect and
fly-by-night Spring trainer @ Trifork
 @author tag in Spring Session’s support for
Spring Security
Layers Of Defense
 Security concerns many levels
 Physical, hardware, network, OS, middleware,
applications, process / social, …
 This talk focuses on applications
Layers Of Defense
 Web application has many layers to protect
 Sometimes orthogonal
 Often additive
Layers Of Defense
 Additivity implies some redundancy
 That’s by design
 Don’t rely on just a single layer of defense
 Might have an error in security config / impl
 Might be circumvented
 AKA Defense in depth
Spring Security
 OSS framework for application-level
authentication & authorization
 Supports common standards & protocols
 Works with any Java web application
Spring Security
Application-level:
 No reliance on container, self-contained
 Portable
 Easy to extend and adapt
 Assumes code itself is trusted
Spring Security
 Decouples authentication & authorization
 Hooks into application through interceptors
 Servlet Filters at web layer
 Aspects at lower layers
 Configured using Java-based fluent API
Spring Security Configuration
Steps to add Spring Security support:
1. Configure dependency and servlet filter chain
2. Centrally configure authentication
3. Centrally configure authorization
4. Configure code-specific authorization
Config: Authentication
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/* set up authentication: */
@Autowired
void configureGlobal(AuthenticationManagerBuilder
authMgrBuilder) throws Exception
{
authMgrBuilder.userDetailsService(
myCustomUserDetailsService());
}
// ...
Config: HTTP Authorization
/* ignore requests to these URLS: */
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(
"/css/**", "/img/**", "/js/**", "/favicon.ico");
}
// ...
Config: HTTP Authorization
/* configure URL-based authorization: */
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers(HttpMethod.POST,
"/projects/**").hasRole("PROJECT_MGR")
.anyRequest().authenticated();
// additional configuration not shown…
}
}
Spring Security Defaults
This gives us:
 Various HTTP Response headers
 CSRF protection
 Default login page
HTTP Response Headers
“We are responsible for actions performed in response to
circumstances for which we are not responsible”
― Allan Massie
Disable Browser Cache
 Modern browsers also cache HTTPS responses
 Attacker could see old page even after user logs out
 In general not good for dynamic content
 For URLs not ignored, these headers are added
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Disable Content Sniffing
 Content type guessed based on content
 Attacker might upload polyglot file
 Valid as both e.g. PostScript and JavaScript
 JavaScript executed on download
 Disabled using this header
X-Content-Type-Options: nosniff
Enable HSTS
 HTTP Strict Transport Security
 Enforce HTTPS for all requests to domain
 Optionally incl. subdomains
 Prevents man-in-the-middling initial request
 Enabled by default for HTTPS requests:
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
HSTS War Story
Note: one HTTPS request triggers HSTS
for entire domain and subdomains
 Webapp might not support HTTPS-only
 Domain may host more than just
your application
 Might be better handled by load
balancer
Disable Framing
 Prevent Clickjacking
 Attacker embeds app in frame as invisible overlay
 Tricks users into clicking on something they shouldn’t
 All framing disabled using this header
 Can configure other options, e.g. SAME ORIGIN
X-Frame-Options: DENY
Block X-XSS Content
 Built-in browser support to recognize
reflected XSS attacks
 http://example.com/index.php?user=<script>alert(
123)</script>
 Ensure support is enabled and
blocks (not fixes) content
X-XSS-Protection: 1; mode=block
Other Headers Support
Other headers you can configure
(disabled by default):
 HTTP Public Key Pinning (HPKP)-related
 Content Security Policy-related
 Referrer-Policy
CSRF / Session Riding Protection
“One thing I learned about riding is to look for trouble
before it happens.”
― Joe Davis
Cross-Site Request Forgery
CSRF tricks logged in users to make requests
 Session cookie sent automatically
 Look legit to server, but user never intended them
Cross-Site Request Forgery
Add session-specific token to all forms
 Correct token means app initiated request
 attacker cannot know token
 Not needed for GET with proper HTTP verb usage
 GETs should be safe
 Also prevents leaking token through URL
CSRF Protection in Spring Security
Default: enabled for non-GET requests
 Using session-scoped token
 Include token as form request parameter
<form action="/logout" method="post">
<input type="submit" value="Log out" />
<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>
</form>
CSRF Protection in Spring Security
 Doesn’t work for JSON-sending SPAs
 Store token in cookie and pass as header instead
 No server-side session state, but still quite secure
 Defaults work with AngularJS as-is
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf()
.csrfTokenRepository(
CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
// additional configuration…
URL-based Authorization
“Does the walker choose the path, or the path the walker?”
― Garth Nix, Sabriel
URL-based Authorization
Very common, esp. with role-based authorization
 Map URL structure to authorities
 Optionally including HTTP methods
 Good for coarse-grained rules
Spring Security Configuration
@Override
protected void configure(HttpSecurity http) throws Exception {
http
/* configure URL-based authorization: */
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers(HttpMethod.POST,
"/projects/**").hasRole("PROJECT_MGR")
// other matchers…
.anyRequest().authenticated();
// additional configuration not shown…
}
}
URL-based Authorization
Might become bloated
 Esp. without role-related base URLs
http.authorizeRequests()
.antMatchers("/products", "/products/**").permitAll()
.antMatchers("/customer-portal-status").permitAll()
.antMatchers("/energycollectives", "/energycollectives/**").permitAll()
.antMatchers("/meterreading", "/meterreading/**").permitAll()
.antMatchers("/smartmeterreadingrequests", "/smartmeterreadingrequests/**").permitAll()
.antMatchers("/offer", "/offer/**").permitAll()
.antMatchers("/renewaloffer", "/renewaloffer/**").permitAll()
.antMatchers("/address").permitAll()
.antMatchers("/iban/**").permitAll()
.antMatchers("/contracts", "/contracts/**").permitAll()
.antMatchers("/zendesk/**").permitAll()
.antMatchers("/payment/**").permitAll()
.antMatchers("/phonenumber/**").permitAll()
.antMatchers("/debtcollectioncalendar/**").permitAll()
.antMatchers("/edsn/**").permitAll()
.antMatchers("/leads/**").permitAll()
.antMatchers("/dynamicanswer/**").permitAll()
.antMatchers("/masterdata", "/masterdata/**").permitAll()
.antMatchers("/invoices/**").permitAll()
.antMatchers("/registerverification", "/registerverification/**").permitAll()
.antMatchers("/smartmeterreadingreports", "/smartmeterreadingreports/**").permitAll()
.antMatchers("/users", "/users/**").permitAll()
.antMatchers("/batch/**").hasAuthority("BATCH_ADMIN")
.antMatchers("/label/**").permitAll()
.antMatchers("/bankstatementtransactions", "/bankstatementtransactions/**").permitAll()
.antMatchers("/directdebitsepamandate", "/directdebitsepamandate/**").permitAll()
.anyRequest().authenticated()
URL-based Authorization
Can be tricky to do properly
 Rules matched in order
 Matchers might not behave
like you think they do
 Need to have a catch-all
 .anyRequest().authenticated();
 .anyRequest().denyAll();
URL Matching Rules Gotchas
http.authorizeRequests()
.antMatchers("/products/inventory/**").hasRole("ADMIN")
.antMatchers("/products/**").hasAnyRole("USER", "ADMIN")
.antMatchers(…
Ordering very
significant here!
.antMatchers("/products/delete").hasRole("ADMIN")
Does NOT match
/products/delete/
(trailing slash)!
.mvcMatchers("/products/delete").hasRole("ADMIN")
Method-level Authorization
“When you make your peace with authority,
you become authority”
― Jim Morrison
Method-Level Security
 Declarative checks before or after method
invocation
 Enable explicitly
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig
extends WebSecurityConfigurerAdapter
{ … }
@PreAuthorize Examples
@PreAuthorize("hasRole('PRODUCT_MGR')")
Product saveNew(ProductForm productForm) {
@PreAuthorize("hasRole('PRODUCT_MGR') &&
#product.companyId == principal.company.id")
void updateProduct(Product product) {
Refer to parameters,
e.g. for multitenancy
@PostAuthorize Example
@PostAuthorize("returnObject.company.id ==
principal.company.id")
Product findProduct(Long productId) {
Refer to returned object
Expressions in @Pre-/PostAuthorize
 Built-ins
 hasRole(), hasAnyRole(), isAuthenticated(),
isAnonymous(), …
 Can add your own…
 Relatively complex
Expressions in @Pre-/PostAuthorize
 …or just call method on Spring Bean instead
@PreAuthorize("@authChecks.isTreatedByCurrentUser(#patient)")
public void addReport(Patient patient, Report report) {
@Service
public class AuthChecks {
public boolean isTreatedByCurrentUser(Patient patient) {
// ...
}
Method-level Security
Support for standard Java @RolesAllowed
 Role-based checks only
 Enable explicitly
@EnableGlobalMethodSecurity(
prePostEnabled = true, jsr250Enabled = true)
@RolesAllowed("ROLE_PRODUCT_MGR")
Product saveNew(ProductForm productForm) {
Programmatic Security
Easy programmatic access & checks
 Nice for e.g. custom interceptors
 Preferably not mixed with business logic
Authentication auth =
SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.getPrincipal() instanceof MyUser) {
MyUser user = (MyUser) auth.getPrincipal();
// ...
Programmatic Use Cases
Look up current user to:
 Perform authorization in custom filter/aspect
 Populate Logger MDC
 Pass current tenant as Controller method parameter
 Auto-fill last-modified-by DB column
 Propagate security context to worker thread
 …
Access Control Lists
“Can’t touch this”
― MC Hammer
ACL Support
 Spring Security supports Access Control Lists
 Fine-grained permissions per secured item
 Check before / after accessing item
 Declaratively or programmatically
 Not needed for most applications
Defining ACLs
 Persisted in dedicated DB tables
 Entity defined by type and ID
 Access to entity per-user or per-authority
 Access permissions defined by int bitmask
 read, write, delete, etc.
 granting or denying
Checking ACLs
 Check performed against instance or type+id
 Multiple options for permission checks
 Using SpEL expressions is easy
@PreAuthorize("hasPermission(#contact, 'delete') or
hasPermission(#contact, 'admin')")
void delete(Contact contact);
@PreAuthorize("hasPermission(#id, 'sample.Contact', 'read') or
hasPermission(#id, 'sample.Contact', 'admin')")
Contact getById(Long id);
Other Concerns
“Concern should drive us into action, not into a depression.”
― Karen Horney
Enforcing HTTPS
 Can enforce HTTPS channel
 Redirect when request uses plain HTTP
 HTTPS is usually important
 Even if your data isn’t
 Attacker could insert malicious content
 Might be better handled by load balancer
Limiting Concurrent Sessions
 How often can single user log in at the same time?
 Limit to max nr of sessions
 Built-in support limited to single node
 Supports multi-node through Spring Session
Password Hashing
 Are you storing your own users and passwords?
 Ensure appropriate hashing algorithm
 BCrypt, PBKDF2 & SCrypt support built in
 Don’t copy old blogs showing MD5/SHA + Salt!
CORS
 Cross-Origin Resource Sharing
 Relaxes same-origin policy
 Allow JS communication with other servers
 Server must allow origin, sent in request header
 Preflight request used to check access:
must be handled before Spring Security!
Enabling CORS Support
 Spring-MVC has CORS support
 For Spring Security, just configure filter
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and()
// ... other config
 No Spring-MVC?
Add CorsConfigurationSource bean
Conclusion
 Spring Security handles security at
all application layers
 Combine to provide defense in depth
 Understand your security framework
 Become unhackable!
 Or at least be able to blame someone else…

More Related Content

What's hot

I Can See Clearly Now - Observing & understanding your Spring applications at...
I Can See Clearly Now - Observing & understanding your Spring applications at...I Can See Clearly Now - Observing & understanding your Spring applications at...
I Can See Clearly Now - Observing & understanding your Spring applications at...
Joris Kuipers
 
Spring Security 5
Spring Security 5Spring Security 5
Spring Security 5
Jesus Perez Franco
 
Enterprise Security mit Spring Security
Enterprise Security mit Spring SecurityEnterprise Security mit Spring Security
Enterprise Security mit Spring Security
Mike Wiesner
 
Java Security Framework's
Java Security Framework'sJava Security Framework's
Java Security Framework's
Mohammed Fazuluddin
 
Vulnerabilities in modern web applications
Vulnerabilities in modern web applicationsVulnerabilities in modern web applications
Vulnerabilities in modern web applications
Niyas Nazar
 
Secure code practices
Secure code practicesSecure code practices
Secure code practices
Hina Rawal
 
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...
CA API Management
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Brian Huff
 
What's New in spring-security-core 2.0
What's New in spring-security-core 2.0What's New in spring-security-core 2.0
What's New in spring-security-core 2.0
Burt Beckwith
 
Access Control Pitfalls v2
Access Control Pitfalls v2Access Control Pitfalls v2
Access Control Pitfalls v2
Jim Manico
 
OWASP Top 10 Proactive Controls
OWASP Top 10 Proactive ControlsOWASP Top 10 Proactive Controls
OWASP Top 10 Proactive Controls
Katy Anton
 
Security asp.net application
Security asp.net applicationSecurity asp.net application
Security asp.net application
ZAIYAUL HAQUE
 
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
 
Top Ten Java Defense for Web Applications v2
Top Ten Java Defense for Web Applications v2Top Ten Java Defense for Web Applications v2
Top Ten Java Defense for Web Applications v2
Jim Manico
 
Deep dive into Java security architecture
Deep dive into Java security architectureDeep dive into Java security architecture
Deep dive into Java security architecture
Prabath Siriwardena
 
2013 OWASP Top 10
2013 OWASP Top 102013 OWASP Top 10
2013 OWASP Top 10
bilcorry
 
Spring security4.x
Spring security4.xSpring security4.x
Spring security4.x
Zeeshan Khan
 
Common Web Application Attacks
Common Web Application Attacks Common Web Application Attacks
Common Web Application Attacks
Ahmed Sherif
 
Api security
Api security Api security
Api security
teodorcotruta
 

What's hot (20)

I Can See Clearly Now - Observing & understanding your Spring applications at...
I Can See Clearly Now - Observing & understanding your Spring applications at...I Can See Clearly Now - Observing & understanding your Spring applications at...
I Can See Clearly Now - Observing & understanding your Spring applications at...
 
Spring Security 5
Spring Security 5Spring Security 5
Spring Security 5
 
Enterprise Security mit Spring Security
Enterprise Security mit Spring SecurityEnterprise Security mit Spring Security
Enterprise Security mit Spring Security
 
Java Security Framework's
Java Security Framework'sJava Security Framework's
Java Security Framework's
 
Vulnerabilities in modern web applications
Vulnerabilities in modern web applicationsVulnerabilities in modern web applications
Vulnerabilities in modern web applications
 
Secure code practices
Secure code practicesSecure code practices
Secure code practices
 
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...
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)
 
What's New in spring-security-core 2.0
What's New in spring-security-core 2.0What's New in spring-security-core 2.0
What's New in spring-security-core 2.0
 
Java Security
Java SecurityJava Security
Java Security
 
Access Control Pitfalls v2
Access Control Pitfalls v2Access Control Pitfalls v2
Access Control Pitfalls v2
 
OWASP Top 10 Proactive Controls
OWASP Top 10 Proactive ControlsOWASP Top 10 Proactive Controls
OWASP Top 10 Proactive Controls
 
Security asp.net application
Security asp.net applicationSecurity asp.net application
Security asp.net application
 
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
 
Top Ten Java Defense for Web Applications v2
Top Ten Java Defense for Web Applications v2Top Ten Java Defense for Web Applications v2
Top Ten Java Defense for Web Applications v2
 
Deep dive into Java security architecture
Deep dive into Java security architectureDeep dive into Java security architecture
Deep dive into Java security architecture
 
2013 OWASP Top 10
2013 OWASP Top 102013 OWASP Top 10
2013 OWASP Top 10
 
Spring security4.x
Spring security4.xSpring security4.x
Spring security4.x
 
Common Web Application Attacks
Common Web Application Attacks Common Web Application Attacks
Common Web Application Attacks
 
Api security
Api security Api security
Api security
 

Similar to Building Layers of Defense with Spring Security

Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009mirahman
 
Security In PHP Applications
Security In PHP ApplicationsSecurity In PHP Applications
Security In PHP Applications
Aditya Mooley
 
XSS
XSSXSS
Web Exploitation Security
Web Exploitation SecurityWeb Exploitation Security
Web Exploitation Security
Aman Singh
 
Implementing application security using the .net framework
Implementing application security using the .net frameworkImplementing application security using the .net framework
Implementing application security using the .net framework
Lalit Kale
 
PCI Security Requirements - secure coding
PCI Security Requirements - secure codingPCI Security Requirements - secure coding
PCI Security Requirements - secure codingHaitham Raik
 
Secure java script-for-developers
Secure java script-for-developersSecure java script-for-developers
Secure java script-for-developers
n|u - The Open Security Community
 
Web application attacks
Web application attacksWeb application attacks
Web application attacks
hruth
 
DevSecOps - automating security
DevSecOps - automating securityDevSecOps - automating security
DevSecOps - automating security
John Staveley
 
ASP.NET 13 - Security
ASP.NET 13 - SecurityASP.NET 13 - Security
ASP.NET 13 - Security
Randy Connolly
 
Intro to Web Application Security
Intro to Web Application SecurityIntro to Web Application Security
Intro to Web Application Security
Rob Ragan
 
Owasp Top 10 - Owasp Pune Chapter - January 2008
Owasp Top 10 - Owasp Pune Chapter - January 2008Owasp Top 10 - Owasp Pune Chapter - January 2008
Owasp Top 10 - Owasp Pune Chapter - January 2008
abhijitapatil
 
Spring4 security
Spring4 securitySpring4 security
Spring4 security
Sang Shin
 
Owasp top 10_openwest_2019
Owasp top 10_openwest_2019Owasp top 10_openwest_2019
Owasp top 10_openwest_2019
Sean Jackson
 
Pci compliance writing secure code
Pci compliance   writing secure codePci compliance   writing secure code
Pci compliance writing secure code
Miva
 
Unifi securitybugs sep2013
Unifi securitybugs sep2013Unifi securitybugs sep2013
Unifi securitybugs sep2013testslidesha12
 
OWASPTop 10
OWASPTop 10OWASPTop 10
OWASPTop 10
InnoTech
 
Web security programming_ii
Web security programming_iiWeb security programming_ii
Web security programming_iigoogli
 
Web Security Programming I I
Web  Security  Programming  I IWeb  Security  Programming  I I
Web Security Programming I IPavu Jas
 

Similar to Building Layers of Defense with Spring Security (20)

Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009
 
Security In PHP Applications
Security In PHP ApplicationsSecurity In PHP Applications
Security In PHP Applications
 
XSS
XSSXSS
XSS
 
Web Exploitation Security
Web Exploitation SecurityWeb Exploitation Security
Web Exploitation Security
 
Implementing application security using the .net framework
Implementing application security using the .net frameworkImplementing application security using the .net framework
Implementing application security using the .net framework
 
PCI Security Requirements - secure coding
PCI Security Requirements - secure codingPCI Security Requirements - secure coding
PCI Security Requirements - secure coding
 
Secure java script-for-developers
Secure java script-for-developersSecure java script-for-developers
Secure java script-for-developers
 
Web application attacks
Web application attacksWeb application attacks
Web application attacks
 
DevSecOps - automating security
DevSecOps - automating securityDevSecOps - automating security
DevSecOps - automating security
 
ASP.NET 13 - Security
ASP.NET 13 - SecurityASP.NET 13 - Security
ASP.NET 13 - Security
 
Intro to Web Application Security
Intro to Web Application SecurityIntro to Web Application Security
Intro to Web Application Security
 
Owasp Top 10 - Owasp Pune Chapter - January 2008
Owasp Top 10 - Owasp Pune Chapter - January 2008Owasp Top 10 - Owasp Pune Chapter - January 2008
Owasp Top 10 - Owasp Pune Chapter - January 2008
 
Spring4 security
Spring4 securitySpring4 security
Spring4 security
 
Owasp top 10_openwest_2019
Owasp top 10_openwest_2019Owasp top 10_openwest_2019
Owasp top 10_openwest_2019
 
Pci compliance writing secure code
Pci compliance   writing secure codePci compliance   writing secure code
Pci compliance writing secure code
 
Unifi securitybugs sep2013
Unifi securitybugs sep2013Unifi securitybugs sep2013
Unifi securitybugs sep2013
 
OWASPTop 10
OWASPTop 10OWASPTop 10
OWASPTop 10
 
demo1
demo1demo1
demo1
 
Web security programming_ii
Web security programming_iiWeb security programming_ii
Web security programming_ii
 
Web Security Programming I I
Web  Security  Programming  I IWeb  Security  Programming  I I
Web Security Programming I I
 

More from Joris Kuipers

Action Jackson! Effective JSON processing in Spring Boot Applications
Action Jackson! Effective JSON processing in Spring Boot ApplicationsAction Jackson! Effective JSON processing in Spring Boot Applications
Action Jackson! Effective JSON processing in Spring Boot Applications
Joris Kuipers
 
Hearts Of Darkness - a Spring DevOps Apocalypse
Hearts Of Darkness - a Spring DevOps ApocalypseHearts Of Darkness - a Spring DevOps Apocalypse
Hearts Of Darkness - a Spring DevOps Apocalypse
Joris Kuipers
 
Day 2 Problems in CQRS & Event Sourcing
Day 2 Problems in CQRS & Event SourcingDay 2 Problems in CQRS & Event Sourcing
Day 2 Problems in CQRS & Event Sourcing
Joris Kuipers
 
Boot Loot
Boot LootBoot Loot
Boot Loot
Joris Kuipers
 
Building and running Spring Cloud-based microservices on AWS ECS
Building and running Spring Cloud-based microservices on AWS ECSBuilding and running Spring Cloud-based microservices on AWS ECS
Building and running Spring Cloud-based microservices on AWS ECS
Joris Kuipers
 
Booting your Microservices Architecture with Spring & Netflix
Booting your Microservices Architecture with Spring & NetflixBooting your Microservices Architecture with Spring & Netflix
Booting your Microservices Architecture with Spring & Netflix
Joris Kuipers
 
Come Fly With Me: Database Migration Patterns with Flyway
Come Fly With Me: Database Migration Patterns with FlywayCome Fly With Me: Database Migration Patterns with Flyway
Come Fly With Me: Database Migration Patterns with Flyway
Joris Kuipers
 

More from Joris Kuipers (7)

Action Jackson! Effective JSON processing in Spring Boot Applications
Action Jackson! Effective JSON processing in Spring Boot ApplicationsAction Jackson! Effective JSON processing in Spring Boot Applications
Action Jackson! Effective JSON processing in Spring Boot Applications
 
Hearts Of Darkness - a Spring DevOps Apocalypse
Hearts Of Darkness - a Spring DevOps ApocalypseHearts Of Darkness - a Spring DevOps Apocalypse
Hearts Of Darkness - a Spring DevOps Apocalypse
 
Day 2 Problems in CQRS & Event Sourcing
Day 2 Problems in CQRS & Event SourcingDay 2 Problems in CQRS & Event Sourcing
Day 2 Problems in CQRS & Event Sourcing
 
Boot Loot
Boot LootBoot Loot
Boot Loot
 
Building and running Spring Cloud-based microservices on AWS ECS
Building and running Spring Cloud-based microservices on AWS ECSBuilding and running Spring Cloud-based microservices on AWS ECS
Building and running Spring Cloud-based microservices on AWS ECS
 
Booting your Microservices Architecture with Spring & Netflix
Booting your Microservices Architecture with Spring & NetflixBooting your Microservices Architecture with Spring & Netflix
Booting your Microservices Architecture with Spring & Netflix
 
Come Fly With Me: Database Migration Patterns with Flyway
Come Fly With Me: Database Migration Patterns with FlywayCome Fly With Me: Database Migration Patterns with Flyway
Come Fly With Me: Database Migration Patterns with Flyway
 

Recently uploaded

TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 

Recently uploaded (20)

TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 

Building Layers of Defense with Spring Security

  • 1. Building Layers of Defense with Spring Security “We have to distrust each other. It is our only defense against betrayal.” ― Tennessee Williams
  • 2. About Me  Joris Kuipers ( @jkuipers)  Hands-on architect and fly-by-night Spring trainer @ Trifork  @author tag in Spring Session’s support for Spring Security
  • 3. Layers Of Defense  Security concerns many levels  Physical, hardware, network, OS, middleware, applications, process / social, …  This talk focuses on applications
  • 4. Layers Of Defense  Web application has many layers to protect  Sometimes orthogonal  Often additive
  • 5. Layers Of Defense  Additivity implies some redundancy  That’s by design  Don’t rely on just a single layer of defense  Might have an error in security config / impl  Might be circumvented  AKA Defense in depth
  • 6. Spring Security  OSS framework for application-level authentication & authorization  Supports common standards & protocols  Works with any Java web application
  • 7. Spring Security Application-level:  No reliance on container, self-contained  Portable  Easy to extend and adapt  Assumes code itself is trusted
  • 8. Spring Security  Decouples authentication & authorization  Hooks into application through interceptors  Servlet Filters at web layer  Aspects at lower layers  Configured using Java-based fluent API
  • 9. Spring Security Configuration Steps to add Spring Security support: 1. Configure dependency and servlet filter chain 2. Centrally configure authentication 3. Centrally configure authorization 4. Configure code-specific authorization
  • 10. Config: Authentication @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { /* set up authentication: */ @Autowired void configureGlobal(AuthenticationManagerBuilder authMgrBuilder) throws Exception { authMgrBuilder.userDetailsService( myCustomUserDetailsService()); } // ...
  • 11. Config: HTTP Authorization /* ignore requests to these URLS: */ @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers( "/css/**", "/img/**", "/js/**", "/favicon.ico"); } // ...
  • 12. Config: HTTP Authorization /* configure URL-based authorization: */ @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers(HttpMethod.POST, "/projects/**").hasRole("PROJECT_MGR") .anyRequest().authenticated(); // additional configuration not shown… } }
  • 13. Spring Security Defaults This gives us:  Various HTTP Response headers  CSRF protection  Default login page
  • 14. HTTP Response Headers “We are responsible for actions performed in response to circumstances for which we are not responsible” ― Allan Massie
  • 15. Disable Browser Cache  Modern browsers also cache HTTPS responses  Attacker could see old page even after user logs out  In general not good for dynamic content  For URLs not ignored, these headers are added Cache-Control: no-cache, no-store, max-age=0, must-revalidate Pragma: no-cache Expires: 0
  • 16. Disable Content Sniffing  Content type guessed based on content  Attacker might upload polyglot file  Valid as both e.g. PostScript and JavaScript  JavaScript executed on download  Disabled using this header X-Content-Type-Options: nosniff
  • 17. Enable HSTS  HTTP Strict Transport Security  Enforce HTTPS for all requests to domain  Optionally incl. subdomains  Prevents man-in-the-middling initial request  Enabled by default for HTTPS requests: Strict-Transport-Security: max-age=31536000 ; includeSubDomains
  • 18. HSTS War Story Note: one HTTPS request triggers HSTS for entire domain and subdomains  Webapp might not support HTTPS-only  Domain may host more than just your application  Might be better handled by load balancer
  • 19. Disable Framing  Prevent Clickjacking  Attacker embeds app in frame as invisible overlay  Tricks users into clicking on something they shouldn’t  All framing disabled using this header  Can configure other options, e.g. SAME ORIGIN X-Frame-Options: DENY
  • 20. Block X-XSS Content  Built-in browser support to recognize reflected XSS attacks  http://example.com/index.php?user=<script>alert( 123)</script>  Ensure support is enabled and blocks (not fixes) content X-XSS-Protection: 1; mode=block
  • 21. Other Headers Support Other headers you can configure (disabled by default):  HTTP Public Key Pinning (HPKP)-related  Content Security Policy-related  Referrer-Policy
  • 22. CSRF / Session Riding Protection “One thing I learned about riding is to look for trouble before it happens.” ― Joe Davis
  • 23. Cross-Site Request Forgery CSRF tricks logged in users to make requests  Session cookie sent automatically  Look legit to server, but user never intended them
  • 24. Cross-Site Request Forgery Add session-specific token to all forms  Correct token means app initiated request  attacker cannot know token  Not needed for GET with proper HTTP verb usage  GETs should be safe  Also prevents leaking token through URL
  • 25. CSRF Protection in Spring Security Default: enabled for non-GET requests  Using session-scoped token  Include token as form request parameter <form action="/logout" method="post"> <input type="submit" value="Log out" /> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> </form>
  • 26. CSRF Protection in Spring Security  Doesn’t work for JSON-sending SPAs  Store token in cookie and pass as header instead  No server-side session state, but still quite secure  Defaults work with AngularJS as-is @Override protected void configure(HttpSecurity http) throws Exception { http.csrf() .csrfTokenRepository( CookieCsrfTokenRepository.withHttpOnlyFalse()) .and() // additional configuration…
  • 27. URL-based Authorization “Does the walker choose the path, or the path the walker?” ― Garth Nix, Sabriel
  • 28. URL-based Authorization Very common, esp. with role-based authorization  Map URL structure to authorities  Optionally including HTTP methods  Good for coarse-grained rules
  • 29. Spring Security Configuration @Override protected void configure(HttpSecurity http) throws Exception { http /* configure URL-based authorization: */ .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers(HttpMethod.POST, "/projects/**").hasRole("PROJECT_MGR") // other matchers… .anyRequest().authenticated(); // additional configuration not shown… } }
  • 30. URL-based Authorization Might become bloated  Esp. without role-related base URLs http.authorizeRequests() .antMatchers("/products", "/products/**").permitAll() .antMatchers("/customer-portal-status").permitAll() .antMatchers("/energycollectives", "/energycollectives/**").permitAll() .antMatchers("/meterreading", "/meterreading/**").permitAll() .antMatchers("/smartmeterreadingrequests", "/smartmeterreadingrequests/**").permitAll() .antMatchers("/offer", "/offer/**").permitAll() .antMatchers("/renewaloffer", "/renewaloffer/**").permitAll() .antMatchers("/address").permitAll() .antMatchers("/iban/**").permitAll() .antMatchers("/contracts", "/contracts/**").permitAll() .antMatchers("/zendesk/**").permitAll() .antMatchers("/payment/**").permitAll() .antMatchers("/phonenumber/**").permitAll() .antMatchers("/debtcollectioncalendar/**").permitAll() .antMatchers("/edsn/**").permitAll() .antMatchers("/leads/**").permitAll() .antMatchers("/dynamicanswer/**").permitAll() .antMatchers("/masterdata", "/masterdata/**").permitAll() .antMatchers("/invoices/**").permitAll() .antMatchers("/registerverification", "/registerverification/**").permitAll() .antMatchers("/smartmeterreadingreports", "/smartmeterreadingreports/**").permitAll() .antMatchers("/users", "/users/**").permitAll() .antMatchers("/batch/**").hasAuthority("BATCH_ADMIN") .antMatchers("/label/**").permitAll() .antMatchers("/bankstatementtransactions", "/bankstatementtransactions/**").permitAll() .antMatchers("/directdebitsepamandate", "/directdebitsepamandate/**").permitAll() .anyRequest().authenticated()
  • 31. URL-based Authorization Can be tricky to do properly  Rules matched in order  Matchers might not behave like you think they do  Need to have a catch-all  .anyRequest().authenticated();  .anyRequest().denyAll();
  • 32. URL Matching Rules Gotchas http.authorizeRequests() .antMatchers("/products/inventory/**").hasRole("ADMIN") .antMatchers("/products/**").hasAnyRole("USER", "ADMIN") .antMatchers(… Ordering very significant here! .antMatchers("/products/delete").hasRole("ADMIN") Does NOT match /products/delete/ (trailing slash)! .mvcMatchers("/products/delete").hasRole("ADMIN")
  • 33. Method-level Authorization “When you make your peace with authority, you become authority” ― Jim Morrison
  • 34. Method-Level Security  Declarative checks before or after method invocation  Enable explicitly @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { … }
  • 35. @PreAuthorize Examples @PreAuthorize("hasRole('PRODUCT_MGR')") Product saveNew(ProductForm productForm) { @PreAuthorize("hasRole('PRODUCT_MGR') && #product.companyId == principal.company.id") void updateProduct(Product product) { Refer to parameters, e.g. for multitenancy
  • 37. Expressions in @Pre-/PostAuthorize  Built-ins  hasRole(), hasAnyRole(), isAuthenticated(), isAnonymous(), …  Can add your own…  Relatively complex
  • 38. Expressions in @Pre-/PostAuthorize  …or just call method on Spring Bean instead @PreAuthorize("@authChecks.isTreatedByCurrentUser(#patient)") public void addReport(Patient patient, Report report) { @Service public class AuthChecks { public boolean isTreatedByCurrentUser(Patient patient) { // ... }
  • 39. Method-level Security Support for standard Java @RolesAllowed  Role-based checks only  Enable explicitly @EnableGlobalMethodSecurity( prePostEnabled = true, jsr250Enabled = true) @RolesAllowed("ROLE_PRODUCT_MGR") Product saveNew(ProductForm productForm) {
  • 40. Programmatic Security Easy programmatic access & checks  Nice for e.g. custom interceptors  Preferably not mixed with business logic Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null && auth.getPrincipal() instanceof MyUser) { MyUser user = (MyUser) auth.getPrincipal(); // ...
  • 41. Programmatic Use Cases Look up current user to:  Perform authorization in custom filter/aspect  Populate Logger MDC  Pass current tenant as Controller method parameter  Auto-fill last-modified-by DB column  Propagate security context to worker thread  …
  • 42. Access Control Lists “Can’t touch this” ― MC Hammer
  • 43. ACL Support  Spring Security supports Access Control Lists  Fine-grained permissions per secured item  Check before / after accessing item  Declaratively or programmatically  Not needed for most applications
  • 44. Defining ACLs  Persisted in dedicated DB tables  Entity defined by type and ID  Access to entity per-user or per-authority  Access permissions defined by int bitmask  read, write, delete, etc.  granting or denying
  • 45. Checking ACLs  Check performed against instance or type+id  Multiple options for permission checks  Using SpEL expressions is easy @PreAuthorize("hasPermission(#contact, 'delete') or hasPermission(#contact, 'admin')") void delete(Contact contact); @PreAuthorize("hasPermission(#id, 'sample.Contact', 'read') or hasPermission(#id, 'sample.Contact', 'admin')") Contact getById(Long id);
  • 46. Other Concerns “Concern should drive us into action, not into a depression.” ― Karen Horney
  • 47. Enforcing HTTPS  Can enforce HTTPS channel  Redirect when request uses plain HTTP  HTTPS is usually important  Even if your data isn’t  Attacker could insert malicious content  Might be better handled by load balancer
  • 48. Limiting Concurrent Sessions  How often can single user log in at the same time?  Limit to max nr of sessions  Built-in support limited to single node  Supports multi-node through Spring Session
  • 49. Password Hashing  Are you storing your own users and passwords?  Ensure appropriate hashing algorithm  BCrypt, PBKDF2 & SCrypt support built in  Don’t copy old blogs showing MD5/SHA + Salt!
  • 50. CORS  Cross-Origin Resource Sharing  Relaxes same-origin policy  Allow JS communication with other servers  Server must allow origin, sent in request header  Preflight request used to check access: must be handled before Spring Security!
  • 51. Enabling CORS Support  Spring-MVC has CORS support  For Spring Security, just configure filter @Override protected void configure(HttpSecurity http) throws Exception { http .cors().and() // ... other config  No Spring-MVC? Add CorsConfigurationSource bean
  • 52. Conclusion  Spring Security handles security at all application layers  Combine to provide defense in depth  Understand your security framework  Become unhackable!  Or at least be able to blame someone else…

Editor's Notes

  1. Browser-side, URL-based, Method-level, Data-level
  2. No dependency on e.g. Spring-MVC
  3. Login page should always be changed to your custom page
  4. Requires proper Content-Type header in responses!
  5. Token exposed through request attributes, adding it can be automated (JSP taglib, Thymeleaf)
  6. Using Annotations & Spring Expression Language
  7. @Pre-/PostAuthorize can be used as meta-annotations for easy DRY reuse
  8. Mention @PostFilter