SlideShare a Scribd company logo
Photos by Trish McGinity - http://mcginityphoto.com © 2015 Raible Designs
Java Web Application Security
Matt Raible
http://raibledesigns.com
@mraible
Blogger on raibledesigns.com
Founder of AppFuse
Father, Skier, Mountain
Biker, Whitewater Rafter
Web Framework Connoisseur
Who is Matt Raible?
Bus Lover
Why am I here?
Purpose
To explore Java webapp security options and
encourage you to be a security expert
Goals
Show how to implement Java webapp security
Show how to penetrate a Java webapp
Show how to fix vulnerabilities
What about YOU?
Why are you here?
Do you care about Security?
Have you used Java EE 7, Spring Security or
Apache Shiro?
What do you want to get from this talk?
Security Development
Java EE, Spring Security, Apache Shiro
SSL and Testing
Verifying Security
OWASP Top 10 & Zed Attack Proxy
Tools and Services
Action!
Session Agenda
Develop
Java EE 7
Security constraints defined in web.xml
web resource collection - URLs and methods
authorization constraints - role names
user data constraint - HTTP or HTTPS
User Realm defined by App Server
Declarative or Programmatic Authentication
Annotations Support
Java EE 7 Demo
Servlet 3.0
HttpServletRequest
authenticate(response)
login(user, pass)
logout()
getRemoteUser()
isUserInRole(name)
Servlet 3.0 and JSR 250
Annotations
@ServletSecurity
@HttpMethodConstraint
@HttpConstraint
@RolesAllowed
@PermitAll
Servlet 3.1
Non-blocking I/O
HTTP protocol upgrade mechanism
Security
Run-as security roles to #init and #destroy
Session Fixation protection
Deny HTTP methods not explicitly covered
by security constraints
JSR 375: Java EE Security API
Improvements to:
User Management
Password Aliasing
Role Mapping
Authentication
Authorization
Learn more on
Java EE Limitations
No error messages for failed logins
No Remember Me
Container has to be configured
Doesn’t support regular expressions for
URLs
Spring Boot with Security
Basic Authentication by default
Fluent API for defining URLs, roles, etc.
Spring MVC Test with Security Annotations
Password Encoding
Remember Me
WebSocket Security
Programmatic API
Spring Security Demo
Spring Security JavaConfig
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.security.config.annotation.authentication.builders.*;
import org.springframework.security.config.annotation.web.configuration.*;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
Enabling Spring Security Annotations
<global-method-security pre-post-annotations="enabled"/>
@EnableGlobalMethodSecurity(prePostEnabled=true)
XML Config:
Java Config:
@EnableGlobalMethodSecurity(jsr250Enabled=true)
@EnableGlobalMethodSecurity(secureEnabled=true)
Spring Security @PreAuthorize
@PreAuthorize("hasRole('ROLE_USER')")
public void create(Contact contact);
@PreAuthorize("hasPermission(#contact, 'admin')")
public void deletePermission(Contact contact, Sid recipient, Permission permission);
@PreAuthorize("#contact.name == authentication.name")
public void doSomething(Contact contact);
@PreAuthorize("hasRole('ROLE_USER')")
@PostFilter("hasPermission(filterObject, 'read') or hasPermission(filterObject, 'admin')")
public List<Contact> getAll();
Spring Security @Secured
@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
public Account readAccount(Long id);
@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
public Account[] findAccounts();
@Secured("ROLE_TELLER")
public Account post(Account account, double amount)}
Spring MVC Test with Security
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class CsrfShowcaseTests {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
}
Spring Security Test Annotations
@WithMockUser // user:password,roles="ROLE_USER"
@WithMockUser(username="admin",roles={"USER","ADMIN"})
@WithUserDetails
@WithSecurityContext
Spring Limitations
Authentication mechanism in WAR
Securing methods only works on
Spring beans
Apache Shiro
Filter defined in WebSecurityConfig
URLs, Roles can be configured in Java
Or use shiro.ini and load from classpath
[main], [urls], [roles]
Cryptography
Session Management
Apache Shiro Demo
Shiro Limitations
Limited Documentation
Getting Roles via LDAP not supported
No out-of-box support for Kerberos
REST Support needs work
Stormpath
Authentication as a Service
Authorization as a Service
Single Sign-On as a Service
A User Management API for Developers
https://stormpath.com
Stormpath with Spring Boot
<dependency>
<groupId>com.stormpath.spring</groupId>
<artifactId>spring-boot-starter-stormpath-thymeleaf</artifactId>
<version>1.0.RC4.5</version>
</dependency>
/register
/login
/logout
Includes Forgot Password
Add CORS Support
http://raibledesigns.com/rd/entry/implementing_ajax_authentication_using_jquery
public class OptionsHeadersFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST");
response.setHeader("Access-Control-Max-Age", "360");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {
}
public void destroy() {
}
}
public class OptionsHeadersFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST");
response.setHeader("Access-Control-Max-Age", "360");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {
}
public void destroy() {
}
}
Global CORS in Spring Boot 1.3
http://raibledesigns.com/rd/entry/implementing_ajax_authentication_using_jquery
public class OptionsHeadersFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST");
response.setHeader("Access-Control-Max-Age", "360");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {
}
public void destroy() {
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**");
}
};
}
}
Securing a REST API
Use Basic or Form Authentication
Use OAuth 2
Use JSON Web Tokens (JWT)
Use Developer Keys
Use an API Management Platform
What have you used?
OAuth 2
https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2
© 2015 Raible Designs
JHipster http://jhipster.github.io/
JHipster Security
Improved Remember Me
Cookie theft protection
CSRF protection
Authentication
HTTP Session
Token-based
OAuth2
Social (Facebook, Google, Twitter)
⚭
⚭
JHipster HTTP Session
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Inject
private AjaxAuthenticationSuccessHandler ajaxAuthenticationSuccessHandler;
@Inject
private AjaxAuthenticationFailureHandler ajaxAuthenticationFailureHandler;
@Inject
private AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler;
JHipster Token-based
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.csrf().disable().headers().frameOptions().disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/register").permitAll()
// additional rules for URLs
.and()
.apply(securityConfigurerAdapter());
}
private XAuthTokenConfigurer securityConfigurerAdapter() {
return new XAuthTokenConfigurer(userDetailsService, tokenProvider);
}
JHipster OAuth2
@Configuration
public class OAuth2ServerConfiguration {
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration
extends ResourceServerConfigurerAdapter {
}
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration
extends AuthorizationServerConfigurerAdapter
implements EnvironmentAware {
}
}
© 2015 Raible Designs
JHipster Social
API Security Projects
Spring Security OAuth - version 2.0.8
Spring Social - version 1.1.4
Facebook, Twitter, LinkedIn, TripIt,
and GitHub Bindings
Penetrate
OWASP Testing Guide and Code Review Guide
OWASP Top 10
OWASP Zed Attack Proxy
Burp Suite
OWASP WebGoat
OWASP
The Open Web Application Security Project (OWASP) is a worldwide not-for-profit
charitable organization focused on improving the security of software.
At OWASP you’ll find free and open ...
Application security tools, complete books, standard security controls and
libraries, cutting edge research
http://www.owasp.org
http://raibledesigns.com/rd/entry/java_web_application_security_part4
Penetration Testing with ZAP
Fixing ZAP Vulnerabilities
<session-config>
<session-timeout>15</session-timeout>
<cookie-config>
<http-only>true</http-only>
<secure>true</secure>
</cookie-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
<form action="${ctx}/j_security_check" id="loginForm"
method="post" autocomplete="off">
7 Security (Mis)Configurations in web.xml
1. Error pages not configured
2. Authentication & Authorization Bypass
3. SSL Not Configured
4. Not Using the Secure Flag
5. Not Using the HttpOnly Flag
6. Using URL Parameters for Session Tracking
7. Not Setting a Session Timeout
http://software-security.sans.org/blog/2010/08/11/security-misconfigurations-java-webxml-files
OWASP Top 10 for 2013
1. Injection
2. Broken Authentication and Session Management
3. Cross-Site Scripting (XSS)
4. Insecure Direct Object References
5. Security Misconfiguration
https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
OWASP Top 10 for 2013
6. Sensitive Data Exposure
7. Missing Function Level Access Control
8. Cross-Site Request Forgery (CSRF)
9. Using Components with Known
Vulnerabilities
10.Unvalidated Redirects and Forwards
https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
Protect
[SWAT] Checklist
Firewalls
IDS and IPS
Audits
Penetration Tests
Code Reviews with Static Analysis Tools
[SWAT] Checklist http://software-security.sans.org/resources/swat
Firewalls
Stateless Firewalls
Stateful Firewalls
Invented by Nir Zuk at Check Point in
the mid-90s
Web App Firewalls
Inspired by the 1996 PHF CGI exploit
Gartner on Firewalls
Content Security Policy
An HTTP Header with whitelist of trusted content
Bans inline <script> tags, inline event handlers and
javascript: URLs
No eval(), new Function(), setTimeout or setInterval
Supported in Chrome 16+, Safari 6+, and Firefox 4+, and
(very) limited in IE 10
Content Security Policy
Content Security Policy: Can I use?
Relax
Web App Firewalls: Imperva, F5
Open Source: WebNight and ModSecurity
Stateful Firewalls: Palo Alto, Check Point, Juniper
IDP/IPS: Sourcefire (Cisco), TippingPoint (HP)
Open Source: Snort
Audits: ENY, PWC, Grant Thornton
Pen Testing: Metasploit, Nessus, Veracode, Burp Suite
Open Source: OWASP ZAP
Remember...
“Security is a quality, and as all other quality, it is important
that we build it into our apps while we are developing
them, not patching it on afterwards like many people do.”
-- Erlend Oftedal
From a comment on raibledesigns.com: http://bit.ly/mjufjR
Action!
Use OWASP and Open Source Security Frameworks
Follow the Security Street Fighter Blog
http://software-security.sans.org/blog
Use OWASP ZAP to pentest your apps
Don’t be afraid of security!
Additional Reading
Securing a JavaScript-based Web Application
http://eoftedal.github.com/WebRebels2012
Michal Zalewski’s “The Tangled Web”
http://lcamtuf.coredump.cx/tangled
Keep in touch!

