SpringBoot 集成JWT

什么是 JSON 网络令牌?

JSON Web Token (JWT) 是一个开放标准 ( RFC 7519 ),它定义了一种紧凑且自包含的方式,用于在各方之间作为 JSON 对象安全地传输信息。该信息可以被验证和信任,因为它是经过数字签名的。JWT 可以使用秘密(使用HMAC算法)或使用RSAECDSA的公钥/私钥对进行签名

虽然 JWT 可以加密以在各方之间提供保密,但我们将重点关注签名令牌。签名令牌可以验证其中包含的声明的完整性,而加密令牌则对其他方隐藏这些声明。当使用公钥/私钥对对令牌进行签名时,签名还证明只有持有私钥的一方才是对其进行签名的一方。

什么时候应该使用 JSON 网络令牌?

以下是 JSON Web Tokens 有用的一些场景:

  • 授权:这是使用 JWT 最常见的场景。用户登录后,每个后续请求都将包含
    JWT,允许用户访问该令牌允许的路由、服务和资源。单点登录是当今广泛使用 JWT 的一项功能,因为它的开销很小,并且能够轻松跨不同域使用。
  • 信息交换:JSON Web Tokens 是一种在各方之间安全传输信息的好方法。因为 JWT
    可以被签名——例如,使用公钥/私钥对——你可以确定发件人就是他们所说的那样。此外,由于使用标头和有效负载计算签名,因此您还可以验证内容是否未被篡改。

什么是 JSON Web Token 结构?

在其紧凑形式中,JSON Web Tokens 由用点 ( .)分隔的三个部分组成,它们是:

  • Header
  • Payload
  • Signature

因此,JWT 通常如下所示。

xxxxx.yyyyy.zzzzz

让我们分解不同的部分。

Header

标头通常由两部分组成:令牌的类型,即 JWT,以及正在使用的签名算法,例如 HMAC SHA256 或 RSA。

例如:

{
    
    
  "alg": "HS256",
  "typ": "JWT"
}

然后,这个 JSON 被Base64Url编码以形成 JWT 的第一部分。

Payload
令牌的第二部分是负载,其中包含声明。声明是关于实体(通常是用户)和附加数据的声明。共有三种类型的声明:注册声明、公共声明和私人声明。

  • 注册声明:这些是一组预定义的声明,这些声明不是强制性的,而是推荐的,以提供一组有用的、可互操作的声明。其中一些是:
    iss(发行者)、 exp(到期时间)、 sub(主题)、 aud(受众)等。

    请注意,声明名称只有三个字符,因为 JWT 是紧凑的。

  • 公共声明:这些可以由使用 JWT 的人随意定义。但是为了避免冲突,它们应该在IANA JSON Web Token Registry中定义或定义为包含抗冲突命名空间的 URI。

  • 私人权利:这些都是使用它们同意并既不是当事人之间建立共享信息的自定义声明注册或公众的权利要求。

一个示例有效载荷可能是:

{
    
    
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

然后对有效负载进行Base64Url编码以形成 JSON Web 令牌的第二部分。

请注意,对于已签名的令牌,此信息虽然受到防篡改保护,但任何人都可以读取。除非加密,否则不要将机密信息放在 JWT 的负载或标头元素中。

Signature

要创建签名部分,您必须获取编码的标头、编码的有效载荷、秘密、标头中指定的算法,并对其进行签名。

例如,如果要使用 HMAC SHA256 算法,则签名将通过以下方式创建:

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)

签名用于验证消息在此过程中没有更改,并且在使用私钥签名的令牌的情况下,它还可以验证 JWT 的发送者是它所说的那个人。

放在一起

输出是三个由点分隔的 Base64-URL 字符串,可以在 HTML 和 HTTP 环境中轻松传递,同时与基于 XML 的标准(如 SAML)相比更加紧凑。

下面显示了一个 JWT,它对前面的标头和有效负载进行了编码,并使用机密进行了签名。

eyJhbGciOiJIUzI1NiJ9.
eyJqdGkiOiI4ODgiLCJzdWIiOiLlsI_nmb0iLCJpYXQiOjE1NTc5MDQxODF9.
ThecMfgYjtoys3JX7dpx3hu6pUm0piZ0tXXreFU_u3Y

创建token

  • 新建的项目中引入pom 依赖
  <dependency>
        <groupId>com.auth0</groupId>
        <artifactId>java-jwt</artifactId>
        <version>3.10.3</version>
    </dependency>
  • 新建TokenUtil 工具类
