SpringBoot Security权限控制自定义failureHandler实例
短信预约 -IT技能 免费直播动态提醒
创建hander文件夹
在 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);
// 使用该方法会出现错误
// request.getRequestDispatcher(strUrl).forward(request, response);
response.sendRedirect(strUrl);
}
}
修改WebSecurityConfig配置
修改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();
}
以上就是SpringBoot Security权限控制自定义failureHandler实例的详细内容,更多关于SpringBoot Security failureHandler的资料请关注编程网其它相关文章!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341