http://raibledesigns.com

@mraible

Presentations

http://slideshare.net/mraible

Code

https://github.com/mraible/java-webapp-security-examples
Questions?

More Related Content

What's hot (20)

PDF
Web App Security for Java Developers - UberConf 2021
Matt Raible
 
PDF
Get Hip with JHipster: Spring Boot + AngularJS + Bootstrap - Devoxx 2015
Matt Raible
 
PDF
Getting Started with Angular - Stormpath Webinar, January 2017
Matt Raible
 
PDF
Get Hip with JHipster - Colorado Springs OSS Meetup April 2016
Matt Raible
 
PDF
Clojure Web Development
Hong Jiang
 
PDF
JavaOne India 2011 - Running your Java EE 6 Apps in the Cloud
Arun Gupta
 
PDF
A Gentle Introduction to Angular Schematics - Angular SF 2019
Matt Raible
 
PDF
A Gentle Introduction to Angular Schematics - Devoxx Belgium 2019
Matt Raible
 
PDF
Spark IT 2011 - Developing RESTful Web services with JAX-RS
Arun Gupta
 
PDF
JAX-RS JavaOne Hyderabad, India 2011
Shreedhar Ganapathy
 
PDF
Case Study: Migrating Hyperic from EJB to Spring from JBoss to Apache Tomcat
VMware Hyperic
 
