SlideShare a Scribd company logo
1
Spring SecuritySpring Security
Sang ShinSang Shin
JPassion.comJPassion.com
““Code with Passion!”Code with Passion!”
2
Topics
• Spring security overview
• Security configuration
• Remember me
• CSRF
3
Spring SecuritySpring Security
OverviewOverview
4
Spring Security Features
• Provides portable and comprehensive security services for Java-
based enterprise software applications
• Handles “authentication” and “authorization”
> “Authentication” is the process of establishing “a principal is who he
claim to be” (a “principal” could be a user, device or some other system)
> “Authorization” (“access-control”) refers to the process of deciding
“whether a principal is allowed to perform an action or access a
resource”
5
Spring Authentication Support
• HTTP BASIC authentication headers
• Form-based authentication (for simple user interface needs)
• HTTP Digest authentication headers
• HTTP X.509 client certificate exchange
• LDAP (a very common approach to cross-platform authentication
needs, especially in large environments)
• OpenID authentication
> OpenID allows you to use an existing account to sign in to multiple
websites, without needing to create new passwords
• Authentication based on pre-established request headers (such as
Computer Associates SiteMinder)
6
Spring Authentication Support (Cont)
• JA-SIG Central Authentication Service (otherwise known as CAS,
which is a popular open source single sign-on system)
• Transparent authentication context propagation for Remote Method
Invocation (RMI) and HttpInvoker (a Spring remoting protocol)
• Automatic "remember-me" authentication (so you can tick a box to
avoid re-authentication for a predetermined period of time)
• Anonymous authentication (allowing every unauthenticated call to
automatically assume a particular security identity)
• Run-as authentication (which is useful if one call should proceed with
a different security identity)
• Java Authentication and Authorization Service (JAAS)
• Java EE container authentication (so you can still use Container
Managed Authentication if desired)
• Kerberos
7
3rd
Party Authentication Support
• Java Open Source Single Sign On (JOSSO)
• OpenNMS Network Management Platform
• AppFuse
• AndroMDA
• Mule ESB
• Direct Web Request (DWR)
• Grails
• Tapestry
• JTrac
• Jasypt
• Roller
• Elastic Path
• Atlassian Crowd
8
Authorization Support
• Three main areas where authorization can be applied
> Authorizing web requests
> Authorizing whether methods can be invoked
> Authorizing access to individual domain object instances
9
SecuritySecurity
ConfigurationConfiguration
10
Security Configuration Example
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/index.html").permitAll()
.antMatchers("/helloworld/sayspring").hasAnyRole("SUPERVISOR")
.antMatchers("/helloworld*").hasAnyRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.defaultSuccessUrl("/default-target-after-login", false)
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/")
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/access-denied");
}
authorization
form login
logout
security exception handling
11
Authentication Manager & Provider
• Authentication manger is a container of multiple authentication providers
• Different types of authentication providers are available
> JAAS, LDAP, ActiveDirectory, OpenID, etc
> Each authentication provider is an implementation of AuthenticatiodnProvider
interface
12
Spring MVC Security Configuration
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
...
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("rod").password("rod").roles("SUPERVISOR", "USER", "TELLER").and()
.withUser("dianne").password("dianne").roles("USER", "TELLER").and()
.withUser("scott").password("scott").roles("USER").and()
.withUser("peter").password("peter").roles("USER").and()
.withUser("sang").password("sang").roles("USER");
}
13
Lab:Lab:
Exercise 1: Step by step of securingExercise 1: Step by step of securing
a web applicationa web application
4957_spring4_security.zip4957_spring4_security.zip
14
Adding a Password Encoder
• Password data can be encoded using a hashing algorithm through
Password encoding class such as BCryptPasswordEncoder
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(yourpassword);
15
Protection from Dictionary Attacks
• When using hashed passwords, it's also a good idea to use a salt
value to protect against dictionary attacks and Spring Security
supports this too.
> Salt is random data that is used as an additional input to a one-
way function that hashes a password
• Ideally you would want to use a randomly generated salt value for
each user, but you can use any property of the UserDetails object
which is loaded by your UserDetailsService.
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(yourpassword, saltSource.getSalt(user));
16
Remember meRemember me
17
Remember me
• The Remember-me feature allows a user to access secured
resources after session timeout without re-logging in
> By default, the session timeout is set to 30 minutes but can be
reconfigured.
18
Remember me Server side configuration
@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/index.html").permitAll()
.antMatchers("/helloworld/sayspring").hasAnyRole("SUPERVISOR")
.antMatchers("/helloworld*").hasAnyRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.defaultSuccessUrl("/default-target-after-login", false)
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/")
.permitAll()
.and()
.rememberMe()
.tokenValiditySeconds(864000)
.and()
.exceptionHandling()
.accessDeniedPage("/access-denied");
}
19
Remember me Client side Request
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<title>Spring Security Example</title>
</head>
<body>
<h3>My custom login page</h3>
<c:if test="${not empty SPRING_SECURITY_LAST_EXCEPTION}">
<font color="red"> Your login attempt was not successful due to <c:out value="$
{SPRING_SECURITY_LAST_EXCEPTION.message}" />.
</font>
</c:if>
<br/><br/>
<form action="login" method="post">
<label>User Name : </label> <input type="text" name="username" /> <br />
<label>Password: </label> <input type="password" name="password" /> <br />
<label>Remember me </label> <input type="checkbox" name="remember-me" />
<input type="submit" value="Sign In" /> <input type="hidden"
name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
</body>
</html>
20
Displaying Remember-me authentication
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>My title</title>
</head>
<body>
<h1>
You are logged in as
<c:out value="${pageContext.request.remoteUser}" />
</h1>
<h2>${message1}</h2>
<sec:authorize access="isRememberMe()">
<h2># This user logged in by "Remember Me Cookies".</h2>
</sec:authorize>
<sec:authorize access="isFullyAuthenticated()">
<h2># This user logged in by ""username/password.</h2>
</sec:authorize>
<form:form action="/logout" method="post">
<input type="submit" value="Sign Out" />
</form:form>
</body>
</html>
Spring provides methods
for checking if the authentication
is done via Remember-me
or via full authentication
21
Lab:Lab:
Exercise 2: Remember meExercise 2: Remember me
4957_spring4_security.zip4957_spring4_security.zip
22
CSRF (Cross-SiteCSRF (Cross-Site
Request Forgery)Request Forgery)
23
CSRF Example Scenario
• The attack works by including a link or script in a page that
accesses a site to which the user is known (or is supposed) to have
been authenticated
• For example, one user, Alice, might be browsing a chat forum where
another user, Mallory, has posted a message. Suppose that Mallory
has crafted an HTML image element that references an action on
Alice's bank's website (rather than an image file)
Mallory: Hello Alice! Look here:
<img src="http://bank.example.com/withdraw?account=Alice&amount=1000000&for=Mallory">
• If Alice's bank keeps her authentication information in a cookie, and
if the cookie hasn't expired, then the attempt by Alice's browser to
load the image will submit the withdrawal form with her cookie, thus
authorizing a transaction without Alice's approval.
source: https://en.wikipedia.org/wiki/Cross-site_request_forgery#Example_and_characteristics
24
CSRF Prevention via CSRF Token
• Most CSRF prevention techniques work by embedding additional
authentication data such as CSRF token into requests that allows
the web application to detect requests from unauthorized locations
• You should use CSRF protection for any request that could be
processed by a browser by normal users
> If you are only creating a service that is used by non-browser clients,
you will likely want to disable CSRF protection.
• On the server side, Spring security automatically enables CSRF
support
• From the client side, CSRF token should be included in all PATCH,
POST, PUT, and DELETE methods
> This can be done using the _csrf request attribute to obtain the current
CsrfToken.
25
CSRF Prevention work at Client
• If you are using Spring MVC <form:form> tag or Thymeleaf, the
CsrfToken is automatically included for you
• Otherwise, you have to explicitly include it (as shown below)
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head><title>Hello World2!</title></head>
<body>
<h1>
User
<c:out value="${pageContext.request.remoteUser}" />
is logged in!
</h1>
<h1>No CSRF error expected since CSRF token is explicitly sent</h1>
<form action="/logout" method="post">
<input type="submit" value="Sign Out" />
<input type="hidden"
name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
</body>
</html>
Since this page is not using
Spring MVC <form:form> tag nor
Thymeleaf, CSRF token needs
to be explicitly sent
26
Lab:Lab:
Exercise 3: CSRFExercise 3: CSRF
4957_spring4_security.zip4957_spring4_security.zip
27
Code with Passion!Code with Passion!
JPassion.comJPassion.com
27

