一、JWT认证流程
二、SpringBoot整合JWT
三、测试
一、JWT认证流程
认证流程如下:
-
用户使用账号和密码发出post请求;
-
服务器使用私钥创建一个jwt;
-
服务器返回这个jwt给浏览器;
-
浏览器将该jwt串在请求头中像服务器发送请求;
-
服务器验证该jwt;
-
返回响应的资源给浏览器。
二、SpringBoot整合JWT
新建一个spring boot项目spring-boot-jwt,按照下面步骤操作。
-
pom.xml引入jar包
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.8.2</version>
</dependency>
2. 新建Jwt工具类
Jwt工具类进行token的生成和认证,工具类代码如下:
package com.example.testmybatis.Util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.JWTVerifier;
import com.example.testmybatis.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @description: Jwt工具类,生成JWT和认证
* @author yyy
*/
public class JwtUtil {
private static final Logger logger= LoggerFactory.getLogger(JwtUtil.class);
/**
* 密码
*/
private static final String SECRET="my_secret";
/**
* 过期时间
*/
private static final long EXPIRATION=1800L;//单位秒
/**
* 生成用户token,并设置token超时时间
* @param user
* @return
*/
public static String createToken(User user){
Date expireDate=new Date(System.currentTimeMillis()+EXPIRATION*1000) ;
Map<String,Object> map=new HashMap<>();
map.put("alg","HS256");
map.put("typ","JWT");
String token= JWT.create()
.withHeader(map)//添加头部
//可以将基本信息放到claims中
.withClaim("id",user.getId())//userId
.withClaim("userName",user.getUserName())//userName
.withClaim("name",user.getName())//name
.withExpiresAt(expireDate)//设置过期日期
.withIssuedAt(new Date())//签发时间
.sign(Algorithm.HMAC256(SECRET));//设置私匙信息
return token;
}
/**
* 校验token并解析token
* @param token
* @return
*/
public static Map<String, Claim> verifyToken(String token){
DecodedJWT jwt=null;
try {
JWTVerifier verifier=JWT.require(Algorithm.HMAC256(SECRET)).build();
jwt=verifier.verify(token);
}
catch (Exception e){
logger.error(e.getMessage());
logger.error("token解码异常");
return null;
}
return jwt.getClaims();
}
}
3.添加JWT过滤器
JWT过滤器中进行token的校验和判断,,token不合法直接返回,合法则解密数据并把数据放到request中供后续使用。
为了使过滤器生效,需要在启动类添加注解@ServletComponentScan(basePackages = "com.example.springbootjwt.filter")。
JWT过滤器代码如下:
package com.example.testmybatis.filter;
import com.auth0.jwt.interfaces.Claim;
import com.example.testmybatis.Util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.scheduling.support.SimpleTriggerContext;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
/**
* JWT过滤器,拦截 /secure的请求
*/
@Slf4j
@WebFilter(filterName = "JwtFilter",urlPatterns = {"/secure/*","/person/*"})
public class JwtFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
final HttpServletRequest request=(HttpServletRequest)servletRequest;
final HttpServletResponse response=(HttpServletResponse)servletResponse;
response.setCharacterEncoding("UTF-8");
//获取 header里的token
final String token=request.getHeader("authorization");
if ("OPTIONS".equals(request.getMethod())){
response.setStatus(HttpServletResponse.SC_OK);
filterChain.doFilter(request,response);
}
else {//Except OPTIONS, other request should be checked by JWT
if(token==null){
response.getWriter().write("没有token!");
return;
}
Map<String, Claim> userData= JwtUtil.verifyToken(token);
if (userData==null){
response.getWriter().write("token不合法!");
return;
}
Integer id=userData.get("id").asInt();
String name=userData.get("name").asString();
String userName=userData.get("userName").asString();
//拦截器,拿到用户信息,并且放入request中
request.setAttribute("id",id);
request.setAttribute("name",name);
request.setAttribute("userName",userName);
filterChain.doFilter(servletRequest,servletResponse);
}
}
@Override
public void destroy() {
}
}
4.添加登录Controller
登录Controller进行登录操作,登录成功后生产token并返回。
登录Controller代码如下:
package com.example.testmybatis.controls;
import com.example.testmybatis.Util.JwtUtil;
import com.example.testmybatis.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* 登录
*/
@Slf4j
@RestController
@RequestMapping("/login")
public class LoginController {
static Map<Integer, User> userMap=new HashMap<>();
static {
User user1=new User(1,"zhangsan","张三","123456");
userMap.put(1,user1);
User user2=new User(2,"lisi","李四","123123");
userMap.put(2,user2);
}
@PostMapping
public String login(User user){
for (User dbUser:userMap.values()){
if (dbUser.getUserName().equals(user.getUserName())&& dbUser.getPassword().equals(user.getPassword())){
log.info("登录成功!生成token!");
String token= JwtUtil.createToken(dbUser);
return token;
}
}
return "";
}
}
5.添加SecureController
SecureController中的请求会被JWT过滤器拦截,合法后才能访问。
SecureController代码如下:
package com.example.testmybatis.controls;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/**
* 需要登录才能访问
*/
@Slf4j
@RestController
@RequestMapping("/secure")
public class SecureController {
@GetMapping("/getUserInfo")
public String login(HttpServletRequest request){
Integer id=(Integer)request.getAttribute("id");
String name=request.getAttribute("name").toString();
String userName=request.getAttribute("userName").toString();
return "当前用户信息:id="+id+",name="+name+",userName="+userName;
}
}
三、测试
测试分两步,首先访问登录接口,登录成功后获取token,然后拿着token在访问查询用户信息接口。
1.访问登录接口
打开PostMan,访问http://localhost:8080/login?userName=zhangsan&password=123456,登录成功后接口返回token