【问题标题】:How can I resolve 'Unresolved compilation problems for authenticationFailureHandler' in Spring Security?如何解决 Spring Security 中的“authenticationFailureHandler 未解决的编译问题”?
【发布时间】:2019-02-12 22:32:03
【问题描述】:

我正在使用 Spring Security 为我的 Web 应用程序构建身份验证入口点。现在,由于我的 successHandler() 和 failureHandler() 方法导致的编译错误,用户无法登录,因此 mr 注册效果很好。

记录的错误是:java.lang.Error:未解决的编译问题: successHandler 无法解析为变量 authenticationFailureHandler 无法解析为变量

我不确定我做错了什么。我正在粘贴我的 Spring Boot 应用程序的安全配置代码。为了解决这个问题,我需要在哪里添加所需的变量或参数(如果有)?

我尝试使用私有修饰符创建 2 个变量,这些修饰符表示处理程序的相同参数,但仍然不起作用

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;

@Autowired
private DataSource dataSource;

@Value("${spring.queries.users-query}")
private String usersQuery;

@Value("${spring.queries.roles-query}")
private String rolesQuery;

@Override
protected void configure(AuthenticationManagerBuilder auth)
        throws Exception {
    auth.
            jdbcAuthentication()
            .usersByUsernameQuery(usersQuery)
            .authoritiesByUsernameQuery(rolesQuery)
            .dataSource(dataSource)
            .passwordEncoder(bCryptPasswordEncoder);
}

@Override
protected void configure(HttpSecurity http) throws Exception {

    http
    .authorizeRequests()
    .antMatchers("/").permitAll()
    .antMatchers("/login").permitAll()
    .antMatchers("/signup_employer").permitAll()
    .antMatchers("/registrations").permitAll()
    .antMatchers("/admin/**").hasAuthority("ADMIN").anyRequest()
    .authenticated().and().csrf().disable()
    .formLogin()
    .loginPage("/login").failureUrl("/login?error=true")
    .defaultSuccessUrl("/admin")
    .usernameParameter("email")
    .passwordParameter("password")
    .successHandler(successHandler)
    .failureHandler(authenticationFailureHandler)
    .and()
    .logout()
    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
    .logoutSuccessUrl("/logout").deleteCookies("JSESSIONID").deleteCookies("my-rememberme")
    .logoutSuccessHandler(logoutSuccessHandler())
    .and().rememberMe()
    .tokenRepository(persistentTokenRepository())
    .and()
    // .exceptionHandling().accessDeniedHandler(accessDeniedHandler())
    //.and()
    .headers().cacheControl().disable()
    .and().sessionManagement()
    .sessionFixation().migrateSession()
    .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
    .invalidSessionUrl("/invalidSession")
    .maximumSessions(1)
    .expiredUrl("/invalidSession");
}

@Bean
public PersistentTokenRepository persistentTokenRepository() {
    JdbcTokenRepositoryImpl tokenRepositoryImpl = new JdbcTokenRepositoryImpl();
    tokenRepositoryImpl.setDataSource(dataSource);
    return tokenRepositoryImpl;
}

@Bean
public LogoutSuccessHandler logoutSuccessHandler() {
    return new CustomLogoutSuccessHandler();
}


@Bean
public AccessDeniedHandler accessDeniedHandler() {

    return new CustomAccessDeniedHandler();
}

@Bean
public AuthenticationEntryPoint unauthorizedEntryPoint() {
    return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/email_templates/**", "/error/**", "/font-awesome/**", "/fonts/**", "/res/**", "/vendor/**", "/js/**", "/img/**");
}

@Bean
public SessionRegistry sessionRegistry() {
    return new SessionRegistryImpl();
}

}

登录成功处理程序:

public class MySimpleUrlAuthenticationSuccessHandler implements 
AuthenticationSuccessHandler {
protected final Log logger = LogFactory.getLog(this.getClass());
protected int SessionTimeout = 1 * 60;
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

public MySimpleUrlAuthenticationSuccessHandler() {
    super();
}

// API

@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final 
HttpServletResponse response, final Authentication authentication) throws 
IOException {
    handle(request, response, authentication);
    clearAuthenticationAttributes(request);
 }

// IMPL

protected void handle(final HttpServletRequest request, final 
HttpServletResponse response, final Authentication authentication) throws 
IOException {
    final String targetUrl = determineTargetUrl(authentication);

    if (response.isCommitted()) {
        logger.debug("Response has already been committed. Unable to 
redirect to " + targetUrl);
        return;
    }
    redirectStrategy.sendRedirect(request, response, targetUrl);
}

protected String determineTargetUrl(final Authentication authentication) {
    boolean isUser = false;
    boolean isAdmin = false;
    final Collection<? extends GrantedAuthority> authorities = 
authentication.getAuthorities();
    for (final GrantedAuthority grantedAuthority : authorities) {
        if (grantedAuthority.getAuthority().equals("USER")) {
            isUser = true;
            break;
        } else if (grantedAuthority.getAuthority().equals("ADMIN")) {
            isAdmin = true;
            break;
        }
    }

    if (isUser) {
        return "/homepage.html";
    } else if (isAdmin) {
        return "/admin";
    } else {
        throw new IllegalStateException();
    }
 }

/**
 * Removes temporary authentication-related data which may have been stored 
 in the session
 * during the authentication process.
 */
protected final void clearAuthenticationAttributes(final HttpServletRequest 
request) {
    final HttpSession session = request.getSession(false);

    if (session == null) {
        return;
    }

    session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}

protected RedirectStrategy getRedirectStrategy() {
    return redirectStrategy;
}

public void setRedirectStrategy(final RedirectStrategy redirectStrategy) {
    this.redirectStrategy = redirectStrategy;
}

}

【问题讨论】:

    标签: java spring spring-boot spring-security


    【解决方案1】:

    configure(HttpSecurity) 方法中的这两行引用了似乎不存在的属性/变量。

    .successHandler(successHandler)
    .failureHandler(authenticationFailureHandler)
    

    我看到你已经创建了你的MySimpleUrlAuthenticationSuccessHandler。将该类的实例提供给successHandler。并对 failureHandler 执行相同的操作,并使用自定义/捆绑的 AuthenticationFailureHandler 实例。

    我想你提到的警告需要将AuthenticationSuccessHandler 定义为 Bean。

    @Configuration
    class MyConfigurationClass {
       ...
    
       @Bean
       AuthenticationSuccessHandler myAuthenticationSuccessHandler() {
          return new MyCustomOrBundledAuthenticationSuccessHandler();
       }
    }
    

    你可以

    .successHandler(myAuthenticationSuccessHandler())
    

    【讨论】:

    • 我已经实例化了捆绑的 failureHandlersuccessHandler 以消除错误。但是在运行时,错误日志告诉我 Consider defining a bean of type 'org.springframework.security.web.authentication.AuthenticationSuccessHandler' in your configuration. 有什么解决方法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 2017-12-02
    • 2015-08-22
    相关资源
    最近更新 更多