spring

Spring security with custom authentication

This tutorial will show you how to use custom authentication with Spring security. When you do some real application you maybe need authentication application from other resource such as integration with other application, using REST Service, SOAP web service… In this post i will help you deal with that kind of authentication in general.

1. Import Project

I will use source code from the post Spring security and broswer back button, and we upgrade code to demo for this post.

You can download source code from here and import to Eclipse IDE.

2. Create Custom Authentication Manager

To custom authentication with generic way i create a custom class implement AuthenticationManager as below

public class CustomAuthenticate implements AuthenticationManager {

	@Override
	public Authentication authenticate(Authentication auth)
			throws AuthenticationException {
		// call third party to authentication here
		// username: auth.getName()
		// password: auth.getCredentials()
		// simple demo check user=dejav and password is 1234
		if (auth.getName().equals("devjav")
				&& auth.getCredentials().equals("1234")) {
			UsernamePasswordAuthenticationToken authenticate = new UsernamePasswordAuthenticationToken(
					auth.getName(), auth.getCredentials(),
					grantAuthorities("user"));
			return authenticate;
		}
		throw new BadCredentialsException(
				"Your login attempt was not successful.Please check your username or password and try again.");
	}

	public Collection<GrantedAuthority> grantAuthorities(String role) {
		List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
		authList.add(new SimpleGrantedAuthority("ROLE_" + role.toUpperCase()));
		return authList;
	}
}

In this demo i will not really call to third party to do particular check, i just authorize user with specific username devjav and password is `1234`.

3. Update Security configuration

I create a bean with class we create above, and reconfigure security.xml file as below

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
	xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	<security:http pattern="/resources/**" security="none" />
	<security:http auto-config="true" use-expressions="true" authentication-manager-ref="customAuthenticationManqger">
		<security:intercept-url pattern="/" access="permitAll" />
		<security:intercept-url pattern="/login.do" access="permitAll" />
		<security:intercept-url pattern="/accessdenied.do" access="permitAll" />
		<security:intercept-url pattern="/home.do" access="hasRole('ROLE_USER')" />
		<security:intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />
		<security:form-login login-page="/login.do" login-processing-url="/dologin.do"
			username-parameter="username" password-parameter="password"
			authentication-failure-url="/login.do?error=true" default-target-url="/home.do"
			always-use-default-target="true" />
		<security:access-denied-handler error-page="/accessdenied.do"/>
		<security:logout logout-success-url="/login.do" logout-url="/logout.do"/>
	</security:http>
	 <bean id="customAuthenticationManqger" class="com.devjav.security.CustomAuthenticate"/>

</beans>

4. Run application

Run application and navigate to this url http://localhost:8080/spring

home-page
Now you can login with devjav and password `1234`

5. Source code

You can download complete source code on this link

Leave a Reply