PDF
Java Web Application Security - UberConf 2011
Matt Raible
 
PDF
Apache Roller, Acegi Security and Single Sign-on
Matt Raible
 
PDF
Java REST API Framework Comparison - PWX 2021
Matt Raible
 
PDF
Java Web Application Security - Jazoon 2011
Matt Raible
 
PDF
Microservices with Spring Boot
Joshua Long
 
PDF
Front End Development for Back End Java Developers - Jfokus 2020
Matt Raible
 
PDF
Front End Development for Back End Developers - Denver Startup Week 2017
Matt Raible
 
PDF
Developing, Testing and Scaling with Apache Camel - UberConf 2015
Matt Raible
 
PDF
Bootiful Development with Spring Boot and React - UberConf 2018
Matt Raible
 
Web App Security for Java Developers - UberConf 2021
Matt Raible
 
Get Hip with JHipster: Spring Boot + AngularJS + Bootstrap - Devoxx 2015
Matt Raible
 
Getting Started with Angular - Stormpath Webinar, January 2017
Matt Raible
 
Get Hip with JHipster - Colorado Springs OSS Meetup April 2016
Matt Raible
 
Clojure Web Development
Hong Jiang
 
JavaOne India 2011 - Running your Java EE 6 Apps in the Cloud
Arun Gupta
 
