Kotlin SpringBoot – Configure Spring Security

In the tutorial, JavaSampleApproach will show you how to configure Security for Kotlin SpringBoot web application.

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
– Bootstrap

II. Goal

We create a Kotlin MVC Web Application as below:

kotlin spring security - project structure

With 5 urls:

– ‘/’: access with everyone.

kotlin spring security - home page

– ‘/user’: must authenticate and be accessed with user ROLE {USER, ADMIN}

kotlin spring security - user page

– ‘/admin’: accessed by user with role Admin

kotlin spring security - admin page

– ‘/login’: login page

kotlin spring security - login page

– ‘/403’: HTTP Error 403 Forbidden

kotlin spring security - access denied

III. Practice

Step to do:
– Create Kotlin Spring Boot project
– Create Controller
– Create View Pages
– Configure WebSecurity

1. Create Kotlin Spring Boot project

Use SpringToolSuite to create a Kotlin SpringBoot project with below dependencies:

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2. Create Controller


package com.javasampleapproach.kotlin.springsecurity.controller

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
class WebController {
  
	@RequestMapping(value="/")
	fun home(): String{
	        return "home"
	}
  
    @RequestMapping(value="/user")
    fun welcome(): String{
        return "user"
    }
 
    @RequestMapping(value="/admin")
    fun admin(): String{
        return "admin"
    }
  
    @RequestMapping(value="/login")
    fun login(): String{
        return "login"
    }
  
  
    @RequestMapping(value="/403")
    fun error403(): String{
        return "403"
    }
}

3. Create View Pages

home.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Security with Spring Boot</title>
</head>
<body>
	<h1>Hello, This is Home page!</h1>
	<a style="color: blue" th:href="@{/user}">User Page</a>
	<br />
	<a style="color: blue" th:href="@{/admin}">Admin Page</a>
</body>
</html>

user.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Welcome Security with Spring Boot!</title>
</head>
<body>
	<h1>Hello, the page is for Users!</h1>
	<a style="color: blue" th:href="@{/}">Home</a>
	<form th:action="@{/logout}" method="post">
		<input type="submit" value="Sign Out" />
	</form>
</body>
</html>

admin.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Welcome Security with Spring Boot!</title>
</head>
<body>
	<h1>Hello, the page is for Admin!</h1>
	<a style="color: blue" th:href="@{/}">Home</a>
	<form th:action="@{/logout}" method="post">
		<input type="submit" value="Sign Out" />
	</form>
</body>
</html>

login.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
	<title>Welcome Security with Spring Boot!</title>
	<meta charset="utf-8"/>
	<meta name="viewport" content="width=device-width, initial-scale=1"/>
	<link rel="stylesheet"
		href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
	<script
		src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<script
		src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body class="container" style="margin:50px">
	<div class="row col-sm-6" 
				style="border: 1px ridge #003312; padding:20px; float: none; margin: 0 auto;">
		<h5 class="text-center" style="font-size: 25px">Sign In</h5>
		<div th:if="${param.error}">
			<p style="color: red">UserName or PassWord is wrong. Please
				check again!</p>
	
		</div>
		<div th:if="${param.logout}">
			<h1 style="color: blue">Logged out.</h1>
		</div>
		<form th:action="@{/login}" method="post">
			<div class="form-group">
				<label for="username">User Name: </label>
				<input type="text" class="form-control" id="username" placeholder="Enter UserName" name="username"/>
			</div>
			<div class="form-group">
				<label for="password">Password: </label>
				<input type="password" class="form-control" id="password" placeholder="Enter Password" name="password"/>
			</div>
			<button type="submit" class="btn btn-primary btn-block">Submit</button>
		</form>
	</div>
</body>
</html>

403.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Security with Spring Boot</title>
</head>
<body>
	<h1>Access is Denied!</h1>
	<a style="color: blue" th:href="@{/}">Home</a>
	<form th:action="@{/logout}" method="post">
		<input type="submit" value="Sign Out" />
	</form>
</body>
</html>

4. Configure WebSecurity

Use WebSecurityConfigurerAdapter which provides a convenient base class to create a WebSecurityConfigurer instance.

Web application has 2 users:
– Admin: admin/admin
– User: user/user


package com.javasampleapproach.kotlin.springsecurity.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
class SecurityConfig : WebSecurityConfigurerAdapter() {

	override fun configure(http: HttpSecurity): Unit {
		http
				.authorizeRequests()
				.antMatchers("/").permitAll()
				.antMatchers("/admin").hasRole("ADMIN")
				.anyRequest().authenticated()
				.and()
				.formLogin()
				.loginPage("/login")
				.permitAll()
				.and()
				.logout()
				.permitAll()
		
		http.exceptionHandling().accessDeniedPage("/403");
	}

	@Autowired
	fun configureGlobal(auth: AuthenticationManagerBuilder): Unit {
		auth
				.inMemoryAuthentication()
				.withUser("user").password("user").roles("USER")
				.and()
				.withUser("admin").password("admin").roles("ADMIN")	
	}
}

IV. SourceCode

KotlinSpringSecurity

One thought on “Kotlin SpringBoot – Configure Spring Security”

  1. This is the best weblog for anybody who wants to search out out about this topic. You notice so much its almost onerous to argue with you (not that I truly would want匟aHa). You positively put a new spin on a topic thats been written about for years. Great stuff, just great!

Leave a Reply

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