Kotlin – integrate Spring Security & H2 Database

In the past post, We had set-up a Kotlin SpringBoot project to develop with H2 database. But if you enable Spring Security in your project, the H2 database console will be blocked with 403 error. So in the tutorial, we will show you how to make configuration for resolving the Access Denied problem.

I. Technologies

– Kotlin 1.2.20
– Apache Maven 3.5.2
– Spring Tool Suite – Version 3.9.0.RELEASE
– Spring Boot – 1.5.10.RELEASE
– H2 database
– Bootstrap

II. Goal

1. Problem

If your project uses H2 database to develop and also enable Spring Security, then when accessing to H2 console path: ‘/h2_console’, an error Access Denied Page will be thrown.

Why?
-> By default, Spring Security will block ‘/h2_console’ path of H2 database.

2. Resolve

Solution is a simple configuration with Spring Security as below segment code:


@Override
protected void configure(HttpSecurity http) throws Exception {
	http.authorizeRequests()
		...
		
	http.csrf().disable();
	http.headers().frameOptions().disable();

http.csrf().disable(): disable CRSF.
http.headers().frameOptions().disable(): H2 database console runs inside a frame, So we need to disable X-Frame-Options in Spring Security.

3. Goal

We create a Kotlin SpringBoot as below structure:

Kotlin - Spring Security H2 - project structure

Make a request to access H2’s console: ‘http://localhost:8080/h2_console’

-> It will redirect to Login page.

Kotlin - Spring Security H2 - login

Login with an account: ‘user/user’, it will redirect to Access Denied Page.

Kotlin - Spring Security H2 - access denied

-> Sign out

Again, make the request to access H2’s console: ‘http://localhost:8080/h2_console’, then login with user: ‘admin/admin’, it will redirect to H2’s login page:

Kotlin - Spring Security H2 - h2-database-security-h2-login-page

Press ‘Connect’. Then make an request in another tab: ‘http://localhost:8080/save’. Then make a query ‘select * from customer’, We have:

Kotlin - Spring Security H2 - select customers

-> Now, It’s already for development Kotlin Spring Boot project with Spring Security and H2 database!

III. Implementation

Step to do
– Create Kotlin Spring Security project
– Implement bussiness Web Application with H2 database

1. Create Kotlin Spring Security project

Follow guides of the article: Kotlin SpringBoot – Configure Spring Security. Then modify the segment code:


package com.javasampleapproach.h2.security;

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.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
				.antMatchers("/", "/home").permitAll()
				.antMatchers("/admin", "/h2_console/**").hasRole("ADMIN").anyRequest()
				.authenticated()
				.and()
				.formLogin().loginPage("/login").permitAll()
				.and()
				.logout().permitAll();
		http.exceptionHandling().accessDeniedPage("/403");
		http.csrf().disable();
		http.headers().frameOptions().disable();
	}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication()
				.withUser("user").password("user").roles("USER")
				.and()
				.withUser("admin").password("admin").roles("ADMIN");
	}
}

2. Implement bussiness Web Application with H2 database

Follow the tutorial Kotlin – Integrate H2 database with Spring JPA to configure H2 database and implement logic for Web application:

– H2 dependency:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
</dependency>

– H2 configuration


spring.h2.console.enabled=true
spring.h2.console.path=/h2_console
spring.datasource.url=jdbc:h2:file:~/h2/testdb
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql=true

– Implement ‘RestAPIs.kotlin’:


package com.javasampleapproach.kotlin.springsecurity.h2.controller

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
 
import com.javasampleapproach.kotlin.springsecurity.h2.model.Customer
import com.javasampleapproach.kotlin.springsecurity.h2.repository.CustomerRepository
 
@RestController
class RestAPIs {
	
    @Autowired
    lateinit var repository: CustomerRepository
       
    @RequestMapping("/save")
    fun process(): String{
        repository.save(Customer(1, "Jack", "Smith"))
        repository.save(Customer(2, "Adam", "Johnson"))
        repository.save(Customer(3, "Kim", "Smith"))
        repository.save(Customer(4, "David", "Williams"))
        repository.save(Customer(5, "Peter", "Davis"))
        return "Done"
    }
       
       
    @RequestMapping("/findall")
    fun findAll(): String{
        var result = ""
		
        for(cust in repository.findAll()){
            result += cust.toString() + "
" } return result } @RequestMapping("/findbyid") fun findById(@RequestParam("id") id: Long): String{ return repository.findOne(id).toString() } @RequestMapping("/findbylastname") fun fetchDataByLastName(@RequestParam("lastname") lastName: String): String{ var result = "" for(cust in repository.findByLastName(lastName)){ result += cust.toString() + "
" } return result } }

IV. Sourcecode

KotlinSpringSecurityH2DB



By grokonez | February 28, 2018.

Last updated on May 2, 2021.



Related Posts


Got Something To Say:

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

*