JWT json_token的简单使用

JWT token认证

  • 这里主要针对java进行讲解,其他语言类似 *

引入jar包

我用的gradle进行的jar包管理 其他类似
// https://mvnrepository.com/artifact/com.auth0/java-jwt
    compile group: 'com.auth0', name: 'java-jwt', version: '2.2.0'

引入操作jwt的工具类

package com.shop.utils;

/**
 * @author 阳十三
 * @email [email protected]
 * @blog http://www.item1024.com
 * @date 2017/9/5
 */

import com.auth0.jwt.JWTSigner;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.internal.com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    private static final String SECRET = "XX#$%()(#*!()!KL<>?N<:{LWPW";

    private static final String EXP = "exp";

    private static final String PAYLOAD = "payload";

    //加密,传入一个对象和有效期
    public static  String sign(T object, long maxAge) {
        try {
            final JWTSigner signer = new JWTSigner(SECRET);
            final Map claims = new HashMap();
            ObjectMapper mapper = new ObjectMapper();
            String jsonString = mapper.writeValueAsString(object);
            claims.put(PAYLOAD, jsonString);
            claims.put(EXP, System.currentTimeMillis() + maxAge);
            return signer.sign(claims);
        } catch(Exception e) {
            return null;
        }
    }

    //解密,传入一个加密后的token字符串和解密后的类型
    public static T unsign(String jwt, Class classT) {
        final JWTVerifier verifier = new JWTVerifier(SECRET);
        try {
            final Map claims= verifier.verify(jwt);
            if (claims.containsKey(EXP) && claims.containsKey(PAYLOAD)) {
                long exp = (Long)claims.get(EXP);
                long currentTimeMillis = System.currentTimeMillis();
                if (exp > currentTimeMillis) {
                    String json = (String)claims.get(PAYLOAD);
                    ObjectMapper objectMapper = new ObjectMapper();
                    return objectMapper.readValue(json, classT);
                }
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }

}

测试

  • controller: *
  /**
     * @param loginName 登录名
     * @param password 密码
     * @return 账户密码登陆
     */
    @RequestMapping("/login.py")
    @ResponseBody
    public String doLogin(HttpServletRequest request, @RequestParam(value = "userName") String loginName, @RequestParam(value = "userPwd") String password) {
        ResultWrapper resultWrapper = new ResultWrapper();
        JwtBean jwtBean = new JwtBean();
        jwtBean.setsta(0);
        try{
            UserInfo userInfo = userInfoService.findUserByLoginName(loginName);
            if(userInfo.getLoginPassword().equals("") || userInfo.getLoginPassword() == null){
                jwtBean.setMsg("您还没有设置密码");
                return new Gson().toJson(jwtBean);
            }

            if (null != userInfo && userInfo.getLoginPassword().equals(MyPwd.md5(password))) {
                SessionAuth sessionAuth = new SessionAuth();
                sessionAuth.setUserId(userInfo.getUserId());
                sessionAuth.setUserName(userInfo.getUserName());
                sessionAuth.setUserType(userInfo.getUserType());
                request.getSession().setAttribute("user", sessionAuth);
                //存储sessionId
                String sessionId = request.getRequestedSessionId();
                redisTemplate.opsForValue().set("userAuthToken"+userInfo.getUserId(),MyPwd.md5(sessionId));
                jwtBean.setMsg("登陆成功");
                jwtBean.setsta(1);
                jwtBean.setUserId(userInfo.getUserId());
                jwtBean.setToken(JwtUtil.sign(userInfo.getUserId(),60L* 1000L* 30L));   #生成token
                return new Gson().toJson(jwtBean);
            }
        }catch(Exception e){
            e.getStackTrace();
        }
        jwtBean.setMsg("用户名或密码错误");
        return new Gson().toJson(jwtBean);
    }
  • interceptor *
 response.setCharacterEncoding("utf-8");
        String token = request.getParameter("token");
        ResultWrapper resultWrapper = new ResultWrapper();
        resultWrapper.OK();
        //token不存在
        if(null != token) {
            int userid = Integer.parseInt(JwtUtil.unsign(token, String.class));
            System.out.println("jwt userid:"+userid);
            //解密token后的loginId与用户传来的loginId不一致,一般都是token过期
            if(loginId>0 && userid>0) {
                if(loginId == userid) {
                    return true;
                }

你可能感兴趣的:(java)