Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring Security - Custom Authentication

DZone's Guide to

Spring Security - Custom Authentication

· Integration Zone
Free Resource

Build APIs from SQL and NoSQL or Salesforce data sources in seconds. Read the Creating REST APIs white paper, brought to you in partnership with CA 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>



The Integration Zone is brought to you in partnership with CA Technologies.  Use CA Live API Creator to quickly create complete application backends, with secure APIs and robust application logic, in an easy to use interface.

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

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}