• 2022谷粒商城学习笔记(十九)认证服务整合短信验证码和OAuth2第三方社交登录


    前言

    本系列博客基于B站谷粒商城,只作为本人学习总结使用。这里我会比较注重业务逻辑的编写和相关配置的流程。有问题可以评论或者联系我互相交流。原视频地址谷粒商城雷丰阳版。本人git仓库地址Draknessssw的谷粒商城


    配置

    依赖

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.3.2.RELEASE</version>
            <relativePath></relativePath>
        </parent>
    
        <groupId>com.xxxx.gulimall</groupId>
        <artifactId>gulimall-auth-server</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>gulimall-auth-server</name>
        <description>谷粒商城-认证中心(社交登录、OAuth2.0、单点登录)</description>
        <properties>
            <java.version>1.8</java.version>
        </properties>
        <dependencies>
            <!--公共模块-->
            <dependency>
                <groupId>com.xxxx.gulimall</groupId>
                <artifactId>gulimall-common</artifactId>
                <version>0.0.1-SNAPSHOT</version>
                <exclusions>
                    <exclusion>
                        <groupId>com.baomidou</groupId>
                        <artifactId>mybatis-plus-boot-starter</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <!--web-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!--测试-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <!--thymeleaf模板引擎-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <!--devtools热启动,实现不重启服务实时更新页面-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <optional>true</optional>
            </dependency>
            <!--属性提示工具,spring源数据处理器,例如prefix="gulimall.thread"-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>
            <!--redis-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
                <exclusions>
                    <exclusion>
                        <groupId>io.lettuce</groupId>
                        <artifactId>lettuce-core</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
            </dependency>
            <!--整合springsession,实现session共享-->
            <dependency>
                <groupId>org.springframework.session</groupId>
                <artifactId>spring-session-data-redis</artifactId>
            </dependency>
            <!--审计模块,监控应用的健康情况、调用信息-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
        </dependencies>
    
        <dependencyManagement>
            <dependencies>
                <!--springcloud-->
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-dependencies</artifactId>
                    <version>Hoxton.SR6</version>
                </dependency>
            </dependencies>
        </dependencyManagement>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <configuration>
                        <excludes>
                            <exclude>
                                <groupId>org.projectlombok</groupId>
                                <artifactId>lombok</artifactId>
                            </exclude>
                        </excludes>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
    • 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

    服务注册

    在这里插入图片描述

    spring:
      application:
        name: gulimall-auth-server
    
      cloud:
        nacos:
          config:
            server-addr: 127.0.0.1:8848
            namespace: d8671d71-6baa-47e4-8d3a-9fddf252ad13
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    其他配置
    在这里插入图片描述

    server.port=20000
    
    spring.thymeleaf.cache=false
    
    spring.redis.host=192.168.75.129
    spring.redis.port=6379
    
    spring.session.store-type=redis
    server.servlet.session.timeout=30m
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    主启动类开启注解

    @EnableFeignClients
    @EnableDiscoveryClient
    
    • 1
    • 2

    域名映射

    在这里插入图片描述
    Resource目录下存放网页
    在这里插入图片描述

    nginx存放登录和注册需要的静态资源

    在这里插入图片描述


    短信验证码服务

    腾讯云短信业务控制台

    首先是创建短信签名,这个是必须的。建议使用公众号或者小程序来创建
    在这里插入图片描述
    创建模板

    在这里插入图片描述
    根据相关接口文档,这时候可以直接去调试界面进行测试

    腾讯云发送短信相关文档

    填写完相关信息后就可以生成代码
    在这里插入图片描述

    需要注意的是,还需要生成密钥来访问
    腾讯云密钥生成

    在这里插入图片描述
    接着回到项目中,将短信验证功能放到第三方服务

    在这里插入图片描述

    package com.xxxx.thirdparty.component;
    
    import com.tencentcloudapi.common.Credential;
    import com.tencentcloudapi.common.exception.TencentCloudSDKException;
    import com.tencentcloudapi.common.profile.ClientProfile;
    import com.tencentcloudapi.common.profile.HttpProfile;
    import com.tencentcloudapi.sms.v20210111.SmsClient;
    import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
    import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
    import lombok.Data;
    import org.springframework.stereotype.Component;
    
    import java.util.Random;
    
    /**
     * @author LinLinD
     * @Create 2022-07-26-16:51
     */
    @Data
    @Component
    public class SmsComponent {
    
    
    
        public void sendSmsCode(String phone,String code) {
            try{
                // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
                // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
                Credential cred = new Credential("", "");
                // 实例化一个http选项,可选的,没有特殊需求可以跳过
                HttpProfile httpProfile = new HttpProfile();
                httpProfile.setEndpoint("sms.tencentcloudapi.com");
                // 实例化一个client选项,可选的,没有特殊需求可以跳过
                ClientProfile clientProfile = new ClientProfile();
                clientProfile.setHttpProfile(httpProfile);
                // 实例化要请求产品的client对象,clientProfile是可选的
                SmsClient client = new SmsClient(cred, "ap-nanjing", clientProfile);
                // 实例化一个请求对象,每个接口都会对应一个request对象
                SendSmsRequest req = new SendSmsRequest();
                String[] phoneNumberSet1 = {phone};
                req.setPhoneNumberSet(phoneNumberSet1);
    
                req.setSmsSdkAppId("");
                req.setSignName("");
                req.setTemplateId("");
    
    
    
                String[] templateParamSet1 = {code};;
                req.setTemplateParamSet(templateParamSet1);
    
                // 返回的resp是一个SendSmsResponse的实例,与请求对象对应
                SendSmsResponse resp = client.SendSms(req);
                // 输出json格式的字符串回包
                System.out.println(SendSmsResponse.toJsonString(resp));
            } catch (TencentCloudSDKException e) {
                System.out.println(e.toString());
            }
        }
    }
    
    • 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

    对应的Controller

    在这里插入图片描述

    package com.xxxx.thirdparty.controller;
    
    import com.xxxx.common.utils.R;
    import com.xxxx.thirdparty.component.SmsComponent;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    
    
    @Controller
    @RequestMapping(value = "/sms")
    public class SmsSendController {
    
        @Autowired
        private SmsComponent smsComponent;
    
        /**
         * 提供给别的服务进行调用
         * @param phone
         * @param code
         * @return
         */
        @GetMapping(value = "/sendCode")
        public R sendCode(@RequestParam("phone") String phone, @RequestParam("code") String code) {
    
    //        int vode=smsComponent.generateValidateCode(6);
    //        String _code=String.valueOf(vode);
            //发送验证码
            smsComponent.sendSmsCode(phone,code);
    
            return R.ok();
        }
    
    }
    
    
    • 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

    在认证服务模块添加调用短信验证的功能

    在这里插入图片描述

    这里使用Redis对验证码进行60s的防刷校验

    	@Autowired
        private ThirdPartFeignService thirdPartFeignService;
    
        @Autowired
        private StringRedisTemplate stringRedisTemplate;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    @ResponseBody
        @GetMapping(value = "/sms/sendCode")
        public R sendCode(@RequestParam("phone") String phone) {
    
            //1、接口防刷
            String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
            if (!StringUtils.isEmpty(redisCode)) {
                //活动存入redis的时间,用当前时间减去存入redis的时间,判断用户手机号是否在60s内发送验证码
                long currentTime = Long.parseLong(redisCode.split("_")[1]);
                if (System.currentTimeMillis() - currentTime < 60000) {
                    //60s内不能再发
                    return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
                }
            }
    
            //2、验证码的再次效验 redis.存key-phone,value-code
            int code = generateValidateCode(6);
            String codeNum = String.valueOf(code);
            String redisStorage = codeNum + "_" + System.currentTimeMillis();
    
            //存入redis,防止同一个手机号在60秒内再次发送验证码
            stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,
                    redisStorage,10, TimeUnit.MINUTES);
    
            thirdPartFeignService.sendCode(phone, codeNum);
    
            return R.ok();
        }
    
        /**
         * 随机生成验证码
         * @param length 长度为4位或者6位
         * @return
         */
        public static Integer generateValidateCode(int length){
            Integer code =null;
            if(length == 4){
                code = new Random().nextInt(9999);//生成随机数,最大为9998
                if(code < 1000){
                    code = code + 1000;//保证随机数为4位数字
                }
            }else if(length == 6){
                code = new Random().nextInt(999999);//生成随机数,最大为999999
                if(code < 100000){
                    code = code + 100000;//保证随机数为6位数字
                }
            }else{
                throw new RuntimeException("只能生成4位或6位数字验证码");
            }
            return code;
        }
    
    • 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

    调用第三方feign接口

    package com.xxxx.gulimall.auth.feign;
    
    import com.xxxx.common.utils.R;
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    
    
    @FeignClient("gulimall-third-party")
    public interface ThirdPartFeignService {
    
        @GetMapping(value = "/sms/sendCode")
        R sendCode(@RequestParam("phone") String phone, @RequestParam("code") String code);
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    注册功能

    注册信息Vo

    package com.xxxx.gulimall.auth.vo;
    
    import lombok.Data;
    import org.hibernate.validator.constraints.Length;
    
    import javax.validation.constraints.NotEmpty;
    import javax.validation.constraints.Pattern;
    
    
    
    @Data
    public class UserRegisterVo {
    
        @NotEmpty(message = "用户名不能为空")
        @Length(min = 6, max = 19, message="用户名长度在6-18字符")
        private String userName;
    
        @NotEmpty(message = "密码必须填写")
        @Length(min = 6,max = 18,message = "密码必须是6—18位字符")
        private String password;
    
        @NotEmpty(message = "手机号不能为空")
        @Pattern(regexp = "^[1]([3-9])[0-9]{9}$", message = "手机号格式不正确")
        private String phone;
    
        @NotEmpty(message = "验证码不能为空")
        private String code;
    
    }
    
    
    • 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

    Controller
    在这里插入图片描述
    从定向到注册页面,捕获错误属性。

    		//如果有错误回到注册页面
            if (result.hasErrors()) {
                Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
                attributes.addFlashAttribute("errors",errors);
    
                //效验出错回到注册页面
                return "redirect:http://auth.gulimall.com/reg.html";
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    获取验证码

    //1、效验验证码
            String code = vos.getCode();
    
    • 1
    • 2

    获取存入Redis里的验证码

    //获取存入Redis里的验证码
            String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
    
    • 1
    • 2

    验证一下验证码是否和Redis缓存中存在的验证码一致,若是一致,删除缓存中的验证码。接着调用远程会员服务注册。注册之后返回注册页面,失败得额外携带失败信息。

    //截取字符串
                if (code.equals(redisCode.split("_")[0])) {
                    //删除验证码;令牌机制
                    stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+vos.getPhone());
                    //验证码通过,真正注册,调用远程服务进行注册
                    R register = memberFeignService.register(vos);
                    if (register.getCode() == 0) {
                        //成功
                        return "redirect:http://auth.gulimall.com/login.html";
                    } else {
                        //失败
                        Map<String, String> errors = new HashMap<>();
                        errors.put("msg", register.getData("msg",new TypeReference<String>(){}));
                        attributes.addFlashAttribute("errors",errors);
                        return "redirect:http://auth.gulimall.com/reg.html";
                    }
    
    
                }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    若是验证码和Redis缓存中存在的验证码不一致,返回注册页面,携带错误消息。

    			else {
                    //效验出错回到注册页面
                    Map<String, String> errors = new HashMap<>();
                    errors.put("code","验证码错误");
                    attributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    最终效果如下:

        /**
         *
         * TODO: 重定向携带数据:利用session原理,将数据放在session中。
         * TODO:只要跳转到下一个页面取出这个数据以后,session里面的数据就会删掉
         * TODO:分布下session问题
         * RedirectAttributes:重定向也可以保留数据,不会丢失
         * 用户注册
         * @return
         */
        @PostMapping(value = "/register")
        public String register(@Valid UserRegisterVo vos, BindingResult result,
                               RedirectAttributes attributes) {
    
            //如果有错误回到注册页面
            if (result.hasErrors()) {
                Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
                attributes.addFlashAttribute("errors",errors);
    
                //效验出错回到注册页面
                return "redirect:http://auth.gulimall.com/reg.html";
            }
    
            //1、效验验证码
            String code = vos.getCode();
    
            //获取存入Redis里的验证码
            String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
            if (!StringUtils.isEmpty(redisCode)) {
                //截取字符串
                if (code.equals(redisCode.split("_")[0])) {
                    //删除验证码;令牌机制
                    stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+vos.getPhone());
                    //验证码通过,真正注册,调用远程服务进行注册
                    R register = memberFeignService.register(vos);
                    if (register.getCode() == 0) {
                        //成功
                        return "redirect:http://auth.gulimall.com/login.html";
                    } else {
                        //失败
                        Map<String, String> errors = new HashMap<>();
                        errors.put("msg", register.getData("msg",new TypeReference<String>(){}));
                        attributes.addFlashAttribute("errors",errors);
                        return "redirect:http://auth.gulimall.com/reg.html";
                    }
    
    
                } else {
                    //效验出错回到注册页面
                    Map<String, String> errors = new HashMap<>();
                    errors.put("code","验证码错误");
                    attributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            } else {
                //效验出错回到注册页面
                Map<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                attributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }
    
    • 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

    视图映射配置
    在这里插入图片描述

    package com.xxxx.gulimall.auth.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    
    @Configuration
    public class GulimallWebConfig implements WebMvcConfigurer {
    
        /**·
         * 视图映射:发送一个请求,直接跳转到一个页面
         * @param registry
         */
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
    
            // registry.addViewController("/login.html").setViewName("login");
            registry.addViewController("/reg.html").setViewName("reg");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    远程接口如下

    @FeignClient("gulimall-member")
    public interface MemberFeignService {
    
        @PostMapping(value = "/member/member/register")
        R register(@RequestBody UserRegisterVo vo);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    在这里插入图片描述

    	@Autowired
        private MemberService memberService;
    
        @PostMapping(value = "/register")
        public R register(@RequestBody MemberUserRegisterVo vo) {
    
            try {
                memberService.register(vo);
            } catch (PhoneException e) {
                return R.error(BizCodeEnum.PHONE_EXIST_EXCEPTION.getCode(),BizCodeEnum.PHONE_EXIST_EXCEPTION.getMessage());
            } catch (UsernameException e) {
                return R.error(BizCodeEnum.USER_EXIST_EXCEPTION.getCode(),BizCodeEnum.USER_EXIST_EXCEPTION.getMessage());
            }
    
            return R.ok();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    用户注册信息Vo

    package com.xxxx.gulimall.member.vo;
    
    import lombok.Data;
    
    
    
    @Data
    public class MemberUserRegisterVo {
    
        private String userName;
    
        private String password;
    
        private String phone;
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    实现类

    设置会员默认等级

    		MemberEntity memberEntity = new MemberEntity();
    
            //设置默认等级
            MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
            memberEntity.setLevelId(levelEntity.getId());
    
    • 1
    • 2
    • 3
    • 4
    • 5

    sql

    	<select id="getDefaultLevel" resultType="com.xxxx.gulimall.member.entity.MemberLevelEntity">
            SELECT * FROM ums_member_level WHERE default_status = 1
        </select>
    
    • 1
    • 2
    • 3

    验证用户手机和用户名的唯一性

    		//检查用户名和手机号是否唯一。感知异常,异常机制
            checkPhoneUnique(vo.getPhone());
            checkUserNameUnique(vo.getUserName());
    
    • 1
    • 2
    • 3
    	@Override
        public void checkPhoneUnique(String phone) throws PhoneException {
    
            Integer phoneCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
    
            if (phoneCount > 0) {
                throw new PhoneException();
            }
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    	@Override
        public void checkUserNameUnique(String userName) throws UsernameException {
    
            Integer usernameCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
    
            if (usernameCount > 0) {
                throw new UsernameException();
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    设置其他信息

    		memberEntity.setNickname(vo.getUserName());
            memberEntity.setUsername(vo.getUserName());
            //密码进行MD5加密
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String encode = bCryptPasswordEncoder.encode(vo.getPassword());
            memberEntity.setPassword(encode);
            memberEntity.setMobile(vo.getPhone());
            memberEntity.setGender(0);
            memberEntity.setCreateTime(new Date());
    
            //保存数据
            this.baseMapper.insert(memberEntity);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    最终如下

    @Override
        public void register(MemberUserRegisterVo vo) {
    
            MemberEntity memberEntity = new MemberEntity();
    
            //设置默认等级
            MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
            memberEntity.setLevelId(levelEntity.getId());
    
            //设置其它的默认信息
            //检查用户名和手机号是否唯一。感知异常,异常机制
            checkPhoneUnique(vo.getPhone());
            checkUserNameUnique(vo.getUserName());
    
            memberEntity.setNickname(vo.getUserName());
            memberEntity.setUsername(vo.getUserName());
            //密码进行MD5加密
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String encode = bCryptPasswordEncoder.encode(vo.getPassword());
            memberEntity.setPassword(encode);
            memberEntity.setMobile(vo.getPhone());
            memberEntity.setGender(0);
            memberEntity.setCreateTime(new Date());
    
            //保存数据
            this.baseMapper.insert(memberEntity);
        }
    
    • 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

    登录功能

    登录信息Vo

    package com.xxxx.gulimall.auth.vo;
    
    import lombok.Data;
    
    
    
    @Data
    public class UserLoginVo {
    
        private String loginacct;
    
        private String password;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    登录成功将登录的相关信息存入session中,重定向到商城主页。否则携带错误消息重定向到登录页面。

    	@PostMapping(value = "/login")
        public String login(UserLoginVo vo, RedirectAttributes attributes, HttpSession session) {
    
            //远程登录
            R login = memberFeignService.login(vo);
    
            if (login.getCode() == 0) {
                MemberResponseVo data = login.getData("data", new TypeReference<MemberResponseVo>() {});
                session.setAttribute(LOGIN_USER,data);
                return "redirect:http://gulimall.com";
            } else {
                Map<String,String> errors = new HashMap<>();
                errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
                attributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    远程服务接口

    package com.xxxx.gulimall.auth.feign;
    
    import com.xxxx.common.utils.R;
    import com.xxxx.gulimall.auth.vo.SocialUser;
    import com.xxxx.gulimall.auth.vo.UserLoginVo;
    import com.xxxx.gulimall.auth.vo.UserRegisterVo;
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    
    /**
     * @author LinLinD
     * @Create 2022-07-26-18:05
     */
    @FeignClient("gulimall-member")
    public interface MemberFeignService {
     	@PostMapping(value = "/member/member/login")
        R login(@RequestBody UserLoginVo vo);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    在这里插入图片描述

     	@PostMapping(value = "/login")
        public R login(@RequestBody MemberUserLoginVo vo) {
    
            MemberEntity memberEntity = memberService.login(vo);
    
            if (memberEntity != null) {
                return R.ok().setData(memberEntity);
            } else {
                return R.error(BizCodeEnum.LOGINACCT_PASSWORD_EXCEPTION.getCode(),BizCodeEnum.LOGINACCT_PASSWORD_EXCEPTION.getMessage());
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    登录信息Vo

    package com.xxxx.gulimall.member.vo;
    
    import lombok.Data;
    
    
    
    	@Data
    	public class MemberUserLoginVo {
    
        private String loginacct;
    
        private String password;
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    实现类

    首先根据登录传过来的登录信息(用户名或者密码)匹配用户表的记录。匹配到记录就获取密码,和传过来的密码进行匹配,匹配成功则成功登录。

    @Override
        public MemberEntity login(MemberUserLoginVo vo) {
    
            String loginacct = vo.getLoginacct();
            String password = vo.getPassword();
    
            //1、去数据库查询 SELECT * FROM ums_member WHERE username = ? OR mobile = ?
            MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                    .eq("username", loginacct).or().eq("mobile", loginacct));
    
            if (memberEntity == null) {
                //登录失败
                return null;
            } else {
                //获取到数据库里的password
                String password1 = memberEntity.getPassword();
                BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
                //进行密码匹配
                boolean matches = passwordEncoder.matches(password, password1);
                if (matches) {
                    //登录成功
                    return memberEntity;
                }
            }
    
            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

    社交登录(第三方账号登录)

    微博和微信都需要备案,所以我这里使用了gitee作为登录的社交账号

    用户在我们系统登录页面,不用点注册或者登录,而是点击Gitee图标跳转到Gitee的登录页,登陆后点击授权按钮,然后获得授权码,然后跳转回我们的系统,,我们用这个授权码获取Token,成功获取到Token后,利用token获取Gitee用户信息,然后,把这个userinfo,注册或者登录我们自己的系统(如果这个社交账号之前没有登陆过,就自动注册并登录,根据Gitee返回的ID判断)

    OAuth2认证流程

    在这里插入图片描述
    在gitee中,设置里配置第三方应用

    回调地址即为授权第三方应用的页面,自定义好地址之后内容由第三方应用提供。

    在这里插入图片描述

    业务

    在这里插入图片描述
    使用HttpUtils工具类对用户授权返回的code获取access_token

    请求路径参考gitee的OAuth文档
    Gitee OAuth文档

    HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), map, new HashMap<>());
    
    • 1

    工具类如下

    package com.xxxx.common.utils;
    
    import org.apache.commons.lang.StringUtils;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpDelete;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.methods.HttpPut;
    import org.apache.http.conn.ClientConnectionManager;
    import org.apache.http.conn.scheme.Scheme;
    import org.apache.http.conn.scheme.SchemeRegistry;
    import org.apache.http.conn.ssl.SSLSocketFactory;
    import org.apache.http.entity.ByteArrayEntity;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    import java.io.UnsupportedEncodingException;
    import java.net.URLEncoder;
    import java.security.KeyManagementException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.X509Certificate;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    
    
    public class HttpUtils {
    
        /**
         * get
         *
         * @param host
         * @param path
         * @param method
         * @param headers
         * @param querys
         * @return
         * @throws Exception
         */
        public static HttpResponse doGet(String host, String path, String method,
                                         Map<String, String> headers,
                                         Map<String, String> querys)
                throws Exception {
            HttpClient httpClient = wrapClient(host);
    
            HttpGet request = new HttpGet(buildUrl(host, path, querys));
            for (Map.Entry<String, String> e : headers.entrySet()) {
                request.addHeader(e.getKey(), e.getValue());
            }
    
            return httpClient.execute(request);
        }
    
        /**
         * post form
         *
         * @param host
         * @param path
         * @param method
         * @param headers
         * @param querys
         * @param bodys
         * @return
         * @throws Exception
         */
        public static HttpResponse doPost(String host, String path, String method,
                                          Map<String, String> headers,
                                          Map<String, String> querys,
                                          Map<String, String> bodys)
                throws Exception {
            HttpClient httpClient = wrapClient(host);
    
            HttpPost request = new HttpPost(buildUrl(host, path, querys));
            for (Map.Entry<String, String> e : headers.entrySet()) {
                request.addHeader(e.getKey(), e.getValue());
            }
    
            if (bodys != null) {
                List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
    
                for (String key : bodys.keySet()) {
                    nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
                }
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
                formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
                request.setEntity(formEntity);
            }
    
            return httpClient.execute(request);
        }
    
        /**
         * Post String
         *
         * @param host
         * @param path
         * @param method
         * @param headers
         * @param querys
         * @param body
         * @return
         * @throws Exception
         */
        public static HttpResponse doPost(String host, String path, String method,
                                          Map<String, String> headers,
                                          Map<String, String> querys,
                                          String body)
                throws Exception {
            HttpClient httpClient = wrapClient(host);
    
            HttpPost request = new HttpPost(buildUrl(host, path, querys));
            for (Map.Entry<String, String> e : headers.entrySet()) {
                request.addHeader(e.getKey(), e.getValue());
            }
    
            if (StringUtils.isNotBlank(body)) {
                request.setEntity(new StringEntity(body, "utf-8"));
            }
    
            return httpClient.execute(request);
        }
    
        /**
         * Post stream
         *
         * @param host
         * @param path
         * @param method
         * @param headers
         * @param querys
         * @param body
         * @return
         * @throws Exception
         */
        public static HttpResponse doPost(String host, String path, String method,
                                          Map<String, String> headers,
                                          Map<String, String> querys,
                                          byte[] body)
                throws Exception {
            HttpClient httpClient = wrapClient(host);
    
            HttpPost request = new HttpPost(buildUrl(host, path, querys));
            for (Map.Entry<String, String> e : headers.entrySet()) {
                request.addHeader(e.getKey(), e.getValue());
            }
    
            if (body != null) {
                request.setEntity(new ByteArrayEntity(body));
            }
    
            return httpClient.execute(request);
        }
    
        /**
         * Put String
         * @param host
         * @param path
         * @param method
         * @param headers
         * @param querys
         * @param body
         * @return
         * @throws Exception
         */
        public static HttpResponse doPut(String host, String path, String method,
                                         Map<String, String> headers,
                                         Map<String, String> querys,
                                         String body)
                throws Exception {
            HttpClient httpClient = wrapClient(host);
    
            HttpPut request = new HttpPut(buildUrl(host, path, querys));
            for (Map.Entry<String, String> e : headers.entrySet()) {
                request.addHeader(e.getKey(), e.getValue());
            }
    
            if (StringUtils.isNotBlank(body)) {
                request.setEntity(new StringEntity(body, "utf-8"));
            }
    
            return httpClient.execute(request);
        }
    
        /**
         * Put stream
         * @param host
         * @param path
         * @param method
         * @param headers
         * @param querys
         * @param body
         * @return
         * @throws Exception
         */
        public static HttpResponse doPut(String host, String path, String method,
                                         Map<String, String> headers,
                                         Map<String, String> querys,
                                         byte[] body)
                throws Exception {
            HttpClient httpClient = wrapClient(host);
    
            HttpPut request = new HttpPut(buildUrl(host, path, querys));
            for (Map.Entry<String, String> e : headers.entrySet()) {
                request.addHeader(e.getKey(), e.getValue());
            }
    
            if (body != null) {
                request.setEntity(new ByteArrayEntity(body));
            }
    
            return httpClient.execute(request);
        }
    
        /**
         * Delete
         *
         * @param host
         * @param path
         * @param method
         * @param headers
         * @param querys
         * @return
         * @throws Exception
         */
        public static HttpResponse doDelete(String host, String path, String method,
                                            Map<String, String> headers,
                                            Map<String, String> querys)
                throws Exception {
            HttpClient httpClient = wrapClient(host);
    
            HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
            for (Map.Entry<String, String> e : headers.entrySet()) {
                request.addHeader(e.getKey(), e.getValue());
            }
    
            return httpClient.execute(request);
        }
    
        private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
            StringBuilder sbUrl = new StringBuilder();
            sbUrl.append(host);
            if (!StringUtils.isBlank(path)) {
                sbUrl.append(path);
            }
            if (null != querys) {
                StringBuilder sbQuery = new StringBuilder();
                for (Map.Entry<String, String> query : querys.entrySet()) {
                    if (0 < sbQuery.length()) {
                        sbQuery.append("&");
                    }
                    if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                        sbQuery.append(query.getValue());
                    }
                    if (!StringUtils.isBlank(query.getKey())) {
                        sbQuery.append(query.getKey());
                        if (!StringUtils.isBlank(query.getValue())) {
                            sbQuery.append("=");
                            sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                        }
                    }
                }
                if (0 < sbQuery.length()) {
                    sbUrl.append("?").append(sbQuery);
                }
            }
    
            return sbUrl.toString();
        }
    
        private static HttpClient wrapClient(String host) {
            HttpClient httpClient = new DefaultHttpClient();
            if (host.startsWith("https://")) {
                sslClient(httpClient);
            }
    
            return httpClient;
        }
    
        private static void sslClient(HttpClient httpClient) {
            try {
                SSLContext ctx = SSLContext.getInstance("TLS");
                X509TrustManager tm = new X509TrustManager() {
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                    @Override
                    public void checkClientTrusted(X509Certificate[] xcs, String str) {
    
                    }
                    @Override
                    public void checkServerTrusted(X509Certificate[] xcs, String str) {
    
                    }
                };
                ctx.init(null, new TrustManager[] { tm }, null);
                SSLSocketFactory ssf = new SSLSocketFactory(ctx);
                ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                ClientConnectionManager ccm = httpClient.getConnectionManager();
                SchemeRegistry registry = ccm.getSchemeRegistry();
                registry.register(new Scheme("https", 443, ssf));
            } catch (KeyManagementException ex) {
                throw new RuntimeException(ex);
            } catch (NoSuchAlgorithmException ex) {
                throw new RuntimeException(ex);
            }
        }
    
    }
    
    
    • 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

    当获取Access_token成功时,做两步处理,转为Json和Vo对象。

     		//2、处理
            if (response.getStatusLine().getStatusCode() == 200) {
                //获取到了access_token,转为通用社交登录对象
                String json = EntityUtils.toString(response.getEntity());
                //String json = JSON.toJSONString(response.getEntity());
                SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    Access_tokenVo如下

    package com.xxxx.gulimall.auth.vo;
    
    import lombok.Data;
    
    
    @Data
    public class SocialUser {
    
        private String access_token;
    
        private String remind_in;
    
        private long expires_in;
    
        private String uid;
    
        private String isRealName;
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    调用远程服务登录,要是成功登录,设置进session里面,返回成功登录页面(首页)。否则返回登录页面。

    //调用远程服务
                R oauthLogin = memberFeignService.oauthLogin(socialUser);
                if (oauthLogin.getCode() == 0) {
                    MemberResponseVo data = oauthLogin.getData("data", new TypeReference<MemberResponseVo>() {});
                    log.info("登录成功:用户信息:{}",data.toString());
    
                    //1、第一次使用session,命令浏览器保存卡号,JSESSIONID这个cookie
                    //以后浏览器访问哪个网站就会带上这个网站的cookie
                    //TODO 1、默认发的令牌。当前域(解决子域session共享问题)
                    //TODO 2、使用JSON的序列化方式来序列化对象到Redis中
                    session.setAttribute(LOGIN_USER,data);
                    
                    //2、登录成功跳回首页
                    return "redirect:http://gulimall.com";
                } else {
                    
                    return "redirect:http://auth.gulimall.com/login.html";
                }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    关于session中cookie的配置和Redis中的数据映射为json。
    因为要共享session中的信息,所以在member服务中也要如此配置。
    在这里插入图片描述

    package com.xxxx.gulimall.auth.config;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.RedisSerializer;
    import org.springframework.session.web.http.CookieSerializer;
    import org.springframework.session.web.http.DefaultCookieSerializer;
    
    
    
    @Configuration
    public class GulimallSessionConfig {
    
        @Bean
        public CookieSerializer cookieSerializer() {
    
            DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer();
    
            //放大作用域
            cookieSerializer.setDomainName("gulimall.com");
            cookieSerializer.setCookieName("GULISESSION");
    
            return cookieSerializer;
        }
    
    
        @Bean
        public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
            return new GenericJackson2JsonRedisSerializer();
        }
    
    }
    
    • 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

    在application.properties文件中配置Redis和SpringSession

    spring.redis.host=192.168.75.129
    spring.redis.port=6379
    
    spring.session.store-type=redis
    server.servlet.session.timeout=30m
    
    • 1
    • 2
    • 3
    • 4
    • 5

    相关依赖

    		<!--redis-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
                <exclusions>
                    <exclusion>
                        <groupId>io.lettuce</groupId>
                        <artifactId>lettuce-core</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
            </dependency>
            <!--整合springsession,实现session共享-->
            <dependency>
                <groupId>org.springframework.session</groupId>
                <artifactId>spring-session-data-redis</artifactId>
            </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    第三方登录远程调用接口

    package com.xxxx.gulimall.auth.feign;
    
    import com.xxxx.common.utils.R;
    import com.xxxx.gulimall.auth.vo.SocialUser;
    import com.xxxx.gulimall.auth.vo.UserLoginVo;
    import com.xxxx.gulimall.auth.vo.UserRegisterVo;
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    
    /**
     * @author LinLinD
     * @Create 2022-07-26-18:05
     */
    @FeignClient("gulimall-member")
    public interface MemberFeignService {
    	@PostMapping(value = "/member/member/oauth2/login")
        R oauthLogin(@RequestBody SocialUser socialUser) throws Exception;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    在member服务中

    	@PostMapping(value = "/oauth2/login")
        public R oauthLogin(@RequestBody SocialUser socialUser) throws Exception {
    
            MemberEntity memberEntity = memberService.login(socialUser);
    
            if (memberEntity != null) {
                return R.ok().setData(memberEntity);
            } else {
                return R.error(BizCodeEnum.LOGINACCT_PASSWORD_EXCEPTION.getCode(),BizCodeEnum.LOGINACCT_PASSWORD_EXCEPTION.getMessage());
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    社交登录的Vo信息和验证服务的Vo一致

    package com.xxxx.gulimall.member.vo;
    
    import lombok.Data;
    
    
    
    @Data
    public class SocialUser {
    
        private String access_token;
    
        private String remind_in;
    
        private long expires_in;
    
        private String uid;
    
        private String isRealName;
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    实现类
    判断用户是否已经登录过了,根据用户社交账号id查询。如果有,更新用户信息

    		//具有登录和注册逻辑
            String uid = socialUser.getUid();
    
            //1、判断当前社交用户是否已经登录过系统
            MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
    
            if (memberEntity != null) {
                //这个用户已经注册过
                //更新用户的访问令牌的时间和access_token
                MemberEntity update = new MemberEntity();
                update.setId(memberEntity.getId());
                update.setAccessToken(socialUser.getAccess_token());
                update.setExpiresIn(socialUser.getExpires_in());
                this.baseMapper.updateById(update);
    
                memberEntity.setAccessToken(socialUser.getAccess_token());
                memberEntity.setExpiresIn(socialUser.getExpires_in());
                return memberEntity;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    没有查到说明用户第一次登录,进行注册。查询第三方应用的信息。插入用户表。
    请求路径如图所示
    在这里插入图片描述

    	@Autowired
        private MemberFeignService memberFeignService;
    
    
        @GetMapping(value = "/oauth2.0/gitee/success")
        public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
    
            Map<String, String> map = new HashMap<>();
            map.put("client_id","");
            map.put("client_secret","");
            map.put("grant_type","authorization_code");
            map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/gitee/success");
            map.put("code",code);
    
            //1、根据用户授权返回的code换取access_token
            HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), map, new HashMap<>());
    
            //2、处理
            if (response.getStatusLine().getStatusCode() == 200) {
                //获取到了access_token,转为通用社交登录对象
                String json = EntityUtils.toString(response.getEntity());
                //String json = JSON.toJSONString(response.getEntity());
                SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
    
                //知道了哪个社交用户
                //1)、当前用户如果是第一次进网站,自动注册进来(为当前社交用户生成一个会员信息,以后这个社交账号就对应指定的会员)
                //登录或者注册这个社交用户
                System.out.println(socialUser.getAccess_token());
                //调用远程服务
                R oauthLogin = memberFeignService.oauthLogin(socialUser);
                if (oauthLogin.getCode() == 0) {
                    MemberResponseVo data = oauthLogin.getData("data", new TypeReference<MemberResponseVo>() {});
                    log.info("登录成功:用户信息:{}",data.toString());
    
                    //1、第一次使用session,命令浏览器保存卡号,JSESSIONID这个cookie
                    //以后浏览器访问哪个网站就会带上这个网站的cookie
                    //TODO 1、默认发的令牌。当前域(解决子域session共享问题)
                    //TODO 2、使用JSON的序列化方式来序列化对象到Redis中
                    session.setAttribute(LOGIN_USER,data);
                    
                    //2、登录成功跳回首页
                    return "redirect:http://gulimall.com";
                } else {
                    
                    return "redirect:http://auth.gulimall.com/login.html";
                }
    
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
    
        }
    
    • 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

    最终效果如下

        @Override
        public MemberEntity login(SocialUser socialUser) throws Exception {
    
            //具有登录和注册逻辑
            String uid = socialUser.getUid();
    
            //1、判断当前社交用户是否已经登录过系统
            MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
    
            if (memberEntity != null) {
                //这个用户已经注册过
                //更新用户的访问令牌的时间和access_token
                MemberEntity update = new MemberEntity();
                update.setId(memberEntity.getId());
                update.setAccessToken(socialUser.getAccess_token());
                update.setExpiresIn(socialUser.getExpires_in());
                this.baseMapper.updateById(update);
    
                memberEntity.setAccessToken(socialUser.getAccess_token());
                memberEntity.setExpiresIn(socialUser.getExpires_in());
                return memberEntity;
            } else {
                //2、没有查到当前社交用户对应的记录我们就需要注册一个
                MemberEntity register = new MemberEntity();
                //3、查询当前社交用户的社交账号信息(昵称、性别等)
                Map<String,String> query = new HashMap<>();
                query.put("access_token",socialUser.getAccess_token());
                query.put("uid",socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<String, String>(), query);
    
                if (response.getStatusLine().getStatusCode() == 200) {
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    String profileImageUrl = jsonObject.getString("profile_image_url");
    
                    register.setNickname(name);
                    register.setGender("m".equals(gender)?1:0);
                    register.setHeader(profileImageUrl);
                    register.setCreateTime(new Date());
                    register.setSocialUid(socialUser.getUid());
                    register.setAccessToken(socialUser.getAccess_token());
                    register.setExpiresIn(socialUser.getExpires_in());
    
                    //把用户信息插入到数据库中
                    this.baseMapper.insert(register);
    
                }
                return register;
            }
    
        }
    
    • 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
  • 相关阅读:
    MySQL 中LIMIT的使用详解
    vscode终端命令报错
    【SQL数据库】数据库的创建、查询、插入等操作使用方法(结合黑皮书教材网站(db-book中的例子)在MySQL Workbench和shell中实现查询操作
    深入思考redis面经
    SSM整合过程梳理
    Llama-7b-hf和vicuna-7b-delta-v0合并成vicuna-7b-v0
    企业常用Linux三剑客awk及案例/awk底层剖析/淘宝网cdn缓存对象分级存储策略案例/磁盘知识/awk统计与计算-7055字
    安卓大作业 图书管理APP
    项目经理之识别项目干系人
    jdbcUrl is required with driverClassName错误解决
  • 原文地址:https://blog.csdn.net/qq_44737138/article/details/126692184