Spring Security Basic Authentication Example

Basic authentication is often used with stateless clients which pass their credentials on each request. It’s quite common to use it in combination with form-based authentication where an application is used through both a browser-based user interface and as a web-service. However, basic authentication transmits the password as plain text so it should only really be used over an encrypted transport layer such as HTTPS.

Because basic authentication header has to be sent with each HTTP request, the web browser needs to cache the credentials for a reasonable period to avoid constant prompting user for the username and password. Caching policy differs between browsers.

BasicAuth in Spring Security

Simplest possible solution to implement basic http authentication is to use “http-basic” tag in spring security configuration file like this:

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

Above setting in your application will enforce the user to authenticate any of webpage or any other resource in your application. Interesting thing is that you do not need to create any login page or session management mechanism. Browser will present a login box before user on your behalf. And because each request contains authentication information just like in http stateless mechanism, you do not need to maintain session also.

Basic Auth Demo

Configure basic-auth in spring security configuration

In our employee management application created in Spring login form based security example, we created login form manually and configured them for various URL patterns.

Lets modify it to use http basic authentication. Our modified application-security.xml will look like this now.

< ?xml version="1.0" encoding="UTF-8"?>
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.0.xsd
	http://www.springframework.org/schema/security/
	http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">

	<http auto-config="true"  use-expressions="true">
		<intercept-url pattern="/login" access="permitAll" />
		<intercept-url pattern="/logout" access="permitAll" />
		<intercept-url pattern="/accessdenied" access="permitAll" />
		<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
		<logout logout-success-url="/logout" />
		<http-basic />
	</http>

	<authentication-manager alias="authenticationManager">
		<authentication-provider>
			<user-service>
				<user lokesh" password="password" authorities="ROLE_USER" />
			</user-service>
		</authentication-provider>
	</authentication-manager>

Verify BasicAuth

Now lets build the application again and run it in application server.

1) Hit the URL “http://localhost:8080/Spring3HibernateIntegration” in browser

A login window appear. Please note that it is browser generated login box and application has only provided relevant headers to browser.

http-basic-authenication-9270993
HTTP basic authentication window

2) Enter incorrect username and password

This will make browser to again present the cleared login box or it will show the error page in some cases like this.

http-basic-authetication-error-9805120
Login error in http basic authentication

3) Enter correct username and password

The correct username and password :: “lokesh” and “password“. When you enter above credentials, employee management screen will appear in browser screen.

employee-management-screen-2005770
Employee management screen

Please let me know if you found any problem in running above configuration.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

6 thoughts on “Spring Security Basic Authentication Example”

  1. With form login it does know where to go after login is success

    With HTTP basic authentication how does it know which page to redirect to after successful login

  2. I try used http-basic authentication but it did not work. could you help me please.
    I put my database schema and security xml context here

    CREATE TABLE user_roles (
    user_role_id INT(11) NOT NULL AUTO_INCREMENT,
    username VARCHAR(45) NOT NULL,
    ROLE VARCHAR(45) NOT NULL,
    PRIMARY KEY (user_role_id),
    UNIQUE KEY uni_username_role (ROLE,username),
    KEY fk_username_idx (username),
    CONSTRAINT fk_username FOREIGN KEY (username) REFERENCES users (username));

    CREATE TABLE users (
    username VARCHAR(45) NOT NULL ,
    password VARCHAR(45) NOT NULL ,
    enabled TINYINT NOT NULL DEFAULT 1 ,
    PRIMARY KEY (username));

    security context

    <!– –>

    <!– –>

    <!–

    –>

    ___________________________________________
    login.jsp

    <input name="j_username" id="j_username" type="text" class="span12" placeholder=" “>

    <script src="”>

    thanks you for your help

  3. Hi Lokesh,
    Does this means we need to store username and password for all users?
    don’t it threat for security as login credentials are on xml file?

  4. Login is working correctly.But Logout is not working…if i again run the project after first login it is not asking for login again simply going to that path

Comments are closed.

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.