Spring MVC security with In-Memory authentication example using Java configuration

STEP 1:- Open Eclipse and Create Dynamic Web Project named SpringSecurityBasicJavaConfig

STEP 2:- Make sure you use Target Runtime as Apache Tomcat 7.0 and Dynamic web module version as 3.0.

STEP 3:- copy below jars to WEB-INF/lib folder.
  • commons-logging-1.2.jar
  • spring-aop-4.1.4.RELEASE.jar
  • spring-beans-4.1.4.RELEASE.jar
  • spring-context-4.1.4.RELEASE.jar
  • spring-core-4.1.4.RELEASE.jar
  • spring-expression-4.1.4.RELEASE.jar
  • spring-security-config-4.0.2.RELEASE.jar
  • spring-security-core-4.0.2.RELEASE.jar
  • spring-security-web-4.0.2.RELEASE.jar
  • spring-web-4.1.4.RELEASE.jar
  • spring-webmvc-4.1.4.RELEASE.jar
STEP 4:- Create Spring security configuration file.
  • Package: com.tutorialsdesk.config
  • Filename: SecurityConfig.java
package com.tutorialsdesk.config;

import org.springframework.beans.factory.annotation.Autowired;
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;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 
 @Autowired
 public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
 auth.inMemoryAuthentication().withUser("user").password("123456").roles("USER");
 auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN","API");
 auth.inMemoryAuthentication().withUser("apiuser").password("123456").roles("API");
 }

 @Override
 protected void configure(HttpSecurity http) throws Exception {

 http.authorizeRequests()
 .antMatchers("/").permitAll()
 .antMatchers("/home").permitAll()
 .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
 .antMatchers("/api/**").access("hasRole('ROLE_ADMIN') or
hasRole('ROLE_API')")
 .and().formLogin()
 .and().exceptionHandling().accessDeniedPage("/Access_Denied");
 
 }
 
}

STEP 5:- Create a class extends AbstractSecurityWebApplicationInitializer, it will load the springSecurityFilterChain automatically.
  • Package: com.tutorialsdesk.config.core
  • Filename: SpringSecurityInitializer.java
package com.tutorialsdesk.config.core;

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

public class SpringSecurityInitializer extends
 AbstractSecurityWebApplicationInitializer {

}
STEP 6:- Create Spring MVC configuration file. A Config class, define the view’s technology and imports above SecurityConfig.java.
  • Package: com.tutorialsdesk.config
  • Filename: AppConfig.java
package com.tutorialsdesk.config;

import org.springframework.context.annotation.Bean;
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;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@EnableWebMvc
@Configuration
@ComponentScan({ "com.tutorialsdesk.controller" })
@Import({ SecurityConfig.class })
public class AppConfig {

 @Bean
 public InternalResourceViewResolver viewResolver() {
 InternalResourceViewResolver viewResolver 
 = new InternalResourceViewResolver();
 viewResolver.setViewClass(JstlView.class);
 viewResolver.setPrefix("/WEB-INF/views/");
 viewResolver.setSuffix(".jsp");
 return viewResolver;
 }
}

STEP 7:- Create a Sevlet Initializer class, to load everything.
  • Package: com.tutorialsdesk.config.core
  • Filename: SpringMvcInitializer.java
package com.tutorialsdesk.config.core;

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

import com.tutorialsdesk.config.AppConfig;

public class SpringMvcInitializer extends
 AbstractAnnotationConfigDispatcherServletInitializer {

 @Override
 protected Class<?>[] getRootConfigClasses() {
 
 return new Class[] { AppConfig.class };
 }

 @Override
 protected Class<?>[] getServletConfigClasses() {
 
 return null;
 }

 @Override
 protected String[] getServletMappings() {
 
 return new String[] { "/" };
 }

}

STEP 8 :- Create Controller Class.
  • Package: com.tutorialsdesk.controller
  • Filename: HelloWorldController.java
package com.tutorialsdesk.controller;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HelloWorldController {

 @RequestMapping(value = { "/", "/home" }, method =
RequestMethod.GET)
 public String homePage(ModelMap model) {
 model.addAttribute("greeting", "Hi, Welcome to mysite. ");
 return "welcome";
 }
 
 @RequestMapping(value = "/admin", method = RequestMethod.GET)
 public String adminPage(ModelMap model) {
 model.addAttribute("user", getPrincipal());
 return "admin";
 }
 
 @RequestMapping(value = "/api", method = RequestMethod.GET)
 public String dbaPage(ModelMap model) {
 model.addAttribute("user", getPrincipal());
 return "api";
 }
 
 @RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
 public String accessDeniedPage(ModelMap model) {
 model.addAttribute("user", getPrincipal());
 return "accessDenied";
 }
 
 private String getPrincipal(){
 String userName = null;
 Object principal =
SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 
 
 if (principal instanceof UserDetails) {
 userName = ((UserDetails)principal).getUsername();
 } else {
 userName = principal.toString();
 
 }
 return userName;
 }
}

STEP 9 :- Create jsp files in /WebContent/WEB-INF/views folder
  • Filename: welcome.jsp
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
 <title>HelloWorld page</title>
</head>
<body>
 Greeting : ${greeting}
 This is a welcome page.
 <br/>
 <br/>
 <br/>
<a href="<c:url value="/admin" />">Admin
Page</a> ( Only Admin user can access this )
<br/>
<br/>
<a href="<c:url value="/api" />">API Page</a>
( Admin or API user can access this )

</body>
</html>

  • Filename: admin.jsp
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
 <title>HelloWorld Admin page</title>
</head>
<body>
 Dear <strong>${user}</strong>, Welcome to Admin Page.
 
 
<form action="logout" method="post">
 <input type="submit" value="Logout" />
 <input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}"/>
</form>
</body>
</html>

  • Filename: api.jsp
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
 <title>DBA page</title>
</head>
<body>
 Dear <strong>${user}</strong>, Welcome to API Page.
 
 <form action="logout" method="post">
 <input type="submit" value="Logout" />
 <input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}"/>
</form>
</body>
</html>

  • Filename: accessDenied.jsp
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
 <title>AccessDenied page</title>
</head>
<body>
 Dear <strong>${user}</strong>, You are not authorized to access this page
 <form action="logout" method="post">
 <input type="submit" value="Logout" />
 <input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}"/>
</form>
 
</body>
</html>

STEP 10 :- Run your project enter below URL in your browser

http://localhost:8080/SpringSecurityBasicJavaConfig/

Keep visiting TutorialsDesk for more tutorials and practical programming examples on Spring MVC. Hope we are able to explain you Spring MVC security with In-Memory authentication example using Java configuration Example, if you have any questions or suggestions please write to us using contact us form. 

Please share us on social media if you like the tutorial.
SHARE
    Blogger Comment
    Facebook Comment