Spring security inMemoryAuthentication and authorization example using spring boot

In this example, we will see Spring security authorization example spring boot. We will use Oracle database and inMemoryAuthentication for authentication.

prerequisites –

  • JDK 1.8
  • Oracle 10g
  • Eclipse
  • maven

We will use the spring boot library (will provide dependency in pom.xml) to make sure all necessary jar/library is easily available for our application. Spring boot will take care of all jar. Let’ s start.

Step 1 – open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’click on next.

Step 2 – Fill all details as below and click on finish.

Step 3 – open pom.xml  and replace the pom.xml with below code.

<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>springsecurityexample</groupId>
  <artifactId>springsecurityexample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>springsecurityexample</name>
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
 </parent>
  <dependencies>
	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!-- <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency> -->
        
   </dependencies>
   
   
   
   
   
   <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <start-class>com.springsecurity.SpringSecurityExample</start-class>
        <java.version>1.8</java.version>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.springsecurity.SpringSecurityExample</mainClass>
                </configuration>
            </plugin>
			<plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <fork>true</fork>
                <executable>C:\Program Files\Java\jdk1.8.0_131\bin\javac.exe</executable>
            </configuration>
        </plugin>
        </plugins>
    </build>
   
    
   
 </project>

 

Note – In pom.xml we have defined javac.exe path in configuration tag. You need to change accordingly i.e where you have installed JDK.

Step 4 – Let maven download all necessary jar. Once it is done we will able to see maven dependency folder which contains different jar files. Create classes and interfaces as below.


 

Step 5 – Define the main class SpringSecurityExample.java

package com.springsecurity.springsecurityexample;



import org.hibernate.SessionFactory;
import org.hibernate.jpa.HibernateEntityManagerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication(scanBasePackages={"com.springsecurity"})
@EntityScan("com.springsecurity.*") 
@EnableScheduling
public class SpringSecurityExample {
	
	
	public static void main(final String[] args) {
		final ConfigurableApplicationContext configurableApplicationContext = SpringApplication
				.run(SpringSecurityExample.class, args);
		
		
	}
	
	@Bean
	public SessionFactory sessionFactory(final HibernateEntityManagerFactory hemf) {
		return hemf.getSessionFactory();
	}
	

	
	
	
	
}

 

Step 6 – Define entity class i.e Book.java

package com.springsecurity.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "book")
public class Book {
	 
	 @Id
	 @GeneratedValue(strategy = GenerationType.AUTO)
	 private int bookId;
	 
	 @Column(name="book_name")
	 private String bookName;
	 
	 @Column(name="auther_name")
	 private String autherName;
	 
	 public String getAutherName() {
		return autherName;
	}

	public void setAutherName(String autherName) {
		this.autherName = autherName;
	}

	public int getPrice() {
		return price;
	}

	public void setPrice(int price) {
		this.price = price;
	}

	@Column(name="price")
	 private int price;

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}

	public int getBookId() {
		return bookId;
	}

	public void setBookId(int bookId) {
		this.bookId = bookId;
	}

	
	 
	 
}

 

Step 7 – Define BookRepository interface extending CrudRepository.

BookRepository.java

package com.springsecurity.repository;



import java.io.Serializable;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.repository.CrudRepository;

import org.springframework.stereotype.Repository;

import com.springsecurity.entity.Book;

@Repository
public interface BookRepository extends CrudRepository<Book,Serializable> {
	public Book findByBookId(int bookId);
	
	
	
}


 

Step 8 – Define service interface i.e BookService.java

package com.springsecurity.service;

import org.springframework.stereotype.Component;

import com.springsecurity.entity.Book;

import java.util.*;
@Component
public interface BookService {
	public Book findByBookId(int bookId);
	public List<Book> findAllBook();
	
}

 

Step 10 – Define service implementation class.

BookServiceImpl.java

