部分概念自行百度,代码部分
Token工具类
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.springframework.beans.factory.annotation.Value;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class TokenUtil {
//过期时间,时间自己定
private static final long EXPIRE_TIME = 24 * 60* 60 * 1000;
// @Value("${EXPIRE_TIME}")
// private static long EXPIRE_TIME;
//私钥
private static final String TOKEN_SECRET = "admin";
/**
* 生成签名,15分钟过期
* @param **username**
* @param **password**
* @return
*/
public static String sign(String username, String password) {
try {
// 设置过期时间
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
// 私钥和加密算法
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
// 设置头部信息
Map<String, Object> header = new HashMap<>(2);
header.put("Type", "Jwt");
header.put("alg", "HS256");
// 返回token字符串
return JWT.create()
.withHeader(header)
.withClaim("loginName", username)
.withClaim("pwd", password)
.withExpiresAt(date)
.sign(algorithm);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 检验token是否正确
* @param **token**
* @return
*/
public static boolean verify(String token){
try {
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = verifier.verify(token);
return true;
} catch (Exception e){
return false;
}
}
public boolean responseData(HttpServletResponse response) throws IOException {
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
// JsonMessage json =new JsonMessage(401, "暂未登录!");
Result result = new Result(-10000, "请先登陆");
// String s = JSON.toJSONString(json);
PrintWriter writer = response.getWriter();
writer.println("401");
return false;
}
}
自定义拦截器,里面的一些判断什么的可以根据自己需求改
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 自定义token拦截器
*/
@Component
//public class TokenInterceptor {
public class TokenInterceptor implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
response.setCharacterEncoding("utf-8");
String token = request.getHeader("token");
//如果请求方法为OPTIONS,就直接return通过。
if (request.getMethod().equals("OPTIONS")) {
response.setStatus(HttpServletResponse.SC_OK);
response.setStatus(200);
return true;
} else if (token == null) {
response.getWriter().write("未发送token");
return false;
} else if (token != null) {
boolean result = TokenUtil.verify(token);
if (result) {
response.getWriter().write("token正确,通过拦截器");
response.setStatus(200);
return true;
}
}
System.out.println("toke过期或错误");
response.getWriter().write("401");
response.setStatus(401);
return false;
}
拦截,对部分接口进行配置,不拦截
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
private TokenInterceptor tokenInterceptor;
public InterceptorConfig(TokenInterceptor tokenInterceptor) {
this.tokenInterceptor = tokenInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
List<String> excludePath = new ArrayList<>();
String sysUserLogin = "/accountuser/login"; //登录接口
String sysUserRegister = "/accountuser/saveuser"; //注册接口
excludePath.add(sysUserLogin);
excludePath.add(sysUserRegister);
registry.addInterceptor(tokenInterceptor).excludePathPatterns(excludePath);//tokenInterceptor
}
/**
* 从token中获取username信息
* @param **token**
* @return
*/
public static String getUserName(String token){
try {
DecodedJWT jwt = JWT.decode(token);
return jwt.getClaim("loginName").asString();
} catch (JWTDecodeException e){
e.printStackTrace();
return null;
}
}
}
在controller层里面的登录接口,
@PostMapping("/login")
public Result<Map<String, Object>> loginUser(@RequestBody Map<String,Object> params,HttpSession session){
/**
*
*账号密码判断
*账号密码正确则
**/
String token = TokenUtil.sign(userTel,Passwd);
System.out.println(token);
if (token != null){
map.put("code", "10000");
map.put("message","认证成功");
map.put("token", token);
map.put("User",user);
}
}
return new Result<Map<String, Object>>().success(map);
}
JWT依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.5.0</version>
</dependency>