Skip to content

Commit

Permalink
升级nutzboot至2.3.5.v20190516;添加JWT验证工具类
Browse files Browse the repository at this point in the history
  • Loading branch information
TomYule committed May 17, 2019
1 parent 5e1d57e commit 8a8ac7c
Show file tree
Hide file tree
Showing 10 changed files with 192 additions and 601 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ NutzSite基于Nutz的开源企业级开发框架
* Quartz 定时任务
* SLog日志记录
* 支付宝
* 微信公众平台
* 阿里云消息推送
* 阿里云短信
* 高德地图
Expand All @@ -23,7 +24,6 @@ NutzSite基于Nutz的开源企业级开发框架
* Excel 导出数据
## 给自己挖坑 后期支持待完善功能
* 审批流
* 微信公众平台
* CMS

本压缩包是一个maven工程, eclipse/idea均可按maven项目导入
Expand Down
22 changes: 20 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<nutzboot.version>2.3.4.v20190410</nutzboot.version>
<nutzboot.version>2.3.5.v20190516</nutzboot.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencyManagement>
Expand Down Expand Up @@ -58,7 +58,6 @@
<version>${nutzboot.version}</version>
</dependency>


<dependency>
<groupId>org.nutz</groupId>
<artifactId>nutzboot-starter-shiro</artifactId>
Expand Down Expand Up @@ -273,6 +272,25 @@
<version>1.20</version>
</dependency>

<!-- api token web server -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.10.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.10.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.10.5</version>
<scope>runtime</scope>
</dependency>

</dependencies>
<repositories>
<repository>
Expand Down
109 changes: 1 addition & 108 deletions src/main/java/io/nutz/nutzsite/common/utils/Encodes.java
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
/**
* Copyright (c) 2005-2012 springside.org.cn
*/
package io.nutz.nutzsite.common.utils;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringEscapeUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;


/**
* 封装各种格式的编码解码工具类.
* 1.Commons-Codec的 hex/base64 编码
Expand All @@ -26,106 +19,6 @@ public class Encodes {
private static final String DEFAULT_URL_ENCODING = "UTF-8";
private static final char[] BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();

/**
* Hex编码.
*/
public static String encodeHex(byte[] input) {
return new String(Hex.encodeHex(input));
}

/**
* Hex解码.
*/
public static byte[] decodeHex(String input) {
try {
return Hex.decodeHex(input.toCharArray());
} catch (DecoderException e) {
throw new RuntimeException(e);
}
}

/**
* Base64编码.
*/
public static String encodeBase64(byte[] input) {
return new String(Base64.encodeBase64(input));
}

/**
* Base64编码.
*/
public static String encodeBase64(String input) {
try {
return new String(Base64.encodeBase64(input.getBytes(DEFAULT_URL_ENCODING)));
} catch (UnsupportedEncodingException e) {
return "";
}
}

// /**
// * Base64编码, URL安全(将Base64中的URL非法字符'+'和'/'转为'-'和'_', 见RFC3548).
// */
// public static String encodeUrlSafeBase64(byte[] input) {
// return Base64.encodeBase64URLSafe(input);
// }

/**
* Base64解码.
*/
public static byte[] decodeBase64(String input) {
return Base64.decodeBase64(input.getBytes());
}

