Allow and Deny requests in Spring Boot Security

This tutorial illustrates about very basic Spring Security. In our we have two pages :
1. hello.html (free from basic security and displayed directly)
2. home.html (whenever this page is called, spring security denies the access)

File Structure

hello.html (protected)

<!DOCTYPE html>
<html>
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <h1>Hello world!</h1>
    </body>
</html>

home.html (allowed)

<!DOCTYPE html>
<html>
<head>
<title>Spring Security Example</title>
</head>
<body>
	<h1>Welcome!</h1>

	<p>
		Click <a th:href="@{/hello}">here</a> to see a greeting.
	</p>
</body>
</html>

WebSecurityConfig.java

package com.example.demo;

import org.springframework.context.annotation.Configuration;
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;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	
	protected void configure(HttpSecurity http) throws Exception {
		http
			.authorizeRequests()
			.antMatchers("/home").permitAll() // Permit requests to /home (you can write multiple requests as .antMatchers("/home", "/work")  
			.anyRequest().denyAll(); // deny all other requests
	}
}

DefaultController.java

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class DefaultController {

	@GetMapping("/home")
	public String home() {
		return "home";
	}

	@GetMapping("/hello")
	public String hello() {
		return "hello";
	}
}

DefaultController.java (controller class)

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class DefaultController {

	@GetMapping("/home")
	public String home() {
		return "home";
	}

	@GetMapping("/hello")
	public String hello() {
		return "hello";
	}

}

SpringSecurityApplication.java (main Application class)

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringSecurityApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringSecurityApplication.class, args);
	}
}

Output (allowed)

Output (Denied)

Leave a Reply

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