Spring Security – Authentication in depth

Spread the love

In thsi article, we would see the in depth details of doing authentication in spring security.

So as you see, normally authentication is done using an user id/pwd or an OTP. Here we will see the types of authentication, Java classes used while authenticating etc.

Using In Memory Authentication:


@EnableWebSecurity
public class SpringSecInMemConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception          {
        auth
            .inMemoryAuthentication()
            .withUser("sa").password("sa123").roles("USER");
}
}

Here AuthenticationManagerBuilder class is used for authentication. We have hardcoded the desired user name and password here. But this type of authentication is not encouraged. Password should be atleast encoded.

@EnableWebSecurity configures auth object in the param to configure method above.

@Bean
public PasswordEncoder passwordEncoder() {
    return NoOpPasswordEncoder.getInstance();
}

We need to declare this bean to encode the passwords.

Using AuthenticationProvider:

This is the most preferred way of doing authentication.

Here the Authentication Manager forwards the request to the respective AuthenticationProvider which can be a JDBC provider , LDAP provider etc.

Let’s look at a basic custom auth provider.

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
    @Override
    public Authentication authenticate(Authentication auth) 
      throws AuthenticationException {
        String user = auth.getName();
        String pwd = auth.getCredentials().toString();

        if ("test".equals(user) && "pass".equals(pwd)) {
            return new UsernamePasswordAuthenticationToken
              (user, pwd, Collections.emptyList());
        } else {
            throw new 
              BadCredentialsException("Auth failed");
        }
    }

    @Override
    public boolean supports(Class<?> auth) {
        return auth.equals(UsernamePasswordAuthenticationToken.class);
    }
}

@EnableWebSecurity
public class TestCustAuthProvidersSecurityConfig 
  extends WebSecurityConfigurerAdapter {
    @Autowired
    CustomAuthenticationProvider customAuthProvider;

    @Override
    public void configure(AuthenticationManagerBuilder auth) 
      throws Exception {

        auth.authenticationProvider(customAuthProvider);
    }
}

If the authentication is not successful then an exception is thrown. 

Next article we would deep dive into JDBC Auth and LDAP based Authentication Provider.

Thanks for reading.