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

The Future of Enterprise Integration: Learn how organizations are re-architecting their integration strategy with data-driven app integration for true digital transformation.

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>



Make your mark on the industry’s leading annual report. Fill out the State of API Integration 2019 Survey and receive $25 to the Cloud Elements store.

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

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}