Spring Security: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
Line 156: Line 156:
                         .logoutSuccessUrl("/");
                         .logoutSuccessUrl("/");
         }
         }
</syntaxhighlight>
=Common Security Threats=
==Introduction==
Spring Security provides default headers which can be customised
==Caching==
By default the headers turn off caching to avoid data being left behind in the browser. You can of course switch this on and it is recommended you do this on a page by page approach. To do this
<syntaxhighlight lang="java" highlight="6">
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
                http
                  .headers().cacheControl().disable()
                  .mvcMatchers("/login").permitAll()
...
</syntaxhighlight>
</syntaxhighlight>

Revision as of 10:44, 28 March 2021

Introduction

Authentication

Spring Security Provides out of the box

  • Basic Web From Authentication
  • Ouath2 and OpenID Connect
  • LDAP
  • JWT JSon Web Tokens

Protection

Includes strategies for

  • Session Fixation (Reusing of the Session ID)
  • Clickjacking(UI redress attack)
  • Cross Site Scripting
  • Cross Site Request Forgery (CSRF)

Session Fixation (Reusing of the Session ID)

Session Fixation is an attack that permits an attacker to hijack a valid user session. The attack explores a limitation in the way the web application manages the session ID, more specifically the vulnerable web application. When authenticating a user, it doesn’t assign a new session ID, making it possible to use an existent session ID. The attack consists of obtaining a valid session ID (e.g. by connecting to the application), inducing a user to authenticate himself with that session ID, and then hijacking the user-validated session by the knowledge of the used session ID. The attacker has to provide a legitimate Web application session ID and try to make the victim’s browser use it.

Clickjacking(UI redress attack)

This is when an attacker uses multiple transparent or opaque layers to trick a user into clicking on a button or link on another page when they were intending to click on the top level page. Thus, the attacker is “hijacking” clicks meant for their page and routing them to another page, most likely owned by another application, domain, or both.

Cross Site Request Forgery (CSRF)

Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they’re currently authenticated. With a little help of social engineering (such as sending a link via email or chat), an attacker may trick the users of a web application into executing actions of the attacker’s choosing. If the victim is a normal user, a successful CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address, and so forth. If the victim is an administrative account, CSRF can compromise the entire web application.

Cross Site Scripting

Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they’re currently authenticated. With a little help of social engineering (such as sending a link via email or chat), an attacker may trick the users of a web application into executing actions of the attacker’s choosing. If the victim is a normal user, a successful CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address, and so forth. If the victim is an administrative account, CSRF can compromise the entire web application.

Spring Security Projects

The framework is broken own into different projects

  • Spring Security Core
  • Spring Security Config
  • Spring Security Test
  • Spring Security Web
  • Spring Security Oauth
  • Spring Security LDAP

Resources

https://github.com/wlesniak/spring-framework-securing-against-common-threats

Getting Started

Introduction

We can add security to a new project with

        <dependencies>
...
                <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-security</artifactId>
                </dependency>
        </dependencies>

Spring uses Filters on request like interceptors in Angular. The filter

Example 1

In the Spring Boot Docs we see [here]

@Configuration(proxyBeanMethods=false)
 @ConditionalOnClass(value=org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.class)
 @ConditionalOnMissingBean(value=org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.class)
 @ConditionalOnWebApplication(type=SERVLET)
public class SpringBootWebSecurityConfiguration

extends Object

For basic authentication we use the WebSecurityConfigurationAdapter. This supports Web and Basic Authentication (Crikey). Here we can extend the class and override the configure

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().anyRequests().authenticated()
            .and().httpBasic();
        }   
}

Example 2

Here is a more complicated example. We can see some basic operations. E.g. Endpoints when logging in and logging out.

public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
                http
                  .csrf()
                  .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                  .and()
                  .authorizeRequests()
                        
                  .mvcMatchers(HttpMethod.GET,"/","/index.html","/portfolio").permitAll()
                  .anyRequest().authenticated()
                  .and()
                  .formLogin()
                  .loginProcessingUrl("/api/login")
                  .and()
                  .logout()
                  .logoutUrl("/api/logout")
                  .logoutSuccessUrl("/");
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
                auth.inMemoryAuthentication().withUser("victoria").password(" 
                   {noop}password").roles("ADMIN")
                .and().withUser("dave").password("{noop}password").roles("USER");
        }

        @Override
        public void configure(WebSecurity web) throws Exception {
                web.ignoring().antMatchers("/css/**", "/webjars/**","/js/**");
        }

}

Success Handling

We can define our own Success Handler by

@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
 
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //do some logic here if you want something to be done whenever
        //the user successfully logs in.
 
        HttpSession session = httpServletRequest.getSession();
        User authUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        session.setAttribute("username", authUser.getUsername());
        session.setAttribute("authorities", authentication.getAuthorities());
 
        //set our response to OK status
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
 
        //since we have created our custom success handler, its up to us to where
        //we will redirect the user after successfully login
        httpServletResponse.sendRedirect("home");
    }
}

From here we can add the class to the formLogin method.

public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
                http
                .csrf()
                        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .and()
                .authorizeRequests()
                        .mvcMatchers(HttpMethod.GET,"/","/index.html","/portfolio").permitAll()
                        .anyRequest().authenticated()
                        .and()
                .formLogin()
                        .loginPage("/api/login").successHandler(new CustomAuthenticationSuccessHandler())
                .and()
                .logout()
                        .logoutUrl("/api/logout")
                        .logoutSuccessUrl("/");
        }

Common Security Threats

Introduction

Spring Security provides default headers which can be customised

Caching

By default the headers turn off caching to avoid data being left behind in the browser. You can of course switch this on and it is recommended you do this on a page by page approach. To do this

public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
                http
                  .headers().cacheControl().disable()
                  .mvcMatchers("/login").permitAll()
...