Learn to use basic authentication to secure rest apis created inside a Spring boot application. The secured rest api will ask for authentication details before giving access the data it secure.
1. Maven dependency
To secure rest apis, we must include spring security related jar files in project runtime. Simplest way to add all required jars is add spring-boot-starter-security dependency.
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.5.RELEASE</version> <relativePath /> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> </dependencies>
2. Configure WebSecurityConfigurerAdapter
To enable authentication and authorization support in spring boot rest apis, we can configure a utility class WebSecurityConfigurerAdapter. It helps in requiring the user to be authenticated prior to accessing any configured URL (or all urls) within our application.
package com.howtodoinjava.rest.config; 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 public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests().anyRequest().authenticated() .and() .httpBasic(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin") .password("{noop}password") .roles("USER"); } }
3. Spring boot security rest basic authentication demo
For demo purpose, we can write a simple REST API given below.
3.1. REST API
@RestController @RequestMapping(path = "/employees") public class EmployeeController { @Autowired private EmployeeDAO employeeDao; @GetMapping(path="/", produces = "application/json") public Employees getEmployees() { return employeeDao.getAllEmployees(); } }
3.2. Access rest api without ‘authorization’ header
Access rest api at URL : HTTP GET http://localhost:8080/employees/

3.3. Access rest api with ‘authorization’ header
Upon passing authorization request header with encoded basic-auth user name and password combination, we will be able to access the rest api response.
Access rest api at URL : HTTP GET http://localhost:8080/employees/

4. Conclusion
In this spring boot security rest basic authentication example, we learned to secure rest apis with basic authentication. It is done in two steps. First step is to include required dependencies e.g. spring-boot-starter-security
. Second step is to configure WebSecurityConfigurerAdapter
and add auth details.
References:
Spring security reference
HTTP Basic Auth
how do you retrieve the basic auth token? i didn’t understand.
I do not retrieve the basic auth token anywhere. It is matched in-memory.
Actually its working fine but if i changed password to incorrect and run 2nd time, it should give status that 401 unauthorization. but its not happening.can u explain me y?
Does this also work on https://localhost:8080/employees/ instead of http://localhost:8080/employees/ ?
Thanks for the good tutorial.
authentication not working for post request.
Check this link –
.csrf().disable()
Hi,
Is there any way to authenticate only POST/PUT rest calls?
Hello,
Based on your sample, I made a similar project. Without Basic Auth security, all works. When I put the security, for all GET requests, it works fine. But, when I try a POST command, I receive a 403 Forbidden. I use the same SecurityConfig.java as yours.
Have you any idea? I try with antMatchers(HttpMethod.POST, /**).hasRole(“USER”) without success.
Thank you in advance.
Try with Postman with URL http://localhost:8080/customer-consent/v1/consents/create. Here is the log I recieve. I got an “invalid CSRF token found” while in SpringConfig, the CSRF is disabled.
Apologize! Forget my post. I miss the annotations on the SecurityConfig class.
Cool !!, You figured it out.
can you please share your code as i am not able to perform role based authorization for post
Hello Lokesh,
Thank you for this simple example it’s really helpful. I tried using it to easily protect an endpoint in a simple Java Spring Boot project but it seems I the password is not verified, only a correct username seems to be necessary, any idea why?
Thank you,
my bad, postman was saving the auth and this is why next it was working
Its working for only localhost and not able to authenticate when calling the api from another server …can anyone pls help?
What problem do you face?
This example is good. I am working on microservices and few calls with token but how to bypass few internal urls (interservice calls) which will not carry token info in header.
Instead of going through the pain of encoding username and passwords, you could always select ‘auth’ as ‘Basic auth’ in the postman/Insomnia UI and add in username and password in plain text itself.
Make a tutorial on jwt spring boot authentication
I will work on it.
What is “.pa” in the exaple above…
Seems a typo error. Thanks for reporting it. Much appreciated.
Good example for basic understanding of spring security.
It would be better if you can add on more step on how to create authorization request header with encoded basic-auth user name and password combination. It will help.