Table of contents
1.
Introduction
2.
Basic Authentication with Spring Security
2.1.
Step 1: Updating pom.xml
2.2.
Step 2: Receive Password
2.3.
Step 3: Logging the password
2.4.
Step 4: Sending Post Request
2.5.
Step 5: Final Authorization 
3.
Frequently Asked Questions
3.1.
What is API basic authentication?
3.2.
Which XML tag is used to implement the basic authentication in Spring Security?
3.3.
Which header is used for basic authentication?
3.4.
How do I authenticate in Spring Security?
3.5.
What is HTTP basic authentication in Spring Security?
3.6.
How do you implement basic authentication in the REST API?
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

Implementing Basic Authentication with Spring Security

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

For accessing the materials, a username or password is not required in various phases, making them not a secure option for resources. 

Spring Security's RESTful web services may be accessed in several ways, one of which is to employ basic authentication. A username and password will be transmitted along with the request for primary authentication. One can access the resource by entering the credentials for login and password.

Another more sophisticated type of authentication is called "Digest Authentication." Here it generates a password digest and sends it across the network. The server is not given access to the actual password. 

Implementing Basic Authentication with Spring Security

Another advanced type of authentication is OAuth (Open Authorization), or OAuth2.

Basic Authentication with Spring Security

Let's examine the implementation of basic authentication in web services.

Step 1: Updating pom.xml

Add the spring-boot-starter-security to pom.xml by opening it. It automatically sets up the bare minimum of security for us. 

@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {


    @Autowired
    private MyBasicAuthenticationEntryPoint authenticationEntryPoint;


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
          .withUser("anxynms").password(passwordEncoder().encode("user1Pass"))
          .authorities("ROLE_USER");
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
          .antMatchers("/securityNone").permitAll()
          .anyRequest().authenticated()
          .and()
          .httpBasic()
          .authenticationEntryPoint(authenticationEntryPoint);


        http.addFilterAfter(new CustomFilter(),
          BasicAuthenticationFilter.class);
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
You can also try this code with Online Java Compiler
Run Code

Step 2: Receive Password

We receive a password in the log once the server is restarted. The password will be different every time the server starts up. 

curl -i --user userl:user1Pass
http://localhost:8080/spring-security-rest-basic-auth/api/foos/1

Step 3: Logging the password

Take note of the password in the log and copy it.

<http-basic entry-point-ref="myBasicAuthenticationEntryPoint"/>
@Component
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

    @Override
    public void commence(
      HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx) 
      throws IOException, ServletException {
        response.addHeader("WWW-Authenticate", "Basic realm="" + getRealmName() + """);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter writer = response.getWriter();
        writer.println("HTTP Status 401 - " + authEx.getMessage());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        setRealmName("anxynms");
        super.afterPropertiesSet();
    }
}
You can also try this code with Online Java Compiler
Run Code
output: Basic Authentication with Spring Security

Step 4: Sending Post Request

Send a POST request while the REST Client Postman is open. To create a user, we are submitting a POST.

  • Please enter the URI for users at localhost:8080.
     
  • Choose the raw radio option by clicking the Body tab.
     
  • Choose JSON as the media type (application/json).
     
  • Name and date of birth should be provided.
     
  • The Send button should be clicked.
     
HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=E5A8D3C16B65A0A007CFAACAEEE6916B; Path=/spring-security-mvc-basic-auth/; HttpOnly
WWW-Authenticate: Basic realm="Spring Security Application"
Content-Type: text/html;charset=utf-8
Postman sample 1

It provides the Status: 401 Unauthorized response.

Step 5: Final Authorization 

Select the Authorization tab in the REST client Postman, then carry out the steps listed below:

  • Make your choice of Basic Auth as the authentication type.
     
  • A username must be provided "User" is the typical username.
     
  • Put the password you copied from the log into the box provided.
     
  • By pressing the Send button.
     
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=301225C7AE7C74B0892887389996785D; Path=/spring-security-mvc-basic-auth/; HttpOnly
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en-US
Content-Length: 90
Date: Thur, 22 Sept 2022 17:21:03 GMT
Postman sample 2


The Status: 201 Created is shown. The password keeps changing every time we restart the server, which is a drawback. Configuring the username and password in the application.properties file will solve this issue.

The following application characteristics are included:

spring.security.user.name = anxynms
spring.security.user.password = password
Postman sample 3


Go to Postman now and attempt to submit a POST request. Status: 401 Unauthorized will now be returned. It's a result of the outdated password we're currently using. Because of this, we must replace the current login and password. Please enter the username and password that we set up in the properties file. We received the following: 201 created.

Frequently Asked Questions

What is API basic authentication?

Your email address and password are passed along to the Edge API using Basic Authentication for each request. The least secure authentication method provided is called Basic Authentication. Only Base64 encoding is used for credentials; neither encryption nor hashing is used.

Which XML tag is used to implement the basic authentication in Spring Security?

You only need to use the HTTP-basic /> configuration element to allow HTTP basic authentication in your Java web application if you are working with Spring Security 3.1 or lower or using an XML configuration file to enable Spring Security in your application.

Which header is used for basic authentication?

Basic HTTP authentication entails the use of a header field called " Authorization: Basic credentials” in a request, where credentials are the ID and password encoded in Base64 format and connected by a single colon.

How do I authenticate in Spring Security?

Spring Security stores the essential data about each authorized user in a ThreadLocal modeled as an Authentication object. For this reason, we must employ the same method Spring Security generally employs to generate the object on a regular authentication to construct and set this authentication object.

What is HTTP basic authentication in Spring Security?

User login information is given on the HTTP request header, specifically the "Authorization" request header, in the case of HTTP basic authentication rather than utilizing a form. Instead of sending the request body, as is the case with form login authentication, this header enables you to provide the username and password as request headers.

How do you implement basic authentication in the REST API?

Users of the REST API can authenticate by providing their user ID and password within an HTTP header.

Conclusion

Using Spring Boot is demonstrated in this post to enable basic authentication in Spring. We discussed using the Java configuration to allow this basic authentication with Spring Security.

If you think this blog has helped you enhance your knowledge about the above question, and if you want to learn more, check out our articles. And many more on our website.

Visit our website to read more such blogs. Make sure that you enroll in the courses we provide, take mock tests, solve problems available, and interview puzzles. Also, you can pay attention to interview stuff- interview experiences and an interview bundle for placement preparations. Do upvote our blog to help fellow ninjas grow.

Live masterclass