生成token
package org.zyyd.base.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
public class JwtTokenUtil {
public static final String TOKEN_HEADER = "Authorization";
public static final String TOKEN_PREFIX = "Bearer ";
private static final String ISS = "asd";
// 过期时间是3600秒,既是1个小时
private static final long EXPIRATION = 1800L;
// 选择了记住我之后的过期时间为7天
private static final long EXPIRATION_REMEMBER = 604800L;
private static InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("jwt.jks");
// 寻找证书文件
private static PrivateKey privateKey = null;
private static PublicKey publicKey = null;
static {
// 将证书文件里边的私钥公钥拿出来
try {
KeyStore keyStore = KeyStore.getInstance("JKS");// java key store 固定常量
keyStore.load(inputStream, "asdasd".toCharArray());
privateKey = (PrivateKey) keyStore.getKey("jwt", "asdasd".toCharArray());// jwt 为 命令生成整数文件时的别名
publicKey = keyStore.getCertificate("jwt").getPublicKey();
} catch (Exception e) {
e.printStackTrace();
}
}
//生成令牌
/**
* 生成令牌
* @param json
userName
* @param isRememberMe
* @return
*/
public static String generateToken(JSONObject json, boolean isRememberMe) {
long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
return Jwts.builder()
.setClaims(null)
.setSubject(json.toJSONString())
.setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
.setIssuer(ISS)
//.signWith(SignatureAlgorithm.HS512, salt)// 不使用公钥私钥
.signWith(SignatureAlgorithm.RS256, privateKey)
.compact();
}
// 从token中获取JSONObject
public static JSONObject parseToken(String token) {
JSONObject json = new JSONObject();
String subject = null;
try {
Claims claims = getTokenBody(token);
subject = claims.getSubject();
} catch (Exception e) {
}
if(StringUtils.isNotBlank(subject)){
json = JSON.parseObject(subject);
}
return json;
}
// 是否已过期
public static boolean isExpiration(String token){
return getTokenBody(token).getExpiration().before(new Date());
}
private static Claims getTokenBody(String token){
return Jwts.parser()
.setSigningKey(publicKey)
.parseClaimsJws(token)
.getBody();
}
}
拦截验证token
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* ClassName: LogFilter
* @Description:
* @author <pengbin>
* @date 2018/12/3 18:13
*/
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);
private AlUserService alUserService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
alUserService = (AlUserService) ac.getBean("alUserServiceImpl");
response.addHeader("Access-Control-Expose-Headers", JwtTokenUtil.TOKEN_HEADER);
String authHeader = request.getHeader(JwtTokenUtil.TOKEN_HEADER);
String url=request.getRequestURI();
if("/selfLearning/alApi/login".equals(url)){
chain.doFilter(request, response);
}else{
if (request.getMethod().equals("OPTIONS")) {
logger.info("浏览器的预请求的处理..");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept,"+JwtTokenUtil.TOKEN_HEADER);
return;
}else {
if (authHeader != null && authHeader.startsWith(JwtTokenUtil.TOKEN_PREFIX)) {
final String authToken = authHeader.substring(JwtTokenUtil.TOKEN_PREFIX.length());
JSONObject json= JwtTokenUtil.parseToken(authToken);
String username = (String) json.get("userName");
// 判断token是否还在有效期内并且能够解析出用户名
if (StringUtils.isNotBlank(username) && !JwtTokenUtil.isExpiration(authToken)) {
/*AlUser alUser = alUserService.getUserByUserName(username);
// 验证用户是否存在
if(StringUtils.isNotBlank(alUser.getUserId()) && "0".equals(alUser.getDeleteFlag())){
}else{
logger.info("用户不存在!");
Message message = new Message();
message.setStatus("0");
message.setMessage("用户不存在!");
response.getWriter().write(JSON.toJSONString(message));
return;
}*/
}else {
logger.info("登录过期!");
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept,Authorization,token");
Message message = new Message();
message.setStatus(0);
message.setMessage("登录过期!");
response.getWriter().write(JSON.toJSONString(message));
return ;
}
}else{
Message message = new Message();
message.setStatus(0);
message.setMessage("尚未登录!");
response.getWriter().write(JSON.toJSONString(message));
return ;
}
chain.doFilter(request, response);
}
}
}
}