Json web token (JWT), 是为了在网络应用环境间传递声明而执行的 一 种 基 于 J S O N textcolor{red}{一种基于JSON} 一种基于JSON的开放标准((RFC 7519).该token被设计为 紧 凑 且 安 全 textcolor{red}{紧凑且安全} 紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场景。JWT的声明一般被用来在 身 份 提 供 者 和 服 务 提 供 者 间 传 递 textcolor{red}{身份提供者和服务提供者间传递} 身份提供者和服务提供者间传递被认证的用户身份信息,以便于从资源服务器获取资源,也可以增加一些额外的其它业务逻辑所必须的声明信息,该token 也可直接被用于认证,也可被加密
textcolor{red}{}
JWT的认证流程图[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TutUz6OI-1652966782320)(C:UsersyuxuaAppDataRoamingTyporatypora-user-imagesimage-20220514170059385.png)]
流程说明
1,浏览器发起请求登陆,携带用户名和密码;
2,服务端验证身份,根据算法,将用户标识符打包生成 token,
3,服务器返回JWT信息给浏览器,JWT不包含敏感信息;
4,浏览器发起请求获取用户资料,把刚刚拿到的 token一起发送给服务器;
5,服务器发现数据中有 token,验明正身;
6,服务器返回该用户的用户资料;
token与session的区别session
Session是存放在服务器端的,可以保存在:内存、数据库、NoSQL中。它采用 空 间 换 时 间 的 策 略 textcolor{red}{空间换时间的策略} 空间换时间的策略来进行身份识别,若Session没有持久化落地存储,一旦服务器重启,Session数据会丢失。
token
Token是放在客户端存储的,采用了 时 间 换 空 间 策 略 textcolor{red}{时间换空间策略} 时间换空间策略,token类似一个令牌它也是无状态的,用户信息都被加密到token中,服务器收到token后解密就可知道是哪个用户。所以在分布式环境中应用广泛。
适用场景
一般购物车功能会采用Session验证,接口校验一般会采用Token验证,具体采用何种方法,需要大家根据自己的业务进行选择。
JwtToken工具配置yml文件
eshop:
security:
jwt-key: eshopmini
token-expired-in: 86400000
工具类
import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
@Component
public class JwtToken {
private static String jwtKey;
private static Integer expiredTimeIn;
private static Integer defaultScope = 8;
@Value("${eshop.security.jwt-key}")
public void setJwtKey(String jwtKey) {
JwtToken.jwtKey = jwtKey;
}
@Value("${eshop.security.token-expired-in}")
public void setExpiredTimeIn(Integer expiredTimeIn) {
JwtToken.expiredTimeIn = expiredTimeIn;
}
public static Optional
权限拦截器
定义
拦截器 是在面向切面编程中应用的,就是在你的service或者一个方法前调用一个方法,或者在方法后调用一个方法。是基于JAVA的反射机制
执行顺序
- 请求到达 DispatcherServlet
- DispatcherServlet 发送至 Interceptor ,执行 preHandle
- 请求达到 Controller
- 请求结束后,postHandle 执行
拦截器和过滤器的执行顺序
过滤前->拦截前->Action处理->拦截后->过滤后
自定义注解、自定义异常、用户权限、设置线程
import com.eshop.api.ApiCode;
import com.eshop.api.UnAuthenticatedException;
import com.eshop.common.bean.LocalUser;
import com.eshop.common.util.JwtToken;
import com.eshop.constant.ShopConstants;
import com.eshop.modules.user.domain.ShopUser;
import com.eshop.modules.user.service.UserService;
import com.eshop.utils.RedisUtils;
import com.auth0.jwt.interfaces.Claim;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Optional;
public class PermissionInterceptor extends HandlerInterceptorAdapter{
@Autowired
private UserService userService;
@Autowired
private RedisUtils redisUtils;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Optional authCheck = this.getAuthCheck(handler);
if (!authCheck.isPresent()){
return true;
}
// 先获取服务端的token
String bearerToken = request.getHeader( "Authorization" );
if (StringUtils.isEmpty( bearerToken )){
throw new UnAuthenticatedException(ApiCode.UNAUTHORIZED);
}
// 获取令牌前缀 防止信息伪造
if (!bearerToken.startsWith("Bearer")){
throw new UnAuthenticatedException(ApiCode.UNAUTHORIZED);
}
String[] tokens = bearerToken.split( " " );
if(!(tokens.length == 2)){
throw new UnAuthenticatedException(ApiCode.UNAUTHORIZED);
}
String token = tokens[1];
Optional
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthCheck {
int value() default 4;
}
注册拦截器
import com.eshop.common.interceptor.PermissionInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Value("${file.path}")
private String path;
@Value("${file.avatar}")
private String avatar;
// 将自己编写的拦截器注册进来
@Bean
public HandlerInterceptor getPermissionInterceptor() {
return new PermissionInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor( this.getPermissionInterceptor() );
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String avatarUtl = "file:" + avatar.replace("\","/");
String pathUtl = "file:" + path.replace("\","/");
// 静态资源处理 addResourceLocations 指的是内部文件放置的目录 setCachePeriod 缓存期限
// 意思就是,前端浏览器访问路径带有/file
public static String escape(String text) {
return encode(text);
}
public static String unescape(String content) {
return decode(content);
}
public static String clean(String content) {
return (new HTMLFilter()).filter(content);
}
private static String encode(String text) {
int len;
if (text != null && (len = text.length()) != 0) {
StringBuilder buffer = new StringBuilder(len + (len >> 2));
for(int i = 0; i < len; ++i) {
char c = text.charAt(i);
if (c < '@') {
buffer.append(TEXT[c]);
} else {
buffer.append(c);
}
}
return buffer.toString();
} else {
return "";
}
}
public static String decode(String content) {
if (StrUtil.isEmpty(content)) {
return content;
} else {
StringBuilder tmp = new StringBuilder(content.length());
int lastPos = 0;
boolean var3 = false;
while(lastPos < content.length()) {
int pos = content.indexOf("%", lastPos);
if (pos == lastPos) {
char ch;
if (content.charAt(pos + 1) == 'u') {
ch = (char)Integer.parseInt(content.substring(pos + 2, pos + 6), 16);
tmp.append(ch);
lastPos = pos + 6;
} else {
ch = (char)Integer.parseInt(content.substring(pos + 1, pos + 3), 16);
tmp.append(ch);
lastPos = pos + 3;
}
} else if (pos == -1) {
tmp.append(content.substring(lastPos));
lastPos = content.length();
} else {
tmp.append(content.substring(lastPos, pos));
lastPos = pos;
}
}
return tmp.toString();
}
}
public static void main(String[] args) {
String html = "";
System.out.println(clean(html));
System.out.println(escape(html));
System.out.println(unescape(html));
}
static {
for(int i = 0; i < 64; ++i) {
TEXT[i] = new char[]{(char)i};
}
TEXT[39] = "'".toCharArray();
TEXT[34] = """.toCharArray();
TEXT[38] = "&".toCharArray();
TEXT[60] = "<".toCharArray();
TEXT[62] = ">".toCharArray();
}
}
xss过滤包装类
增加一个xssHttpServletRequestWrapper类,这个类重写了获取参数的方法,在获取参数时做了xss替换处理
import com.eshop.utils.html.EscapeUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
public XssHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
}
public String[] getParameterValues(String name) {
String[] values = super.getParameterValues(name);
if (values == null) {
return super.getParameterValues(name);
} else {
int length = values.length;
String[] escapseValues = new String[length];
for(int i = 0; i < length; ++i) {
//过滤一切可能的xss攻击字符串
escapseValues[i] = EscapeUtil.clean(values[i]).trim();
}
return escapseValues;
}
}
}
XssFilter过滤器
import cn.hutool.core.util.StrUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
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;
public class XssFilter implements Filter {
public List excludes = new ArrayList();
public boolean enabled = false;
public XssFilter() {
}
public void init(FilterConfig filterConfig) throws ServletException {
String tempExcludes = filterConfig.getInitParameter("excludes");
String tempEnabled = filterConfig.getInitParameter("enabled");
//将不需要xss过滤的接口添加到列表中
if (StrUtil.isNotEmpty(tempExcludes)) {
String[] url = tempExcludes.split(",");
for(int i = 0; url != null && i < url.length; ++i) {
this.excludes.add(url[i]);
}
}
if (StrUtil.isNotEmpty(tempEnabled)) {
this.enabled = Boolean.valueOf(tempEnabled);
}
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
//如果该访问接口在排除列表里面则不拦截
if (this.handleExcludeURL(req, resp)) {
chain.doFilter(request, response);
} else {
//拦截该url并进行xss过滤
XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest)request);
chain.doFilter(xssRequest, response);
}
}
private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
if (!this.enabled) {
//如果xss开关关闭了,则所有url都不拦截
return true;
} else if (this.excludes != null && !this.excludes.isEmpty()) {
String url = request.getServletPath();
Iterator var4 = this.excludes.iterator();
Matcher m;
do {
if (!var4.hasNext()) {
return false;
}
String pattern = (String)var4.next();
Pattern p = Pattern.compile("^" + pattern);
m = p.matcher(url);
} while(!m.find());
return true;
} else {
return false;
}
}
public void destroy() {
}
}
注册Bean过滤
import cn.hutool.core.util.StrUtil;
import com.eshop.xss.XssFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.DispatcherType;
import java.util.HashMap;
import java.util.Map;
@Configuration(proxyBeanMethods = false)
public class FilterConfig
{
@Value("${xss.enabled}")
private String enabled;
@Value("${xss.excludes}")
private String excludes;
//${} 从配置文件中读取xss.urlPatterns的值
@Value("${xss.urlPatterns}")
private String urlPatterns;
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
// 注册bean过滤器
public FilterRegistrationBean xssFilterRegistration()
{
FilterRegistrationBean registration = new FilterRegistrationBean();
// 设置分发器 分发器的类型为 请求
registration.setDispatcherTypes(DispatcherType.REQUEST);
// 设置过滤器
registration.setFilter(new XssFilter());
// 设置 增加父网址 以 “,” 号分割
registration.addUrlPatterns(StrUtil.split(urlPatterns, ","));
// 设置过滤名字
registration.setName("xssFilter");
// 设置顺序
registration.setOrder(Integer.MAX_VALUE);
// 创建 map 命名为 初始化参数
Map initParameters = new HashMap();
initParameters.put("excludes", excludes);
initParameters.put("enabled", enabled);
// 过滤器设置初始化参数 将其 initParameters 放入
registration.setInitParameters(initParameters);
// 并返回
return registration;
}
}
置分发器 分发器的类型为 请求
registration.setDispatcherTypes(DispatcherType.REQUEST);
// 设置过滤器
registration.setFilter(new XssFilter());
// 设置 增加父网址 以 “,” 号分割
registration.addUrlPatterns(StrUtil.split(urlPatterns, “,”));
// 设置过滤名字
registration.setName(“xssFilter”);
// 设置顺序
registration.setOrder(Integer.MAX_VALUE);
// 创建 map 命名为 初始化参数
Map
initParameters.put(“excludes”, excludes);
initParameters.put(“enabled”, enabled);
// 过滤器设置初始化参数 将其 initParameters 放入
registration.setInitParameters(initParameters);
// 并返回
return registration;
}
}