More Related Content

PPTX
Building Secure User Interfaces With JWTs
PPTX
JWT Authentication with AngularJS
PDF
Super simple application security with Apache Shiro
PPT
PDF
Authentication: Cookies vs JWTs and why you’re doing it wrong
PDF
Securing Web Applications with Token Authentication
PPTX
ApacheCon 2014: Infinite Session Clustering with Apache Shiro & Cassandra
PDF
OAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
Building Secure User Interfaces With JWTs
JWT Authentication with AngularJS
Super simple application security with Apache Shiro
Authentication: Cookies vs JWTs and why you’re doing it wrong
Securing Web Applications with Token Authentication
ApacheCon 2014: Infinite Session Clustering with Apache Shiro & Cassandra
OAuth 2.0 – A standard is coming of age by Uwe Friedrichsen

What's hot (20)

PPTX
Secure Coding for NodeJS
PDF
JavaOne 2014 - Securing RESTful Resources with OAuth2
PPTX
Intro to Apache Shiro
PDF
Securing REST APIs
PPTX
W3 conf hill-html5-security-realities
PPTX
Building Secure User Interfaces With JWTs (JSON Web Tokens)
PPTX
Help! I Have An Identity Crisis: A look at various mechanisms of Single Sign On
PPTX
Token Authentication for Java Applications
PPTX
Building Layers of Defense with Spring Security
PPTX
Octopus framework; Permission based security framework for Java EE
PDF
PHP Experience 2016 - [Palestra] Json Web Token (JWT)
PPTX
Adding Identity Management and Access Control to your Application, Authorization
PDF
Xss frame work
PPTX
Access Control Pitfalls v2
PPTX
Top 10 Web Hacks 2012
PDF
What the Heck is OAuth and OpenID Connect? Connect.Tech 2017
PDF
The Unintended Risks of Trusting Active Directory
PPTX
Rest API Security
PDF
Shields Up! Securing React Apps
PDF
Apache2 BootCamp : Restricting Access
Secure Coding for NodeJS
JavaOne 2014 - Securing RESTful Resources with OAuth2
Intro to Apache Shiro
Securing REST APIs
W3 conf hill-html5-security-realities
Building Secure User Interfaces With JWTs (JSON Web Tokens)
Help! I Have An Identity Crisis: A look at various mechanisms of Single Sign On
Token Authentication for Java Applications
Building Layers of Defense with Spring Security
Octopus framework; Permission based security framework for Java EE
PHP Experience 2016 - [Palestra] Json Web Token (JWT)
Adding Identity Management and Access Control to your Application, Authorization
Xss frame work
Access Control Pitfalls v2
Top 10 Web Hacks 2012
What the Heck is OAuth and OpenID Connect? Connect.Tech 2017
The Unintended Risks of Trusting Active Directory
Rest API Security
Shields Up! Securing React Apps
Apache2 BootCamp : Restricting Access
Ad

