SpringCloud 框架基本模块梳理 (二)

SpringCloud 框架基本模块梳理 (二)

前言
本周更新的慢了一点,内容其实也不多。本篇接上篇来聊一下gateway的鉴权。这个词比较晦涩,要是说成接口访问权限校验没准显得直白一些。
一、组件版本介绍
JWT 3.4 (新晋成员)
redis

二、核心步骤
(关于JWT的使用可以参阅各大论坛大佬的帖子,这里就不过多的展开,只讲方法,不扩展)
1、生成token
核心方法如下:

JWT.create().withAudience(user.getId().toString())
                        .sign(Algorithm.HMAC256(user.getPassword()))

2、校验token
核心方法如下:

JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
jwtVerifier.verify(token);

三、插话
要不顺带提一下redis的配置方式,以及简单的使用。。。
jar包需要引入

<dependency>
   	<groupId>org.springframework.data</groupId>
         <artifactId>spring-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.3</version>
</dependency>

配置文件中需要声明redis的服务地址(此处省略了redis的配置说明,找起来也容易的)
在默认的配置下,使用org.springframework.data.redis.core.RedisTemplate,主要方法有两个:opsForCluster 和 delete ,两者都接收一个String型的参数,前者做存,后者做删除,当然还有个重要的过期时间设置 expire()方法,接收三个参数(Object-通常是redis里的key值,timeOut-过期时间,TimeUnit.MILLISECONDS-时间单位)—不建议在并发下使用。

四、效果展示
本次就没有效果展示了,贴一下token验证的代码吧。

public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) {
        String token = "";
        Cookie[] cookies = httpServletRequest.getCookies();
        if(cookies != null){
            for (Cookie cookie : cookies){
                if(cookie.getName().equals("Admin-Token")){
                    token = cookie.getValue();
                }
            }
        }

        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        //检查是否有passtoken注释,有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    throw new RuntimeException("无token,请重新登录");
                }
                // 获取 token 中的 user id
                Integer userId;
                try {
                    userId = Integer.parseInt(JWT.decode(token).getAudience().get(0));
                } catch (JWTDecodeException j) {
                    throw new RuntimeException("401");
                }
                TestUser user = userService.findUserById(userId);
                if (user == null) {
                    throw new RuntimeException("用户不存在,请重新登录");
                }
                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new RuntimeException("401");
                }
                return true;
            }
        }
        return true;
    }

这就是jwt使用最重要的部分了,实际应用中,可以将获取的token存放至redis中,在过期时间内重复的校验都是OK的。
五、结语
(这一周有点懒散,见谅!)

发布了4 篇原创文章 · 获赞 17 · 访问量 1310

猜你喜欢

转载自blog.csdn.net/qq_35317619/article/details/105004080