jwttoken

本文介绍了如何在Spring Boot应用中使用JWT(JSON Web Tokens)进行用户身份验证,包括Token的创建、解析以及用户ID的获取。重点讲解了如何设置密钥、设置有效期,并演示了如何通过JWT进行用户权限验证的过程。
摘要由CSDN通过智能技术生成

jwt技术

package com.xiang.util;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xiang.pojo.User;
import com.xiang.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;

public class JwtToken {
    /**
     * APP登录Token的生成和解析
     *
     */

    /** token秘钥,请勿泄露,请勿随便修改 backups:JKKLJOoasdlfj */
    public static final String SECRET = "JKKLJOoasdlfj";
    /** token 过期时间: 10天 */
    public static final int calendarField = Calendar.DATE;
    public static final int calendarInterval = 10;

    /**
     * JWT生成Token.<br/>
     *
     * JWT构成: header, payload, signature
     *
     * @param user_id
     *            登录成功后用户user_id, 参数user_id不可传空
     */
    public static String createToken(String user_id) throws Exception {
        Date iatDate = new Date();
        // expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresDate = nowTime.getTime();

        // header Map
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        // build token
        // param backups {iss:Service, aud:APP}
        String token = JWT.create().withHeader(map) // header
                .withClaim("iss", "Service") // payload
                .withClaim("aud", "APP").withClaim("user_id", null == user_id ? null : user_id)
                .withIssuedAt(iatDate) // sign time
                .withExpiresAt(expiresDate) // expire time
                .sign(Algorithm.HMAC256(SECRET)); // signature

        return token;
    }

    /**
     * 解密Token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
             e.printStackTrace();
            // token 校验失败, 抛出Token验证非法异常
        }
        return jwt.getClaims();
    }

    /**
     * 根据Token获取user_id
     *
     * @param token
     * @return user_id
     */
    public static String getAppUID(String token) {
        Map<String, Claim> claims = verifyToken(token);
        Claim user_id_claim = claims.get("user_id");
        if (null == user_id_claim || StringUtils.isEmpty(user_id_claim.asString())) {
            // token 校验失败, 抛出Token验证非法异常
        }
        return user_id_claim.asString();
//        return Long.valueOf(user_id_claim.asString());
    }

    //对token进行解码到UUID,在通过UUID查询用户是否存在
    public  static boolean isUser(String token){
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserServiceImpl userService=context.getBean("UserServiceImpl",UserServiceImpl.class);

        System.out.println("===============================>"+token);
        if(token==null||token.equals("null")){
            return false;
        }
        String id=JwtToken.getAppUID(token);
        Map<String,Object> map=new HashMap<>();
        map.put("id",id);
       User user= userService.selectUser(map);
       if(user==null) {
           return false;
       }else {
           return true;
       }

    }
    //判断是否持有token令牌
//        if(!JwtToken.isUser(request.getHeader("Authorization"))){
//            LoginUtil loginUtil = new LoginUtil(403, "未授权");
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("meta", loginUtil);
//            return jsonObject.toJSONString();
//        }

}

需要导入依赖包 (maven)

<!--        jwt数据加密-->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.15.0</version>
        </dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值