package cn.wizzer.modules.services.sys;
import cn.wizzer.common.base.Globals;
import cn.wizzer.common.base.Result;
import cn.wizzer.common.base.Service;
import cn.wizzer.modules.models.sys.Sys_api;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.crypto.MacProvider;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Files;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import java.io.*;
import java.security.Key;
import java.util.Date;
/**
* Created by wizzer on 2016/8/11.
*/
@IocBean(args = {"refer:dao"})
public class SysApiService extends Service<Sys_api> {
private static final Log log = Logs.get();
public SysApiService(Dao dao) {
super(dao);
}
private static final String at="accessToken";
public static Key key;
/**
* 生成token
*
* @param date 失效时间
* @param appId appId
* @return
*/
public String generateToken(Date date, String appId) throws IOException, ClassNotFoundException {
if (key == null)
key = MacProvider.generateKey();
String token = Jwts.builder()
.setSubject(appId)
.signWith(SignatureAlgorithm.HS512, key)
.setExpiration(date)
.compact();
// 计算失效秒,7889400秒三个月
Date temp = new Date();
long interval = (date.getTime() - temp.getTime())/1000;
jedis().setex(at+appId ,(int)interval,token);
return token;
}
/**
* 验证token
*
* @param appId AppId
* @param token token
* @return
*/
public boolean verifyToken(String appId, String token) {
try {
if (key == null) {
//ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(Globals.AppRoot + "/WEB-INF/apikey/" + appId + ".key"));
String _token = jedis().get(at+appId);
key = (Key) _token;
key = (Key) keyIn.readObject();
keyIn.close();
}
Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject().equals(appId);
return true;
} catch (Exception e) {
log.debug(e.getMessage());
return false;
}
}
}
8 回复
ObjectInputStream keyIn = new ObjectInputStream(new ByteArrayInputStream(_key.getBytes()));
PS: 上述代码中,并没有把Key序列化到redis
@wendal 怎么把key序列化到redis redis可以存什么类型
@IocBean(args = {"refer:dao"}, create="init")
public class SysApiService extends Service<Sys_api> {
public void init() {
byte[] buf = jedis().get("api:key".getBytes());
if (buf == null) { // 建新的key
key = MacProvider.generateKey();
ByteArrayOutputStream bao = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bao);
oos.writeObject(key);
buf = bao.toByteArray();
jedis().set("api:key".getBytes(), buf);
} else { // 重用老key
key = (Key) new ObjectInputStream(new ByteArrayInputStream(buf)).readObject();
}
}
@wendal 谢谢兽总
@wendal 兽总 论坛的token也可以采用这个方式嘛
@wendal 看起来很吊
添加回复
请先登陆