import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.jwt.demo.config.UserLoginPermission;
import com.jwt.demo.db.bean.UserRole;
import com.jwt.demo.db.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * token 工具类
 * @author chenlirun
 * @date 2021/7/8 17:27
 */
@Component
public class UserLoginTokenUtil {
    
    

    /**
     * 查询用户访问权限
     * @author chenlirun
     * @date 2021/7/18 17:36
     */
    @Autowired
    private UserRoleMapper userRoleMapper;

    // 静态实例化类对象
    private static UserLoginTokenUtil userLoginTokenUtil;

    /**
     * @PostConstruct
     * 1、首先这个注解是由Java提供的,它用来修饰一个非静态的void方法。它会在服务器加载Servlet的时候运行,并且只运行一次。
     * 2、用于处理普通工具类中方法无法被 static修饰,加入这个注解之后就可以在类初始化之前执行这个注解下的方法。
     * 3、我这个就是工具类中无法注入 mapper
     */
    @PostConstruct
    public void init(){
    
    
        userLoginTokenUtil=this;
    }


    //设置 token 过期时间为 30 分钟
    public static final long EXPIRE_TIME=30*60*1000;

    /**
     * 生成 token 签名,30分钟后过期
     *
     * @author chenlirun
     * @date 2021/7/8 17:52
     */
    public static String sign(Long id){
    
    
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        // 设置jwt 令牌,Algorithm.HMAC256() 加密令牌
        Algorithm algorithm = Algorithm.HMAC256(TokenLoginInfo.secret);
        return JWT.create().withClaim("id",id) // 设置属性,可以是当前登录的用户信息,给 Payload
                .withExpiresAt(date) // 设置过期时间
                .withIssuedAt(new Date()) // 设置当前创建时间
                .sign(algorithm); // 签发一个新的jwt 令牌
    }

    /**
     * 校验 token
     * @author chenlirun
     * @date 2021/7/8 17:56
     */
    public static boolean verify(String token,Long id,String secret){
    
    
        try {
    
    
            Algorithm algorithm = Algorithm.HMAC256(secret);
            /**
             * JWT.require(): 验证签名的算法
             * .build(): 使用已经提供的配置创建一个新的可重用的JWTVerifier实例。
             *          返回:一个新的jwtverification实例。
              */
            JWTVerifier verifier = JWT.require(algorithm).withClaim("id", id).build();
            verifier.verify(token);
            return true;
        }catch (Exception e){
    
    
            return false;
        }

    }

    /**
     * 解析token,id
     * @author chenlirun
     * @date 2021/7/9 11:20
     */
    public static Long getTokenById(HttpServletRequest request){
    
    
        String token = request.getHeader("token");
        /**
         * 解码给定的Json Web令牌。
         * 注意,这个方法并不验证令牌的签名!只有在您信任令牌或您已经验证了它时才使用它。
         * 返回:解码后的jwt。抛出:JWTDecodeException
         * -如果令牌的任何部分包含一个无效的jwt或每个jwt部分的JSON格式。
         */
        DecodedJWT decode = JWT.decode(token);
        return decode.getClaim("id").asLong();
    }

    /**
     * 认证token
     * @author chenlirun
     * @date 2021/7/16 14:56
     */
    public static boolean validToken(HttpServletRequest request, UserLoginPermission tag){
    
    
        String token = request.getHeader("token");
        if(token==null){
    
    
            throw new BaseException(BaseCodeResult.ERROR,"当前未登录");
        }
        Long userId = UserLoginTokenUtil.getTokenById(request);
        // 验证 token 签名
        System.out.println(TokenLoginInfo.secret);
        boolean verifySuccess = UserLoginTokenUtil.verify(token, userId, TokenLoginInfo.secret);
        if(!verifySuccess){
    
    
            throw new BaseException(BaseCodeResult.ERROR,"token 签名不正确");
        }
        // 验证访问权限
        UserRole userRole = userLoginTokenUtil.userRoleMapper.selectByUserId(userId);
        Byte roleId = userRole.getRoleId();
        if (ObjectUtil.isEmpty(userRole)){
    
    
            throw new BaseException(BaseCodeResult.ERROR,"该用户无可用权限");
        }
        /**
         * String.indexOf()
         * 返回此字符串中指定子字符串的第一个匹配项的索引。
         * 返回的索引是k中最小的值:这.开始与(斯特,k)如果kexists没有这个值,则返回-1。
         * str -要搜索的子字符串。
         * 返回:指定子字符串第一个匹配项的索引,如果没有匹配项则返回-1。
         */
        int i = tag.role().indexOf(String.valueOf(roleId));
        if(i == -1){
    
    
            throw new BaseException(BaseCodeResult.ERROR,"无访问权限");
        }
        return true;
    }
}

