Java 如何解决';authenticationFailureHandler';的未解决编译问题;春天的安全?
我正在使用SpringSecurity为我的web应用程序构建一个身份验证入口点。现在,除了由于我的successHandler()和failureHandler()方法导致编译错误,用户无法登录之外,mr注册还可以正常工作 记录的错误为:java.lang.error:未解决的编译问题: successHandler无法解析为变量 authenticationFailureHandler无法解析为变量 我不确定我做错了什么。我正在粘贴spring boot应用程序的安全配置代码。为了解决这个问题,我需要在哪里添加所需的变量或参数(如果有) 我尝试创建两个带有私有修饰符的变量,它们表示处理程序的相同参数,但仍然不起作用Java 如何解决';authenticationFailureHandler';的未解决编译问题;春天的安全?,java,spring,spring-boot,spring-security,Java,Spring,Spring Boot,Spring Security,我正在使用SpringSecurity为我的web应用程序构建一个身份验证入口点。现在,除了由于我的successHandler()和failureHandler()方法导致编译错误,用户无法登录之外,mr注册还可以正常工作 记录的错误为:java.lang.error:未解决的编译问题: successHandler无法解析为变量 authenticationFailureHandler无法解析为变量 我不确定我做错了什么。我正在粘贴spring boot应用程序的安全配置代码。为了解决这个问
@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;
}
}
公共类mysimpleurauthenticationsuccesshandler实现
AuthenticationSuccessHandler{
受保护的最终日志记录器=LogFactory.getLog(this.getClass());
受保护的int SessionTimeout=1*60;
private RedirectStrategy RedirectStrategy=新的DefaultRedirectStrategy();
public MySimpleUrlAuthenticationSuccessHandler(){
超级();
}
//原料药
@凌驾
验证成功时的公共无效(最终HttpServletRequest请求,最终
HttpServletResponse,最终身份验证)抛出
IOException{
处理(请求、响应、身份验证);
clearAuthenticationAttributes(请求);
}
//恳求
受保护的无效句柄(最终HttpServletRequest请求,最终
HttpServletResponse,最终身份验证)抛出
IOException{
最终字符串targetUrl=determiniteTargetUrl(身份验证);
if(response.isCommitted()){
logger.debug(“已提交响应。无法
重定向到“+targetUrl”);
返回;
}
redirectStrategy.sendRedirect(请求、响应、目标URL);
}
受保护的字符串determinateTargetUrl(最终身份验证){
布尔值isUser=false;
布尔值isAdmin=false;
最终集合configure(HttpSecurity)
方法中的这两行引用了似乎不存在的属性/变量
.successHandler(successHandler)
.failureHandler(authenticationFailureHandler)
我看到您已经创建了您的MySimpleUrlAuthenticationSuccessHandler
。请向successHandler
提供该类的实例。并使用自定义/绑定的AuthenticationFailureHandler
的实例对failureHandler
执行相同的操作
我想您提到的警告需要将AuthenticationSuccessHandler
定义为Bean
@Configuration
class MyConfigurationClass {
...
@Bean
AuthenticationSuccessHandler myAuthenticationSuccessHandler() {
return new MyCustomOrBundledAuthenticationSuccessHandler();
}
}
那么你可以
.successHandler(myAuthenticationSuccessHandler())
我已经实例化了捆绑的
failureHandler
和successHandler
,它们删除了错误。但是在运行时,错误日志告诉我考虑在您的配置中定义一个类型为“org.springframework.security.web.authentication.AuthenticationSuccessHandler”的bean。
有解决方法吗?