Deny all requests

In this article, we will see how to customize a spring security application to deny all requests and return a forbidden error with HTTP status 403.
This article assumes that you know how to configure security in a spring boot application.

Create configuration
Create a configuration class for customizing spring security behavior for handling incoming requests.

This class should
1. extend WebSecurityConfigurerAdapter class residing in package.

2. Be marked with @Configuration annotation to signify that it is a configuration class.

WebSecurityConfigurerAdapter contains a method configure(HttpSecurity http), with default implementation. This default implementation authenticates all incoming requests with a user name and password.

To deny all incoming requests, we need to override this method in our configuration class as shown below.

public class SecurityConfig extends 
       WebSecurityConfigurerAdapter {

  protected void configure(HttpSecurity http) 
       throws Exception {

This implementation configures spring security to deny all incoming requests.

In the above method chain,
1. authorizeRequests() instructs spring security to restrict requests based on URL patterns and/or user roles.

2. anyRequest() configures all requests to be authorized irrespective of URL patterns.

3. denyAll() is applied to deny all requests, even if they are from trusted source with authenticated users.
This is the method, that is required to deny requests.

Spring docs for denyAll() state,

Specify that URLs are not allowed by anyone.

Suppose the spring boot web application is running on port 8080 at URL http://localhost:8080/springapp, you will get below response when this URL is accessed from browser

Spring boot security request denied error

If accessed through postman, this URL will return below response

  "timestamp": "2021-08-29T19:13:09.169+00:00",
  "status": 403,
  "error": "Forbidden",
  "path": "/springapp"

Response remains the same, even if we supply a valid user name and password along with the request.

This shows that we have successfully customized our spring security application to deny all requests received by it.
Hope the article was informative.

Liked the article ? Spread the word...