Как я могу решить «Нерешенные проблемы компиляции для authenticationFailureHandler» в Spring Security? - PullRequest
0 голосов
/ 13 февраля 2019

Я использую Spring Security для создания точки входа аутентификации для моего веб-приложения.Теперь регистрация mr работает хорошо, поскольку пользователь не может войти в систему из-за ошибки компиляции, возникшей из-за моих методов successHandler () и failHandler ().

Зарегистрированная ошибка: java.lang.Error: Неразрешенные проблемы компиляции: successHandler не может быть разрешен с переменной authenticationFailureHandler не может быть разрешен с переменной

Я не уверен, что я делаю неправильно,Я вставляю код конфигурации безопасности моего весеннего загрузочного приложения.Где мне нужно добавить необходимую переменную или параметры (если таковые имеются) для решения этой проблемы?

Я пытался создать 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;
}

}

1 Ответ

0 голосов
/ 13 февраля 2019

Эти две строки в методе configure(HttpSecurity) относятся к свойствам / переменным, которые, по-видимому, не существуют.

.successHandler(successHandler)
.failureHandler(authenticationFailureHandler)

Я вижу, вы создали MySimpleUrlAuthenticationSuccessHandler.Укажите экземпляр этого класса для successHandler.И проделайте то же самое с failureHandler с экземпляром вашего пользовательского / связанного AuthenticationFailureHandler.

Я полагаю, что упомянутое вами предупреждение требует определения AuthenticationSuccessHandler как Bean.

@Configuration
class MyConfigurationClass {
   ...

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

Вы можете тогда

.successHandler(myAuthenticationSuccessHandler())
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...