spring security的登录文件一般会自己重新定义,重新里面的方法 configure,设置方法参数属性,达到重新自定意拦截登录以及重定向方法的作用。
方法参数为 HttpSecurity http
//设置表单提交
http.formLogin().
//重新定义表单的username接受值的key
usernameParameter("name").
//重新定义表单的password接受值的key
passwordParameter("pass").
//当发现/login为登录时,必须和表单提交的地址一致,去执行UserDateilsServiceImpl
loginProcessingUrl("/login").
//自定义登录页面
loginPage("/login.html").
//登录成功后跳转页面,POST请求
successForwardUrl("toMain").
//登录成功后的处理器,不能和successForwardUrl共存
successHandler(new MyAuthenticationSuccessHandler("自定西成功路径")).
//登录失败跳转路径,POST请求
failureForward("/toError").
//登录失败后处理器,不能和failuerForward共存
failureHandler(new MyAuthenticationFailureHandler("自定失败处理页面路径.html"));
//请求拦截的配置
//授权认证
http.authorizeRequests()
//登录失败页面不需要认证拦截
.antMatchers("/error.html").permitAll()
//去登陆页面不需要认证拦截
.antMatchers("/login.html").permitAll()
//除了登陆和登陆出错的页面,其他的请求都应该被拦截,需要认证才能访问
.anyRequest().authenticated();
//关系CSRF防护
http.csrf().disable();
//自定义错误信息以及返回的状态码和描述
htt.exceptionHandling()
.authenticationEntryPoint(authenticationErrorHandler)
.accessDeniedHandler(jwtAccessDeniedHandler)
MyAuthenticationSuccessHandler和MyAuthenticationFailureHandler是自定义的跳转类,需要实现对应的AuthenticationSuccessHandler和AuthenticationFailureHandler里面的方法进行重写。
authenticationErrorHandler和jwtAccessDeniedHandler 都是实现对应方法进行重写,已jwtAccessDeniedHandler 错误的重现代码示例:
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
// 当用户尝试访问安全的REST资源而不提供任何凭据时,将调用此方法发送401 响应
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException==null?"Unauthorized":authException.getMessage());
}
}