• SpringBoot整合JWT、实现登录和拦截


    一、JWT简介

    1.什么是JWT

    JWT其全称为JSON Web Token,官网地址:https://jwt.io/

    JSON Web令牌(JWT)是一个开放标准(RFC 7519),它定义了一种紧凑和自成一体的方式,用于在各方之间作为JSON对象安全地传输信息。这些信息可以被验证和信任,因为它是数字签名的。JWT可以使用秘密(使用HMAC算法)或使用RSA或ECDSA进行公钥/私钥对进行签名。

    它将用户信息加密到token里,服务器不保存任何用户信息。服务器通过使用保存的密钥验证token的正确性,只要正确即通过验证;应用场景如用户登录。

    2.为什么要用JWT

    随着技术的发展,分布式web应用的普及,通过session管理用户登录状态成本越来越高,因此慢慢发展成为token的方式做登录身份校验,然后通过token去取redis中的缓存的用户信息,随着之后jwt的出现,校验方式更加简单便捷化,无需通过redis缓存,而是直接根据token取出保存的用户信息,以及对token可用性校验,单点登录更为简单。

    3.传统Session认证的弊端

    我们知道HTTP本身是一种无状态的协议,这就意味着如果用户向我们的应用提供了用户名和密码来进行用户认证,认证通过后HTTP协议不会记录下认证后的状态,那么下一次请求时,用户还要再一次进行认证,因为根据HTTP协议,我们并不知道是哪个用户发出的请求,所以为了让我们的应用能识别是哪个用户发出的请求,我们只能在用户首次登录成功后,在服务器存储一份用户登录的信息,这份登录信息会在响应时传递给浏览器,告诉其保存为cookie,以便下次请求时发送给我们的应用,这样我们的应用就能识别请求来自哪个用户了,这是传统的基于session认证的过程

    然而,传统的session认证有如下的问题:

    • 每个用户的登录信息都会保存到服务器的session中,随着用户的增多,服务器开销会明显增大
    • 由于session是存在与服务器的物理内存中,所以在分布式系统中,这种方式将会失效。虽然可以将session统一保存到Redis中,但是这样做无疑增加了系统的复杂性,对于不需要redis的应用也会白白多引入一个缓存中间件
    • 对于非浏览器的客户端、手机移动端等不适用,因为session依赖于cookie,而移动端经常没有cookie
    • 因为session认证本质基于cookie,所以如果cookie被截获,用户很容易收到跨站请求伪造攻击。并且如果浏览器禁用了cookie,这种方式也会失效
    • 前后端分离系统中更加不适用,后端部署复杂,前端发送的请求往往经过多个中间件到达后端,cookie中关于session的信息会转发多次
    • 由于基于Cookie,而cookie无法跨域,所以session的认证也无法跨域,对单点登录不适用

    4.JWT认证的优势

    对比传统的session认证方式,JWT的优势是:

    • 简洁:JWT Token数据量小,传输速度也很快
    • 因为JWT Token是以JSON加密形式保存在客户端的,所以JWT是跨语言的,原则上任何web形式都支持
    • 不需要在服务端保存会话信息,也就是说不依赖于cookie和session,所以没有了传统session认证的弊端,特别适用于分布式微服务
    • 单点登录友好:使用Session进行身份认证的话,由于cookie无法跨域,难以实现单点登录。但是,使用token进行认证的话, token可以被保存在客户端的任意位置的内存中,不一定是cookie,所以不依赖cookie,不会存在这些问题
    • 适合移动端应用:使用Session进行身份认证的话,需要保存一份信息在服务器端,而且这种方式会依赖到Cookie(需要 Cookie 保存 SessionId),所以不适合移动端

    5.JWT结构

    JWT由3部分组成:标头(Header)、有效载荷(Payload)和签名(Signature)。在传输的时候,会将JWT的3部分分别进行Base64编码后用.进行连接形成最终传输的字符串 【中间用 . 分隔】

    JWTString=Base64(Header).Base64(Payload).HMACSHA256(base64UrlEncode(header)+"."+base64UrlEncode(payload),secret)
    
    • 1

    一个标准的JWT生成的token格式如下:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI1IiwiaWF0IjoxNTY1NTk3MDUzLCJleHAiOjE1NjU2MDA2NTN9.qesdk6aeFEcNafw5WFm-TwZltGWb1Xs6oBEk5QdaLzlHxDM73IOyeKPF_iN1bLvDAlB7UnSu-Z-Zsgl_dIlPiw

    二、SpringBoot整合JWT

    官网推荐了6个Java使用JWT的开源库,其中比较推荐使用的是java-jwt和jjwt-root

    1.引入依赖

    在pom文件中引入依赖

     <!--JWT-->
     <dependency>
         <groupId>com.auth0</groupId>
         <artifactId>java-jwt</artifactId>
         <version>4.2.1</version>
     </dependency>
     <dependency>
         <groupId>io.jsonwebtoken</groupId>
         <artifactId>jjwt</artifactId>
         <version>0.9.1</version>
     </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2.JWT工具类

    import cn.hutool.core.date.DateUtil;
    import cn.hutool.core.util.StrUtil;
    import com.auth0.jwt.JWT;
    import com.auth0.jwt.algorithms.Algorithm;
    import com.erfou.entity.UserEntity;
    import com.erfou.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    
    import javax.annotation.PostConstruct;
    import javax.servlet.http.HttpServletRequest;
    import java.util.Date;
    
    @Component
    public class TokenUtils {
        private static UserService staticUserService;
    
        @Autowired
        private UserService userService;
    
        @PostConstruct
        public void setUserService(){
            staticUserService=userService;
        }
        public static String genToken(String userId,String sign){
            return JWT.create().withAudience(userId)  //将userId 保存到token里面,作为载荷
                    .withExpiresAt(DateUtil.offsetHour(new Date(),2))//2小时后token过期
                    .sign(Algorithm.HMAC256(sign)); //以sign作为token的密钥
        }
    
        //获取当前登录的用户信息
        public static UserEntity getCurrentUser(){
            try{
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                String token = request.getHeader("token");
                if (StrUtil.isNotBlank(token)){
                    String userId = JWT.decode(token).getAudience().get(0);
                    return staticUserService.getById(Integer.valueOf(userId));
                }
            }catch (Exception e){
                return null;
    
            }
            return null;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48

    3.自定义拦截器

    拦截除login、register外所有请求判断有没有token或token信息

    InterceptorConfig.java

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class InterceptorConfig implements WebMvcConfigurer {
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(jwtInterceptor())
                    .addPathPatterns("/**")
                    .excludePathPatterns("/user/login","/user/register");  //拦截除登录注册以外请求,通过判断token是否合法来决定是否需要登录
        }
    
        @Bean
        public JwtInterceptor jwtInterceptor(){
            return new JwtInterceptor();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    JwtInterceptor.java

    import cn.hutool.core.util.StrUtil;
    import com.auth0.jwt.JWT;
    import com.auth0.jwt.JWTVerifier;
    import com.auth0.jwt.algorithms.Algorithm;
    import com.auth0.jwt.exceptions.JWTDecodeException;
    import com.auth0.jwt.exceptions.JWTVerificationException;
    import com.erfou.constant.HttpStatus;
    import com.erfou.entity.UserEntity;
    import com.erfou.exception.ServiceException;
    import com.erfou.service.UserService;
    import org.springframework.web.servlet.HandlerInterceptor;
    
    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class JwtInterceptor implements HandlerInterceptor {
    
        @Resource
        private UserService userService;
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {
            String token = request.getHeader("token");
            //执行认证
            if (StrUtil.isBlank(token)){
                throw new ServiceException("无token,请重新登录!",HttpStatus.UNAUTHORIZED);
            }
            //获取token中的userId
            String userId;
            try{
                userId= JWT.decode(token).getAudience().get(0);
            }catch (JWTDecodeException j){
                throw new ServiceException("token验证失败,请重新登录!",HttpStatus.UNAUTHORIZED);
            }
            //根据token中的userId查询数据库
            UserEntity user=userService.getById(userId);
            if (user==null){
                throw new ServiceException("用户不存在,请重新登录!",HttpStatus.UNAUTHORIZED);
            }
    
            //用户密码加签验证token
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
            try{
                jwtVerifier.verify(token);  //验证token
            }catch (JWTVerificationException e){
                throw new  ServiceException("token验证失败,请重新登录!",HttpStatus.UNAUTHORIZED);
            }
            return true;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51

    4.异常处理

    1.自定义异常ServiceException

    /**
     * 业务异常
     * 
     * @author ruoyi
     */
    public final class ServiceException extends RuntimeException
    {
        private static final long serialVersionUID = 1L;
    
        /**
         * 错误码
         */
        private Integer code;
    
        /**
         * 错误提示
         */
        private String message;
    
        /**
         * 错误明细,内部调试错误
         *
         *
         */
        private String detailMessage;
    
        /**
         * 空构造方法,避免反序列化问题
         */
        public ServiceException()
        {
        }
    
        public ServiceException(String message)
        {
            this.message = message;
        }
    
        public ServiceException(String message, Integer code)
        {
            this.message = message;
            this.code = code;
        }
    
        public String getDetailMessage()
        {
            return detailMessage;
        }
    
        @Override
        public String getMessage()
        {
            return message;
        }
    
        public Integer getCode()
        {
            return code;
        }
    
        public ServiceException setMessage(String message)
        {
            this.message = message;
            return this;
        }
    
        public ServiceException setDetailMessage(String detailMessage)
        {
            this.detailMessage = detailMessage;
            return this;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72

    2.全局异常处理器

    import com.erfou.constant.HttpStatus;
    import com.erfou.domain.AjaxResult;
    import com.erfou.utils.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.validation.BindException;
    import org.springframework.web.HttpRequestMethodNotSupportedException;
    import org.springframework.web.bind.MethodArgumentNotValidException;
    import org.springframework.web.bind.MissingPathVariableException;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.RestControllerAdvice;
    import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
    
    import javax.servlet.http.HttpServletRequest;
    import java.nio.file.AccessDeniedException;
    
    /**
     * 全局异常处理器
     * 
     * @author ruoyi
     */
    @RestControllerAdvice
    public class GlobalExceptionHandler
    {
        private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
        /**
         * 权限校验异常
         */
        @ExceptionHandler(AccessDeniedException.class)
        public AjaxResult handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request)
        {
            String requestURI = request.getRequestURI();
            log.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
            return AjaxResult.error(HttpStatus.FORBIDDEN, "没有权限,请联系管理员授权");
        }
    
        /**
         * 请求方式不支持
         */
        @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
        public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                HttpServletRequest request)
        {
            String requestURI = request.getRequestURI();
            log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
            return AjaxResult.error(e.getMessage());
        }
    
        /**
         * 业务异常
         */
        @ExceptionHandler(ServiceException.class)
        public AjaxResult handleServiceException(ServiceException e, HttpServletRequest request)
        {
            log.error(e.getMessage(), e);
            Integer code = e.getCode();
            return StringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage());
        }
    
        /**
         * 请求路径中缺少必需的路径变量
         */
        @ExceptionHandler(MissingPathVariableException.class)
        public AjaxResult handleMissingPathVariableException(MissingPathVariableException e, HttpServletRequest request)
        {
            String requestURI = request.getRequestURI();
            log.error("请求路径中缺少必需的路径变量'{}',发生系统异常.", requestURI, e);
            return AjaxResult.error(String.format("请求路径中缺少必需的路径变量[%s]", e.getVariableName()));
        }
    
        /**
         * 请求参数类型不匹配
         */
        @ExceptionHandler(MethodArgumentTypeMismatchException.class)
        public AjaxResult handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request)
        {
            String requestURI = request.getRequestURI();
            log.error("请求参数类型不匹配'{}',发生系统异常.", requestURI, e);
            return AjaxResult.error(String.format("请求参数类型不匹配,参数[%s]要求类型为:'%s',但输入值为:'%s'", e.getName(), e.getRequiredType().getName(), e.getValue()));
        }
    
        /**
         * 拦截未知的运行时异常
         */
        @ExceptionHandler(RuntimeException.class)
        public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request)
        {
            String requestURI = request.getRequestURI();
            log.error("请求地址'{}',发生未知异常.", requestURI, e);
            return AjaxResult.error(e.getMessage());
        }
    
        /**
         * 系统异常
         */
        @ExceptionHandler(Exception.class)
        public AjaxResult handleException(Exception e, HttpServletRequest request)
        {
            String requestURI = request.getRequestURI();
            log.error("请求地址'{}',发生系统异常.", requestURI, e);
            return AjaxResult.error(e.getMessage());
        }
    
        /**
         * 自定义验证异常
         */
        @ExceptionHandler(BindException.class)
        public AjaxResult handleBindException(BindException e)
        {
            log.error(e.getMessage(), e);
            String message = e.getAllErrors().get(0).getDefaultMessage();
            return AjaxResult.error(message);
        }
    
        /**
         * 自定义验证异常
         */
        @ExceptionHandler(MethodArgumentNotValidException.class)
        public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e)
        {
            log.error(e.getMessage(), e);
            String message = e.getBindingResult().getFieldError().getDefaultMessage();
            return AjaxResult.error(message);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127

    3.同一封装返回结果

    
    import com.erfou.constant.HttpStatus;
    import com.erfou.utils.StringUtils;
    
    import java.util.HashMap;
    import java.util.Objects;
    
    /**
     * 操作消息提醒
     * 
     * @author ruoyi
     */
    public class AjaxResult extends HashMap<String, Object>
    {
        private static final long serialVersionUID = 1L;
    
        /** 状态码 */
        public static final String CODE_TAG = "code";
    
        /** 返回内容 */
        public static final String MSG_TAG = "msg";
    
        /** 数据对象 */
        public static final String DATA_TAG = "data";
    
        /**
         * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。
         */
        public AjaxResult()
        {
        }
    
        /**
         * 初始化一个新创建的 AjaxResult 对象
         * 
         * @param code 状态码
         * @param msg 返回内容
         */
        public AjaxResult(int code, String msg)
        {
            super.put(CODE_TAG, code);
            super.put(MSG_TAG, msg);
        }
    
        /**
         * 初始化一个新创建的 AjaxResult 对象
         * 
         * @param code 状态码
         * @param msg 返回内容
         * @param data 数据对象
         */
        public AjaxResult(int code, String msg, Object data)
        {
            super.put(CODE_TAG, code);
            super.put(MSG_TAG, msg);
            if (StringUtils.isNotNull(data))
            {
                super.put(DATA_TAG, data);
            }
        }
    
        /**
         * 返回成功消息
         * 
         * @return 成功消息
         */
        public static AjaxResult success()
        {
            return AjaxResult.success("操作成功");
        }
    
        /**
         * 返回成功数据
         * 
         * @return 成功消息
         */
        public static AjaxResult success(Object data)
        {
            return AjaxResult.success("操作成功", data);
        }
    
        /**
         * 返回成功消息
         * 
         * @param msg 返回内容
         * @return 成功消息
         */
        public static AjaxResult success(String msg)
        {
            return AjaxResult.success(msg, null);
        }
    
        /**
         * 返回成功消息
         * 
         * @param msg 返回内容
         * @param data 数据对象
         * @return 成功消息
         */
        public static AjaxResult success(String msg, Object data)
        {
            return new AjaxResult(HttpStatus.SUCCESS, msg, data);
        }
    
        /**
         * 返回警告消息
         *
         * @param msg 返回内容
         * @return 警告消息
         */
        public static AjaxResult warn(String msg)
        {
            return AjaxResult.warn(msg, null);
        }
    
        /**
         * 返回警告消息
         *
         * @param msg 返回内容
         * @param data 数据对象
         * @return 警告消息
         */
        public static AjaxResult warn(String msg, Object data)
        {
            return new AjaxResult(HttpStatus.WARN, msg, data);
        }
    
        /**
         * 返回错误消息
         * 
         * @return 错误消息
         */
        public static AjaxResult error()
        {
            return AjaxResult.error("操作失败");
        }
    
        /**
         * 返回错误消息
         * 
         * @param msg 返回内容
         * @return 错误消息
         */
        public static AjaxResult error(String msg)
        {
            return AjaxResult.error(msg, null);
        }
    
        /**
         * 返回错误消息
         * 
         * @param msg 返回内容
         * @param data 数据对象
         * @return 错误消息
         */
        public static AjaxResult error(String msg, Object data)
        {
            return new AjaxResult(HttpStatus.ERROR, msg, data);
        }
    
        /**
         * 返回错误消息
         * 
         * @param code 状态码
         * @param msg 返回内容
         * @return 错误消息
         */
        public static AjaxResult error(int code, String msg)
        {
            return new AjaxResult(code, msg, null);
        }
    
        /**
         * 是否为成功消息
         *
         * @return 结果
         */
        public boolean isSuccess()
        {
            return Objects.equals(HttpStatus.SUCCESS, this.get(CODE_TAG));
        }
    
        /**
         * 是否为警告消息
         *
         * @return 结果
         */
        public boolean isWarn()
        {
            return Objects.equals(HttpStatus.WARN, this.get(CODE_TAG));
        }
    
        /**
         * 是否为错误消息
         *
         * @return 结果
         */
        public boolean isError()
        {
            return Objects.equals(HttpStatus.ERROR, this.get(CODE_TAG));
        }
    
        /**
         * 方便链式调用
         *
         * @param key 键
         * @param value 值
         * @return 数据对象
         */
        @Override
        public AjaxResult put(String key, Object value)
        {
            super.put(key, value);
            return this;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217

    3.登录实现

    此处使用的是mybatis-plus查询数据库采用用户名密码登录最后返回token

        public LoginVo login(LoginBo bo) {
            UserEntity user = userMapper.selectOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUsername, bo.getUsername()));
            LoginVo loginVo = new LoginVo();
            if(user!=null){
                if(validPassword(user,bo.getPassword())){
                    loginVo.setToken(TokenUtils.genToken(user.getId().toString(),user.getPassword()));
                }else{
                    throw new BaseException("用户名密码不正确");
                }
            }else{
                throw new BaseException("用户不存在");
            }
            return loginVo;
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    4.调用示例

    登录
    在这里插入图片描述
    错误的token
    在这里插入图片描述

  • 相关阅读:
    Flink RoaringBitmap去重
    排序算法(Java实现)
    数据结构与算法 | 数组(Array)
    Day-07 修改 Nginx 配置文件
    PCB设计仿真之探讨源端串联端接
    聚观早报 | 慧聪网经营困难宣布停工;推特工程副总投奔 Meta
    图像处理之Bolb分析(一)
    2.3线性表的链式表示
    c# Collections
    UDP通信
  • 原文地址:https://blog.csdn.net/qq_43548590/article/details/133792555