在 java 源码目录下创建hander文件夹, 在该文件夹下创建CustomAuthenticationFailHander类文件
package com.edurt.hander;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component(value = "customAuthenticationFailHander")
public class CustomAuthenticationFailHander extends SimpleUrlAuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
System.out.println("登录失利!!!");
this.returnJson(response, exception);
}
private void returnJson(HttpServletResponse response,
AuthenticationException exception) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().println("{\"ok\":0,\"msg\":\"" + exception.getLocalizedMessage() + "\"}");
}
private void returnErrorPage(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
String strUrl = request.getContextPath() + "/loginErrorPath";
request.getSession().setAttribute("status", 0);
request.getSession().setAttribute("message", exception.getLocalizedMessage());
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
response.sendRedirect(strUrl);
}
}
修正WebSecurityConfig配置文件支持自定义Handler
@Autowired
private CustomAuthenticationFailHander customAuthenticationFailHander;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests().antMatchers("/").permitAll()
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.anyRequest().authenticated()
.and().formLogin().loginPage("/user/login")
.failureHandler(customAuthenticationFailHander)
.defaultSuccessUrl("/").permitAll()
.and().logout().logoutSuccessUrl("/user/login").permitAll();
}