DefaultAuthenticationEventPublisher未触发任何事件。有谁能告诉我我的代码有什么问题吗?@EventListener不工作。
事件没有被解雇,请帮助我。我尝试了没有@EventListener的旧方法。我如何触发并捕捉这些事件?我跟着
@Component
public class AuthenticationEvents {
@EventListener
public void onSuccess(AuthenticationSuccessEvent success) {
System.out.println(success);
System.out.println("success event");
// ...
}
@EventListener
public void onFailure(AbstractAuthenticationFailureEvent failures) {
System.out.println(failures);
System.out.println("failed event");
// ...
}
@EventListener
public void onFailure(AuthenticationFailureBadCredentialsEvent failures) {
System.out.println(failures);
System.out.println("failed event");
// ...
}
}
这是配置类:
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// https://www.baeldung.com/role-and-privilege-for-spring-security-registration
//https://www.bezkoder.com/spring-boot-jwt-authentication/
UserDetailsServiceImpl userDetailsServiceImpl;
/**
* AuthenticationProvider is interface that has authenticate method
* DaoAuthenticationProvider is AuthenticationProvider-s implementation
* DaoAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider
* Configured daoAuthenticationProvider with appUserDetailsService which implements userDetailsService.
*
* @return
*/
@Bean
AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsServiceImpl);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return daoAuthenticationProvider;
}
@Bean
public DefaultAuthenticationEventPublisher authenticationEventPublisher() {
return new DefaultAuthenticationEventPublisher();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationEventPublisher(authenticationEventPublisher());
auth.authenticationProvider(authenticationProvider());
}
@Bean
public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter();
}
//
// @Bean
// AuthenticationSuccessListener authenticationSuccessListenerBean(){
// return new AuthenticationSuccessListener();
// }
// @Bean
// CorsConfigurationSource corsConfigurationSource() {
//// https://stackoverflow.com/questions/36968963/how-to-configure-cors-in-a-spring-boot-spring-security-application
// UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
// return source;
// }
@Override
protected void configure(HttpSecurity http) throws Exception {
//hasAuthority(‘ROLE_ADMIN') is similar to hasRole(‘ADMIN')
//because the ‘ROLE_‘ prefix gets added automatically.
//hasRole(myString) ads "ROLE_" to string and checks that way.
//for instance if in database we have "ROLE_ADMIN" and we provide hasRole("ADMIN") it will work.
http.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers("/api/utility/**").permitAll()
.antMatchers("/api/security/auth/**").permitAll();
// .anyRequest().authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
// .anyRequest().authenticated();
}
@Override
public void configure(WebSecurity web) throws Exception {
// web.ignoring().antMatchers(
//// "/api/security/**"
//// "/auth/**",
//// "/register",
//// "/admin/**",
//// "/garden/**",
//// "/place/**",
//// "/person/**"
// );
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
这是过滤器:
public class AuthTokenFilter extends OncePerRequestFilter {
@Autowired
private JwtUtils jwtUtils;
@Autowired
private UserDetailsServiceImpl userDetailsService;
@Autowired
private AuthenticationProvider authenticationProvider;
public AuthTokenFilter() {
}
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {
try {
String jwt = parseJwt(request);
if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
// String userName = jwtUtils.getUserNameFromJwtToken(jwt);
// UserDetailsImpl userDetails = userDetailsService.loadUserByUsername(userName);
// User user = userDetails.getUser();
// Collection<SimpleGrantedAuthority> simpleGrantedAuthorities = userDetails.getAuthorities();
// System.out.println(simpleGrantedAuthorities);
// UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword(), simpleGrantedAuthorities);
//
// Authentication authentication = authenticationProvider.authenticate(usernamePasswordAuthenticationToken);
// SecurityContextHolder.getContext().setAuthentication(authentication);
String username = jwtUtils.getUserNameFromJwtToken(jwt);
UserDetailsImpl userDetails = userDetailsService.loadUserByUsername(username);
Collection<SimpleGrantedAuthority> simpleGrantedAuthorities = userDetails.getAuthorities();
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
userDetails,
null,
simpleGrantedAuthorities
);
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception e) {
System.out.println("dkwajd lakwjd lkawjdlk wajl dkjawl djalk jdlakw ");
// throw new AuthenticationException("გთხოვთ დალოგინდით სისტემაში");
// logger.error("Cannot set user authentication: {}", e);
}
filterChain.doFilter(request, response);
}
private String parseJwt(HttpServletRequest request) {
String headerAuth = request.getHeader("Authorization");
if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) {
return headerAuth.substring(7, headerAuth.length());
}
return null;
}
}
请帮帮我。
2条答案
按热度按时间mzsu5hc01#
我刚刚遇到你的问题,因为我自己正在实现一个AuthenticationEventPublisher,以确保我的应用程序安全。
我建议你看看Spring Docs中的这个指南:https://docs.spring.io/spring-security/reference/servlet/authentication/events.html
请特别注意这一部分:
发布者执行精确的Exception匹配,这意味着这些异常的子类也不会产生事件。
我在我的应用程序中做了什么(它工作):
活动发布者:
AuthenticationEvents:
登录失败事件的完整日志消息:
jm2pwxwz2#
您需要将
AuthenticationEventPublisher
设置为AuthenticationManager
。