Spring Security LDAP ручной вход с именем пользователя и паролем с использованием контроллера - PullRequest
0 голосов
/ 20 сентября 2019

У меня к приложениям интерфейс и аутентификация.Когда я получаю сообщение для метода входа в систему (приложение для аутентификации), я хочу выполнить ручную аутентификацию, как я делал с «UsernamePasswordAuthenticationToken» и пользовательским AuthenticationManager.Есть что-то вроде «UsernamePasswordAuthenticationToken», но для LdapAuthentication?Я искал в документах, но не могу найти решение.Как я могу это сделать?Это мой код:

  1. WebSecurityConfig:
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private AuthTokenConfig authTokenConfig;

    @Autowired
    Environment env;

    @Override
    public void configure(WebSecurity webSecurity) throws Exception
    {
        if(env.acceptsProfiles("!prod")){
            webSecurity.ignoring().antMatchers("/v2/api-docs/**");
            webSecurity.ignoring().antMatchers("/swagger.json");
            webSecurity.ignoring().antMatchers("/swagger-ui.html");
            webSecurity.ignoring().antMatchers("/swagger-resources");
            webSecurity.ignoring().antMatchers("/configuration/security");
            webSecurity.ignoring().antMatchers("/configuration/ui");
            webSecurity.ignoring().antMatchers("/webjars/**");
        }
        webSecurity
        .ignoring()
                // All of Spring Security will ignore the requests
                .antMatchers(HttpMethod.POST, "/session/login")
                .antMatchers("/password/forgotpwd")
                .antMatchers("/password/updatepwd")
                .antMatchers("/password/externalmanagement")
                .antMatchers(HttpMethod.GET, "/password/configuration")
                .antMatchers("/signup")
                .antMatchers("/signup/complete");
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().authenticated();

        http.csrf().disable();
        http.apply(authTokenConfig);


    }

    /*@Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }*/

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        String //userDnPatterns = "(&(objectClass=user)(cn={0}))",
                userDnPatterns = "cn={0},ou=Department,dc=org,dc=com",
                serverURL = "ldap://localhost:389/dc=org,dc=com",
                managerDn = "cn=admin,dc=org,dc=com",
                managerPassword = "passwordValue";

        auth
                .ldapAuthentication()
                .userDetailsContextMapper(new CustomLDAPUserDetailsContextMapper())
                .userDnPatterns(userDnPatterns)
                .contextSource()
                .url(serverURL)
                .managerDn(managerDn)
                .managerPassword(managerPassword)
                .and()
                .passwordCompare()
                .passwordEncoder(new LdapShaPasswordEncoder())
                .passwordAttribute("userPassword");
    }


    @Bean
    public AuthenticationManager customAuthenticationManager() throws Exception {
        return authenticationManager();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return super.userDetailsService();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        PasswordEncoder encoder = new Password();
        return encoder;
    }
AuthTokenConfig:
@Component("authTokenConfig")
public class AuthTokenConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private SessionService sessionService;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        AuthTokenFilter customFilter = new AuthTokenFilter(userDetailsService,sessionService);
        http.addFilterBefore(customFilter, BasicAuthenticationFilter.class);
    }
}
AuthTokenFilter:
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        try {
            String authToken = sessionService.getAuthToken(httpServletRequest);

            if (StringUtils.hasText(authToken)) {
                SessionStorage sessionStorage = sessionService.findSessionByAuthToken(authToken);
                if(sessionStorage==null){
                    httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "UserNotLoggedIn");
                }
                else{
                    String username = sessionStorage.getUsername();

                    UserDetails userDetails = customUserDetailsService.loadUserByUsername(username);

                    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userDetails,
                            userDetails.getPassword(), userDetails.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(token);
                    filterChain.doFilter(servletRequest, servletResponse);
                }
            }
            else{
                httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "UserNotLoggedIn");
            }
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage());
            ex.printStackTrace();
            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error checking user session");
        }
...