package com.springsecurity.serviceimpl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.Repository;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.springsecurity.entity.Book;
import com.springsecurity.repository.BookRepository;
import com.springsecurity.service.BookService;
@Service("bookServiceImpl")
public class BookServiceImpl implements BookService{
	
@Autowired
private BookRepository bookRepository;


public Book findByBookId(int bookId) {
	Book book = bookRepository.findByBookId(bookId);
	
	return book;
}



public List<Book> findAllBook() {
	List<Book> listOfBook = (List<Book>) bookRepository.findAll();
	return listOfBook;
}


}

 

Step 10 – Define controller class.


BookController.java

package com.springsecurity.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.springsecurity.entity.Book;
import com.springsecurity.service.BookService;
import java.util.*;
@RestController
@RequestMapping("/book")
public class BookController {
	@Autowired
	private BookService bookService;
	
	@RequestMapping(value = "/getbook",method = RequestMethod.GET)
    @ResponseBody
    public Book getBookDetails(int bookId) {
		Book bookResponse = bookService.findByBookId(bookId);
		
		return bookResponse;
	}
	
	@RequestMapping(value = "/getallbook",method = RequestMethod.GET)
    @ResponseBody
    public List<Book> getAllBook() {
		List<Book> bookResponse = bookService.findAllBook();
		
		return bookResponse;
	}
	
	
}

 

Step 11 – Define Config class.

Config.java


package com.springsecurity.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
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.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableJpaRepositories(basePackages = "com.springsecurity.repository")
@EnableWebSecurity
public class Config extends WebSecurityConfigurerAdapter{
	
	@Override
	protected void configure(HttpSecurity httpSecurity) throws Exception {
		httpSecurity.csrf().disable().authorizeRequests().antMatchers("/book/getbook").
		hasAnyRole("user").and().formLogin();
		httpSecurity.csrf().disable().authorizeRequests().antMatchers("/book/getallbook")
		.hasAnyRole("admin").and().formLogin();
	}
	
	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder authManagerBuilder) {
		try {
		authManagerBuilder.inMemoryAuthentication().withUser("rakesh").password("abc").roles("admin");
		authManagerBuilder.inMemoryAuthentication().withUser("kumar").password("xyz").roles("user");
		}catch(Exception e) {
			e.printStackTrace();
		}
		
	}
	

}

 

 

Step 12 – Define application.properties file

application.properties

# Connection url for the database
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=SYSTEM
spring.datasource.password=oracle1
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
 
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
 
# Show or not log for each sql query
spring.jpa.show-sql = true
 
 
spring.jpa.hibernate.ddl-auto =update
 
 
 
 
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
 
server.port = 9091
 
  useBuiltinConverters: true
 
  #useAutoMapping: true
  
  
  mapNulls: true
 
 
logging.level.org.springframework.transaction.interceptor=TRACE

 

Step 13 – Run the SpringSecurityExample.java. The application should deploy and book table will be created.

 

Step 14 – insert some record in Database.

insert into book (book_id,BOOK_NAME,AUTHER_NAME,PRICE) values (1,’aother1′,’rakesh’,12);

Step 15 – We have two rest API in the controller class.

  • http://localhost:9091/book/getbook
  • http://localhost:9091/book/getallbook

 

Step 16 – Testing http://localhost:9091/book/getbook URI

  • Open a new browser and paste the above URI, it will redirect to the login page. Since we have provided user role and secured this URI with username kumar and password xyz Config.java, we need to provide a credential.

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable().authorizeRequests().antMatchers(“/book/getbook”).
hasAnyRole(“user”).and().formLogin();
httpSecurity.csrf().disable().authorizeRequests().antMatchers(“/book/getallbook”)
.hasAnyRole(“admin”).and().formLogin();
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder authManagerBuilder) {
try {
authManagerBuilder.inMemoryAuthentication().withUser(“rakesh”).password(“abc”).roles(“admin”);
authManagerBuilder.inMemoryAuthentication().withUser(“kumar”).password(“xyz”).roles(“user”);
}catch(Exception e) {
e.printStackTrace();
}

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Let’s test another URI http://localhost:9091/book/getallbook