Home  >  Spring 4

Spring 4 MVC Security Annotation Login Example with Gradle

By Arvind Rai, December 20, 2014
Spring 4 MVC security annotation removes all the XML settings for security into java code. Defining authentication and authorization can be done in Java code now. In spring security, there are different classes that has been introduced which configure authentication and authorization. WebSecurityConfigurerAdapter and GlobalAuthenticationConfigurerAdapter are used in config class that configures authentication. AbstractSecurityWebApplicationInitializer configures DelegatingFilterProxy and ContextLoaderListener. AbstractAnnotationConfigDispatcherServletInitializer has methods that can be overridden to map URL and initialize config class.

Software Required to Run Example

To run the example we are using software as given.
1. JDK 6
2. Tomcat 7
3. Eclipse Juno
4. Gradle 2.0

Project Structure in Eclipse

Find the project structure in eclipse.
Spring 4 MVC Security Annotation Login Example with Gradle

WebSecurityConfigurerAdapter and GlobalAuthenticationConfigurerAdapter

WebSecurityConfigurerAdapter provides the base class for WebSecurityConfigurer. WebSecurityConfigurerAdapter has a method configure() that can be overridden to configure role and URL pattern. It also provides a default form login. In our security config class, there are two roles USER and ADMIN. There are two URL pattern one for admin and another USER.
SecurityConfig.java
package com.concretepage.config;  
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
@Configuration
@ComponentScan("com.concretepage")
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().
		antMatchers("/app/admin/**").access("hasRole('ROLE_ADMIN')").
		antMatchers("/app/user/**").access("hasRole('ROLE_USER')").
		and().formLogin();
	}
	@Configuration
	protected static class AuthenticationConfiguration extends
			GlobalAuthenticationConfigurerAdapter {
		@Override
		public void init(AuthenticationManagerBuilder auth) throws Exception {
			  auth.inMemoryAuthentication().withUser("ravan").password("ravan123").roles("USER");
			  auth.inMemoryAuthentication().withUser("ram").password("ram123").roles("ADMIN");

		}
	} 
}   
Find the another config class that can be used to define any application label bean.
AppConfig.java
package com.concretepage.config;  
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration 
@ComponentScan("com.concretepage") 
@EnableWebMvc   
@Import({ SecurityConfig.class })
public class AppConfig {  
}  

AbstractSecurityWebApplicationInitializer

AbstractSecurityWebApplicationInitializer provides the availability of DelegatingFilterProxy and ContextLoaderListener and are registered automatically.
SecurityInitializer.java
package com.concretepage.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}  

AbstractAnnotationConfigDispatcherServletInitializer

AbstractAnnotationConfigDispatcherServletInitializer registers dispatcher servlet. This class provides different methods getRootConfigClasses(), getServletConfigClasses() and getServletMappings() to configure config class and URL mapping.
WebAppInitializer.java
package com.concretepage.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer  {
    @Override
    protected Class<?>[] getRootConfigClasses() {
	return new Class[] { AppConfig.class };
    }
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    } 
} 

Controller Class to Serve Request and Response

In our controller class, we are using two methods which will map with two URL mapping, one for user and one for admin.
AppController.java
package com.concretepage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/app")
public class AppController {
	@RequestMapping("/admin")
	public @ResponseBody String getAdminInfo() {
		String msg ="Welcome to Admin.";
		return msg;
	}
	
	@RequestMapping("/user")
	public @ResponseBody String getUserInfo() {
		String msg ="Welcome to User.";
		return msg;
	}
}	
 

Jar Dependency Using Gradle

Find all JAR dependency for spring security with spring boot strap.
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'war'
archivesBaseName = 'Spring4'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
    compile 'org.springframework.boot:spring-boot-starter-web:1.1.5.RELEASE'
    compile 'org.springframework.boot:spring-boot-starter-security:1.1.5.RELEASE'
    compile 'org.springframework.ldap:spring-ldap-core:2.0.2.RELEASE'
    compile 'org.springframework.security:spring-security-ldap:3.2.5.RELEASE'
} 

Output UI

To test the application, there are two URL one is http://localhost:8080/Spring4-1/app/admin for admin and http://localhost:8080/Spring4-1/app/user for user. First access using admin URL. You will get the login form.
Spring 4 MVC Security Annotation Login Example with Gradle
If we enter wrong username and password, then below default message will be displayed.
Spring 4 MVC Security Annotation Login Example with Gradle
As we have configured an admin ram/ram123, login using this credentials. You will get welcome message.
Spring 4 MVC Security Annotation Login Example with Gradle
Now as admin is logged, if user URL is being tried to access, then below UI will be displayed.
Spring 4 MVC Security Annotation Login Example with Gradle

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS










Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us