JWT介绍:
JWT 只是缩写,全拼则是JSON Web Tokens,是目前流行的跨域认证解决方案,一种基于JSON的、用于在网络上声明某种主张的令牌token。JWT验证方式是将用户信息通过加密生成token,每次请求服务端只需要使用保存的密钥验证token的正确性,不用再保存任何session数据了,进而服务端变得无状态,容易实现拓展。
1:实现JWT工具类
package com.xch.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import javax.servlet.http.Cookie;
import java.util.Date;
public class TokenUtil {
private static final long EXPIRE_TIME = 24*60*60*1000; //有效时长
private static final String TOKEN_SECRET = "ben"; // 秘钥
/**
* 签名 生成
* @parm userName
* */
public static String sign(String userName){
String token = null;
try {
Date expiresAt = new Date(System.currentTimeMillis()+EXPIRE_TIME);
token = JWT.create()
.withIssuer("auth0")
.withClaim("userName",userName)
.withExpiresAt(expiresAt)
//使用HMAC256算法加密
.sign(Algorithm.HMAC256(TOKEN_SECRET));
}catch (Exception e){
e.printStackTrace();
}
return token;
}
/**
* 签名验证
* @param token
* */
public static boolean verify(Cookie token){
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET))
.withIssuer("auth0").build();
DecodedJWT jwt = verifier.verify((DecodedJWT) token);
System.out.println("认证通过");
System.out.println("userName"+jwt.getClaim("userName").asString());
System.out.println("过期时间:"+jwt.getExpiresAt());
return true;
}catch (Exception e){
return false;
}
}
}
1.1:JWT加密算法
JWT加密算法
HS256 HMAC256 HMAC with SHA-256 HS384 HMAC384 HMAC with SHA-384 HS512 HMAC512 HMAC with SHA-512 RS256 RSA256 RSASSA-PKCS1-v1_5 with SHA-256 RS384 RSA384 RSASSA-PKCS1-v1_5 with SHA-384 RS512 RSA512 RSASSA-PKCS1-v1_5 with SHA-512 ES256 ECDSA256 ECDSA with curve P-256 and SHA-256 ES384 ECDSA384 ECDSA with curve P-256 and SHA-384 ES512 ECDSA512 ECDSA with curve P-256 and SHA-512
2:实现Interceptor进行token认证,放行通过认证的请求
package com.xch.config;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Interceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("123");
if (HttpMethod.OPTIONS.toString().equals(request.getMethod())){
System.out.println("OPTIONS请求,放行");
return true;
}
//设置contentType,解决中文乱码
response.setContentType("text/html;charset=utf-8");
Cookie[] cookies = request.getCookies();
Cookie Token =null;
if (cookies!=null)
for (Cookie cookie : cookies) {
if ("token".equals(cookie.getName())){
Token = cookie;
break;
}
}
//返回true,认证通过,放行 不放行
return TokenUtil.verify(Token);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
3:实现拦截器配置类
package com.xch.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
@EnableWebMvc
@Configuration
public class MvcConfig implements WebMvcConfigurer {
//登录拦截
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration interceptorRegistration = registry.addInterceptor(new inInterceptor());
System.out.println("拦截请求");
//拦截所有请求
interceptorRegistration.addPathPatterns("/**");
//哪些请求不用拦截
interceptorRegistration.excludePathPatterns("/myLogin","/Login","/**/*.html","/**/*.js","/**/*.css");
}
}
配置好了之后,除了自己设置好的不用拦截的请求外,其它的请求都会被拦截进行token认证,只有通过认证,请求才会放行。