自定义登录页面
在自定义的WebSecurityConfigurerAdapter的子类重写的configure方法中添加.loginPage(String url)方法指明登录页的路径。
由于登录页不需要身份验证,所以配置不认证该url。
image.png
自定义登录成功处理
自定义类实现org.springframework.security.web.authentication.AuthenticationSuccessHandler,并重写其onAuthenticationSuccess()方法
image.png
该方法接收一个
Authentication接口实现对象,该对象封装了认证信息。可以将该对象以json方式发送到前台。
@Component(value = "imoocAuthenticationSuccessHandler")
public class ImoocAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Autowired
private ObjectMapper objectMapper;
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Authentication authentication) throws IOException, ServletException {
httpServletResponse.setContentType("application/json; charset=utf-8");
httpServletResponse.getWriter().write(objectMapper.writeValueAsString(authentication));
}
}
image.png
配置successHandler
image.png
自定义登录错误处理
自定义类实现AuthenticationFailureHandler,并重写其 onAuthenticationFailure方法
image.png
该方法接收一个AuthenticationException,封装了认证错误信息。
@Component(value = "imoocAuthenticationFailureHandler")
public class ImoocAuthenticationFailureHandler implements AuthenticationFailureHandler {
@Autowired
private ObjectMapper objectMapper;
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
AuthenticationException e) throws IOException, ServletException {
httpServletResponse.setContentType("application/json; charset=utf-8");
httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); //500错误信息
httpServletResponse.getWriter().write(objectMapper.writeValueAsString(e));
}
}
配置失败处理器
image.png
若要使用SpringSecurity默认的成功处理方式,则继承
SavedRequestAwareAuthenticationSuccessHandler默认认证失败的处理类
SimpleUrlAuthenticationFailureHandler











网友评论