Viewers also liked (20)

ODP
Android tutorials6 run_your_app
PPTX
Brief about outsourcing
ODP
Patient safety program scd
PPT
видеоэкскурсия в красный берег(полная)
PPTX
Guide to choose your outsourcing partner
PPTX
Ray Kirby: Lectures are STILL Appropriate
ODP
Preventing the spread of infection
PPTX
копия три слагаемых успешного урока английского языка
PPTX
就職活動は遅らせるべきか
PPTX
Doing things with manuscripts: CLIR post doc-seminar, Bryn Mawr College 7.31....
PPTX
Dairyfree
PPSX
PPT
уголовная ответственность
PPTX
Sue Hardman - video lectures
PPT
электронные физминутки
DOC
59828 employee benefits compliance checklist for small employers 021312
PDF
Wasicunwitkotko
PPTX
Our encounter with d8
Android tutorials6 run_your_app
Brief about outsourcing
Patient safety program scd
видеоэкскурсия в красный берег(полная)
Guide to choose your outsourcing partner
Ray Kirby: Lectures are STILL Appropriate
Preventing the spread of infection
копия три слагаемых успешного урока английского языка
就職活動は遅らせるべきか
Doing things with manuscripts: CLIR post doc-seminar, Bryn Mawr College 7.31....
Dairyfree
уголовная ответственность
Sue Hardman - video lectures
электронные физминутки
59828 employee benefits compliance checklist for small employers 021312
Wasicunwitkotko
Our encounter with d8
Ad

