Browse Source

弄个token试试

v2
蟑螂恶霸 2 years ago
parent
commit
1272560150
  1. 6
      lib/EmergencyService/zdxtEmergencyAuthService/pom.xml
  2. 6
      lib/EmergencyService/zdxtEmergencyAuthService/src/main/java/com/zdxt/auth/framework/config/ResourcesConfig.java
  3. 53
      lib/EmergencyService/zdxtEmergencyAuthService/src/main/java/com/zdxt/auth/framework/shiro/jwt/JWTInterceptor.java
  4. 171
      lib/EmergencyService/zdxtEmergencyAuthService/src/main/java/com/zdxt/auth/framework/shiro/jwt/JWTUtils.java
  5. 46
      lib/EmergencyService/zdxtLawEnforcementCodeService/src/main/java/com/zdxt/code/controller/ThirdLoginController.java
  6. 11
      lib/EmergencyServiceApi/emergencyAuthServiceApi/src/main/java/com/zdxt/auth/dto/UserBean.java

6
lib/EmergencyService/zdxtEmergencyAuthService/pom.xml

@ -101,6 +101,12 @@
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId> <artifactId>httpcore</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies> </dependencies>
</project> </project>

6
lib/EmergencyService/zdxtEmergencyAuthService/src/main/java/com/zdxt/auth/framework/config/ResourcesConfig.java

@ -1,5 +1,6 @@
package com.zdxt.auth.framework.config; package com.zdxt.auth.framework.config;
import com.zdxt.auth.framework.shiro.jwt.JWTInterceptor;
import com.zdxt.common.config.RuoYiConfig; import com.zdxt.common.config.RuoYiConfig;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
@ -54,6 +55,9 @@ public class ResourcesConfig implements WebMvcConfigurer
@Override @Override
public void addInterceptors(InterceptorRegistry registry) public void addInterceptors(InterceptorRegistry registry)
{ {
registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**"); // registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");
registry.addInterceptor(new JWTInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/thirdLogin/doLogin");// 除了登录放行,其他接口都token验证
} }
} }

53
lib/EmergencyService/zdxtEmergencyAuthService/src/main/java/com/zdxt/auth/framework/shiro/jwt/JWTInterceptor.java

@ -0,0 +1,53 @@
package com.zdxt.auth.framework.shiro.jwt;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureGenerationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
* @Author: kylin
* @Date: 2024/4/30 11:37 下午
* @Version: 1.0
* @Desc: TODO
*/
public class JWTInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("token");
Map<String, Object> map = new HashMap<>();
try {
JWTVerifier verify = JWTUtils.verify(token);
map.put("state", true);
map.put("msg", "请求成功");
}catch (SignatureGenerationException e){
e.printStackTrace();
map.put("msg","无效签名");
}catch (TokenExpiredException e){
e.printStackTrace();
map.put("msg","token过期");
}catch (AlgorithmMismatchException e){
e.printStackTrace();
map.put("msg","token算法不一致");
}
catch (Exception e) {
e.printStackTrace();
map.put("msg","token无效");
}
map.put("state", false); // 设置状态
// 将map转为json
String json = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(json);
return false;
}
}

171
lib/EmergencyService/zdxtEmergencyAuthService/src/main/java/com/zdxt/auth/framework/shiro/jwt/JWTUtils.java

