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:-
Dependency
For Maven Projects : Use below code, in your pom.xml file
<https://mvnrepository.com/artifact/org.springframework.security/spring-security-web --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.3.1.RELEASE</version> </dependency>
For Gradle Projects : Use below code, in your build.gradle
For Gradle Projects : Use below code, in your build.gradle // https://mvnrepository.com/artifact/org.springframework.security/spring-security-web compile group: 'org.springframework.security', name: 'spring-security-web', version: '5.3.1.RELEASE'
Configuration
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.
@Configuration
@EnableAutoConfiguration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
}
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.
@Override protected void configure(final HttpSecurity http) throws Exception { //Globally Accessible, anyone can access to file or directory .antMatchers("/publc","/register").permitAll() }
hasRole(String role) : Allows access to only user which has supplied role.
hasRole(String role) //Allows access to only user which has supplied role. @Override protected void configure(final HttpSecurity http) throws Exception { //Only User which has Admin Role can access this. .antMatchers("/admin/*").hasRole("ADMIN") }
hasAnyRole(String roleA, String roleB) : Allows access to only user which associated to any one role.
hasAnyRole(String roleA, String roleB) //Allows access to only user which associated to any one role. @Override protected void configure(final HttpSecurity http) throws Exception { //User with Admin role or Customer role can access this. .antMatchers("/customer/*").hasAnyRole("ADMIN","CUSTOMER") }
hasIpAddress(String ipAddress) : Allows access to only specifies IP-Address.
@Override protected void configure(final HttpSecurity http) throws Exception { //Restricts Dashboard access to provided IP-Address .antMatchers("/dashboard/**").hasIpAddress("11.11.11.11") }
So we have covered most commonly use cases for securing APIs of an application.
Thanks,
Yasir