When HTTP basic authentication is configured, web browser will display a login dialog for user authentication. This tutorial show you how to configure HTTP basic authentication in Spring Security.

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

Last Spring Security form-based login example will be reused, but switch authentication to support HTTP basic.

1. Spring Security

To enable HTTP basic, just change “form-login” to “http-basic” tag.

<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.0.xsd
	http://www.springframework.org/schema/security
	http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
 
	<!-- HTTP basic authentication in Spring Security -->
	<http>
		<intercept-url pattern="/welcome*" access="ROLE_USER" />
		<http-basic />
	</http>
 
	<authentication-manager>
	   <authentication-provider>
	       <user-service>
		   <user name="mkyong" password="123456" authorities="ROLE_USER" />
	       </user-service>
	   </authentication-provider>
	</authentication-manager>
 
</beans:beans>

Done, that’s all.

2. Demo

When access the secured URL, browser will display a login dialog box automatically.

URL : http://localhost:8080/SpringMVC/welcome

http basic example

Download Source Code

References

  1. Spring Security hello world example
  2. Spring Security form-based login example
Tags :
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.
My website mkyong.com is hosted by Liquid Web, I really like their fast and helpful support, it saved me a lot of time. Furthermore, their servers are extremely reliable, fast and stable, I don't remember when was the last time we had server downtime. Btw, they're offering $100 Coupon now, if you are sourcing for great hosting provider, go grab it.

Related Posts

Popular Posts