美文网首页
JWT放到拦截器中使用

JWT放到拦截器中使用

作者: 天马行空_9f6e | 来源:发表于2021-07-09 14:05 被阅读0次

    maven进入包

    <!--    start    jwt引入-->

    <dependency>

    <groupId>io.jsonwebtoken</groupId>

    <artifactId>jjwt</artifactId>

    <version>0.9.1</version>

    </dependency>

    <!--    end    jwt引入-->

    新建一个类ResultVO作为返回前端的类型

    package com.bruce.vo;

    import io.swagger.annotations.ApiModel;

    import io.swagger.annotations.ApiModelProperty;

    import lombok.AllArgsConstructor;

    import lombok.Data;

    import lombok.NoArgsConstructor;

    import lombok.ToString;

    /**

    * @Auther:BruceWong

    * @Date: 2021/6/16 - 06 - 16 - 11:15

    * @Description:com.bruce.vo

    * @Version: 1.0

    */

    @Data

    @NoArgsConstructor

    @AllArgsConstructor

    @ToString

    @ApiModel(value = "响应的VO对象",description = "封装接口返回给前端的数据")

    public class ResultVO {

        @ApiModelProperty("响应状态码")

        private int code;

        @ApiModelProperty("响应提示信息")

        private String msg;

        @ApiModelProperty("响应数据内容")

        private Object data;

    }

    新建一个类TokenInterceptor并实现HandlerInterceptor

    package com.bruce.interceptor;

    import com.bruce.vo.ResultStatus;

    import com.bruce.vo.ResultVO;

    import com.bruce.vo.TokenSecret;

    import com.fasterxml.jackson.databind.ObjectMapper;

    import io.jsonwebtoken.*;

    import org.springframework.stereotype.Component;

    import org.springframework.web.servlet.HandlerInterceptor;

    import javax.servlet.http.HttpServletRequest;

    import javax.servlet.http.HttpServletResponse;

    import java.io.IOException;

    import java.io.PrintWriter;

    @Component

    public class TokenInterceptor implements HandlerInterceptor {

        @Override

        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

            String method = request.getMethod();

            if ("options".equalsIgnoreCase(method)) {

                return true;

            }

            String token = request.getHeader("token");

            if (token == null) {

                ResultVO resultVO = new ResultVO(ResultStatus.NO, "请先登录", null);

                doResponse(response, resultVO);

            } else {

                try {

                    JwtParser parser = Jwts.parser();

                    parser.setSigningKey(TokenSecret.SUFIX);

                    Jws<Claims> claimsJws = parser.parseClaimsJws(token);

                    return HandlerInterceptor.super.preHandle(request, response, handler);

                } catch (ExpiredJwtException e) {

                    ResultVO resultVO = new ResultVO(ResultStatus.NO, "登录过期请重新登录", null);

                    doResponse(response, resultVO);

                } catch (UnsupportedJwtException e) {

                    ResultVO resultVO = new ResultVO(ResultStatus.NO, "Token不合法,请自重", null);

                    doResponse(response, resultVO);

                } catch (Exception e) {

                    ResultVO resultVO = new ResultVO(ResultStatus.NO, "请先登录", null);

                    doResponse(response, resultVO);

                }

            }

            return false;

        }

        private void doResponse(HttpServletResponse response, ResultVO resultVO) throws IOException {

            response.setContentType("application/json");

            response.setCharacterEncoding("utf-8");

            PrintWriter out = response.getWriter();

            String s = new ObjectMapper().writeValueAsString(resultVO);

            out.print(s);

            out.flush();

            out.close();

        }

    }

    新建一个拦截器的配置类InterceptorConfig并实现WebMvcConfigurer接口

    package com.bruce.config;

    import com.bruce.interceptor.TokenInterceptor;

    import org.springframework.beans.factory.annotation.Autowired;

    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 {

        @Autowired

        private TokenInterceptor checkTokenInterceptor;

        @Override

        public void addInterceptors(InterceptorRegistry registry) {

            registry.addInterceptor(checkTokenInterceptor)

                    .addPathPatterns("/shopcart/**").addPathPatterns("/order/**")  //设置要拦截过滤的请求url

                    .excludePathPatterns("/user/**");                              //设置不要要拦截过滤的请求url

        }

    }

    配置过后,当请求/shopcart或/order路径下的内容的时候,就会过滤判断如果没有发现token或者token有问题则会被拦截

    相关文章

      网友评论

          本文标题:JWT放到拦截器中使用

          本文链接:https://www.haomeiwen.com/subject/xcjfpltx.html