JWT类用于登陆人信息的加密解密

package com.cmcc.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.security.Key;
import java.util.Date;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import net.sf.json.JSONObject;

//Sample method to construct a JWT
public class JWT {
    private final static String apiKey="cmcc#*1234";
    public static String createJWT(String id, String issuer, String subject,
            long ttlMillis) {

        // The JWT signature algorithm we will be using to sign the token
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        // We will sign our JWT with our ApiKey secret
//        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey
//                .getSecret());
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes,
                signatureAlgorithm.getJcaName());

        // Let"s set the JWT Claims
        JwtBuilder builder = Jwts.builder().setId(id).setIssuedAt(now)
                .setSubject(subject).setIssuer(issuer)
                .signWith(signatureAlgorithm, signingKey);

        // if it has been specified, let"s add the expiration
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }

        // Builds the JWT and serializes it to a compact, URL-safe string
        return builder.compact();
    }
    public static JSONObject parseJWT(String jwt) {
        //This line will throw an exception if it is not a signed JWS (as expected)
        JSONObject json=new JSONObject();
        json.put("success", true);
        try{
        Claims claims = Jwts.parser()        
           .setSigningKey(DatatypeConverter.parseBase64Binary(apiKey))
           .parseClaimsJws(jwt).getBody();
        String ID=claims.getId();
        String Subject=claims.getSubject();
        String Issuer=claims.getIssuer();
        Long Expiration=claims.getExpiration().getTime();
        json.put("code", "0");
        if(new Date().getTime()>Expiration){
            json.put("code", "1001");
            json.put("msg", "token过期");
        }else{
            json.put("id", ID);
            json.put("subject", Subject);
            json.put("user", Issuer);
        }
        return json;
        }catch(Exception e){
            json.put("code", "1002");
            json.put("msg", "token验证失败");
            return json;
        }
        }
    public static void main(String[]args){
//        user u=new user();
//        u.setName("admin");
//        u.setPassword("admin");
//        System.out.println(createJWT("admin",JSONObject.fromObject(u).toString(),"test",30000000));
//        System.out.println(parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJhZG1pbiIsImlhdCI6MTQzNjUwMzIyNywic3ViIjoidGVzdCIsImlzcyI6ImFkbWluIiwiZXhwIjoxNDM2NTA2MjI3fQ.hKWir-hr097SRJL3vBhx8FmIzZ2Bp7tEEopYO9drUBs"));
    }
}

 

例子:

@RequestMapping(value="mianLogin",method=RequestMethod.GET)
    public ResponseMessage mianLogin(HttpServletRequest req,HttpSession session) throws Exception{
        ResponseMessage rs=new ResponseMessage();
        try{
            TemplateUser user = sev.getMianLogin();
            String loginName = user.getLogin_name();
            String ip=Servlets.getRemoteHost(req);
            String token=JWT.createJWT(user.getUserid(),JacksonUtil.toJson(user),ip,3*24*3600*1000);
            session.setAttribute("token", token);
            session.setAttribute("tokenid", user.getUserid());
            JSONObject json=new JSONObject();
            json.put("loginName", loginName);
            json.put("userid", user.getUserid());
            rs.setData(json);
            rs.setCode(HttpStatus.OK.value());
        }catch(Exception e){
            rs.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        return rs;
    }

 

net.sf.json.JSONObject rs = JWT.parseJWT(token);

你可能感兴趣的:(JWT类用于登陆人信息的加密解密)