JAVA全系列 教程
3762个小节阅读:7095.4k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
接下来我们使用Spring Security编写管理员认证和授权功能。Spring Security在访问接口时进行认证和授权,所以Spring Security的相关代码编写在管理员API模块。
之前使用Spring Security时,登录后会配置跳转页面。但百战商城是前后端分离项目,所有认证和授权的结果,只是返回json字符串让前端去处理。所以我们要创建认证成功处理器
、认证失败处理器
、未登录处理器
、权限不足处理器
、登出成功处理器
处理不同的结果,Spring Security通过实现接口编写结果处理器。
在管理员API模块引入Spring Security的依赖
xxxxxxxxxx
<!-- spring security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
编写认证成功、认证失败处理器
xxxxxxxxxx
// 登录成功处理器
public class MyLoginSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setContentType("text/json;charset=utf-8");
BaseResult result = new BaseResult(200, "登录成功", null);
response.getWriter().write(JSON.toJSONString(result));
}
}
// 登录失败处理器
public class MyLoginFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.setContentType("text/json;charset=utf-8");
BaseResult result = new BaseResult(402, "用户名或密码错误", null);
response.getWriter().write(JSON.toJSONString(result));
}
}
编写未登录处理器
xxxxxxxxxx
// 未登录处理器
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.setContentType("text/json;charset=utf-8");
BaseResult result = new BaseResult(401, "用户名未登录", null);
response.getWriter().write(JSON.toJSONString(result));
}
}
编写权限不足处理器
xxxxxxxxxx
// 权限不足处理器
public class MyAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.setContentType("text/json;charset=utf-8");
BaseResult result = new BaseResult(403, "权限不足", null);
response.getWriter().write(JSON.toJSONString(result));
}
}
编写登出成功处理器
xxxxxxxxxx
// 登出成功处理器
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setContentType("text/json;charset=utf-8");
BaseResult result = new BaseResult(200, "注销成功", null);
response.getWriter().write(JSON.toJSONString(result));
}
}