Sunday, December 30, 2018

Spring Security Form Login

Spring Security Form Login

1. Introduction

This article is going to focus on Login with Spring Security.The implementation of this Spring Login tutorial can be found in the GitHub project – this is an Eclipse based project, so it should be easy to import and run as it is.


Demo:http://localhost:8080/SpringSecurity-csrf/


 

On successful login,user is redirected to the next page.

 Directory Structure:

2. The Maven Dependencies

  1. spring-security-core : It contains core authentication and access-control classes and interfaces.
  2. spring-security-web : It contains filters and related web-security infrastructure code. It also enable URL based security which we are going to use in this demo.
  3. spring-security-config : It contains the security namespace parsing code. You need it if you are using the Spring Security XML file for configuration.


3. Spring Security Java Configuration

Let’s start by creating a Spring Security configuration class that extends WebSecurityConfigurerAdapter. By adding @EnableWebSecurity,we get Spring Security and MVC integration support.

We can have multiple authentication managers defined in the spring security configuration. I have defined in-memory-auth for in-memory authentication.

DemoSecurityConfig.java


package com.demo.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.core.userdetails.User;
import org.springframework.security.core.userdetails.User.UserBuilder;

@Configuration
@EnableWebSecurity
public class DemoSecurityConfig extends WebSecurityConfigurerAdapter {

               @Override
               protected void configure(AuthenticationManagerBuilder auth) throws Exception {
                              // add our users for in memory authentication
                              UserBuilder users = User.withDefaultPasswordEncoder();

                              auth.inMemoryAuthentication().withUser(users.username("john").password("test123").roles("EMPLOYEE"))
                                                            .withUser(users.username("mary").password("test123").roles("MANAGER"))
                                                            .withUser(users.username("susan").password("test123").roles("ADMIN"));

               }

               // custom login page
               @Override
               protected void configure(HttpSecurity http) throws Exception {
                              http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage("/showMyLoginPage")
                                                            .loginProcessingUrl("/authenticateTheUser").permitAll()
                                                            .and().logout().permitAll();
               }

}
 

 2. DemoAppConfig.java

package com.demo.config;

import org.codehaus.plexus.component.annotations.Component;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;


@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.demo")
public class DemoAppConfig {
               //define a bean for ViewResolver
              
               @Bean
               public ViewResolver viewResolver() {
                              InternalResourceViewResolver viewResolver=new InternalResourceViewResolver();
                              viewResolver.setPrefix("/WEB-INF/view/");
                              viewResolver.setSuffix(".jsp");
                             
                              return viewResolver;
                             
               }

}
 

3.MySpringMvcDispatcherServletInitializer.java


package com.demo.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{

       @Override
       protected Class<?>[] getRootConfigClasses() {
             // TODO Auto-generated method stub
             return null;
       }

       @Override
       protected Class<?>[] getServletConfigClasses() {
             // TODO Auto-generated method stub
             return new Class[] {DemoAppConfig.class};
       }

       @Override
       protected String[] getServletMappings() {
             // TODO Auto-generated method stub
             return new String[] {"/"};
       }

}




4.SecuirtyWebApplicationInitializer.java

package com.demo.config;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SecuirtyWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

}

 

 

Controller Class

i.LoginController.java

package com.demo.config;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SecuirtyWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

}

 
 ii.DemoController.java

package com.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class DemoController {
              
               @GetMapping("/")
               public String showHome() {
                              return "home";
               }

}
  

Best practice is to use the Spring MVC Form tag <form:form>

- Provides automatic support for security defenses.
- Spring security protects against Cross-site request
Forgery(CSRF)



CSRF- A security attack where an evil website
tricks you into executing an action
on a web application that you are currently logged in.

CSRF protection:

- Embed addtional authentication data/token into all HTML forms.
- On subsequent request ,wen app wil verify token before processing.

Spring security filter

- Spring security uses the syschronizer token pattern
- Each request includes a sesion cookie and randomly
generated token.

- For request processing,Spring security verify token
before processing.

<form:form> automatically adds CSRF token.

Example:

<input type="hidden" name="_csrf" value="3882f111-b8e8-45fd-afd2-d0696095f03a" />
 
Manually add CSRF:
 
<input type="hidden" name="${_csrf.parameterName}" value="{_csrf_token}"/>

Secure URL based on roles.

The most common approach to specifying a URL is through antMatchers.

Spring Security Role Based Access

i.Create Supporting Controller code and View pages
ii.Create view pages
Home Page
-/Leader  (role-MANAGER)
-/systems (role-ADMIN)

iii. Update your Spring security java configuration file.


The implementation of this Spring security Role Based Access tutorial can be found in the GitHub project 

General syntax

antMatchers(<<add path to math on>>).hasRole(<<authorized role>>)

Restrict access to a given path "/systems/**"

For multiple roles check

antMatchers(<<add path to math on>>).hasAnyRole(<<authorized role>>)

antMatchers("/").hasRole("EMPLOYEE")
antMatchers("/leaders/**").hasRole("MANAGER")
antMatchers("/systems/**").hasRole("ADMIN")

Custom Access Denied Page

Access Denied- You are not authorized to access this resource. 

 


 Spring security JSP tags

<security:authorize access="hasRole('MANAGER')">
<a href="${pageContext.request.contextPath}/leaders">LeaderShip Meeting(Only for Manager peers)</a>
<br>
</security:authorize >

- Only show section for users with MANAGER role





















0 comments:

Post a Comment