# SPRING Security : Secure Web Application

In 
Published 2022-12-03

This tutorial explains to you how you can secure a Web Application with Spring 5.

In order to secure a Web Application using Spring Security 5, you need a Web Application first. My demo will start from my Spring MVC Web Application I have created before this article. You can see it here .

In order to secure the application above, I will add the following the pom.xml file:

The version of the artifact could be a more recent one, but I tested my application using 5.0.4.RELEASE.

Now you can add the security classes :

WebSecurityInitializer.java
package com.example.config;
 
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
 
public class WebSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
 
    //public WebSecurityInitializer() {
    //  super(WebSecurityConfig.class);
    //}
}
WebSecurityConfig
package com.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

    String encoded = passwordEncoder.encode("pass1");

    System.out.println("encoded="+encoded);

    auth.inMemoryAuthentication().passwordEncoder(NoOpPasswordEncoder.getInstance())
            .withUser("user").password("u").authorities("USER")
            .and()
            .withUser("admin").password("a").authorities("USER","ADMIN");
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/myLogout").permitAll()
            .antMatchers("/shared/**").permitAll()
            .antMatchers("/no-access/*").denyAll()
            .antMatchers("/secured/**").hasAuthority("USER")
            .antMatchers("/admin-content/**").hasAuthority("ADMIN")
            .and()
            .formLogin() //Default login
            .and()
            .logout().logoutSuccessUrl("/myLogout").permitAll()
            .and().csrf().disable();
  }
}

Add WebSecurityConfig.class into the MyAppStarter class :

package com.example.starter;
 
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.example.config.WebConfig;
import com.example.config.WebSecurityConfig;

public class MyAppStarter extends AbstractAnnotationConfigDispatcherServletInitializer{
 
    // Load database and spring security configurations
    @Override
    protected Class<!--?-->[] getRootConfigClasses() {
        return new Class[] { WebSecurityConfig.class};
    }
 
    // Load spring web configuration
    @Override
    protected Class<!--?-->[] getServletConfigClasses() {
        return new Class[] {WebConfig.class};
    }
 
    @Override
    protected String[] getServletMappings() {
        return new String[] {"/"};
    }
     
}

In addition to the start non-secured application I use an index.jsp and myLogout.jsp with the following definitions:

When you run the application, you will see the following index page:

When you click on "Logout" button you will see the logout page, and you will be logged out automatically:

When you click on a secured link you will the the default login page:

If you are logged in, you can access a secured page:

In my case, you cannot access the Page0 and for this reason you will see the following screen: