27
1 Spring Security Spring Security Sang Shin Sang Shin JPassion.com JPassion.com Code with Passion!” Code with Passion!”

Spring4 security

Embed Size (px)

Citation preview

1

Spring SecuritySpring Security

Sang ShinSang ShinJPassion.comJPassion.com

““Code with Passion!”Code with Passion!”

2

Topics• Spring security overview• Security configuration• Remember me• CSRF

3

Spring Security Spring 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

Security Security ConfigurationConfiguration

10

Security Configuration Example@Configuration@EnableWebSecuritypublic 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@EnableWebSecuritypublic 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 securing Exercise 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@EnableWebMvcSecuritypublic 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 methodsfor checking if the authentication

is done via Remember-meor via full authentication

21

Lab:Lab:

Exercise 2: Remember meExercise 2: Remember me4957_spring4_security.zip4957_spring4_security.zip

22

CSRF (Cross-SiteCSRF (Cross-SiteRequest 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 usingSpring MVC <form:form> tag norThymeleaf, CSRF token needs

to be explicitly sent

26

Lab:Lab:

Exercise 3: CSRFExercise 3: CSRF4957_spring4_security.zip4957_spring4_security.zip

27

Code with Passion!Code with Passion!JPassion.comJPassion.com

27