这个工具类,集生成、认证token 为一体的,如果只是想生成token认证token,不做其他操作的话,到这里已经可以了。只需创建一个测试类,调用工具类中的方法。
例如:

生成token:UserLoginTokenUtil.sign(Long id)

注意:public static boolean validToken(HttpServletRequest request, UserLoginPermission tag)这个方法下面拦截请求的时候用的。
userRoleMapper.selectByUserId(Long id):是查询当前用户的访问权限

<select id="selectByUserId" parameterType="java.lang.Long" resultMap="BaseResultMap">
    select * from jwt_user_role where user_id = #{userId}
  </select>

配置请求拦截器

下面的操作是为了实现用户访问权限的拦截的功能。

  • 新建一个配置类,继承WebMvcConfigurer接口,重写方法。
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


/**
 * spring Mvc生命周期拦截器配置
 * @author chenlirun
 * @date 2021/7/14 12:00
 */
public class InterceptorConfig implements WebMvcConfigurer {
    
    

    /**
     * Add Spring MVC lifecycle interceptors for pre- and post-processing of
     * controller method invocations and resource handler requests.
     * Interceptors can be registered to apply to all requests or be limited
     * to a subset of URL patterns.
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    

        registry.addInterceptor(new AuthenticationInterceptor())
                .addPathPatterns("/**");
    }

    /**
     * Configure "global" cross origin request processing. The configured CORS
     * mappings apply to annotated controllers, functional endpoints, and static
     * resources.
     * <p>Annotated controllers can further declare more fine-grained config via
     * {@link CrossOrigin @CrossOrigin}.
     * In such cases "global" CORS configuration declared here is
     * {@link CorsConfiguration#combine(CorsConfiguration) combined}
     * with local CORS configuration defined on a controller method.
     *
     * @param registry
     * @see CorsRegistry
     * @see CorsConfiguration#combine(CorsConfiguration)
     * @since 4.2
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
    
    
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS", "HEAD")
                .maxAge(3600*24);
    }
}

配置访问权限的拦截

  • 自定义一个注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;

@Target({
    
    ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserLoginPermission {
    
    

    //登录认证
    boolean login() default true;

    //角色认证
    String role();


}

Target:描述了注解修饰的对象范围,取值在java.lang.annotation.ElementType定义,常用的包括:

  • METHOD:用于描述方法
  • PACKAGE:用于描述包
  • PARAMETER:用于描述方法变量
  • TYPE:用于描述类、接口或enum类型

Retention: 表示注解保留时间长短。取值在java.lang.annotation.RetentionPolicy中,取值为:

  • SOURCE:在源文件中有效,编译过程中会被忽略
  • CLASS:随源文件一起编译在class文件中,运行时忽略
  • RUNTIME:在运行时有效

只有定义为RetentionPolicy.RUNTIME时,我们才能通过注解反射获取到注解。所以,假设我们要自定义一个注解,它用在字段上,并且可以通过反射获取到,功能是用来描述字段的长度和作用。

  • 新建一个访问标记类
public class RolePermission {
    
    

    public static final String User_ADMIN="1" ;

    public static final String USER_GROUP="1,2,3";

    public static final String COMMON="1,2,3";

}
  • 配置处理token认证拦截器
import com.jwt.demo.util.BaseCodeResult;
import com.jwt.demo.util.BaseException;
import com.jwt.demo.util.UserLoginTokenUtil;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理程序拦截器
 * @author chenlirun
 * @date 2021/7/18 18:00
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    
    


    /**
     * Intercept the execution of a handler. Called after HandlerMapping determined
     * an appropriate handler object, but before HandlerAdapter invokes the handler.
     * <p>DispatcherServlet processes a handler in an execution chain, consisting
     * of any number of interceptors, with the handler itself at the end.
     * With this method, each interceptor can decide to abort the execution chain,
     * typically sending an HTTP error or writing a custom response.
     * <p><strong>Note:</strong> special considerations apply for asynchronous
     * request processing. For more details see
     * {@link AsyncHandlerInterceptor}.
     * <p>The default implementation returns {@code true}.
     *
     * @param request  current HTTP request
     * @param response current HTTP response
     * @param handler  chosen handler to execute, for type and/or instance evaluation
     * @return {@code true} if the execution chain should proceed with the
     * next interceptor or the handler itself. Else, DispatcherServlet assumes
     * that this interceptor has already dealt with the response itself.
     * @throws Exception in case of errors
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        if(handler instanceof HandlerMethod){
    
    
            HandlerMethod handlerMethod=(HandlerMethod) handler;
            // 发现方法上的注解
            UserLoginPermission annotation = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), UserLoginPermission.class);
            // 如果方法级别为空,则将类级别赋值
            if(annotation==null){
    
    
                // 发现加载类上的注解
                annotation = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), UserLoginPermission.class);
            }
            /**
             * 如果标记属性都为空,则抛出异常
             * 若方法级别标记为空,类级别标记不为空,则继续进行认证
             */
            if(annotation==null){
    
    
                throw new BaseException(BaseCodeResult.ERROR,"未设置权限标记");
            }else {
    
    
                boolean login = annotation.login();
                if (login){
    
    
                   UserLoginTokenUtil.validToken(request, annotation);
                }
            }
        }
        return true;
    }

    /**
     * Intercept the execution of a handler. Called after HandlerAdapter actually
     * invoked the handler, but before the DispatcherServlet renders the view.
     * Can expose additional model objects to the view via the given ModelAndView.
     * <p>DispatcherServlet processes a handler in an execution chain, consisting
     * of any number of interceptors, with the handler itself at the end.
     * With this method, each interceptor can post-process an execution,
     * getting applied in inverse order of the execution chain.
     * <p><strong>Note:</strong> special considerations apply for asynchronous
     * request processing. For more details see
     * {@link AsyncHandlerInterceptor}.
     * <p>The default implementation is empty.
     *
     * @param request      current HTTP request
     * @param response     current HTTP response
     * @param handler      the handler (or {@link HandlerMethod}) that started asynchronous
     *                     execution, for type and/or instance examination
     * @param modelAndView the {@code ModelAndView} that the handler returned
     *                     (can also be {@code null})
     * @throws Exception in case of errors
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    
    

    }

    /**
     * Callback after completion of request processing, that is, after rendering
     * the view. Will be called on any outcome of handler execution, thus allows
     * for proper resource cleanup.
     * <p>Note: Will only be called if this interceptor's {@code preHandle}
     * method has successfully completed and returned {@code true}!
     * <p>As with the {@code postHandle} method, the method will be invoked on each
     * interceptor in the chain in reverse order, so the first interceptor will be
     * the last to be invoked.
     * <p><strong>Note:</strong> special considerations apply for asynchronous
     * request processing. For more details see
     * {@link AsyncHandlerInterceptor}.
     * <p>The default implementation is empty.
     *
     * @param request  current HTTP request
     * @param response current HTTP response
     * @param handler  the handler (or {@link HandlerMethod}) that started asynchronous
     *                 execution, for type and/or instance examination
     * @param ex       any exception thrown on handler execution, if any; this does not
     *                 include exceptions that have been handled through an exception resolver
     * @throws Exception in case of errors
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    
    

    }

}
  • 新建一个JWT令牌
public class TokenLoginInfo {
    
    

    public static final String secret="df23554ajrlucmdtw54";

}
  • 测试:

注解使用方式:将自定义的注解加载控制器类上或者是方法体上
在这里插入图片描述

方法体中
在这里插入图片描述

测试用户登录生成token签名

@SpringBootTest
class DemoApplicationTests {
    
    

    @Autowired
    private UserLoginMapper userLoginMapper;


    @Test
    public void login(){
    
    
        Long id=8L;
        UserLogin userLogin = userLoginMapper.selectByPrimaryKey(id);


        String sign = UserLoginTokenUtil.sign(id);
        System.out.println(sign);
    }

}

输出结果:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6OCwiZXhwIjoxNjI2Njc3MjIxLCJpYXQiOjE2MjY2NzU0MjF9.ZSCSktsH4UFptBRZ0qfuwwzF0Q9os9nk77ktqNjnPdk

猜你喜欢

转载自blog.csdn.net/CSDN_java1005/article/details/118889104