SpringBoot JWT令牌保护、注册、登录、统一异常拦截、封装返回结果

上一篇 SpringBoot Mybatis-Plus逻辑删除和自动填入默认值

一、前言

  • 封装返回结果,错误码、提示消息、返回数据。
  • 统一的异常拦截,对业务上手动抛出的异常或者系统自己抛出的异常进行统一拦截,统一返回数据给前端。
  • JWT(Json Web Token),就是接口令牌,令牌在登录成功的时候返回给前端,前端保存下来,后面所有的请求要传回令牌给服务端,服务端验证令牌来决定放不放行。并且令牌中可以保存用户ID、用户名等信息。
  • 代码用到了Mybatis-Plus,可以看我之前的文章

二、目录结构

QQ截图20210514131542.png

三、Maven依赖包

在pom.xml dependencies添加下面依赖

        
            io.jsonwebtoken
            jjwt
            0.9.1
        

        
            cn.hutool
            hutool-all
            5.6.5
        

        
            org.springframework.security
            spring-security-crypto
            5.3.3.RELEASE
        
  • jjwt就 Java Json Web Token
  • hutool-all 封装了很多好用的Java工具类,强烈推荐,非常好用,官网地址:https://www.hutool.cn/
  • spring-security-crypto 密码加密和解码工具

四、封装统一返回结果

CommonResult 类

package com.llh.springbootdemo.config;


/**
 * @author llh
 */
public class CommonResult {
    private Integer code;
    private String msg;
    private T data;

    public CommonResult(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public CommonResult(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static  CommonResult success(T t) {
        return new CommonResult(200, "操作成功", t);
    }

    public static  CommonResult error(T t) {
        return new CommonResult(300, "操作失败", t);
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "CommonResult{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}


  • 使用
    @PostMapping("/register")
    public CommonResult register(@RequestBody UserInfo userInfo) {
        return CommonResult.success(userInfoService.register(userInfo));
    }

    @PostMapping("/login")
    public CommonResult login(@RequestBody UserInfo userInfo) {
        return CommonResult.success(userInfoService.login(userInfo));
    }

返回结果如下:

{
    "code": 200,
    "msg": "操作成功",
    "data": true
}

五、统一异常拦截

GlobalExceptionHandler 类

package com.llh.springbootdemo.config;


import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author llh
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public CommonResult exceptionHandler(Exception e) {
        return CommonResult.error(e.getMessage());
    }
}
  • 这里只是做了Exception的处理,您可以加上自定义的异常处理。

六、注册功能

PasswordEncoder#encode对密码进行加密,加密是非对称加密,就是相同的密码加密后的字符串都不一样。

    @Override
    public Boolean register(UserInfo userInfo) {
        List selectedList = list(new LambdaQueryWrapper()
                .eq(UserInfo::getUsername, userInfo.getUsername()));
        if (!selectedList.isEmpty()) {
            throw new RuntimeException("注册失败,该用户名已存在");
        }
        // 密码加密
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = passwordEncoder.encode(userInfo.getPassword());
        userInfo.setPassword(encodedPassword);
        return save(userInfo);
    }

七、登录功能

PasswordEncoder#matches验证密码

    @Override
    public String login(UserInfo userInfo) {
        List selectedList = list(new LambdaQueryWrapper()
                .eq(UserInfo::getUsername, userInfo.getUsername()));
        if (selectedList.isEmpty()) {
            throw new RuntimeException("登录失败,账号不存在");
        }
        UserInfo selected = selectedList.get(0);
        String encodedPassword = selected.getPassword();
        // 判断密码是否正确
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        boolean result = passwordEncoder.matches(userInfo.getPassword(), encodedPassword);
        if (!result) {
            throw new RuntimeException("登录失败,用户密码错误");
        }
        // 生成令牌
        HashMap map = new HashMap<>(2);
        map.put("userId", selected.getId());
        String token = JwtUtil.generateToken(map);
        return token;
    }

八、JWT的生成与验证工具类

JwtUtil 类

package com.llh.springbootdemo.utils;

import cn.hutool.core.date.DateUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

/**
 * @author llh
 */
public class JwtUtil {
    /**
     * 令牌密码 不少于32位
     */
    private static final String SECRET = "token_secret";

    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "Bearer";

    /**
     * 令牌过期时间
     */
    private static final Integer EXPIRE_SECONDS = 60 * 60 * 24 * 7;


    /**
     * 生成令牌
     */
    public static String generateToken(Map map) {
        String jwt = Jwts.builder()
                .setSubject("user info").setClaims(map)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setExpiration(DateUtil.offsetSecond(new Date(), EXPIRE_SECONDS))
                .compact();
        return TOKEN_PREFIX + "_" + jwt;
    }

    /**
     * 验证令牌
     */
    public static Map resolveToken(String token) {
        if (token == null) {
            throw new RuntimeException("令牌为空");
        }
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replaceFirst(TOKEN_PREFIX + "_", ""))
                    .getBody();
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("令牌已过期");
        } catch (Exception e) {
            throw new RuntimeException("令牌解析异常");
        }
    }

}

九、统一请求拦截

拦截所有的请求进入拦截器,从请求头获取令牌,解析令牌,并保存用户ID到上下文对象中

TokenInterceptor 类 令牌拦截器

package com.llh.springbootdemo.config;

import com.llh.springbootdemo.utils.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author llh
 */
public class TokenInterceptor implements HandlerInterceptor {