A Gentle Introduction to Angular Schematics - Angular SF 2019
Matt Raible
 
A Gentle Introduction to Angular Schematics - Devoxx Belgium 2019
Matt Raible
 
Spark IT 2011 - Developing RESTful Web services with JAX-RS
Arun Gupta
 
JAX-RS JavaOne Hyderabad, India 2011
Shreedhar Ganapathy
 
Case Study: Migrating Hyperic from EJB to Spring from JBoss to Apache Tomcat
VMware Hyperic
 
Java Web Application Security - UberConf 2011
Matt Raible
 
Apache Roller, Acegi Security and Single Sign-on
Matt Raible
 
Java REST API Framework Comparison - PWX 2021
Matt Raible
 
Java Web Application Security - Jazoon 2011
Matt Raible
 
Microservices with Spring Boot
Joshua Long
 
Front End Development for Back End Java Developers - Jfokus 2020
Matt Raible
 
Front End Development for Back End Developers - Denver Startup Week 2017
Matt Raible
 
Developing, Testing and Scaling with Apache Camel - UberConf 2015
Matt Raible
 
Bootiful Development with Spring Boot and React - UberConf 2018
Matt Raible
 

Viewers also liked (7)

PDF
Testing Angular Applications - Jfokus 2017
Matt Raible
 
PDF
Cloud Native PWAs (progressive web apps with Spring Boot and Angular) - DevNe...
Matt Raible
 
PDF
Building a PWA with Ionic, Angular and Spring Boot - Jfokus 2017
Matt Raible
 
PDF
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
Matt Raible
 
PDF
What's New in JHipsterLand - DevNexus 2017
Matt Raible
 
PDF
Get Hip with JHipster: Spring Boot + AngularJS + Bootstrap - DOSUG February 2016
Matt Raible
 
PDF
Devoxx : being productive with JHipster
Julien Dubois
 
Testing Angular Applications - Jfokus 2017
Matt Raible
 
Cloud Native PWAs (progressive web apps with Spring Boot and Angular) - DevNe...
Matt Raible
 
Building a PWA with Ionic, Angular and Spring Boot - Jfokus 2017
Matt Raible
 
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
Matt Raible
 
What's New in JHipsterLand - DevNexus 2017
Matt Raible
 
Get Hip with JHipster: Spring Boot + AngularJS + Bootstrap - DOSUG February 2016
Matt Raible
 
Devoxx : being productive with JHipster
Julien Dubois
 
Ad

Similar to Java Web Application Security with Java EE, Spring Security and Apache Shiro - Rich Web Experience 2015 (20)

PDF
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Matt Raible
 
PPTX
Building Layers of Defense with Spring Security
Joris Kuipers
 
PDF
Spring security jwt tutorial toptal
jbsysatm
 
PDF
Java Web Application Security - Denver JUG 2013
Matt Raible
 
PPTX
Comprehensive_SpringBoot_Auth.pptx wokring
JayaPrakash579769
 
PPTX
Spring Security 5
Jesus Perez Franco
 
PDF
Spring Security
Sumit Gole
 
PDF
Spring security4.x
Zeeshan Khan
 
PDF
Spring4 security
Sang Shin
 
PDF
From 0 to Spring Security 4.0
robwinch
 
PDF
Spring Security in Action 1st Edition Laurentiu Spilca Spilcă Laurenţiu
ticeyfedorvt
 
PPTX
springb security.pptxdsdsgfdsgsdgsdgsdgdsgdsgds
zmulani8
 
PPTX
Java EE 8 security and JSON binding API
Alex Theedom
 
PPTX
Spring WebApplication development
ThirupathiReddy Vajjala
 
PDF
JavaCro'14 - Securing web applications with Spring Security 3 – Fernando Redo...
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
PDF
Building layers of defense for your application
VMware Tanzu
 
PDF
Lesson07_Spring_Security_API.pdf
Scott Anderson
 
PDF
Spring Security
Knoldus Inc.
 
PDF
10 Excellent Ways to Secure Your Spring Boot Application - The Secure Develop...
Matt Raible
 
PPTX
Spring Security 3
Jason Ferguson
 
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Matt Raible
 
Building Layers of Defense with Spring Security
Joris Kuipers
 
