Spring security switch to Ldap authentication and database authorities

后端 未结 4 443
灰色年华
灰色年华 2020-12-08 01:34

I implemented database authentication for my web page and web service. It work well for both, now I have to add Ldap authentication. I have to authenticate through remote L

4条回答
  •  悲哀的现实
    2020-12-08 01:54

    You need to create a CustomAuthenticationProvider wich implements AuthenticationProvider, and override authenticate method, for example:

    @Component
    public class CustomAuthenticationProvider
        implements AuthenticationProvider {
    
        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            String username = authentication.getName();
            String password = authentication.getCredentials().toString();
    
            boolean authenticated = false;
            /**
             * Here implements the LDAP authentication
             * and return authenticated for example
             */
            if (authenticated) {
    
                String usernameInDB = "";
                /**
                 * Here look for username in your database!
                 * 
                 */
                List grantedAuths = new ArrayList<>();
                grantedAuths.add(new     SimpleGrantedAuthority("ROLE_USER"));
                Authentication auth = new     UsernamePasswordAuthenticationToken(usernameInDB, password,     grantedAuths);
                return auth;
            } else {
                return null;
            }
        }
    
        @Override
        public boolean supports(Class authentication) {
            return     authentication.equals(UsernamePasswordAuthenticationToken.class);
        }
    
    }
    

    Then, in your SecurityConfig, you need to override the configure thats use AuthenticationManagerBuilder:

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(this.authenticationProvider);
    }
    

    You can autowire the CustomAuthenticationProvider doing this:

    @Autowired
    private CustomAuthenticationProvider authenticationProvider;
    

    Doing this, you can override the default authentication behaviour.

提交回复
热议问题