Spring Security for Kotlin

Deepak
2 min readJan 2, 2018

--

Let us see how to use Spring Security in Kotlin to create a Login process and authenticate users from Database.

Create a Spring Boot maven project and add the following dependencies shown below.

The first step is to create the Spring Boot Application class. This class will be created automatically if you are using Intellij or Eclipse to create a spring Boot Project.

Now lets create the application.properties file which will have all the configuration needed for JPA and Datasource

You can edit the application.properties file based on your DB configuration.

The next step is to Create data classes for User and Role.

Now create the Data layer i.e, JPA Repositories for User and Role

Before we dive into the Security part we will have to create few Custom User Details Service classes which will be required in the Security Configuration.

Now comes the Web Security Configuration. Lets create the required beans first and then move to the Security Configuration.

The Configuration class below creates PasswordEncoder Bean

The Configuration class below creates PasswordEncoderAndMatcher Bean

Now lets create the WebSecurityConfiguration class which has the security configuration and Authentication Manager

Now lets create a Dummy Rest Controller to test the Security configuration which we did.

But before you run the KotlinApplication.kt lets create a data.sql file in the resources folder to create a user for now as we do not have a registration form.

With all the classes which we have created and the configuration which we did until now has secured the application which will have the url http://localhost:8080/api/* and when you try to access the URL it will lead to a default spring security login page.

Now, we can test it by running KotlinApplication.kt file and go to the URL http://localhost:8080/api/test where you will be redirected to http://localhost:8080/login

Before login when trying to access http://localhost:8080/api/test

and now you can try logging in using username and password as “spdeepak”.

After login with the credentials

The complete project can be found here:

https://github.com/spdeepak/Example/tree/master/Kotlin-Spring-Security-DB-Authentication

NOTE: The project will be improved over time with a custom Login page, access denied page, logout settings etc.

--

--