Spring security jwt tutorial toptal
jbsysatm
 
Java Web Application Security - Denver JUG 2013
Matt Raible
 
Comprehensive_SpringBoot_Auth.pptx wokring
JayaPrakash579769
 
Spring Security 5
Jesus Perez Franco
 
Spring Security
Sumit Gole
 
Spring security4.x
Zeeshan Khan
 
Spring4 security
Sang Shin
 
From 0 to Spring Security 4.0
robwinch
 
Spring Security in Action 1st Edition Laurentiu Spilca Spilcă Laurenţiu
ticeyfedorvt
 
springb security.pptxdsdsgfdsgsdgsdgsdgdsgdsgds
zmulani8
 
Java EE 8 security and JSON binding API
Alex Theedom
 
Spring WebApplication development
ThirupathiReddy Vajjala
 
JavaCro'14 - Securing web applications with Spring Security 3 – Fernando Redo...
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Building layers of defense for your application
VMware Tanzu
 
Lesson07_Spring_Security_API.pdf
Scott Anderson
 
Spring Security
Knoldus Inc.
 
10 Excellent Ways to Secure Your Spring Boot Application - The Secure Develop...
Matt Raible
 
Spring Security 3
Jason Ferguson
 
Ad

More from Matt Raible (20)

PDF
Keep Identities in Sync the SCIMple Way - ApacheCon NA 2022
Matt Raible
 
PDF
Micro Frontends for Java Microservices - Belfast JUG 2022
Matt Raible
 
PDF
Micro Frontends for Java Microservices - Dublin JUG 2022
Matt Raible
 
PDF
Micro Frontends for Java Microservices - Cork JUG 2022
Matt Raible
 
PDF
Comparing Native Java REST API Frameworks - Seattle JUG 2022
Matt Raible
 
PDF
Reactive Java Microservices with Spring Boot and JHipster - Spring I/O 2022
Matt Raible
 
PDF
Comparing Native Java REST API Frameworks - Devoxx France 2022
Matt Raible
 
PDF
Lock That Sh*t Down! Auth Security Patterns for Apps, APIs, and Infra - Devne...
Matt Raible
 
PDF
Native Java with Spring Boot and JHipster - Garden State JUG 2021
Matt Raible
 
PDF
Web App Security for Java Developers - PWX 2021
Matt Raible
 
PDF
Mobile App Development with Ionic, React Native, and JHipster - Connect.Tech ...
Matt Raible
 
PDF
Lock That Shit Down! Auth Security Patterns for Apps, APIs, and Infra - Joker...
Matt Raible
 
PDF
Java REST API Framework Comparison - UberConf 2021
Matt Raible
 
PDF
Native Java with Spring Boot and JHipster - SF JUG 2021
Matt Raible
 
PDF
Lock That Shit Down! Auth Security Patterns for Apps, APIs, and Infra - Sprin...
Matt Raible
 
PDF
Reactive Java Microservices with Spring Boot and JHipster - Denver JUG 2021
Matt Raible
 
PDF
Get Hip with JHipster - Colorado Springs Open Source User Group 2021
Matt Raible
 
PDF
JHipster and Okta - JHipster Virtual Meetup December 2020
Matt Raible
 
PDF
Java REST API Comparison: Micronaut, Quarkus, and Spring Boot - jconf.dev 2020
Matt Raible
 
PDF
Security Patterns for Microservice Architectures - SpringOne 2020
Matt Raible
 
Keep Identities in Sync the SCIMple Way - ApacheCon NA 2022
Matt Raible
 
Micro Frontends for Java Microservices - Belfast JUG 2022
Matt Raible
 
Micro Frontends for Java Microservices - Dublin JUG 2022
Matt Raible
 
Micro Frontends for Java Microservices - Cork JUG 2022
Matt Raible
 
Comparing Native Java REST API Frameworks - Seattle JUG 2022
Matt Raible
 
Reactive Java Microservices with Spring Boot and JHipster - Spring I/O 2022
Matt Raible
 
Comparing Native Java REST API Frameworks - Devoxx France 2022
Matt Raible
 
Lock That Sh*t Down! Auth Security Patterns for Apps, APIs, and Infra - Devne...
Matt Raible
 
Native Java with Spring Boot and JHipster - Garden State JUG 2021
Matt Raible
 
Web App Security for Java Developers - PWX 2021
Matt Raible
 
