JSON Web Token(JWT)是目前最流行的跨域身份验证解决方案。
即在用户登录成功以后,为用户颁发一个token(令牌),用户便可以使用这个token令牌访问后台的接口
使用JWT可以对接口的参数进行加密,在后台验证成功以后才能真正进行处理
基于cookie的认证,存在如下问题:
基于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;
}
com.auth0
java-jwt
3.9.0
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 userQueryWrapper = new QueryWrapper();
//传入查询条件
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 getUserFolderByUserID() {
String token = request.getHeader("token");
System.out.println(token);
String id = TokenUtil.getId(token);
QueryWrapper userFolderQueryWrapper = new QueryWrapper<>();
userFolderQueryWrapper.eq("user_userid", id);
List list = userFolderService.list(userFolderQueryWrapper);
System.out.println(list);
return list;
}
当我们请求头不携带token时:
当我们携带时: