Here is Spring Security Example using Java Configuration.

Spring Security provides comprehensive security services for Java EE-based enterprise software applications. There is a particular emphasis on supporting projects built using The Spring Framework, which is the leading Java EE solution for enterprise software development. If you’re not using Spring for developing enterprise applications, we warmly encourage you to take a closer look at it. Some familiarity with Spring – and in particular dependency injection principles – will help you get up to speed with Spring Security more easily.

Technology

  1. Spring-MVC
  2. Spring-Security
  3. Tomcat 8
  4. Java 8
  5. Maven

Project Structure

Spring Security Example

Spring Security Example

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.springapp</groupId>
    <artifactId>spring-security-java-configuration</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>spring-security-java-configuration</name>
    <properties>
        <spring.version>4.3.4.RELEASE</spring.version>
        <spring.security.version>4.2.0.RELEASE</spring.security.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Spring Security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>spring-security-java-configuration</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 

WebConfig.Java

package com.javadeveloperzone.configs;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * Created by Subhash Lamba on 19-01-2017.
 */
public class WebConfigs extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringWebConfig.class};
    }
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringWebConfig.class};
    }
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

}

SpringWebConfig.java

package com.javadeveloperzone.configs;
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.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
 * Created by JavaDeveloperZone on 19-01-2017.
 */
@EnableWebMvc
@Configuration
@ComponentScan({"com.javadeveloperzone"})
@Import({ SpringSecurityWebConfig.class })
public class SpringWebConfig extends WebMvcConfigurerAdapter  {
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/pages/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}

SpringSecurityWebConfig.java

Create our Spring Security Java Configuration. The configuration creates a Servlet Filter known as the springSecurityFilterChain which is responsible for all the security (protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, etc) within your application. You can find the most basic example of a Spring Security Java Configuration below:

package com.javadeveloperzone.configs;
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;
/**
 * Created by JavaDeveloperZone on 18-03-2017.
 */
@Configuration
@EnableWebSecurity
public class SpringSecurityWebConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("javadeveloperzone").password("javadeveloperzone").roles("USER");
        auth.inMemoryAuthentication().withUser("javadeveloperzone1").password("javadeveloperzone1").roles("ADMIN");
        auth.inMemoryAuthentication().withUser("javadeveloperzone2").password("javadeveloperzone2").roles("CLIENT");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/admin/home")
                .permitAll()
                .and()
                .authorizeRequests()
                .anyRequest().authenticated();
        http.csrf().disable();              // enable if require csrf protection
        http.logout().logoutSuccessUrl("/logoutSuccess").permitAll();
        http.sessionManagement().maximumSessions(1).expiredUrl("/logoutSuccess");
    }
}

SecurityWebApplicationInitialzer.java

If we were using Spring elsewhere in our application we probably already had a WebApplicationInitializer that is loading our Spring Configuration. If we use the previous configuration we would get an error. Instead, we should register Spring Security with the existing ApplicationContext. For example, if we were using Spring MVC our SecurityWebApplicationInitializer would look something like the following:

package com.javadeveloperzone.configs;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
/**
 * Created by Java Developer Zone on 18-03-2017.
 */
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: Java Developer Zone
  Date: 18-03-2017
  Time: 07:34
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title></title>
</head>
<body>
<form name='f' action='/login' method='POST'>
    User<input type='text' name='username' value=''>
    Password:<input type='password' name='password'/>
    <%--<input type="hidden"
           name="${_csrf.parameterName}"
           value="${_csrf.token}"/>--%>
    <input name="submit" type="submit" value="Login"/>
</form>
</body>
</html>

home.jsp

<%--
  Created by IntelliJ IDEA.
  User: Lenovo
  Date: 18-03-2017
  Time: 11:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title></title>
</head>
<body>
    ${message}
    Click here to logout : <a href="/logout" >logout</a>
</body>
</html>

Output:

Login Page:
Spring Security Example Login

Spring Security Example Login

Home Page After Login:
Spring Security Example Home

Spring Security Example Home

References:

https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/

 

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *