Spring Boot Sping Boot DefaultAuthenticationEventPublisher未触发事件

kpbwa7wx  于 2023-06-22  发布在  Spring
关注(0)|答案(2)|浏览(104)

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;
    }
}

请帮帮我。

mzsu5hc0

mzsu5hc01#

我刚刚遇到你的问题,因为我自己正在实现一个AuthenticationEventPublisher,以确保我的应用程序安全。
我建议你看看Spring Docs中的这个指南:https://docs.spring.io/spring-security/reference/servlet/authentication/events.html
请特别注意这一部分:
发布者执行精确的Exception匹配,这意味着这些异常的子类也不会产生事件。
我在我的应用程序中做了什么(它工作):
活动发布者:

@Configuration
public class EventPublishers {
    /***
     * Publishes authentication success and failure events.
     * 
     * Ref:
     * https://docs.spring.io/spring-security/reference/servlet/authentication/events.html
     * 
     * @param applicationEventPublisher
     * @return
     */
    @Bean
    public AuthenticationEventPublisher authenticationEventPublisher(
            ApplicationEventPublisher applicationEventPublisher) {
        return new DefaultAuthenticationEventPublisher(applicationEventPublisher);
    }
}

AuthenticationEvents:

@Component
@Slf4j
public class AuthenticationEvents {
    @EventListener
    public void onSuccess(AuthenticationSuccessEvent success) {
        final Authentication authentication = success.getAuthentication();
        log.info("Successful authentication event: \nDetails: {}\nPrincipal: {}", authentication.getDetails(), authentication.getPrincipal());
    }

    @EventListener
    public void onFailure(AbstractAuthenticationFailureEvent failures) {
        final Authentication authentication = failures.getAuthentication();
        log.info("Failure authentication event: \nDetails: {}\nPrincipal: {}", authentication.getDetails(), authentication.getPrincipal());
        log.info("full authentication: {}", authentication);
        log.info("Failure exception: {}", failures.getException());
        log.info("Full failure: {}", failures);
    }
}

登录失败事件的完整日志消息:

2022-07-31 14:15:02.731  INFO 8650 --- [nio-8080-exec-6] n.s.testapp.events.AuthenticationEvents    : Failure authentication event: 
Details: WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=69D3B7B0A4AF89F3E63CB4649BE1620F]
Principal: user
2022-07-31 14:15:02.731  INFO 8650 --- [nio-8080-exec-6] n.s.testapp.events.AuthenticationEvents    : full authentication: UsernamePasswordAuthenticationToken [Principal=user, Credentials=[PROTECTED], Authenticated=false, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=69D3B7B0A4AF89F3E63CB4649BE1620F], Granted Authorities=[]]
2022-07-31 14:15:02.731  INFO 8650 --- [nio-8080-exec-6] n.s.testapp.events.AuthenticationEvents    : Failure exception: {}

org.springframework.security.authentication.BadCredentialsException: Bad credentials
        at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:141) ~[spring-security-core-5.7.1.jar:5.7.1]
        at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:182) ~[spring-security-core-5.7.1.jar:5.7.1]
        at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:201) ~[spring-security-core-5.7.1.jar:5.7.1]
        at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:85) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:227) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:217) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:132) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.20.jar:5.3.20]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:91) ~[spring-web-5.3.20.jar:5.3.20]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.20.jar:5.3.20]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.20.jar:5.3.20]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:112) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:82) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.20.jar:5.3.20]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.security.web.session.DisableEncodeUrlFilter.doFilterInternal(DisableEncodeUrlFilter.java:42) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.20.jar:5.3.20]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183) ~[spring-security-web-5.7.1.jar:5.7.1]
        at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:354) ~[spring-web-5.3.20.jar:5.3.20]
        at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:267) ~[spring-web-5.3.20.jar:5.3.20]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.20.jar:5.3.20]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.20.jar:5.3.20]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.20.jar:5.3.20]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.20.jar:5.3.20]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:96) ~[spring-boot-actuator-2.7.0.jar:2.7.0]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.20.jar:5.3.20]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.20.jar:5.3.20]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.20.jar:5.3.20]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1743) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
        at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]

2022-07-31 14:15:02.731  INFO 8650 --- [nio-8080-exec-6] n.s.testapp.events.AuthenticationEvents    : Full failure: org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent[source=UsernamePasswordAuthenticationToken [Principal=user, Credentials=[PROTECTED], Authenticated=false, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=69D3B7B0A4AF89F3E63CB4649BE1620F], Granted Authorities=[]]]
jm2pwxwz

jm2pwxwz2#

您需要将AuthenticationEventPublisher设置为AuthenticationManager

@Bean
public AuthenticationManager authenticationManager(
@Qualifier(value = "clientAuthProvider") AuthenticationProvider provider,
@Qualifier(value = "authenticationEventPublisher") AuthenticationEventPublisher publisher
) {
   ProviderManager providerManager = new ProviderManager(provider);
   providerManager.setAuthenticationEventPublisher(publisher);
  return providerManager;
}

@Bean(name = "authenticationEventPublisher")
public AuthenticationEventPublisher authenticationEventPublisher(
ApplicationEventPublisher publisher
) {
 return new DefaultAuthenticationEventPublisher(publisher);
}

相关问题