Spring Security - Explained

Spring security primarily focuses on providing authentication and authorization to the applications. 

Spring security enables security as layers. 1st at the URL level and then at the method level. So, even if some security intrusion passes at the URL level. It can be blocked 

at the method level later.

We can enable this Spring security either by using XML namespaces or annotations.
In this post, I have mentioned the steps to enable the spring security at the URL level in an application.

Basic setup:

 public class SpringSecurityInitializer
 extends AbstractSecurityWebApplicationInitializer {  
 }  

Extending a class with AbstractSecurityWebApplicationInitializer creates the below filter mapping in web.xml and also add security.xml to ContextConfigLocation. 


 <filter>  
 <filter-name>springSecurityFilterChain</filter-name>  
 <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
 </filter>  
 <filter-mapping>  
 <filter-name>springSecurityFilterChain</filter-name>  
 <url-pattern>/*</url-pattern>  
 </filter-mapping>  



How filters works??


The general behaviour of Servlet filter is to intercept the request before reaching the Servlet. As this behaviour is analogous to AOP. Spring has choosen this to build its security framework


In the above xml, springSecurityFilterChain is configured as a Servlet Filter.

It works as an interceptor(proxy) for all our Controlllers. It means every requests made to an application has to go through this filter before reaching the controller. 
So, before reaching controllers Spring can check the authenticity of the request and delegates the request to the Controller if the request is authenticated.

In Spring Security framework,  springSecurityFilterChain is not the only filter which handles Spring security. Internally, springSecurityFilterChain calls a set of filters (which are responsible for URL interception, form authentication, logout handling, appending CSRF token, etc.,) before delegating the user's request  to the controller. 


Going back to where we have started, we have a web component registered from spring security f/w and spring security is plugged in to our application.


Basically, spring security provides security infrastructure to our application. For the infrastructure to work,we have to provide certain i/ps which spring security expects. 


This is how we provide the i/p!!!!!



  @EnableWebSecurity   
  public class SecurityConfig extends WebSecurityConfigurerAdapter {   
    @Override   
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {   
       auth   
       .inMemoryAuthentication()   
       .withUser("naresh")   
       .password("naresh")   
       .roles("USER");   
    }      
    @Override   
    protected void configure(HttpSecurity http) throws Exception {   
       http.authorizeRequests()   
         .antMatchers("/admin/**").hasRole("ADMIN")   
         .anyRequest().authenticated()   
            .and()   
         //.httpBasic();   
         .formLogin()   
         //.loginPage("/customLogin")   
         //.permitAll()   
            .and()   
         .logout().logoutSuccessUrl("/login?logout").invalidateHttpSession(true)   
            .and()   
         //csrf()   
    }   
  }   


1. Location of the user details/repository


protected void configure(AuthenticationManagerBuilder auth) throws Exception 

Builds the authentication details of the user using AuthenticationManagerBuilder. However, this can be configured at the memory, database, LDAP, etc., level also.
In the above example we used in-memory authentication.

XML look a like of the configure(AuthenticationManagerBuilder auth) method

 <authentication-manager >  
     <authentication-provider>  
       <user-service>  
         <user name="naresh" password="naresh" authorities="USER" />  
       </user-service>  
     </authentication-provider>  
 </authentication-manager>  


2. Which URLs/resources to authenticate?


protected void configure(HttpSecurity http) throws Exception 

Builds the security information of URLs/resources using HttpSecurity Class.

How Spring decodes this method??

http.authorizeRequests() - Authorize the request
antMatchers("/admin/**").hasRole("ADMIN") - Restrict the  access to /admin page(s) only for the admin role users
anyRequest().authenticated() - Authenticate every other request which does not match with the /admin.
httpBasic() - Authenticate user using basic authentication
formLogin() - Authenticate user using form based login and also provide a login page for authentication iccase a non login user access the application.
logout() - provides logout support 
csrf() -authentication should be done with the help of CSRF token to prevent CRSF(Cross site request forgery) attack

XML look a like of the configure(HttpSecurity http) method
<http>
<intercept-url pattern="/**" access="authenticated"/>
<form-login />
<http-basic />

</http>

And finally, we include import the security.xml bean definitions to an existing servlet-context.xml using the below code.


 @EnableWebMvc  
 @Configuration  
 @ComponentScan(basePackages ={"com.javarephrased.springsecurity.*"})  
 @Import({SecurityConfig.class})  
 public class ApplicationConfigClass {  
      @Bean  
      public InternalResourceViewResolver viewResolver(){  
           InternalResourceViewResolver viewResolver =   
                     new InternalResourceViewResolver();  
           viewResolver.setViewClass(JstlView.class);  
           viewResolver.setPrefix("/WEB-INF/views/");  
           viewResolver.setSuffix(".jsp");  
           return viewResolver;  
      }  
 }  

The above code creates a servlet-context.xml which is mvc enabled and looks for the controller annotations in com.javarephrased.springsecurity.*
@Import({SecurityConfig.class}) annotation in the above class imports security.xml beans to servlet-context.xml

In the next post, I will target some more features of Spring security......

Happy Reading!!!!

Comments

Popular posts from this blog

Distributed database design using CAP theorem

SQL Analytical Functions - Partition by (to split resultset into groups)

Easy approach to work with files in Java - Java NIO(New input output)