实现二维码登录功能(及单点登录重定向)

 <div class="qrcodeCanvas">
   <div id="qrcode" v-loading="expireLoading"></div>
   <div class="markQr" v-if="expireSign" @click="getCode">
     <i class="iconfont icon-tuzhishuchu-xiazaichajianshuaxin"></i>
   </div>
 </div>
 <p class="bottomText">{{expireSign?'点击重新获取':'请用XXX扫描二维码登录'}}</p>

data参数:
      qrcode: null,
      qrCodeStr: "",
      getInfoCode: "",
      expireSign: false, // 是否展示二维码蒙版层
      expireLoading: false, // 控制loading状态


methods方法:

// 首先在用户选择切换到二维码扫码页面时,获取后台传递的二维码地址
    getCode() {
      this.expireLoading = true;    this.expireSign = false;
      // 向后台发送请求获取code
        .get("/xx/xx/xx)
        .then(res => {
          this.qrCodeStr = res.qrCode; // 二维码code    this.getInfoCode = res.code;    //  登录的code码
          this.createQrcode(res.qrCode);  // 1. *创建一个二维码*
          this.checkLogin();   // *2. 检查登录状态,单点  模拟form表单登录重定向*
        })
        .catch(() => {
          this.expireLoading = false;  this.expireSign = true;  
          this.$message({ type: "error", message: "获取二维码失败!" });
        });
    },

使用qrcodejs2生成二维码

步骤:
1. 安装:cnpm i qrcodejs2 -S  
2. 引入: import QRCode from "qrcodejs2"; 
3. 使用:
    // 创造二维码
    createQrcode(str) {
      if (this.qrcode) {
        this.qrcode.clear(); // clear the code.
        this.qrcode.makeCode(str);
      } else {
        this.qrcode = new QRCode("qrcode", {
          width: 152,
          height: 152,
          text: str // 二维码地址
        });
      }
      this.expireLoading = false;
      this.expireSign = false;
    },
   /**
     * 扫码登录,轮询登录结果
     */
    checkLogin() {
      let that = this;
      this.timer1 = setInterval(() => {
        if (that.getInfoCode) {
          that.$axios
            .get("/auth/qrcode/check?code=" + that.getInfoCode)
            .then(res => {
              if (res.body.countDown == 1) {
                that.$message({
                  type: "warning",
                  message: "二维码失效,请重新扫描!"
                });
                that.expireSign = true;
                that.expireLoading = false;
                window.clearInterval(that.timer1);
              } else {
                if (res.body.status == "1") {
                  that.expireLoading = true;
                }
                if (res.body.status == "2") {
                // status为2,代表二维码登录成功,清除轮询
                  window.clearInterval(that.timer1);
                  // 进行登录准备
                  this.beforeCodeSubmit()
                  // that.expireLoading = false;
                }
              }
            })
            .catch(() => {
              that.expireLoading = false;
              that.expireSign = true;
              that.$message({ type: "error", message: "登录失败!" });
              window.clearInterval(that.timer1);
            });
        }
      }, 3000);
    },
    //code登录准备
    beforeCodeSubmit() {
    // 参数
      const route = this.$route;
      const query = route.query || {};
      //登录成功后的回跳地址
      const redirect_uri = query.redirect_uri && decodeURIComponent(query.redirect_uri) || location.origin;
      const data = {
        grant_type: 'qrcode',
        code: this.getInfoCode,
        client_id: 'portal',
        response_type: 'code',
        redirect_uri,
        login_page: location.origin + '/#/login',
      }
      this.codeSubmit(data)
    },
    //code模拟form登录框,只有用原生form表单提交才可以重定向
    codeSubmit(data){
        const $form = document.createElement('form');
        $form.setAttribute('action', this.$config.baseURL + '/auth/oauth/appqr/code');
        $form.setAttribute('method','post');
        for(let key in data){
          const $el = document.createElement('input');
          $el.setAttribute('name',key);
          $el.value = data[key];
          $form.appendChild($el);
        }
        document.documentElement.appendChild($form);
        $form.submit();
    },

效果:
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中实现二维码登录可以通过以下步骤来完成: 1. 添加依赖:在`pom.xml`文件中添加`spring-boot-starter-web`和`spring-boot-starter-security`依赖。 2. 创建二维码生成工具类:可以使用第三方库,如`zxing`来生成二维码。创建一个工具类,使用该库生成二维码图片,并将图片保存到服务器上。 3. 创建登录页面:创建一个登录页面,包含一个二维码图片和一个轮询接口用于检查用户是否已扫描二维码。 4. 创建登录控制器:创建一个控制器,处理用户的登录请求。当用户扫描二维码后,前端会发送一个请求到后端,后端会验证二维码的有效性,并返回给前端一个标识表示用户已扫描二维码。 5. 创建认证提供者:创建一个认证提供者,用于验证用户的身份。在该提供者中,可以通过用户已扫描二维码的标识来判断用户是否已登录。 6. 配置Spring Security:在`application.properties`文件中配置Spring Security,设置登录页面、认证提供者等相关信息。 7. 测试登录:启动应用程序,访问登录页面,扫描二维码进行登录测试。 以上是实现二维码登录的基本步骤,具体的代码实现可以参考以下示例: ```java // 生成二维码工具类 public class QRCodeUtil { public static void generateQRCode(String text, int width, int height, String filePath) { try { BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height); Path path = FileSystems.getDefault().getPath(filePath); MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path); } catch (Exception e) { e.printStackTrace(); } } } // 登录控制器 @Controller public class LoginController { @GetMapping("/login") public String login(Model model) { // 生成二维码并保存到服务器 String qrCodeText = "http://example.com/scan"; // 替换为实际的扫描地址 QRCodeUtil.generateQRCode(qrCodeText, 200, 200, "qrcode.png"); // 替换为实际的保存路径 model.addAttribute("qrCodeText", qrCodeText); return "login"; } @GetMapping("/checkLogin") @ResponseBody public boolean checkLogin() { // 检查用户是否已扫描二维码,返回相应的标识 return true; // 已扫描二维码 } } // 认证提供者 @Component public class CustomAuthenticationProvider implements AuthenticationProvider { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { // 验证用户的身份,可以通过已扫描二维码的标识来判断用户是否已登录 if (authentication.isAuthenticated()) { return authentication; } else { throw new BadCredentialsException("Invalid QR Code"); } } @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } } // Spring Security配置 @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomAuthenticationProvider authenticationProvider; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .and() .logout() .logoutSuccessUrl("/login") .and() .authenticationProvider(authenticationProvider); } } ``` 请注意,上述代码仅为示例,实际应用中可能需要根据具体需求进行适当的修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值