Over a million developers have joined DZone.

Spring Security - Custom Authentication

· Integration Zone

Is iPaaS solving the right problems? Not knowing the fundamental difference between iPaaS and dPaaS could cost you down the road. Brought to you in partnership with Liaison Technologies.

In this post I will explain how to authenticate a user using spring security.

public class CustomAuthenticationProvider implements AuthenticationProvider {

private static Logger logger = LoggerFactory.getLogger(CustomAuthenticationProvider.class);


public Authentication authenticate(Authentication authentication ) throws AuthenticationException {

    String userName = authentication.getName().trim();
        String password = authentication.getCredentials().toString().trim();
        Authentication auth = null;

    CustomLogin login = new CustomLogin();
    //Authenticate the user based on your custom logic
String  role = login.getApplicationRole(userName, password, "ADMIN","DEVELOPER");

        if (role != null)
        {

        Collection<GrantedAuthority> grantedAuths = new SimpleGrantedAuthority(role.trim());

        ApplicationUser appUser = new ApplicationUser(userName,password, true, true, true, true,grantedAuths,"TestEmail");

        auth = new UsernamePasswordAuthenticationToken(appUser, password, grantedAuths);

            return auth;
        }
        else 
        {
          return null;
        }

    }

    @Override
    public boolean supports(Class<? extends Object> authentication) {
        return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
    }
Here you see a custom user authentication class using spring security. This class implements AuthenticationProvider interface available in spring security package. AuthenticationProvider has a method called authenticate which is implemented in the custom authentication class which will be invoked by spring security when a user login.
Within this method, you can authenticate the user based on any custom logic. Here once a user is authenticated, we get a ROLE for that user. Then we create an object of SimpleGrantedAuthority passing that role into it. After that we create custom user object which will have user name, credentials , granted authority object and any other fields like email etc. Then we create UsernamePasswordAuthenticationToken using the custom user object, credentials and granted authority(ROLE) and return that auth object back to spring security.


public class ApplicationUser extends User {


private static final long serialVersionUID = 1L;

    private final String email;

    public ApplicationUser(String username, String password, boolean enabled,
        boolean accountNonExpired, boolean credentialsNonExpired,
        boolean accountNonLocked,
        Collection<GrantedAuthority> authorities,
        String email) {

            super(username, password, enabled, accountNonExpired,
               credentialsNonExpired, accountNonLocked, authorities);

            this.email = email;
    }


public String getEmail() {
return email;
}



 }

Add this to the spring security config file

<authentication-manager>
 <authentication-provider ref="CustomAuthenticationProvider"/>
 </authentication-manager>

<bean id="CustomAuthenticationProvider" class="com.custom.security.CustomAuthenticationProvider">
</bean>



Discover the unprecedented possibilities and challenges, created by today’s fast paced data climate and why your current integration solution is not enough, brought to you in partnership with Liaison Technologies.

Topics:
java ,enterprise-integration ,xml ,tutorial ,integration ,authentication ,spring security

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}