Similar to Spring4 security (20)

PDF
Building layers of defense for your application
PDF
Spring Security in Action 1st Edition Laurentiu Spilca Spilcă Laurenţiu
PDF
Spring security jwt tutorial toptal
PPTX
Spring Security services for web applications
PDF
Spring security4.x
PPT
Spring Security Introduction
PDF
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
PDF
Java Web Application Security - Denver JUG 2013
PPTX
SCWCD : Secure web : CHAP : 7
PPTX
SCWCD : Secure web
PPTX
Defending web applications v.1.0
PPTX
Spring Security 5
PPTX
Utilize the Full Power of GlassFish Server and Java EE Security
PDF
Spring Security in Action 1st Edition Laurentiu Spilca
PDF
Java Web Application Security - Jazoon 2011
PDF
Java Web Application Security - UberConf 2011
PPTX
Spring Security
PDF
Spring Security
PDF
Spring5 hibernate5 security5 lab step by step
PPTX
Java EE 8 security and JSON binding API
Building layers of defense for your application
Spring Security in Action 1st Edition Laurentiu Spilca Spilcă Laurenţiu
Spring security jwt tutorial toptal
Spring Security services for web applications
Spring security4.x
Spring Security Introduction
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Java Web Application Security - Denver JUG 2013
SCWCD : Secure web : CHAP : 7
SCWCD : Secure web
Defending web applications v.1.0
Spring Security 5
Utilize the Full Power of GlassFish Server and Java EE Security
Spring Security in Action 1st Edition Laurentiu Spilca
Java Web Application Security - Jazoon 2011
Java Web Application Security - UberConf 2011
Spring Security
Spring Security
Spring5 hibernate5 security5 lab step by step
Java EE 8 security and JSON binding API

Recently uploaded (20)

PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPTX
Introduction to Artificial Intelligence
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
top salesforce developer skills in 2025.pdf
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
Transform Your Business with a Software ERP System
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Design an Analysis of Algorithms I-SECS-1021-03
ISO 45001 Occupational Health and Safety Management System
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Introduction to Artificial Intelligence
How to Choose the Right IT Partner for Your Business in Malaysia
Design an Analysis of Algorithms II-SECS-1021-03
top salesforce developer skills in 2025.pdf
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
CHAPTER 2 - PM Management and IT Context
Transform Your Business with a Software ERP System
Which alternative to Crystal Reports is best for small or large businesses.pdf
PTS Company Brochure 2025 (1).pdf.......
Odoo POS Development Services by CandidRoot Solutions
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
How to Migrate SBCGlobal Email to Yahoo Easily
2025 Textile ERP Trends: SAP, Odoo & Oracle
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025