    /**
     * 请求头
     */
    private static final String HEADER_AUTH = "Authorization";

    /**
     * 安全的url,不需要令牌
     */
    private static final List SAFE_URL_LIST = Arrays.asList("/userInfo/login", "/userInfo/register");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        response.setContentType("application/json; charset=utf-8");

        String url = request.getRequestURI().substring(request.getContextPath().length());
        System.out.println(url);
        // 登录和注册等请求不需要令牌
        if (SAFE_URL_LIST.contains(url)) {
            return true;
        }

        // 从请求头里面读取token
        String token = request.getHeader(HEADER_AUTH);
        if (token == null) {
            throw new RuntimeException("请求失败,令牌为空");
        }

        // 解析令牌
        Map map = JwtUtil.resolveToken(token);
        Long userId = Long.parseLong(map.get("userId").toString());
        ContextHolder.setUserId(userId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ContextHolder.shutdown();
    }
}
  • 所有的请求都通过preHandle方法
  • ContextHolder.setUserId(userId);请求开始将解析的用户id放入上下文对象。
  • ContextHolder.shutdown();请求结束从上下文对象中剔除用户id。

WebMvcConfiguration 类 添加拦截器到MVC配置中

package com.llh.springbootdemo.config;


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * @author llh
 */
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TokenInterceptor());
    }
}

ContextHolder 类 上下文对象类

package com.llh.springbootdemo.config;

/**
 * @author llh
 */
public class ContextHolder {
    public static ThreadLocal context = new ThreadLocal<>();

    public static void setUserId(Long userId) {
        context.set(userId);
    }

    public static Long getUserId() {
        return context.get();
    }

    public static void shutdown() {
        context.remove();
    }
}

  • 主要用到了ThreadLocal,就是在一个请求线程中都可以获取到上下文对象。
  • 如修改密码 Long userId = ContextHolder.getUserId(); 获取用户id。
  • 修改密码根据用户id去更新数据,用户id直接从上下文对象中拿,这样就不用从前端传过来,如果从前端传过来,相当于任何人都能修改其它人的密码了,非常不安全。
  • 从上下文中拿,也就是从令牌中拿,对接口就行了保护,只能自己操作自己的数据。
    @Override
    public Boolean changePassword(UserInfo userInfo) {
        // 密码加密
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = passwordEncoder.encode(userInfo.getPassword());

        UserInfo updateUserInfo = new UserInfo();
        updateUserInfo.setPassword(encodedPassword);
        // 从上下文对象里面获取用户id,而不是用户传过来的
        Long userId = ContextHolder.getUserId();
        updateUserInfo.setId(userId);
        return updateById(updateUserInfo);
    }

十、完整的代码

UserInfoService

package com.llh.springbootdemo.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.llh.springbootdemo.entity.UserInfo;

/**
 * @author llh
 */
public interface UserInfoService extends IService {
    /**
     * 注册
     *
     * @param userInfo 注册信息
     * @return 是否成功
     */
    Boolean register(UserInfo userInfo);

    /**
     * 登录
     *
     * @param userInfo 登录信息
     * @return 令牌
     */
    String login(UserInfo userInfo);

    /**
     * 更改密码
     *
     * @param userInfo 用户信息
     * @return 是否成功
     */
    Boolean changePassword(UserInfo userInfo);
}