@ -0,0 +1,171 @@
package com.zdxt.auth.framework.shiro.jwt;
/**
* @ClassName JwtUtil
* @Description TODO
* @Author Administrator
* @Date 2021/02/01 15:04:33
* @Verison 1.0
*/
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import org.apache.commons.lang3.StringUtils;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JWTUtils {
//过期时间 3天
private static final long EXPIRE_TIME = 3 * 24 * 60 * 60 * 1000;
//私钥
private static final String TOKEN_SECRET = "huiming@7122^$";
/**
* 生成签名15分钟过期
* 根据内部改造支持6中类型Integer,Long,Boolean,Double,String,Date
* @param map
* @return
*/
public static String sign(Map<String,Object> map) {
try {
// 设置过期时间
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
// 私钥和加密算法
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
// 设置头部信息
Map<String, Object> header = new HashMap<>(2);
header.put("typ", "jwt");
// 返回token字符串
JWTCreator.Builder builder = JWT.create()
.withHeader(header)
.withIssuedAt(new Date()) //发证时间
.withExpiresAt(date); //过期时间
// .sign(algorithm); //密钥
map.entrySet().forEach(entry -> {
if (entry.getValue() instanceof Integer) {
builder.withClaim( entry.getKey(),(Integer)entry.getValue());
} else if (entry.getValue() instanceof Long) {
builder.withClaim( entry.getKey(),(Long)entry.getValue());
} else if (entry.getValue() instanceof Boolean) {
builder.withClaim( entry.getKey(),(Boolean) entry.getValue());
} else if (entry.getValue() instanceof String) {
builder.withClaim( entry.getKey(),String.valueOf(entry.getValue()));
} else if (entry.getValue() instanceof Double) {
builder.withClaim( entry.getKey(),(Double)entry.getValue());
} else if (entry.getValue() instanceof Date) {
builder.withClaim( entry.getKey(),(Date)entry.getValue());
}
});
return builder.sign(algorithm);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 检验token是否正确
* @param **token**
* @return
*/
public static JWTVerifier verify(String token){
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
verifier.verify(token);
return verifier;
}
/**
*获取用户自定义Claim集合
* @param token
* @return
*/
public static Map<String, Claim> getClaims(String token){
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
Map<String, Claim> jwt = verifier.verify(token).getClaims();
return jwt;
}
/**
* 获取过期时间
* @param token
* @return
*/
public static Date getExpiresAt(String token){
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
return JWT.require(algorithm).build().verify(token).getExpiresAt();
}
/**
* 获取jwt发布时间
*/
public static Date getIssuedAt(String token){
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
return JWT.require(algorithm).build().verify(token).getIssuedAt();
}
/**
* 验证token是否失效
*
* @param token
* @return true:过期 false:没过期
*/
public static boolean isExpired(String token) {
try {
final Date expiration = getExpiresAt(token);
return expiration.before(new Date());
}catch (TokenExpiredException e) {
// e.printStackTrace();
return true;
}
}
/**
* 直接Base64解密获取header内容
* @param token
* @return
*/
public static String getHeaderByBase64(String token){
if (StringUtils.isEmpty(token)){
return null;
}else {
byte[] header_byte = Base64.getDecoder().decode(token.split("\\.")[0]);
String header = new String(header_byte);
return header;
}
}
/**
* 直接Base64解密获取payload内容
* @param token
* @return
*/
public static String getPayloadByBase64(String token){
if (StringUtils.isEmpty(token)){
return null;
}else {
byte[] payload_byte = Base64.getDecoder().decode(token.split("\\.")[1]);
String payload = new String(payload_byte);
return payload;
}
}
}

46
lib/EmergencyService/zdxtLawEnforcementCodeService/src/main/java/com/zdxt/code/controller/ThirdLoginController.java

@ -1,15 +1,19 @@
package com.zdxt.code.controller; package com.zdxt.code.controller;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWTVerifier;
import com.zdxt.auth.dto.UserBean; import com.zdxt.auth.dto.UserBean;
import com.zdxt.auth.feign.UserApi; import com.zdxt.auth.feign.UserApi;
import com.zdxt.auth.framework.shiro.jwt.JWTUtils;
import com.zdxt.auth.framework.shiro.nopaddword.LoginType; import com.zdxt.auth.framework.shiro.nopaddword.LoginType;
import com.zdxt.auth.framework.shiro.nopaddword.UserToken; import com.zdxt.auth.framework.shiro.nopaddword.UserToken;
import com.zdxt.auth.project.system.user.service.IUserService;
import com.zdxt.code.domain.SiqLogin; import com.zdxt.code.domain.SiqLogin;
import com.zdxt.code.service.ThirdLoginService; import com.zdxt.code.service.ThirdLoginService;
import com.zdxt.code.utils.HttpUtil; import com.zdxt.code.utils.HttpUtil;
import com.zdxt.code.utils.IdCardCryptoUtil; import com.zdxt.code.utils.IdCardCryptoUtil;
import com.zdxt.common.ZDResponse; import com.zdxt.common.ZDResponse;
import com.zdxt.domain.auth.User;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils; import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authc.UsernamePasswordToken;
@ -17,10 +21,7 @@ import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -79,4 +80,41 @@ public class ThirdLoginController {
thirdLoginService.addSiqUserCompany(jsonObject); thirdLoginService.addSiqUserCompany(jsonObject);
return thirdLoginService.siqLogin(jsonObject); return thirdLoginService.siqLogin(jsonObject);
} }
@Autowired private IUserService iUserService;
@GetMapping("/doLogin")
@ResponseBody
public Map<String, Object> login(User user){
Map<String, Object> map = new HashMap<>();
try{
User userDB = iUserService.selectUserByLoginName(user.getLoginName());
Map<String,Object> payload = new HashMap<>();
payload.put("id", userDB.getUserId());
payload.put("name", userDB.getLoginName());
String token = JWTUtils.sign(payload);
map.put("state", true);
map.put("msg", "认证成功");
map.put("token", token);
}catch (Exception e){
map.put("state", false);
map.put("msg", e.getMessage());
}
return map;
}
@PostMapping("/user/test")
public Map<String,Object> test(String token){
Map<String, Object> map = new HashMap<>();
log.info("当前token为:[{}]",token);
JWTVerifier verify = JWTUtils.verify(token);
map.put("state", true);
map.put("msg", "请求成功");
return map;
}
} }

11
lib/EmergencyServiceApi/emergencyAuthServiceApi/src/main/java/com/zdxt/auth/dto/UserBean.java

@ -20,6 +20,9 @@ import java.util.Map;
public class UserBean implements Serializable { public class UserBean implements Serializable {
private static final long serialVersionUID = -8035734163527004279L; private static final long serialVersionUID = -8035734163527004279L;
/** token信息 */
private String token;
/** /**
* 用户ID * 用户ID
@ -281,6 +284,14 @@ public class UserBean implements Serializable {
this.lawCertificateNum = lawCertificateNum; this.lawCertificateNum = lawCertificateNum;
} }
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
@Override @Override
public String toString() { public String toString() {
return "UserBean{" + return "UserBean{" +

Loading…
Cancel
Save