Mobile App Development with Ionic, React Native, and JHipster - Connect.Tech ...
Matt Raible
 
Lock That Shit Down! Auth Security Patterns for Apps, APIs, and Infra - Joker...
Matt Raible
 
Java REST API Framework Comparison - UberConf 2021
Matt Raible
 
Native Java with Spring Boot and JHipster - SF JUG 2021
Matt Raible
 
Lock That Shit Down! Auth Security Patterns for Apps, APIs, and Infra - Sprin...
Matt Raible
 
Reactive Java Microservices with Spring Boot and JHipster - Denver JUG 2021
Matt Raible
 
Get Hip with JHipster - Colorado Springs Open Source User Group 2021
Matt Raible
 
JHipster and Okta - JHipster Virtual Meetup December 2020
Matt Raible
 
Java REST API Comparison: Micronaut, Quarkus, and Spring Boot - jconf.dev 2020
Matt Raible
 
Security Patterns for Microservice Architectures - SpringOne 2020
Matt Raible
 

Recently uploaded (20)

PDF
Database Benchmarking for Performance Masterclass: Session 1 - Benchmarking F...
ScyllaDB
 
PDF
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
PPTX
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
PDF
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
PDF
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
 
PDF
UiPath Agentic AI ile Akıllı Otomasyonun Yeni Çağı
UiPathCommunity
 
PDF
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
PDF
Kubernetes - Architecture & Components.pdf
geethak285
 
PDF
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
PDF
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
PDF
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
PDF
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
PPTX
Practical Applications of AI in Local Government
OnBoard
 
PDF
The Growing Value and Application of FME & GenAI
Safe Software
 
PPSX
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
PDF
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
ScyllaDB
 
