Выполнить код при успешной аутентификации Spring boot - PullRequest
0 голосов
/ 27 декабря 2018

Я хочу выполнить код при успешной аутентификации, чтобы добавить определенные роли к моему объекту пользователя:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Value("${ad.domain}")
    private String AD_DOMAIN;

    @Value("${ad.url}")
    private String AD_URL;

    @Autowired
    UserRoleComponent userRoleComponent;

    private final Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        this.logger.info("Verify logging level"); //works
        http
                .authorizeRequests()
                .anyRequest()
                .fullyAuthenticated()
            .and()
                .formLogin()
                .successHandler(new AuthenticationSuccessHandler() {

                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

                        userRoleComponent.testIt();
                        redirectStrategy.sendRedirect(request, response, "/");

                    }
                })
            .and()
                .httpBasic();

        http.formLogin().defaultSuccessUrl("/", true);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(activeDirectoryLdapAuthenticationProvider());
    }

    @Bean
    public AuthenticationManager authenticationManager() {
        return new ProviderManager(Arrays.asList(activeDirectoryLdapAuthenticationProvider()));
    }

    @Bean
    public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
        ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(AD_DOMAIN,
                AD_URL);
        provider.setConvertSubErrorCodesToExceptions(true);
        provider.setUseAuthenticationRequestCredentials(true);
        return provider;
    }
}

Поэтому я попытался добавить новый AuthenticationSuccessHandler, чтобы вставить код, который будет выполняться в компоненте (этовот где роли должны быть добавлены).

В моем UserRoleController:

@Component
public class UserRoleComponent {

    private Logger logger = LoggerFactory.getLogger(UserRoleComponent.class);

    public void testIt() {
        this.logger.info("=============== User Authentication ==============");
        System.out.println("================ User Authentication ================");

    }

}

Теперь, к сожалению, когда я успешно захожу, вывод не выводится.Как я могу решить эту проблему?

Редактировать: я проверил, что уровень входа в систему правильный, и system.out.println также не работает.

...