Spring4 security

  • 1. 1 Spring SecuritySpring Security Sang ShinSang Shin JPassion.comJPassion.com ““Code with Passion!”Code with Passion!”
  • 2. 2 Topics • Spring security overview • Security configuration • Remember me • CSRF
  • 4. 4 Spring Security Features • Provides portable and comprehensive security services for Java- based enterprise software applications • Handles “authentication” and “authorization” > “Authentication” is the process of establishing “a principal is who he claim to be” (a “principal” could be a user, device or some other system) > “Authorization” (“access-control”) refers to the process of deciding “whether a principal is allowed to perform an action or access a resource”
  • 5. 5 Spring Authentication Support • HTTP BASIC authentication headers • Form-based authentication (for simple user interface needs) • HTTP Digest authentication headers • HTTP X.509 client certificate exchange • LDAP (a very common approach to cross-platform authentication needs, especially in large environments) • OpenID authentication > OpenID allows you to use an existing account to sign in to multiple websites, without needing to create new passwords • Authentication based on pre-established request headers (such as Computer Associates SiteMinder)
  • 6. 6 Spring Authentication Support (Cont) • JA-SIG Central Authentication Service (otherwise known as CAS, which is a popular open source single sign-on system) • Transparent authentication context propagation for Remote Method Invocation (RMI) and HttpInvoker (a Spring remoting protocol) • Automatic "remember-me" authentication (so you can tick a box to avoid re-authentication for a predetermined period of time) • Anonymous authentication (allowing every unauthenticated call to automatically assume a particular security identity) • Run-as authentication (which is useful if one call should proceed with a different security identity) • Java Authentication and Authorization Service (JAAS) • Java EE container authentication (so you can still use Container Managed Authentication if desired) • Kerberos
  • 7. 7 3rd Party Authentication Support • Java Open Source Single Sign On (JOSSO) • OpenNMS Network Management Platform • AppFuse • AndroMDA • Mule ESB • Direct Web Request (DWR) • Grails • Tapestry • JTrac • Jasypt • Roller • Elastic Path • Atlassian Crowd
  • 8. 8 Authorization Support • Three main areas where authorization can be applied > Authorizing web requests > Authorizing whether methods can be invoked > Authorizing access to individual domain object instances
  • 10. 10 Security Configuration Example @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/index.html").permitAll() .antMatchers("/helloworld/sayspring").hasAnyRole("SUPERVISOR") .antMatchers("/helloworld*").hasAnyRole("USER") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .failureUrl("/login?error") .defaultSuccessUrl("/default-target-after-login", false) .permitAll() .and() .logout() .logoutSuccessUrl("/") .permitAll() .and() .exceptionHandling() .accessDeniedPage("/access-denied"); } authorization form login logout security exception handling
  • 11. 11 Authentication Manager & Provider • Authentication manger is a container of multiple authentication providers • Different types of authentication providers are available > JAAS, LDAP, ActiveDirectory, OpenID, etc > Each authentication provider is an implementation of AuthenticatiodnProvider interface
  • 12. 12 Spring MVC Security Configuration @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { ... @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("rod").password("rod").roles("SUPERVISOR", "USER", "TELLER").and() .withUser("dianne").password("dianne").roles("USER", "TELLER").and() .withUser("scott").password("scott").roles("USER").and() .withUser("peter").password("peter").roles("USER").and() .withUser("sang").password("sang").roles("USER"); }
  • 13. 13 Lab:Lab: Exercise 1: Step by step of securingExercise 1: Step by step of securing a web applicationa web application 4957_spring4_security.zip4957_spring4_security.zip
  • 14. 14 Adding a Password Encoder • Password data can be encoded using a hashing algorithm through Password encoding class such as BCryptPasswordEncoder PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String hashedPassword = passwordEncoder.encode(yourpassword);
  • 15. 15 Protection from Dictionary Attacks • When using hashed passwords, it's also a good idea to use a salt value to protect against dictionary attacks and Spring Security supports this too. > Salt is random data that is used as an additional input to a one- way function that hashes a password • Ideally you would want to use a randomly generated salt value for each user, but you can use any property of the UserDetails object which is loaded by your UserDetailsService. PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String hashedPassword = passwordEncoder.encode(yourpassword, saltSource.getSalt(user));
  • 17. 17 Remember me • The Remember-me feature allows a user to access secured resources after session timeout without re-logging in > By default, the session timeout is set to 30 minutes but can be reconfigured.
  • 18. 18 Remember me Server side configuration @Configuration @EnableWebMvcSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/index.html").permitAll() .antMatchers("/helloworld/sayspring").hasAnyRole("SUPERVISOR") .antMatchers("/helloworld*").hasAnyRole("USER") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .failureUrl("/login?error") .defaultSuccessUrl("/default-target-after-login", false) .permitAll() .and() .logout() .logoutSuccessUrl("/") .permitAll() .and() .rememberMe() .tokenValiditySeconds(864000) .and() .exceptionHandling() .accessDeniedPage("/access-denied"); }
  • 19. 19 Remember me Client side Request <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <title>Spring Security Example</title> </head> <body> <h3>My custom login page</h3> <c:if test="${not empty SPRING_SECURITY_LAST_EXCEPTION}"> <font color="red"> Your login attempt was not successful due to <c:out value="$ {SPRING_SECURITY_LAST_EXCEPTION.message}" />. </font> </c:if> <br/><br/> <form action="login" method="post"> <label>User Name : </label> <input type="text" name="username" /> <br /> <label>Password: </label> <input type="password" name="password" /> <br /> <label>Remember me </label> <input type="checkbox" name="remember-me" /> <input type="submit" value="Sign In" /> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> </form> </body> </html>
  • 20. 20 Displaying Remember-me authentication <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <title>My title</title> </head> <body> <h1> You are logged in as <c:out value="${pageContext.request.remoteUser}" /> </h1> <h2>${message1}</h2> <sec:authorize access="isRememberMe()"> <h2># This user logged in by "Remember Me Cookies".</h2> </sec:authorize> <sec:authorize access="isFullyAuthenticated()"> <h2># This user logged in by ""username/password.</h2> </sec:authorize> <form:form action="/logout" method="post"> <input type="submit" value="Sign Out" /> </form:form> </body> </html> Spring provides methods for checking if the authentication is done via Remember-me or via full authentication
  • 21. 21 Lab:Lab: Exercise 2: Remember meExercise 2: Remember me 4957_spring4_security.zip4957_spring4_security.zip
  • 23. 23 CSRF Example Scenario • The attack works by including a link or script in a page that accesses a site to which the user is known (or is supposed) to have been authenticated • For example, one user, Alice, might be browsing a chat forum where another user, Mallory, has posted a message. Suppose that Mallory has crafted an HTML image element that references an action on Alice's bank's website (rather than an image file) Mallory: Hello Alice! Look here: <img src="http://bank.example.com/withdraw?account=Alice&amount=1000000&for=Mallory"> • If Alice's bank keeps her authentication information in a cookie, and if the cookie hasn't expired, then the attempt by Alice's browser to load the image will submit the withdrawal form with her cookie, thus authorizing a transaction without Alice's approval. source: https://en.wikipedia.org/wiki/Cross-site_request_forgery#Example_and_characteristics
  • 24. 24 CSRF Prevention via CSRF Token • Most CSRF prevention techniques work by embedding additional authentication data such as CSRF token into requests that allows the web application to detect requests from unauthorized locations • You should use CSRF protection for any request that could be processed by a browser by normal users > If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection. • On the server side, Spring security automatically enables CSRF support • From the client side, CSRF token should be included in all PATCH, POST, PUT, and DELETE methods > This can be done using the _csrf request attribute to obtain the current CsrfToken.
  • 25. 25 CSRF Prevention work at Client • If you are using Spring MVC <form:form> tag or Thymeleaf, the CsrfToken is automatically included for you • Otherwise, you have to explicitly include it (as shown below) <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head><title>Hello World2!</title></head> <body> <h1> User <c:out value="${pageContext.request.remoteUser}" /> is logged in! </h1> <h1>No CSRF error expected since CSRF token is explicitly sent</h1> <form action="/logout" method="post"> <input type="submit" value="Sign Out" /> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> </form> </body> </html> Since this page is not using Spring MVC <form:form> tag nor Thymeleaf, CSRF token needs to be explicitly sent
  • 26. 26 Lab:Lab: Exercise 3: CSRFExercise 3: CSRF 4957_spring4_security.zip4957_spring4_security.zip
  • 27. 27 Code with Passion!Code with Passion! JPassion.comJPassion.com 27