Я хочу выполнить код при успешной аутентификации, чтобы добавить определенные роли к моему объекту пользователя:
@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 также не работает.
@SimonMartinelli Это странно. Вы также использовали LDAP-аутентификацию? Я использую страницу входа по умолчанию, которая есть в Spring-Security.
У меня есть свой, но код тот же
Я также попытался добавить System.out.println в onAuthenticationSuccess (без промежуточного вызова метода), но он также не печатает ... Итак, похоже, что он не выполняет этот onAuthenticationSuccess - я перезаписал это другой зависимостью, которую я добавил позже? Возможно ли такое?
попробуйте удалить basic () и http.formLogin (). defaultSuccessUrl ("/", true);




Я пробовал это, и это работает. Вы пробовали отлаживать свой код? установить точку останова