如何在Spring Security中解决“ authenticationFailureHandler的未解决的编译问题”?

时间:2019-02-12 22:32:04

标签: java spring spring-boot spring-security

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

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

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

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

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

}

1 个答案:

答案 0 :(得分:1)

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

.successHandler(successHandler)
.failureHandler(authenticationFailureHandler)

我看到您已经创建了MySimpleUrlAuthenticationSuccessHandler。向successHandler提供该类的实例。并使用failureHandler和自定义/捆绑的AuthenticationFailureHandler实例进行相同操作。

我想您提到的警告要求将AuthenticationSuccessHandler定义为Bean。

@Configuration
class MyConfigurationClass {
   ...

   @Bean
   AuthenticationSuccessHandler myAuthenticationSuccessHandler() {
      return new MyCustomOrBundledAuthenticationSuccessHandler();
   }
}

您可以

.successHandler(myAuthenticationSuccessHandler())