Secure API/URLs with Spring Security
This tutorial will walk you through, few methods for securing API in Spring Boot using Spring Security.
We will see how we can create custom WebSecurityConfigurerAdapter by extending WebSecurityConfigurerAdapter Class and doing so we would be able to override the default configurations of the HttpSecurity.
When we talk about securing an API, we look for few options to adopt:-
For Maven Projects : Use below code, in your pom.xml file
For Gradle Projects : Use below code, in your build.gradle
For quick and easy-to-start solution, we use AntMatchers.
We just need to extend WebSecurityConfigurerAdapter, now we can override the methods provided in this base class.
Let's start with most common methods, which we use for securing url.
permitAll() : Applies No Restriction. All Url specified in this block can be access.
hasRole(String role) : Allows access to only user which has supplied role.
hasAnyRole(String roleA, String roleB) : Allows access to only user which associated to any one role.
hasIpAddress(String ipAddress) : Allows access to only specifies IP-Address.
So we have covered most commonly use cases for securing APIs of an application.