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

Share, secure, distribute, control, and monetize your APIs with the platform built with performance, time-to-value, and growth in mind. Free 90-day trial of 3Scale by Red Hat

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>



Explore the core elements of owning an API strategy and best practices for effective API programs. Download the API Owner's Manual, brought to you by 3Scale by Red Hat

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 }}