UserInfoServiceImpl

package com.llh.springbootdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.llh.springbootdemo.config.ContextHolder;
import com.llh.springbootdemo.entity.UserInfo;
import com.llh.springbootdemo.mapper.UserInfoMapper;
import com.llh.springbootdemo.service.UserInfoService;
import com.llh.springbootdemo.utils.JwtUtil;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * @author llh
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl implements UserInfoService {
    @Override
    public Boolean register(UserInfo userInfo) {
        List selectedList = list(new LambdaQueryWrapper()
                .eq(UserInfo::getUsername, userInfo.getUsername()));
        if (!selectedList.isEmpty()) {
            throw new RuntimeException("注册失败,该用户名已存在");
        }
        // 密码加密
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = passwordEncoder.encode(userInfo.getPassword());
        userInfo.setPassword(encodedPassword);
        return save(userInfo);
    }

    @Override
    public String login(UserInfo userInfo) {
        List selectedList = list(new LambdaQueryWrapper()
                .eq(UserInfo::getUsername, userInfo.getUsername()));
        if (selectedList.isEmpty()) {
            throw new RuntimeException("登录失败,账号不存在");
        }
        UserInfo selected = selectedList.get(0);
        String encodedPassword = selected.getPassword();
        // 判断密码是否正确
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        boolean result = passwordEncoder.matches(userInfo.getPassword(), encodedPassword);
        if (!result) {
            throw new RuntimeException("登录失败,用户密码错误");
        }
        // 生成令牌
        HashMap map = new HashMap<>(2);
        map.put("userId", selected.getId());
        String token = JwtUtil.generateToken(map);
        return token;
    }

    @Override
    public Boolean changePassword(UserInfo userInfo) {
        // 密码加密
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = passwordEncoder.encode(userInfo.getPassword());

        UserInfo updateUserInfo = new UserInfo();
        updateUserInfo.setPassword(encodedPassword);
        // 从上下文对象里面获取用户id,而不是用户传过来的
        Long userId = ContextHolder.getUserId();
        updateUserInfo.setId(userId);
        return updateById(updateUserInfo);
    }

}


UserInfoController

package com.llh.springbootdemo.controller;

import com.llh.springbootdemo.config.CommonResult;
import com.llh.springbootdemo.entity.UserInfo;
import com.llh.springbootdemo.service.UserInfoService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author llh
 */
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {
    @Resource
    private UserInfoService userInfoService;


    @PostMapping("/register")
    public CommonResult register(@RequestBody UserInfo userInfo) {
        return CommonResult.success(userInfoService.register(userInfo));
    }

    @PostMapping("/login")
    public CommonResult login(@RequestBody UserInfo userInfo) {
        return CommonResult.success(userInfoService.login(userInfo));
    }

    @PostMapping("/changePassword")
    public CommonResult changePassword(@RequestBody UserInfo userInfo) {
        return CommonResult.success(userInfoService.changePassword(userInfo));
    }

}


pom.xml



    
        org.springframework.boot
        spring-boot-starter-parent
        2.3.2.RELEASE
         
    

    4.0.0
    com.llh
    spring-boot-demo
    1.0.0
    spring-boot-demo
    springboot project description

    
        2.1.4
        3.4.2
    

    
        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            mysql
            mysql-connector-java
        

        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            ${mybatis-spring-boot.version}
        

        
            com.baomidou
            mybatis-plus-boot-starter
            ${mybatis-plus.version}
        

        
            io.jsonwebtoken
            jjwt
            0.9.1
        

        
            cn.hutool
            hutool-all
            5.6.5
        

        
            org.springframework.security
            spring-security-crypto
            5.3.3.RELEASE
        
    



十一、测试

11.1 注册

查看数据库 密码是加密后的


1112.png
QQ截图20210517091142.png

11.2 登录

登录成功返回令牌


QQ截图20210517090905.png

11.3 修改密码

需要在请求头Authorization加上令牌

QQ截图20210517090954.png

密码修改由123456->12345678


QQ截图20210517091107.png

十二、结语

源码地址:https://github.com/tigerleeli/xiaohuge-blog/tree/master/spring-boot-jwt

你可能感兴趣的:(SpringBoot JWT令牌保护、注册、登录、统一异常拦截、封装返回结果)