Thursday, April 26, 2018

Spring Security and Spring Boot Setup in Java Web Application

Features:

LDAP authentication, authorization, role-based access control,  remembers the password, URL protection, concurrent active sessions management 

Steps to Add Spring Security:

1.       Declare a delegating proxy filter in web.xml or using annotations.
2.       Add the ContextLoaderListener in web.xml or using annotations.
3.       Provide actual security constraints(security chain filter) on applicationContext-Security.xml or using annotations

Internal Flow of Spring Security:

1.       Filters are created, maintained and destroyed by Servlet Container.
2.       Web Container initializes the declared filters by calling their init(FilterConfig config) method.
3.       Filter  then delegates the actual pre-processing and post processing task to Spring Aware Filter implementations provided by Spring Framework

Steps to Call Spring Security Flow

1.       Every time a request or response comes and matches the URL pattern of the filter then Servlet container calls the DelegatingFilterProxy's doFilter() method for the request and response filtering.
2.       doFilter method has access to ServletRequest,ServletResponse and a FilterChain object, which means it can modify request headers,response headers and response body before sending the request to Servlet response to Client.
3.       Filter Chain Object has been used to further routing.

Version:

Spring Boot Version: 1.5.12
Java Version:8

Setting Up Eclipse Workspace:

1.       Create a simple maven project in Eclipse
2.       Add the following spring-boot project
                <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/xsd/maven-4.0.0.xsd">
                <modelVersion>4.0.0</modelVersion>
                <groupId>com.deepdiveonjava</groupId>
                <artifactId>SpringSecurityPOC</artifactId>
                <version>0.0.1-SNAPSHOT</version>
                <parent>
                                <groupId>org.springframework.boot</groupId>
                                <artifactId>spring-boot-starter-parent</artifactId>
                                <version>1.5.12.RELEASE</version>
                </parent>
      <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
      </properties>            
<!-- Add typical dependencies for a web application -->
                <dependencies>
                                <dependency>
                                                <groupId>org.springframework.boot</groupId>
                                                <artifactId>spring-boot-starter-web</artifactId>
                                </dependency>
 <dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
                </dependencies>
                <!-- Package as an executable jar -->
                <build>
                                <plugins>
                                                <plugin>
                                                                <groupId>org.springframework.boot</groupId>
                                                                <artifactId>spring-boot-maven-plugin</artifactId>
                                                </plugin>
                                </plugins>
                </build>
</project>
3.       Create the main class MyApplication:
@SpringBootApplication
public class MyApplication {
                public static void main(String[] args) {
                                // TODO Auto-generated method stub
                                SpringApplication.run(MyApplication.class, args);

                }

}
4.       Add WebSecurityConfig changes:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//@Bean tag means it will add reference variable of                userDetailsService of type UserDetailsService in //Application context
        @Bean
        public UserDetailsService userDetailsService()
        {
                        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
                        manager.createUser(User.withUsername("rohit").password("jaimatadi").roles("USER").build());
                        return manager;
        }

}
5.       Add the SecurityWebApplicationInitializer in the project
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer{
        public SecurityWebApplicationInitializer()
        {
                        super(WebSecurityConfig.class);
        }

}
6.       Add WebController in the project:
@RestController
@RequestMapping(value = "/webcontroller")
public class WebController {
       
        @RequestMapping("/hello")
        public Map<String, Object> helloWorld() {
                        Map<String,Object> responseMap = new HashMap<String,Object>();
                        Map<String,Object> statusMap = new HashMap<String,Object>();
                        responseMap.put("id", "World");
                        statusMap.put("status", "Success");
                        statusMap.put("code", 200);
                        responseMap.put("response", statusMap);
                        return responseMap;
        }
}

Execution of the Project:

1.       Run the Spring Boot Application
2.       Hit the Controller link and you will redirected to the form login
3.       URL:
http://localhost:8080/webcontroller/hello
4.       It will be redirected to the Spring form login page and above credentials will work for the same.


References:

http://javarevisited.blogspot.in/2017/05/how-to-enable-spring-security-in-java-web-application.html
https://docs.spring.io/spring-boot/docs/1.5.12.RELEASE/reference/pdf/spring-boot-reference.pdf
https://docs.spring.io/spring-security/site/docs/4.2.x/reference/pdf/spring-security-reference.pdf
https://docs.spring.io/spring/docs/4.3.x/spring-framework-reference/pdf/spring-framework-reference.pdf