Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Spring Security - UserDetailsService vs. AuthenticationProvider

    • 0
    • 2
    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 6.14k
    Comment on it

    We can use Custome UserDetailsService and custom AuthenticationProvider for user authentication in Spring Security. Here I'm taking example of custom UserDetailsService.

    UserDetailsService is a Core interface which loads user-specific data. It is used throughout the framework as a user DAO and it is used by the DaoAuthenticationProvider.

    AuthenticationProvider can process a specific Authentication implementation.

    See the below steps to use custom UserDetailsService and AuthenticationProvider in Spring security for user authentication:

      1. Define the below configuration in your applicationContext-security.xml file
    <beans:beans xmlns=""
        <http auto-config='true'>
          <intercept-url pattern="/secured/*" access="ROLE_USER" />
          <logout logout-success-url="/logout"/>
        <!-- Authentication Manager -->
        <!-- This will override the settings of authentication manager bean. -->
        <authentication-manager alias="authenticationManager">
        <authentication-provider user-service-ref="userDetailsService">
            <password-encoder hash="sha" base64="true" />
        <!-- Beans and Providers -->
        <beans:bean id="userDetailsService"

      2. Write the below class which implements UserDetailsService

    package com.evon.authentication;
    import java.util.Vector;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.dao.DataAccessException;
    import com.storistic.authorization.Role;
    import com.storistic.dbservices.response.model.UserLoginResponse;
    public class AuthenticationService implements UserDetailsService
        private Logger logger = LoggerFactory.getLogger(AuthenticationService.class);
        public UserDetails loadUserByUsername(String username)
                throws UsernameNotFoundException, DataAccessException
        logger.debug("Loading user by name: " + userName);
        Vector userAuthorities = new Vector();
            userAuthorities.add(new GrantedAuthorityImpl(Role.USER_ROLE.roleName()));
            userAuthorities.add(new GrantedAuthorityImpl(;
            UserDetails user = new User(username, "password", true, true, true, true, userAuthorities);
            return user;

 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: