Fork me on GitLab

JWT+MD5+WebMVC的token配置

  1.导入pom文件

<!--       slf4j-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<!-- jwt-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version> </dependency>

  2.创建工具类

// md5
public
String getMd5(String password){ return DigestUtils.md5DigestAsHex(password.getBytes()); }
public class JWTUtil {
    // token 私钥
    private static final String TOKEN_SECRET = "f23sda56d6a1d1adawgdssf1se";
    // 有效时间
    private static final long TOKEN_TIME = 30 * 60 * 1000;
    // 生成token
    public String sing(String userName, String userId){
        // 过期时间
        Date date = new Date(System.currentTimeMillis() + TOKEN_TIME);
        // 私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC512(TOKEN_SECRET);
        // 设置头部信息
        HashMap<String, Object> header = new HashMap<>();
        header.put("typ", "JWT");
        header.put("alg", "HS512");
        return JWT.create()
                .withHeader(header)
                .withClaim("userName", userName)
                .withClaim("userId", userId)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    // 解码token
    public boolean verfiy(String token){
        try{
            Algorithm algorithm = Algorithm.HMAC512(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT verify = verifier.verify(token);
            return true;
        }catch (Exception e){
            return false;
        }
    }
}

jwt刷新配置

@ControllerAdvice
public class JwtRefreshAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest req,
                                  ServerHttpResponse resp) {
        ServletServerHttpRequest ssReq = (ServletServerHttpRequest)req;
        ServletServerHttpResponse ssResp = (ServletServerHttpResponse)resp;
        if(ssReq == null || ssResp == null
                || ssReq.getServletRequest() == null
                || ssResp.getServletResponse() == null) {
            return body;
        }

        HttpServletResponse response = ssResp.getServletResponse();

        //刷新jwt
        JwtModel jwtModel = JwtContextHolder.getJwtModel();
        if (null == jwtModel) {
            return body;
        }
        JwtUtil.createSession(jwtModel.getData(),response);

        // 防止ThredLocal未回收导致的内存溢出
        JwtContextHolder.reset();

        return body;
    }
}

WebMVC中配置

@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowCredentials(true)
                .allowedMethods("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE")
                .exposedHeaders("TOKEN");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SessionInterceptor())
                .addPathPatterns("/admin/**")
                .addPathPatterns("/web/**")
                // 添加配置 /web下的接口不能直接访问
                .excludePathPatterns("/admin/login")
                .excludePathPatterns("/app/sign/checkAutoPay")
                .excludePathPatterns("/app/sign/getToken")
                .excludePathPatterns("/app/sign/checkPhone")
                .excludePathPatterns("/app/sign/register")
                .excludePathPatterns("/app/sign/login")
                .excludePathPatterns("/app/sign/sendMsgYzm")
                .excludePathPatterns("/app/sign/autoLogin")
                .excludePathPatterns("/app/sign/boundUser")
                .excludePathPatterns("/app/sign/chooseUser");
    }

}

登陆成功后创建token放入请求头

 public static void createSession(Map<String, Object> data, HttpServletResponse response, int expireTime) {
        JwtModel jwtModel = new JwtModel();
        //设置过期时间
        jwtModel.setExpireDate(DateUtils.addMilliseconds(new Date(), expireTime));
        jwtModel.setData(data);
        String jwt = JwtUtil.createJwt(jwtModel);
        response.setHeader(TOKEN_NAME, jwt);
    }

 

posted @ 2020-08-19 13:44  隐琳琥  阅读(428)  评论(0编辑  收藏  举报