本项目依赖于下面jar包:
核心类Jwt.java结构:
2个静态方法createToken和validToken,分别用于生成TOKEN和校验TOKEN; 定义了枚举TokenState,用于表示验证token时的结果,用户可根据结果进行不同处理:
使用示例
获取token
Mappayload=new HashMap (); Date date=new Date(); payload.put("uid", "291969452");//用户id payload.put("iat", date.getTime());//生成时间 payload.put("ext",date.getTime()+1000*60*60);//过期时间1小时 String token=Jwt.createToken(payload); System.out.println("token:"+token);
校验token
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
项目应用中代码:
JAT 工具类
public class Jwt { /** * 秘钥 */ private static final byte[] SECRET="3d990d2276917dfac04467df11fff26d".getBytes(); /** * 初始化head部分的数据为 * { * "alg":"HS256", * "type":"JWT" * } */ private static final JWSHeader header=new JWSHeader(JWSAlgorithm.HS256, JOSEObjectType.JWT, null, null, null, null, null, null, null, null, null, null, null); /** * 生成token,该方法只在用户登录成功后调用 * * @param Map集合,可以存储用户id,token生成时间,token过期时间等自定义字段 * @return token字符串,若失败则返回null */ public static String createToken(Mappayload) { String tokenString=null; // 创建一个 JWS object JWSObject jwsObject = new JWSObject(header, new Payload(new JSONObject(payload))); try { // 将jwsObject 进行HMAC签名 jwsObject.sign(new MACSigner(SECRET)); tokenString=jwsObject.serialize(); } catch (JOSEException e) { System.err.println("签名失败:" + e.getMessage()); e.printStackTrace(); } return tokenString; } /** * 校验token是否合法,返回Map集合,集合中主要包含 state状态码 data鉴权成功后从token中提取的数据 * 该方法在过滤器中调用,每次请求API时都校验 * @param token * @return Map */ public static Map validToken(String token) { Map resultMap = new HashMap (); try { JWSObject jwsObject = JWSObject.parse(token); Payload payload = jwsObject.getPayload(); JWSVerifier verifier = new MACVerifier(SECRET); if (jwsObject.verify(verifier)) { JSONObject jsonOBj = payload.toJSONObject(); // token校验成功(此时没有校验是否过期) resultMap.put("state", TokenState.VALID.toString()); // 若payload包含ext字段,则校验是否过期 if (jsonOBj.containsKey("ext")) { long extTime = Long.valueOf(jsonOBj.get("ext").toString()); long curTime = new Date().getTime(); // 过期了 if (curTime > extTime) { resultMap.clear(); resultMap.put("state", TokenState.EXPIRED.toString()); } } resultMap.put("data", jsonOBj); } else { // 校验失败 resultMap.put("state", TokenState.INVALID.toString()); } } catch (Exception e) { //e.printStackTrace(); // token格式不合法导致的异常 resultMap.clear(); resultMap.put("state", TokenState.INVALID.toString()); } return resultMap; } }
TokenState
package com.jwt; /** * 枚举,定义token的三种状态 * @author [email protected] * */ public enum TokenState { /** * 过期 */ EXPIRED("EXPIRED"), /** * 无效(token不合法) */ INVALID("INVALID"), /** * 有效的 */ VALID("VALID"); private String state; private TokenState(String state) { this.state = state; } /** * 根据状态字符串获取token状态枚举对象 * @param tokenState * @return */ public static TokenState getTokenState(String tokenState){ TokenState[] states=TokenState.values(); TokenState ts=null; for (TokenState state : states) { if(state.toString().equals(tokenState)){ ts=state; break; } } return ts; } public String toString() { return this.state; } public String getState() { return state; } public void setState(String state) { this.state = state; } }
junit 测试结果
package com.jwt; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.junit.Test; /** * 单元测试(请自行引入junit4 Jar包) */ public class JwtTestCase { @Test @SuppressWarnings("unchecked") public void test1() { // 正常生成token---------------------------------------------------------------------------------------------------- String token = null; Mappayload = new HashMap (); Date date = new Date(); payload.put("uid", "291969452");// 用户id payload.put("iat", date.getTime());// 生成时间:当前 payload.put("ext", date.getTime() + 2000 * 60 * 60);// 过期时间2小时 token = Jwt.createToken(payload); System.out.println("新生成的token是:" + token+"\n马上将该token进行校验"); Map resultMap = Jwt.validToken(token); System.out.println("校验结果是:" + getResult((String)resultMap.get("state")) ); HashMap dataobj = (HashMap ) resultMap.get("data"); System.out.println("从token中取出的payload数据是:" +dataobj.toString()); } public void test2() { // 校验过期---------------------------------------------------------------------------------------------------- String token = null; Map payload = new HashMap (); Date date = new Date(); payload.put("uid", "291969452");// 用户id payload.put("iat", date.getTime());// 生成时间 payload.put("ext", date.getTime());// 过期时间就是当前 token = Jwt.createToken(payload); System.out.println("新生成的token是:" + token+"\n马上将该token进行校验"); Map resultMap = Jwt.validToken(token); System.out.println("校验结果是:" + getResult((String)resultMap.get("state")) ); } @SuppressWarnings("unchecked") public void test2_1() { // 不校验过期(当payload中无过期ext字段时)---------------------------------------------------------------------------------------------------- String token = null; Map payload = new HashMap (); Date date = new Date(); payload.put("uid", "291969452");// 用户id payload.put("iat", date.getTime());// 生成时间 token = Jwt.createToken(payload); System.out.println("新生成的token是:" + token+"\n马上将该token进行校验"); Map resultMap = Jwt.validToken(token); System.out.println("校验结果是:" + getResult((String)resultMap.get("state")) ); HashMap dataobj = (HashMap ) resultMap.get("data"); System.out.println("从token中取出的payload数据是:" +dataobj.toString()); } public void test3() { // 校验非法token的情况---------------------------------------------------------------------------------------------------- String token = null; Map payload = new HashMap (); Date date = new Date(); payload.put("uid", "291969452");// 用户id payload.put("iat", date.getTime());// 生成时间 payload.put("ext", date.getTime());// 过期时间就是当前 token = Jwt.createToken(payload); System.out.println("新生成的token是:" + token); System.out.println("将新生成的token加点调料再来进行校验"); token = token + "YouAreSB"; Map resultMap = Jwt.validToken(token); System.out.println("校验结果是:" + getResult((String)resultMap.get("state")) ); System.out.println("原因是(非法token,payload参数可能经过中间人篡改,或者别人伪造的token)" ); } public void test4() { // 校验异常的情况---------------------------------------------------------------------------------------------------- String token = "123"; System.out.println("我胡乱传一个token:" + token); Map resultMap = Jwt.validToken(token); System.out.println("校验结果是:" + getResult((String)resultMap.get("state")) ); System.out.println("原因是(token格式不合法导致的程序异常)"); } public String getResult(String state) { switch (TokenState.getTokenState(state)) { case VALID: //To do somethings state = "有效token"; break; case EXPIRED: state = "过期token"; break; case INVALID: state = "无效的token"; break; } return state; } }
loginServlet 使用,具体使用springmvc还是struts 可以参考servlet写法
package com.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.minidev.json.JSONObject; import com.jwt.Jwt; @WebServlet(urlPatterns="/servlet/login",loadOnStartup=1) public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 5285600116871825644L; /** * 校验用户名密码 */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName=request.getParameter("userName"); String password =request.getParameter("password"); JSONObject resultJSON=new JSONObject(); //用户名密码校验成功后,生成token返回客户端 if("admin".equals(userName)&&"123".equals(password)){ //生成token Mappayload=new HashMap (); Date date=new Date(); payload.put("uid", "admin");//用户ID payload.put("iat", date.getTime());//生成时间 payload.put("ext",date.getTime()+1000*60*60);//过期时间1小时 String token=Jwt.createToken(payload); resultJSON.put("success", true); resultJSON.put("msg", "登陆成功"); resultJSON.put("token", token); }else{ resultJSON.put("success", false); resultJSON.put("msg", "用户名密码不对"); } //输出结果 output(resultJSON.toJSONString(), response); } public void output(String jsonStr,HttpServletResponse response) throws IOException{ response.setContentType("text/html;charset=UTF-8;"); PrintWriter out = response.getWriter(); out.println(jsonStr); out.flush(); out.close(); } }
每次请求都需要验证token 是否有效
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
|
调用获取信息的接口
mainServlet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
|
跨域过滤器
package com.filter; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebInitParam; import com.thetransactioncompany.cors.CORSConfiguration; import com.thetransactioncompany.cors.CORSFilter; /** * 服务端跨域处理过滤器,该过滤器需要依赖cors-filter-2.2.1.jar和java-property-utils-1.9.1.jar * @author [email protected] * */ @WebFilter(urlPatterns={"/*"},asyncSupported=true, initParams={ @WebInitParam(name="cors.allowOrigin",value="*"), @WebInitParam(name="cors.supportedMethods",value="CONNECT, DELETE, GET, HEAD, OPTIONS, POST, PUT, TRACE"), @WebInitParam(name="cors.supportedHeaders",value="token,Accept, Origin, X-Requested-With, Content-Type, Last-Modified"),//注意,如果token字段放在请求头传到后端,这里需要配置 @WebInitParam(name="cors.exposedHeaders",value="Set-Cookie"), @WebInitParam(name="cors.supportsCredentials",value="true") }) public class Filter0_CrossOriginResource extends CORSFilter implements javax.servlet.Filter{ public void init(FilterConfig config) throws ServletException { System.out.println("跨域资源处理过滤器初始化了"); super.init(config); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("跨域过滤器"); super.doFilter(request, response, chain); } public void setConfiguration(CORSConfiguration config) { super.setConfiguration(config); } }
验证登陆过滤器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
|
jsp页面测试代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
|
具体代码地址:https://github.com/bigmeow/JWT