一. 什么是
JSON Web Token(JWT)定制软件是目前最流行的定制软件跨域身份验证解决方案。
二.JWT定制软件一般用于做什么
- 授权
定制软件即在用户登录成功以后,定制软件为用户颁发一个token(令牌),定制软件用户便可以使用这个token定制软件令牌访问后台的接口
- 加密
使用JWT定制软件可以对接口的参数进行加密,定制软件在后台验证成功以后才定制软件能真正进行处理
三.为什么要使用JWT进行认证,而不使用session、cookie?
基于cookie的认证,存在如下问题:
- CSRF:session基于cookie,如果cookie被截获,用户很容易收到跨站请求伪造的攻击。
基于session的认证,存在如下问题:
- 开销大:每个用户在认证之后,都要在服务端做一次记录,以方便该用户下次请求的鉴别。通常session保存在内存中,随着认证用户的增多,服务端存储session的开销显著增大。
- 扩展性低:用户认证记录存储在认证服务器的内存中,这意味着用户下次请求仍要访问这台服务器才能拿到授权。在分布式应用上,这限制了负载均衡的能力,进而限制了整个应用的扩展能力。
JWT是一种基于token的认证机制,它类似于HTTP协议一样是无状态的,不需要在服务端保留用户的认证信息或者会话信息。除此之外,基于token的鉴权机制不需要考虑用户在哪一台服务器登录,为应用扩展提供了便利。
说了这么多,那我们就通过一个小案例来实战一下~
环境准备:
一个简单的springboot工程:
基本的user实体类:
- package com.example.mybatixtest.pojo;
-
- import com.baomidou.mybatisplus.annotation.IdType;
- import com.baomidou.mybatisplus.annotation.TableField;
- import com.baomidou.mybatisplus.annotation.TableId;
- import com.baomidou.mybatisplus.annotation.TableName;
- import java.io.Serializable;
-
- import com.sun.xml.internal.ws.developer.Serialization;
- import lombok.Data;
-
- /**
- *
- * @TableName user
- */
- @TableName(value ="user")
- @Data
- @Serialization
- public class User implements Serializable {
- /**
- *
- */
- private String userId;
-
- /**
- *
- */
- private String username;
-
- /**
- *
- */
- private String password;
-
- @TableField(exist = false)
- private static final long serialVersionUID = 1L;
- }
1.我们先在pom.xml文件中导入jwt依赖
- <!--引入jwt-->
- <dependency>
- <groupId>com.auth0</groupId>
- <artifactId>java-jwt</artifactId>
- <version>3.9.0</version>
- </dependency>
2.创建一个JWT工具类,封装JWT的相关操作(加密、验证、解密)
- package com.canrio.onlinemusic.utils;
-
- import com.auth0.jwt.JWT;
- import com.auth0.jwt.JWTVerifier;
- import com.auth0.jwt.algorithms.Algorithm;
- import com.auth0.jwt.interfaces.DecodedJWT;
- import org.springframework.stereotype.Component;
-
- import java.util.Date;
-
- @Component
- public class TokenUtil {
-
- private static final long EXPIRE_TIME= 15*60*1000;
- private static final String TOKEN_SECRET="token123"; //密钥盐
-
- /**
- * 签名生成
- * @return
- */
- public static String sign(String name,String userId){
-
- String token = null;
- try {
- Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
- token = JWT.create()
- .withIssuer("auth0").withClaim("id","id")
- .withClaim("username", name)
- .withClaim("userId",userId)
- .withExpiresAt(expiresAt)
- // 使用了HMAC256加密算法。
- .sign(Algorithm.HMAC256(TOKEN_SECRET));
- } catch (Exception e){
- e.printStackTrace();
- }
- return token;
-
- }
- /**
- * 签名验证
- * @param token
- * @return
- */
- public static boolean verify(String token){
-
- try {
- JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
- DecodedJWT jwt = verifier.verify(token);
- System.out.println("认证通过:");
- System.out.println("issuer: " + jwt.getIssuer());
- System.out.println("username: " + jwt.getClaim("username").asString());
- System.out.println("userId: " + jwt.getClaim("userId").asString());
- System.out.println("id"+jwt.getClaim("id").asString());
- System.out.println("过期时间: " + jwt.getExpiresAt());
- return true;
- } catch (Exception e){
- return false;
- }
- }
-
- public static String getId(String token){
-
-
- JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
- DecodedJWT jwt = verifier.verify(token);
- String id = jwt.getClaim("userId").asString();
- return id;
-
- }
- }
3.创建一个登录拦截器LoginInterceptor,用于获取请求的Token并进行验证
- package com.example.mybatixtest.interceptor;
-
- import com.example.mybatixtest.utils.TokenUtil;
- import org.springframework.http.HttpMethod;
- import org.springframework.stereotype.Component;
- import org.springframework.web.servlet.HandlerInterceptor;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- @Component //在容器中进行注册
- public class LoginInterceptor implements HandlerInterceptor {
-
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
- System.out.println("OPTIONS请求,放行");
- return true;
- }
- String token = request.getHeader("token");
- if(TokenUtil.verify(token)){
- return true;
- }
- // 失败我们跳转回登录页面
- request.setAttribute("msg","登录出错");
- request.getRemoteHost();
- request.getRequestDispatcher("/login").forward(request,response);
- return false;
- }
-
- }
4.修改web配置,添加一个配置类WebConfig对LoginInterceptor进行注册和制定拦截规则
- package com.example.mybatixtest.config;
-
- import com.example.mybatixtest.interceptor.LoginInterceptor;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
-
- //@Configuration 告诉springboot这是一个配置类
- @Configuration
- public class WebConfig implements WebMvcConfigurer {
-
- @Autowired
- LoginInterceptor loginInterceptor;
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- registry.addInterceptor(loginInterceptor)
- .addPathPatterns("/**") //默认对所有请求进行拦截
- .excludePathPatterns("/userLogin","/static/**"); //对login页面和静态资源不拦截
- }
- }
5.我们编写简单的请求进行验证
- @GetMapping(value = "/userLogin")
- public String userLogin(@RequestParam("username") String username, @RequestParam("password") String password) {
- //创建一个条件构造器
- QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>();
- //传入查询条件
-
- userQueryWrapper.eq("username", username).eq("password", password);
- User user = userService.getOne(userQueryWrapper);
- if (user != null) {
- String res = TokenUtil.sign(username, user.getUserid());
- System.out.println(res);
- return res;
- }
-
- return "失败";
-
- }
6.使用postman进行验证,我们可以发现用户端得到了一串token字符串
7.这里再用我之前做过的小项目对token进行验证
- /**
- * 根据返回的token解析用户id并返回该用户的歌单列表
- *
- * @return
- */
- @GetMapping("/getUserFolderByUserId")
- public List<UserFolder> getUserFolderByUserID() {
- String token = request.getHeader("token");
- System.out.println(token);
- String id = TokenUtil.getId(token);
- QueryWrapper<UserFolder> userFolderQueryWrapper = new QueryWrapper<>();
- userFolderQueryWrapper.eq("user_userid", id);
- List<UserFolder> list = userFolderService.list(userFolderQueryWrapper);
- System.out.println(list);
- return list;
- }
当我们请求头不携带token时:
当我们携带时: