目录
1、JWT定义
1、1 JWT工作流程
1、2 JWT优点
2、添加依赖项到pom.xml
3、创建用户实体类
4、实现认证服务
5、登录请求处理
6、生成JWT
JWT(JSON Web Token)是一种用于在网络应用间传递信息的安全传输方式。它是一种紧凑且自包含的方式,通过使用数字签名来验证数据的完整性和真实性。
JWT由三部分组成,使用.
进行分隔:
优点包括:
org.springframework.boot
spring-boot-starter-security
io.jsonwebtoken
jjwt
0.9.1
创建一个表示用户的实体类,例如User
,其中包含用户名和密码等属性。
如下:
创建一个类实现Spring Security的UserDetailsService
接口,用于加载用户信息。在该类中,根据用户名查询数据库,获取用户信息,包括密码。
public List findAllService() {
return userMapper.findAllUser();
}
public ResultResponse login(String name,String password) {
UserEntity user=userMapper.checkPassword(name,password);
if(user != null){
//不等于null就开始颁发jwt
String token = jwtUtils.generateToken(name);
System.out.println(token);
return ResultResponse.returnToken(ResultResponse.success("颁发token成功",token));
}
return ResultResponse.illegalToken();
}
public ResultResponse info(String token) {
String tokenString = token;
String subject = JwtUtils.getSubject(tokenString);
UserDTO userinfo=userMapper.getUserByUsername(subject);
int status=userinfo.getStatus();
if(status==1){
String role=userinfo.getRoleName();
Map map = new HashMap<>();
String[] roles = {role};
map.put("name", userinfo.getName());
map.put("avatar", userinfo.getAvatar());
map.put("roles", roles);
return ResultResponse.returnToken(ResultResponse.success("用户信息获取成功",map));
}
return ResultResponse.returnToken(ResultResponse.fail("用户已经被禁用",userinfo));
}
创建一个登录请求处理的Controller,用于处理用户登录请求。在该Controller中,接收用户名和密码参数,并进行认证。
@CrossOrigin
@PostMapping("/user/login")
public ResultResponse login(@RequestBody UserEntity user) {
String username = user.getUsername();
String password = user.getPassword();
// 生成JWT并返回给客户端,用户名和密码正确就生成jwt
return userService.login(username,password);
}
在认证成功后,使用JJWT库生成JWT,并将JWT作为响应返回给客户端.
@Component
public class InterceptorConfig implements WebMvcConfigurer {
private JdbcTemplate jdbcTemplate;
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptor() {
//给前端输出json的方法
private void returnJson(HttpServletResponse response, String json) throws Exception{
PrintWriter writer = null;
try {
writer = response.getWriter();
writer.write(json);
} catch (IOException e) {
} finally {
if (writer != null)
writer.close();
}
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("已经进入拦截器");
// 设置跨域访问的响应头信息
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, X-Token");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=utf-8");
// 获取tokenHeader
String tokenHeader = request.getHeader("x-token");
System.out.println("前端传入X-Token是============="+tokenHeader);
// 进行token合法性验证
if(!JwtUtils.validateToken(tokenHeader)){
String jsonString = JSON.toJSONString(ResultResponse.illegalToken());
returnJson(response,jsonString);
System.out.println("未放行!!!");
return false;
}
// 鉴权操作
String path = request.getRequestURI();
String sub = JwtUtils.getSubject(tokenHeader);
System.out.println(path);
// 从数据库中查询用户角色id
Integer roleId = jdbcTemplate.queryForObject("SELECT role FROM tskj_user WHERE name = ?", Integer.class, sub);
String targets = jdbcTemplate.queryForObject("SELECT targets FROM tskj_role WHERE id = ?", String.class, roleId);
String tarid = jdbcTemplate.queryForObject("SELECT id FROM tskj_target WHERE target = ? and status=1", String.class, path);
if (targets.contains(tarid)) {
System.out.println("拥有此节点权限:"+path);
} else {
String jsonString = JSON.toJSONString(ResultResponse.illegalToken());
returnJson(response,jsonString);
System.out.println("不拥有此节点权限:"+path);
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// System.out.println("请求处理完毕,但还没有进行视图渲染");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// System.out.println("整个请求处理完成,视图已渲染完毕");
}
}).addPathPatterns("/**/*").excludePathPatterns("/tskj/user/login","/static/*","/tskj/setting/getSetData","/tskj/user/logout");
System.out.println("拦截器已经初始化并添加成功");
WebMvcConfigurer.super.addInterceptors(registry);
}
public InterceptorConfig(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
以上步骤是一个基本的实现流程。
,结束!下课!