SpringBoot集成JWT

pom.xml

<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>

com.jwt.config

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public JwtInterceptor jwtInterceptor(){
        return new JwtInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration registration = registry.addInterceptor(jwtInterceptor());
        registration
                .addPathPatterns("/jwt/**") //拦截所有jwt开头的url
                .excludePathPatterns("/jwt/login","/jwt/parse"); //除了这两个地址以外
    }
}

com.jwt.utils

@Slf4j
public class JwtUtils {

    /**
     * 存放token的请求头对应的key的名字
     */
    private static String headKey = "token";
    /**
     * 加密的secret
     */
    private static String secret = "lzxTestSecret";
    /**
     * 过期时间,单位为秒
     */
    private static long expireTime = 1800L;


    /**
     * 生成jwt token
     *
     * @param userInfoMap
     * @return
     */
    public static String generateToken(Map<String, Object> userInfoMap) {
        if (Objects.isNull(userInfoMap)) {
            userInfoMap = new HashMap<>(16);
        }
        //过期时间
        Date expireDate = new Date(System.currentTimeMillis() + expireTime * 1000);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT") //设置头部信息
                .setExpiration(expireDate) //过期时间
                .setClaims(userInfoMap) //自定义信息
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();

    }

    /**
     * 校验token并解析token
     *
     * @param token
     * @return
     */
    public static Claims verifyAndGetClaimsByToken(String token) {
        try {
            return Jwts.parser().setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getHeadKey(){
        return headKey;
    }
}
public class JwtInterceptor extends HandlerInterceptorAdapter {

    public static final String USER_INFO_KEY = "user_info_key";

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

        //获取token
        String token = request.getHeader(JwtUtils.getHeadKey());
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter(JwtUtils.getHeadKey());
        }
        //token为空
        if (StringUtils.isEmpty(token)) {
            this.writerErrorMsg("401", JwtUtils.getHeadKey() + " can not be blank", response);
            return false;
        }

        //校验并解析token,如果token过期或被篡改,返回null
        Claims claims = JwtUtils.verifyAndGetClaimsByToken(token);
        if (null == claims) {
            this.writerErrorMsg("401", JwtUtils.getHeadKey() + " 失效,请重新登录", response);
            return false;
        }

        //校验通过后,设置用户信息到request中,
        request.setAttribute(USER_INFO_KEY, claims);
        return true;
    }

    /**
     * 利用response直接输出错误信息
     *
     * @param code
     * @param msg
     * @param response
     * @throws IOException
     */
    private void writerErrorMsg(String code, String msg, HttpServletResponse response) throws IOException {
        Map<String, Object> result = new HashMap<>();
        result.put("code", code);
        result.put("msg", msg);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(result));
    }

}
@RestController
@RequestMapping("jwt")
public class TestJwtController {


    /**
     * 模拟登录
     * @param dto
     * @return
     */
    @PostMapping("login")
    public String login(@RequestBody User dto) {
        // 这里登录就简单的模拟下
        if ("wsl".equals(dto.getUserName()) && "123456".equals(dto.getPassword())) {
            Map<String, Object> userInfoMap = new HashMap<>();
            for (int i = 0; i < 10; i++) {
                userInfoMap.put("userName"+i, "隔壁老王" + i);
            }
            String token = JwtUtils.generateToken(userInfoMap);
            return token;
        } else {
            System.out.println("用户名或密码错误");
        }
        return null;
    }

    /**
     * 解码
     * @param token
     * @return
     */
    @GetMapping("/parse")
    public Claims parse(String token){
        return JwtUtils.verifyAndGetClaimsByToken(token);
    }

    /**
     * 测试拦截url
     * @param request
     * @return
     */
    @GetMapping("test")
    public String test(HttpServletRequest request) {
        // 登录成功后,从request中获取用户信息
        Claims claims = (Claims) request.getAttribute(JwtInterceptor.USER_INFO_KEY);
        if (null != claims) {
            return (String) claims.get("userName");
        } else {
            return "fail";
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值