/**
* Base64解码.
*/
public static String decodeBase64String(String input) {
try {
return new String(Base64.decodeBase64(input.getBytes()), DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
return "";
}
}

/**
* Base62编码。
*/
public static String encodeBase62(byte[] input) {
char[] chars = new char[input.length];
for (int i = 0; i < input.length; i++) {
chars[i] = BASE62[((input[i] & 0xFF) % BASE62.length)];
}
return new String(chars);
}

/**
* Html 转码.
*/
public static String escapeHtml(String html) {
return StringEscapeUtils.escapeHtml4(html);
}

/**
* Html 解码.
*/
public static String unescapeHtml(String htmlEscaped) {
return StringEscapeUtils.unescapeHtml4(htmlEscaped);
}

/**
* Xml 转码.
*/
public static String escapeXml(String xml) {
return StringEscapeUtils.escapeXml10(xml);
}

/**
* Xml 解码.
*/
public static String unescapeXml(String xmlEscaped) {
return StringEscapeUtils.unescapeXml(xmlEscaped);
}

/**
* URL 编码, Encode默认为UTF-8.
*/
Expand Down
158 changes: 158 additions & 0 deletions src/main/java/io/nutz/nutzsite/common/utils/JWTUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
package io.nutz.nutzsite.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.nutz.mvc.Mvcs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.Key;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
* jwt验证工具类
* @author Hamming_Yu on 2018/11/13.
*/
public class JWTUtil {
private static Logger log = LoggerFactory.getLogger(JWTUtil.class);

//We will sign our JWT with our ApiKey secret
private static Key key;
private static String issuer="nutzsite";

/**
* 一天
*/
private static long tokenValidityInSeconds = 1800L;
/**
* 一个月失效
*/
private static long tokenValidityInSecondsForRememberMe = 2592000L;

static {
//初始化api.key 文件存放位置
Path fpath= Paths.get("api.key");
//创建文件
if(!Files.exists(fpath)) {
try {
Files.createFile(fpath);
// Files.createDirectory(fpath);
key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
try ( ObjectOutputStream keyOut = new ObjectOutputStream(new FileOutputStream(fpath.toFile()))){
keyOut.writeObject(key);
keyOut.close();
} catch (IOException e) {
log.debug(e.getMessage());
}
} catch (IOException e) {
e.printStackTrace();
}
}else {
try (ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(fpath.toFile()))){
key = (Key) keyIn.readObject();
keyIn.close();
} catch (IOException e) {
log.debug(e.getMessage());
} catch (ClassNotFoundException e) {
log.debug(e.getMessage());
}
}
}

/**
* 创建token
* @param id
* @return
*/
public static String createJWT(String id) {
// long nowMillis = System.currentTimeMillis();
Date exp = DateUtils.addMonths(new Date(),1) ;
//Let's set the JWT Claims
JwtBuilder builder = Jwts.builder().setId(id)
.setIssuedAt(new Date())
.setSubject(id)
.setIssuer(issuer)
.signWith(key);
builder.setExpiration(exp);

//Builds the JWT and serializes it to a compact, URL-safe string
return builder.compact();
}

/**
* 验证token
* @param token
* @return
*/
public static boolean verifyToken(String token) {
try {
Claims claims = Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(token).getBody();
if(!issuer.equals(claims.getIssuer()) &&
!claims.getIssuer().equals( claims.getSubject() ) ){
return false;
}
return true;
} catch (Exception e) {
log.debug(e.getMessage());
// e.printStackTrace();
return false;
}
}

/**
* 获取ID
* @return
*/
public static String getId() {
HttpServletRequest request = Mvcs.getReq();
Map<String, String> map = new HashMap<String, String>();
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String key = (String) headerNames.nextElement();
String value = request.getHeader(key);
map.put(key, value);
}
try{
String token=map.get("authorization");
if(verifyToken(token)){
Claims claims = Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(token).getBody();
return claims.getId();
}
}catch (Exception e){
log.debug(e.getMessage());
e.printStackTrace();

}
return null;
}

/**
* Sample method to validate and read the JWT
* @param jwt
*/
public static void parseJWT(String jwt) {
//This line will throw an exception if it is not a signed JWS (as expected)
Claims claims = Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(jwt).getBody();
// System.out.println("ID: " + claims.getId());
// System.out.println("Subject: " + claims.getSubject());
// System.out.println("Issuer: " + claims.getIssuer());
// System.out.println("Expiration: " + claims.getExpiration());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public Object upload(@Param("Filedata") TempFile tf, HttpServletRequest req, Ada
} else if (tf == null) {
return Result.error("空文件");
} else {
String url = UpLoadUtil.upLoadFileSysConfigPath(tf,"112321");
String url = UpLoadUtil.upLoadFileSysConfigPath(tf,"tmp");
String u = req.getServletContext().getContextPath();
return Result.success("上传成功", u + url );
}
Expand Down
Loading

0 comments on commit 8a8ac7c

Please sign in to comment.