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:

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:

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:

– H2 configuration

– Implement ‘RestAPIs.kotlin’:

IV. Sourcecode

KotlinSpringSecurityH2DB

By JavaSampleApproach | February 28, 2018.

Related Posts


Got Something To Say:

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

*