Spring Security - How to use Basic Authentication?

We will start with What Basic Authentication is and then do project setup and enable basic authentication using yaml and xml both.

1. What is Basic Authentication?

2. Project setup

We will start with adding spring-boot-starter-security dependency in pom.xml.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

3. Configuration for Basic Authentication

We need to register BasicAuthenticationFilter and BasicAuthenticationEntryPoint as bean in the Spring context.

@Bean
BasicAuthenticationFilter basicAuthFilter(AuthenticationManager authenticationManager, BasicAuthenticationEntryPoint basicAuthEntryPoint) {
return new BasicAuthenticationFilter(authenticationManager, basicAuthEntryPoint());
}

@Bean
BasicAuthenticationEntryPoint basicAuthEntryPoint() {
BasicAuthenticationEntryPoint bauth = new BasicAuthenticationEntryPoint();
bauth.setRealmName("gauravdotcc");
return bauth;
}

3. Enabling basic authentication and configuring properties

Basic Authenication is by default enabled when you add spring-security in your classpath. You need to configure the username and password for basic authentication. Here are some of the security properties. You can see SecurityProperties for other properties that you can configure like realm name etc.

security: 
basic:
enabled: true
user:
name: gauravdotcc
password: S3crets

4. XML based configuration for Basic Authentication

<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd"
>


<http>
<intercept-url pattern="/*" access="ROLE_USER" />

<!-- Adds Support for basic authentication -->
<http-basic/>
</http>

<authentication-manager>
<authentication-provider>
<user-service>
<user name="gauravdotcc" password="S3crets" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>

This is how to enable basic authentication in Spring Boot application using Spring Security. You can get the full working example code for basic authentication on Github.



Tags: Spring Framework, Spring Security, Spring Boot, Spring Security Basic Authentication example, Basic Authentication Example

← Back home