• 尚医通-手机验证码登录与gateway拦截实现


    需求分析

    1,登录采取弹出层的形式

    2,登录方式:

    (1)手机号码+手机验证码

    (2)微信扫描

    3,无注册界面,第一次登录根据手机号判断系统是否存在,如果不存在则自动注册

    4,微信扫描登录成功必须绑定手机号码,即:第一次扫描成功后绑定手机号,以后登录扫描直接登录成功

    5,网关统一判断登录状态,如何需要登录,页面弹出登录层

    搭建环境

    创建模块 service-user

    配置文件

    # 服务端口
    server.port=8150
    # 服务名
    spring.application.name=service-user
    
    # 环境设置dev,test,prod
    spring.profiles.active=dev
    
    # mysql数据库连接
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/yygh_user?characterEncoding=utf-8&useSSL=false
    spring.datasource.username=root
    spring.datasource.password=sugon666
    
    
    spring.redis.host=127.0.0.1
    spring.redis.port=6379
    spring.redis.database= 0
    spring.redis.timeout=1800000
    
    #返回json的全局时间格式
    spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
    spring.jackson.time-zone=GMT+8
    
    # nacos服务地址
    spring.cloud.nacos.discovery.server-addr=localhost:8848
    
    # 配置mapper xml文件的路径
    #mybatis-plus.mapper-locations=classpath:com/atguigu/yygh/user/mapper/xml/*.xml
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    配置网关

    # 设置路由 id
    spring.cloud.gateway.routes[2].id=service-user
    # 设置路由uri
    spring.cloud.gateway.routes[2].uri=lb://service-user
    # 设置路由断言,代理servicerId为auth-service的/user/路径
    spring.cloud.gateway.routes[2].predicates=Path=/*/user/**
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    image-20221122134406019

    主要创建下 UserInfo 相关的 类,这里不赘述

    手机登录基本实现

    // 用户手机号登录接口
    @PostMapping("login")
    @ApiOperation("用户手机号登录接口")
    public Result login(@RequestBody LoginVo loginVo) {
        Map<String, Object> info = userInfoService.loginUser(loginVo);
        return Result.ok(info);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    这块比较常规,用的 token + jwt

    // 手机号登录
        public Map<String, Object> loginUser(LoginVo loginVo) {
            // 从 loginVo 获取到 输入的手机号和验证码
            String phone = loginVo.getPhone();
            String code = loginVo.getCode();
            // 非空判断
            if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
                throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
            }
    
            // TODO 判断手机验证码和输入的验证码是否一致
            //String redisCode = redisTemplate.opsForValue().get(phone);
            //if (!code.equals(redisCode)) {
             //   throw new HospitalException(ResultCodeEnum.CODE_ERROR);
            //}
    
            // 判断是否第一次登录:查询数据库
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", phone);
            UserInfo userInfo = baseMapper.selectOne(wrapper);
            if (userInfo == null) {
                // 添加信息到数据库
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
    
            // 不是第一次,直接登录
            //校验是否被禁用
            if (userInfo.getStatus() == 0) {
                throw new HospitalException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
            }
            // 返回登录信息
            Map<String, Object> map = new HashMap<>();
            // 返回登录用户名称
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);
    
          // TODO 生成 jwt 的 token
            // 返回 token 信息
            map.put("token", JwtHelper.createToken(userInfo.getId(), name));
    
            return map;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52

    jwt 集成

    依赖

    <dependency>
        <groupId>io.jsonwebtokengroupId>
        <artifactId>jjwtartifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4

    工具类

    public class JwtHelper {
        private static long tokenExpiration = 24 * 60 * 60 * 1000; //token1过期时间设置 单位:毫秒
        private static String tokenSignKey = "123456";  //签名秘钥
    
        //根据参数生成token
        public static String createToken(Long userId, String userName) {
            String token = Jwts.builder()
                    .setSubject("YYGH-USER")
                    .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                    .claim("userId", userId)
                    .claim("userName", userName)
                    .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                    .compressWith(CompressionCodecs.GZIP)
                    .compact();
            return token;
        }
    
        //根据token字符串得到用户id
        public static Long getUserId(String token) {
            if (StringUtils.isEmpty(token)) return null;
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            Integer userId = (Integer) claims.get("userId");
            return userId.longValue();
        }
    
        //根据token字符串得到用户名称
        public static String getUserName(String token) {
            if (StringUtils.isEmpty(token)) return "";
            Jws<Claims> claimsJws
                    = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("userName");
        }
    
        public static void main(String[] args) {
            String token = JwtHelper.createToken(1L, "lucy");
            System.out.println(token);
            System.out.println(JwtHelper.getUserId(token));
            System.out.println(JwtHelper.getUserName(token));
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    调用

    map.put("token", JwtHelper.createToken(userInfo.getId(), name));
    
    • 1

    Swagger 测试,输入一个不存在的

    image-20221122135929349

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rZHpTvhv-1669282098210)(https://yixinglian.oss-cn-hangzhou.aliyuncs.com/blogimage-20221122140725584.png)]

    看到已经写入 user_info 表了

    整合 阿里云短信服务

    首先创建个msm的模块

    image-20221122141338003

    我用的是这个测试,点进来

    <dependency>
      <groupId>com.aliyungroupId>
      <artifactId>alibabacloud-dysmsapi20170525artifactId>
      <version>2.0.22version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    我用的最新版本的异步的sdk

    aliyun.sms.regionId=default
    aliyun.sms.accessKeyId=xxxx
    aliyun.sms.secret=xxx
    
    • 1
    • 2
    • 3

    把配置信息读取到 配置类

    @Component
    public class ConstantPropertiesUtils implements InitializingBean {
        @Value("${aliyun.sms.regionId}")
        private String regionId;
    
        @Value("${aliyun.sms.accessKeyId}")
        private String accessKeyId;
    
        @Value("${aliyun.sms.secret}")
        private String secret;
    
        public static String REGION_Id;
        public static String ACCESS_KEY_ID;
        public static String SECRECT;
    
        @Override
        public void afterPropertiesSet() throws Exception {
            REGION_Id=regionId;
            ACCESS_KEY_ID=accessKeyId;
            SECRECT=secret;
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    controller 发送验证码接口实现

    // 发送手机验证码
        @GetMapping("send/{phone}")
        public Result sendCode(@PathVariable String phone) throws ExecutionException, InterruptedException {
            //从redis获取验证码,如果获取获取到,返回ok
            // key 手机号  value 验证码
            String code = redisTemplate.opsForValue().get(phone);
            if (!StringUtils.isEmpty(code)) {
                return Result.ok();
            }
            // 如果从redis获取不到
            // 生成验证码
            code = RandomUtil.getSixBitRandom();
            redisTemplate.opsForValue().set(phone, code);
    
            //调用service方法,通过整合短信服务进行发送
            boolean isSend = msmService.send(phone, code);
            //生成验证码放到redis里面,设置有效时间
            if (isSend) {
                redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
                return Result.ok();
            } else {
                return Result.fail().message("发送短信失败");
            }
        }
    
    
    @Override
    public boolean send(String phone, String code) {
        DefaultProfile profile = DefaultProfile.getProfile(ConstantPropertiesUtils.REGION_Id,
                ConstantPropertiesUtils.ACCESS_KEY_ID, ConstantPropertiesUtils.SECRECT);
    
        IAcsClient client = new DefaultAcsClient(profile);
    
    
        SendSmsRequest request = new SendSmsRequest();
        request.setSignName("阿里云短信测试");
        request.setTemplateCode("SMS_154950909");
        request.setPhoneNumbers(phone);
    
        Map<String, String> param = new HashMap<>();
        param.put("code", code);
    
        request.setTemplateParam(JSONObject.toJSONString(param));
    
        try {
            SendSmsResponse response = client.getAcsResponse(request);
            System.out.println(response.getCode());
            System.out.println(new Gson().toJson(response));
            return response.getCode().equals("OK");
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54

    这里给出我的实现,注意点

    • 设置两分钟验证码的过期时间,如果已经发送过直接返回 true,否则把验证码存储到 redis ,并且发送验证码

    我们放开前面登录的注释

    String redisCode = redisTemplate.opsForValue().get(phone);
    if (!code.equals(redisCode)) {
        throw new HospitalException(ResultCodeEnum.CODE_ERROR);
    }
    
    • 1
    • 2
    • 3
    • 4

    前端整合

    前端两个api 文件

    import request from '@/utils/request'
    
    const api_name = `/api/user`
    
    export default {
        //手机登录接口
        login(userInfo) {
            return request({
                url: `${api_name}/login`,
                method: `post`,
                data: userInfo
            })
        }
    }
    
    import request from '@/utils/request'
    
    const api_name = `/api/msm`
    
    export default {
        sendCode(mobile) {
            return request({
                url: `${api_name}/send/${mobile}`,
                method: `get`
            })
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    myHeader

    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
    • 354
    • 355
    • 356
    • 357
    • 358
    • 359
    • 360
    • 361
    • 362
    • 363
    • 364
    • 365
    • 366
    • 367
    • 368
    • 369
    • 370
    • 371
    • 372
    • 373
    • 374
    • 375
    • 376
    • 377
    • 378
    • 379
    • 380
    • 381
    • 382
    • 383
    • 384
    • 385
    • 386
    • 387
    • 388
    • 389
    • 390
    • 391
    • 392
    • 393
    • 394
    • 395
    • 396
    • 397
    • 398
    • 399

    Cookie 记录登录成功的用户信息

    npm install js-cookie
    
    • 1

    这块参考上面前端代码即可

    用户登录网关整合

    网关层处理登录部门校验

    添加 filter

    @Component
    public class AuthGlobalFilter implements GlobalFilter, Ordered {
    
        private AntPathMatcher antPathMatcher = new AntPathMatcher();
    
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            ServerHttpRequest request = exchange.getRequest();
            String path = request.getURI().getPath();
            System.out.println("==="+path);
    
            //内部服务接口,不允许外部访问
            if(antPathMatcher.match("/**/inner/**", path)) {
                ServerHttpResponse response = exchange.getResponse();
                return out(response, ResultCodeEnum.PERMISSION);
            }
    
    
            //api接口,异步请求,校验用户必须登录
            if(antPathMatcher.match("/api/**/auth/**", path)) {
                Long userId = this.getUserId(request);
                if(StringUtils.isEmpty(userId)) {
                    ServerHttpResponse response = exchange.getResponse();
                    return out(response, ResultCodeEnum.LOGIN_AUTH);
                }
            }
            return chain.filter(exchange);
        }
    
        @Override
        public int getOrder() {
            return 0;
        }
    
        /**
         * api接口鉴权失败返回数据
         * @param response
         * @return
         */
        private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
            Result result = Result.build(null, resultCodeEnum);
            byte[] bits = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            //指定编码,否则在浏览器中会中文乱码
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }
    
        /**
         * 获取当前登录用户id
         * @param request
         * @return
         */
        private Long getUserId(ServerHttpRequest request) {
            String token = "";
            List<String> tokenList = request.getHeaders().get("token");
            if(null  != tokenList) {
                token = tokenList.get(0);
            }
            if(!StringUtils.isEmpty(token)) {
                return JwtHelper.getUserId(token);
            }
            return null;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65

    前端 request.js 统一处理

    • 请求拦截器:处理发出请求不带 token
    • 响应拦截器:处理返回值 208 (gateway 返回),跳转登录页
    import axios from "axios";
    import { MessageBox, Message } from "element-ui";
    import cookie from "js-cookie"
    
    // 创建axios实例
    const service = axios.create({
      baseURL: "http://localhost:81",
      timeout: 15000, // 请求超时时间
    });
    // http request 拦截器
    service.interceptors.request.use(
      (config) => {
        //判断cookie是否有token值
        if (cookie.get("token")) {
          //token值放到cookie里面
          config.headers["token"] = cookie.get("token");
        }
        return config;
      },
      (err) => {
        return Promise.reject(err);
      }
    );
    
    // http response 拦截器
    service.interceptors.response.use(
      (response) => {
        //状态码是208
        if (response.data.code === 208) {
          //弹出登录输入框
          loginEvent.$emit("loginDialogEvent");
          return;
        } else {
          if (response.data.code !== 200) {
            Message({
              message: response.data.message,
              type: "error",
              duration: 5 * 1000,
            });
            return Promise.reject(response.data);
          } else {
            return response.data;
          }
        }
      },
      (error) => {
        return Promise.reject(error.response);
      }
    );
    export default service;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
  • 相关阅读:
    ETL工具(数据同步)
    *javaSE 面试题
    C语言——简易版扫雷
    CSS基础教程
    【TensorFlow深度学习】创建与操作张量的典型实践与技巧
    时序数据库-10-[IoTDB]的DBeaver连接管理和命令行操作
    sql注入学习笔记
    激励是改善业绩的关键
    Linux基础IO
    【Java】ArrayList集合使用
  • 原文地址:https://blog.csdn.net/qq_39007838/article/details/128023066