PDF
From Chatbot to Destroyer of Endpoints - Can ChatGPT Automate EDR Bypasses (1...
Priyanka Aash
 
PPTX
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
PDF
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
Database Benchmarking for Performance Masterclass: Session 1 - Benchmarking F...
ScyllaDB
 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
 
UiPath Agentic AI ile Akıllı Otomasyonun Yeni Çağı
UiPathCommunity
 
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
Kubernetes - Architecture & Components.pdf
geethak285
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
Practical Applications of AI in Local Government
OnBoard
 
The Growing Value and Application of FME & GenAI
Safe Software
 
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
ScyllaDB
 
From Chatbot to Destroyer of Endpoints - Can ChatGPT Automate EDR Bypasses (1...
Priyanka Aash
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 

Java Web Application Security with Java EE, Spring Security and Apache Shiro - Rich Web Experience 2015

  • 1. Photos by Trish McGinity - http://mcginityphoto.com © 2015 Raible Designs Java Web Application Security Matt Raible http://raibledesigns.com @mraible
  • 2. Blogger on raibledesigns.com Founder of AppFuse Father, Skier, Mountain Biker, Whitewater Rafter Web Framework Connoisseur Who is Matt Raible? Bus Lover
  • 3. Why am I here? Purpose To explore Java webapp security options and encourage you to be a security expert Goals Show how to implement Java webapp security Show how to penetrate a Java webapp Show how to fix vulnerabilities
  • 4. What about YOU? Why are you here? Do you care about Security? Have you used Java EE 7, Spring Security or Apache Shiro? What do you want to get from this talk?
  • 5. Security Development Java EE, Spring Security, Apache Shiro SSL and Testing Verifying Security OWASP Top 10 & Zed Attack Proxy Tools and Services Action! Session Agenda
  • 7. Java EE 7 Security constraints defined in web.xml web resource collection - URLs and methods authorization constraints - role names user data constraint - HTTP or HTTPS User Realm defined by App Server Declarative or Programmatic Authentication Annotations Support
  • 8. Java EE 7 Demo
  • 10. Servlet 3.0 and JSR 250 Annotations @ServletSecurity @HttpMethodConstraint @HttpConstraint @RolesAllowed @PermitAll
  • 11. Servlet 3.1 Non-blocking I/O HTTP protocol upgrade mechanism Security Run-as security roles to #init and #destroy Session Fixation protection Deny HTTP methods not explicitly covered by security constraints
  • 12. JSR 375: Java EE Security API Improvements to: User Management Password Aliasing Role Mapping Authentication Authorization Learn more on
  • 13. Java EE Limitations No error messages for failed logins No Remember Me Container has to be configured Doesn’t support regular expressions for URLs
  • 14. Spring Boot with Security Basic Authentication by default Fluent API for defining URLs, roles, etc. Spring MVC Test with Security Annotations Password Encoding Remember Me WebSocket Security Programmatic API
  • 16. Spring Security JavaConfig import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.*; import org.springframework.security.config.annotation.authentication.builders.*; import org.springframework.security.config.annotation.web.configuration.*; @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("password").roles("USER"); } }
  • 17. Enabling Spring Security Annotations <global-method-security pre-post-annotations="enabled"/> @EnableGlobalMethodSecurity(prePostEnabled=true) XML Config: Java Config: @EnableGlobalMethodSecurity(jsr250Enabled=true) @EnableGlobalMethodSecurity(secureEnabled=true)
  • 18. Spring Security @PreAuthorize @PreAuthorize("hasRole('ROLE_USER')") public void create(Contact contact); @PreAuthorize("hasPermission(#contact, 'admin')") public void deletePermission(Contact contact, Sid recipient, Permission permission); @PreAuthorize("#contact.name == authentication.name") public void doSomething(Contact contact); @PreAuthorize("hasRole('ROLE_USER')") @PostFilter("hasPermission(filterObject, 'read') or hasPermission(filterObject, 'admin')") public List<Contact> getAll();
  • 19. Spring Security @Secured @Secured("IS_AUTHENTICATED_ANONYMOUSLY") public Account readAccount(Long id); @Secured("IS_AUTHENTICATED_ANONYMOUSLY") public Account[] findAccounts(); @Secured("ROLE_TELLER") public Account post(Account account, double amount)}
  • 20. Spring MVC Test with Security import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @WebAppConfiguration public class CsrfShowcaseTests { @Autowired private WebApplicationContext context; private MockMvc mvc; @Before public void setup() { mvc = MockMvcBuilders .webAppContextSetup(context) .apply(springSecurity()) .build(); } }
  • 21. Spring Security Test Annotations @WithMockUser // user:password,roles="ROLE_USER" @WithMockUser(username="admin",roles={"USER","ADMIN"}) @WithUserDetails @WithSecurityContext
  • 22. Spring Limitations Authentication mechanism in WAR Securing methods only works on Spring beans
  • 23. Apache Shiro Filter defined in WebSecurityConfig URLs, Roles can be configured in Java Or use shiro.ini and load from classpath [main], [urls], [roles] Cryptography Session Management
  • 25. Shiro Limitations Limited Documentation Getting Roles via LDAP not supported No out-of-box support for Kerberos REST Support needs work
  • 26. Stormpath Authentication as a Service Authorization as a Service Single Sign-On as a Service A User Management API for Developers https://stormpath.com
  • 27. Stormpath with Spring Boot <dependency> <groupId>com.stormpath.spring</groupId> <artifactId>spring-boot-starter-stormpath-thymeleaf</artifactId> <version>1.0.RC4.5</version> </dependency> /register /login /logout Includes Forgot Password
  • 28. Add CORS Support http://raibledesigns.com/rd/entry/implementing_ajax_authentication_using_jquery public class OptionsHeadersFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET,POST"); response.setHeader("Access-Control-Max-Age", "360"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); response.setHeader("Access-Control-Allow-Credentials", "true"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) { } public void destroy() { } } public class OptionsHeadersFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET,POST"); response.setHeader("Access-Control-Max-Age", "360"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); response.setHeader("Access-Control-Allow-Credentials", "true"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) { } public void destroy() { } }
  • 29. Global CORS in Spring Boot 1.3 http://raibledesigns.com/rd/entry/implementing_ajax_authentication_using_jquery public class OptionsHeadersFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET,POST"); response.setHeader("Access-Control-Max-Age", "360"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); response.setHeader("Access-Control-Allow-Credentials", "true"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) { } public void destroy() { } } import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class MyConfiguration { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**"); } }; } }
  • 30. Securing a REST API Use Basic or Form Authentication Use OAuth 2 Use JSON Web Tokens (JWT) Use Developer Keys Use an API Management Platform What have you used?
  • 32. © 2015 Raible Designs JHipster http://jhipster.github.io/
  • 33. JHipster Security Improved Remember Me Cookie theft protection CSRF protection Authentication HTTP Session Token-based OAuth2 Social (Facebook, Google, Twitter) ⚭ ⚭
  • 34. JHipster HTTP Session @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Inject private AjaxAuthenticationSuccessHandler ajaxAuthenticationSuccessHandler; @Inject private AjaxAuthenticationFailureHandler ajaxAuthenticationFailureHandler; @Inject private AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler;
  • 35. JHipster Token-based @Override protected void configure(HttpSecurity http) throws Exception { http .exceptionHandling() .authenticationEntryPoint(authenticationEntryPoint) .and() .csrf().disable().headers().frameOptions().disable() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/api/register").permitAll() // additional rules for URLs .and() .apply(securityConfigurerAdapter()); } private XAuthTokenConfigurer securityConfigurerAdapter() { return new XAuthTokenConfigurer(userDetailsService, tokenProvider); }
  • 36. JHipster OAuth2 @Configuration public class OAuth2ServerConfiguration { @Configuration @EnableResourceServer protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { } @Configuration @EnableAuthorizationServer protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware { } }
  • 37. © 2015 Raible Designs JHipster Social
  • 38. API Security Projects Spring Security OAuth - version 2.0.8 Spring Social - version 1.1.4 Facebook, Twitter, LinkedIn, TripIt, and GitHub Bindings
  • 39. Penetrate OWASP Testing Guide and Code Review Guide OWASP Top 10 OWASP Zed Attack Proxy Burp Suite OWASP WebGoat
  • 40. OWASP The Open Web Application Security Project (OWASP) is a worldwide not-for-profit charitable organization focused on improving the security of software. At OWASP you’ll find free and open ... Application security tools, complete books, standard security controls and libraries, cutting edge research http://www.owasp.org
  • 43. 7 Security (Mis)Configurations in web.xml 1. Error pages not configured 2. Authentication & Authorization Bypass 3. SSL Not Configured 4. Not Using the Secure Flag 5. Not Using the HttpOnly Flag 6. Using URL Parameters for Session Tracking 7. Not Setting a Session Timeout http://software-security.sans.org/blog/2010/08/11/security-misconfigurations-java-webxml-files
  • 44. OWASP Top 10 for 2013 1. Injection 2. Broken Authentication and Session Management 3. Cross-Site Scripting (XSS) 4. Insecure Direct Object References 5. Security Misconfiguration https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
  • 45. OWASP Top 10 for 2013 6. Sensitive Data Exposure 7. Missing Function Level Access Control 8. Cross-Site Request Forgery (CSRF) 9. Using Components with Known Vulnerabilities 10.Unvalidated Redirects and Forwards https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
  • 46. Protect [SWAT] Checklist Firewalls IDS and IPS Audits Penetration Tests Code Reviews with Static Analysis Tools
  • 48. Firewalls Stateless Firewalls Stateful Firewalls Invented by Nir Zuk at Check Point in the mid-90s Web App Firewalls Inspired by the 1996 PHF CGI exploit
  • 50. Content Security Policy An HTTP Header with whitelist of trusted content Bans inline <script> tags, inline event handlers and javascript: URLs No eval(), new Function(), setTimeout or setInterval Supported in Chrome 16+, Safari 6+, and Firefox 4+, and (very) limited in IE 10
  • 53. Relax Web App Firewalls: Imperva, F5 Open Source: WebNight and ModSecurity Stateful Firewalls: Palo Alto, Check Point, Juniper IDP/IPS: Sourcefire (Cisco), TippingPoint (HP) Open Source: Snort Audits: ENY, PWC, Grant Thornton Pen Testing: Metasploit, Nessus, Veracode, Burp Suite Open Source: OWASP ZAP
  • 54. Remember... “Security is a quality, and as all other quality, it is important that we build it into our apps while we are developing them, not patching it on afterwards like many people do.” -- Erlend Oftedal From a comment on raibledesigns.com: http://bit.ly/mjufjR
  • 55. Action! Use OWASP and Open Source Security Frameworks Follow the Security Street Fighter Blog http://software-security.sans.org/blog Use OWASP ZAP to pentest your apps Don’t be afraid of security!
  • 56. Additional Reading Securing a JavaScript-based Web Application http://eoftedal.github.com/WebRebels2012 Michal Zalewski’s “The Tangled Web” http://lcamtuf.coredump.cx/tangled