Home  >  Article  >  Java  >  How to implement code scanning login based on Java

How to implement code scanning login based on Java

王林
王林forward
2023-04-20 08:22:061267browse

    Principle Analysis

    1. Identity Authentication Mechanism

    Before introducing the principle of scanning QR code to log in, let’s first talk about the server side Identity authentication mechanism. Taking the ordinary "account password" login method as an example, after the server receives the user's login request, it first verifies the legitimacy of the account and password. If the verification is passed, the server will assign a token to the user, which is associated with the user's identity information and can be used as the user's login credentials. Later, when the PC sends a request again, it needs to carry the token in the Header or Query parameter of the request. The server can identify the current user based on the token. The advantage of token is that it is more convenient and secure. It reduces the risk of account and password being hijacked, and users do not need to repeatedly enter their account and password. The process of logging in via account and password on the PC is as follows:

    How to implement code scanning login based on Java

    Scan code login is essentially an identity authentication method. The difference between account password login and scan code login is that the former It uses the account and password of the PC to apply for a token for the PC, and the latter uses the token device information of the mobile phone to apply for a token for the PC. The purpose of these two login methods is the same, both for the PC to obtain "authorization" from the server. Before applying for a token for the PC, both need to prove their identity to the server, that is, the server must know the current Who is the user so that the server can generate a PC token for it? Since the mobile phone must be logged in before scanning the QR code, the mobile phone itself has saved a token, which can be used for server-side identification. So why does the mobile phone still need device information when verifying identity? In fact, the identity authentication on the mobile phone is slightly different from that on the PC:

    • The mobile phone also needs to enter the account number and password before logging in, but the login request also contains the device in addition to the account password. Information, such as device type, device id, etc.

    • After receiving the login request, the server will verify the account and password. After passing the verification, it will associate the user information with the device information, that is, store them in a data structure. .

    • The server generates a token for the mobile phone and associates the token with user information and device information, that is, using token as key and structure as value, the key-value pair is persisted Save it locally and then return the token to the mobile phone.

    • The mobile phone sends a request, carrying token and device information. The server queries the structure based on the token and verifies whether the device information in the structure is the same as the device information on the mobile phone to determine the user. effectiveness.

    After we successfully log in on the PC, we can browse the web normally for a short period of time, but then we have to log in again when we visit the website. This is because the token has an expiration time, which is relatively small. A long validity period increases the risk of token hijacking. However, it seems that this problem rarely occurs on mobile phones. For example, after successfully logging in to WeChat, you can always use it, even if you close WeChat or restart your phone. This is because the device information is unique. Even if the token is hijacked, the attacker cannot prove his identity to the server due to different device information. This greatly improves the security factor, so the token can be used for a long time. The process of logging in through the account and password on the mobile phone is as follows:

    How to implement code scanning login based on Java

    2. Process Overview

    After understanding the identity authentication mechanism of the server, let’s talk about scanning The entire process of code login. Taking the web version of WeChat as an example, after we click the QR code to log in on the PC, the QR code picture will pop up on the browser page. At this time, open WeChat on the mobile phone to scan the QR code. The PC will then display "Scanning", and the mobile phone will After clicking to confirm the login, the PC will display "Login successful".

    In the above process, the server can respond to the PC side according to the operations of the mobile phone side. So how does the server side associate the two? The answer is through the "QR code", strictly speaking, through the content in the QR code. Use a QR code decoder to scan the QR code on the web version of WeChat, and you can get the following content:

    How to implement code scanning login based on Java

    From the picture above, we know that the QR code actually contains A URL. After the mobile phone scans the QR code, it will send a request to the server based on the URL. Next, we open the developer tools of the PC browser:

    How to implement code scanning login based on Java

    It can be seen that after the QR code is displayed, the PC side has never been "idle". It continuously sends requests to the server through polling to learn the results of the mobile side operation. Here we notice that there is a parameter uuid in the URL sent by the PC, with the value "Adv-NP1FYw==". This uuid also exists in the URL contained in the QR code. From this we can infer that the server will generate a QR code id before generating the QR code. The QR code id is bound to the status, expiration time and other information of the QR code and stored together on the server. The mobile terminal can operate the status of the QR code on the server side based on the QR code id, and the PC side can query the server side about the status of the QR code based on the QR code id.

    The QR code is initially in the "to be scanned" state. After the mobile phone scans the code, the server changes its status to the "to be confirmed" state. At this time, the polling request from the PC arrives and the server returns " Awaiting confirmation" response. After the mobile phone confirms the login, the QR code changes to the "Confirmed" status. The server generates a token for identity authentication for the PC. When the PC asks again, it can get this token. The entire scan code login process is shown in the figure below:

    How to implement code scanning login based on Java

    1. #The PC sends a "scan code login" request, and the server generates a QR code ID. And store the expiration time, status and other information of the QR code.

    2. The PC side obtains the QR code and displays it.

    3. The PC starts polling to check the status of the QR code. The QR code is initially in the "to be scanned" state.

    4. Scan the QR code on your mobile phone to get the QR code ID.

    5. The mobile phone sends a "scan code" request to the server. The request carries the QR code id, mobile phone token and device information.

    6. The server verifies the legitimacy of the mobile user. After passing the verification, it sets the QR code status to "to be confirmed" and associates the user information with the QR code. Generate a one-time token for the mobile phone, which is used as a credential to confirm login.

    7. When the PC side polls, it is detected that the QR code status is "pending confirmation".

    8. The mobile phone sends a "confirm login" request to the server. The request carries the QR code id, one-time token and device information.

    9. The server verifies the one-time token. After passing the verification, the QR code status is set to "Confirmed" and a PC token is generated for the PC.

    10. When the PC side polled, it detected that the QR code status was "Confirmed" and obtained the PC side token. After that, the PC side stopped polling.

    11. The PC accesses the server through the PC token.

    During the above process, we noticed that after scanning the code on the mobile phone, the server will return a one-time token. This token is also an identity credential, but it can only be used once. The function of the one-time token is to ensure that the "scan code request" and "confirm login" request are issued by the same mobile phone. In other words, mobile phone users cannot "confirm login for other users."

    I don’t know much about one-time tokens, but it can be speculated that in the cache of the server, the value mapped by the one-time token should include the QR code information and device passed in the "scan code" request information and user information.

    Code implementation

    1. Environment preparation

    • JDK 1.8: The project is written in Java language.

    • Maven: dependency management.

    • Redis: Redis not only serves as a database to store user identity information (MySQL is not used to simplify operations), but also serves as a cache to store QR code information, token information, etc.

    2. Mainly depends on

    • SpringBoot: the basic environment of the project.

    • Hutool: Open source tool class, in which QrCodeUtil can be used to generate QR code images.

    • Thymeleaf: Template engine for page rendering.

    3. Generate QR code

    The generation of QR code and the saving logic of QR code status are as follows:

    @RequestMapping(path = "/getQrCodeImg", method = RequestMethod.GET)
    public String createQrCodeImg(Model model) {
    
       String uuid = loginService.createQrImg();
       String qrCode = Base64.encodeBase64String(QrCodeUtil.generatePng("http://127.0.0.1:8080/login/uuid=" + uuid, 300, 300));
    
       model.addAttribute("uuid", uuid);
       model.addAttribute("QrCode", qrCode);
    
       return "login";
    }

    PC access" When making a "Login" request, the server calls the createQrImg method to generate a uuid and a LoginTicket object. The LoginTicket object encapsulates the user's userId and the status of the QR code. The server then stores the uuid as the key and the LoginTicket object as the value into the Redis server, and sets the validity time to 5 minutes (the validity time of the QR code). The logic of the createQrImg method is as follows:

    public String createQrImg() {
       // uuid
       String uuid = CommonUtil.generateUUID();
       LoginTicket loginTicket = new LoginTicket();
       // 二维码最初为 WAITING 状态
       loginTicket.setStatus(QrCodeStatusEnum.WAITING.getStatus());
    
       // 存入 redis
       String ticketKey = CommonUtil.buildTicketKey(uuid);
       cacheStore.put(ticketKey, loginTicket, LoginConstant.WAIT_EXPIRED_SECONDS, TimeUnit.SECONDS);
    
       return uuid;
    }

    我们在前一节中提到,手机端的操作主要影响二维码的状态,PC 端轮询时也是查看二维码的状态,那么为什么还要在 LoginTicket 对象中封装 userId 呢?这样做是为了将二维码与用户进行关联,想象一下我们登录网页版微信的场景,手机端扫码后,PC 端就会显示用户的头像,虽然手机端并未确认登录,但 PC 端轮询时已经获取到了当前扫码的用户(仅头像信息)。因此手机端扫码后,需要将二维码与用户绑定在一起,使用 LoginTicket 对象只是一种实现方式。二维码生成后,我们将其状态置为 "待扫描" 状态,userId 不做处理,默认为 null。

    4. 扫描二维码

    手机端发送 "扫码" 请求时,Query 参数中携带着 uuid,服务端接收到请求后,调用 scanQrCodeImg 方法,根据 uuid 查询出二维码并将其状态置为 "待确认" 状态,操作完成后服务端向手机端返回 "扫码成功" 或 "二维码已失效" 的信息:

    @RequestMapping(path = "/scan", method = RequestMethod.POST)
    @ResponseBody
    public Response scanQrCodeImg(@RequestParam String uuid) {
       JSONObject data = loginService.scanQrCodeImg(uuid);
       if (data.getBoolean("valid")) {
          return Response.createResponse("扫码成功", data);
       }
       return Response.createErrorResponse("二维码已失效");
    }

    scanQrCodeImg 方法的主要逻辑如下:

    public JSONObject scanQrCodeImg(String uuid) {
       // 避免多个移动端同时扫描同一个二维码
       lock.lock();
       JSONObject data = new JSONObject();
       try {
          String ticketKey = CommonUtil.buildTicketKey(uuid);
          LoginTicket loginTicket = (LoginTicket) cacheStore.get(ticketKey);
    
          // redis 中 key 过期后也可能不会立即删除
          Long expired = cacheStore.getExpireForSeconds(ticketKey);
          boolean valid = loginTicket != null &&
                   QrCodeStatusEnum.parse(loginTicket.getStatus()) == QrCodeStatusEnum.WAITING &&
                   expired != null &&
                   expired >= 0;
          if (valid) {
                User user = hostHolder.getUser();
                if (user == null) {
                   throw new RuntimeException("用户未登录");
                }
                // 修改扫码状态
                loginTicket.setStatus(QrCodeStatusEnum.SCANNED.getStatus());
                Condition condition = CONDITION_CONTAINER.get(uuid);
                if (condition != null) {
                   condition.signal();
                   CONDITION_CONTAINER.remove(uuid);
                }
                // 将二维码与用户进行关联
                loginTicket.setUserId(user.getUserId());
                cacheStore.put(ticketKey, loginTicket, expired, TimeUnit.SECONDS);
    
                // 生成一次性 token, 用于之后的确认请求
                String onceToken = CommonUtil.generateUUID();
    
                cacheStore.put(CommonUtil.buildOnceTokenKey(onceToken), uuid, LoginConstant.ONCE_TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
    
                data.put("once_token", onceToken);
          }
          data.put("valid", valid);
          return data;
       } finally {
          lock.unlock();
       }
    }

    1.首先根据 uuid 查询 Redis 中存储的 LoginTicket 对象,然后检查二维码的状态是否为 "待扫描" 状态,如果是,那么将二维码的状态改为 "待确认" 状态。如果不是,那么该二维码已被扫描过,服务端提示用户 "二维码已失效"。我们规定,只允许第一个手机端能够扫描成功,加锁的目的是为了保证 查询 + 修改 操作的原子性,避免两个手机端同时扫码,且同时检测到二维码的状态为 "待扫描"。

    2.上一步操作成功后,服务端将 LoginTicket 对象中的 userId 置为当前用户(扫码用户)的 userId,也就是将二维码与用户信息绑定在一起。由于扫码请求是由手机端发送的,因此该请求一定来自于一个有效的用户,我们在项目中配置一个拦截器(也可以是过滤器),当拦截到 "扫码" 请求后,根据请求中的 token(手机端发送请求时一定会携带 token)查询出用户信息,并将其存储到 ThreadLocal 容器(hostHolder)中,之后绑定信息时就可以从 ThreadLocal 容器将用户信息提取出来。注意,这里的 token 指的手机端 token,实际中应该还有设备信息,但为了简化操作,我们忽略掉设备信息。

    3.用户信息与二维码信息关联在一起后,服务端为手机端生成一个一次性 token,并存储到 Redis 服务器,其中 key 为一次性 token 的值,value 为 uuid。一次性 token 会返回给手机端,作为 "确认登录" 请求的凭证。

    上述代码中,当二维码的状态被修改后,我们唤醒了在 condition 中阻塞的线程,这一步的目的是为了实现长轮询操作,下文中会介绍长轮询的设计思路。

    5. 确认登录

    手机端发送 "确认登录" 请求时,Query 参数中携带着 uuid,且 Header 中携带着一次性 token,服务端接收到请求后,首先验证一次性 token 的有效性,即检查一次性 token 对应的 uuid 与 Query 参数中的 uuid 是否相同,以确保扫码操作和确认操作来自于同一个手机端,该验证过程可在拦截器中配置。验证通过后,服务端调用 confirmLogin 方法,将二维码的状态置为 "已确认":

    @RequestMapping(path = "/confirm", method = RequestMethod.POST)
    @ResponseBody
    public Response confirmLogin(@RequestParam String uuid) {
       boolean logged = loginService.confirmLogin(uuid);
       String msg = logged ? "登录成功!" : "二维码已失效!";
       return Response.createResponse(msg, logged);
    }

    confirmLogin 方法的主要逻辑如下:

    public boolean confirmLogin(String uuid) {
       String ticketKey = CommonUtil.buildTicketKey(uuid);
       LoginTicket loginTicket = (LoginTicket) cacheStore.get(ticketKey);
       boolean logged = true;
       Long expired = cacheStore.getExpireForSeconds(ticketKey);
       if (loginTicket == null || expired == null || expired == 0) {
          logged = false;
       } else {
          lock.lock();
          try {
                loginTicket.setStatus(QrCodeStatusEnum.CONFIRMED.getStatus());
                Condition condition = CONDITION_CONTAINER.get(uuid);
                if (condition != null) {
                   condition.signal();
                   CONDITION_CONTAINER.remove(uuid);
                }
                cacheStore.put(ticketKey, loginTicket, expired, TimeUnit.SECONDS);
          } finally {
                lock.unlock();
          }
       }
       return logged;
    }

    该方法会根据 uuid 查询二维码是否已经过期,如果未过期,那么就修改二维码的状态。

    6. PC 端轮询

    轮询操作指的是前端重复多次向后端发送相同的请求,以获知数据的变化。轮询分为长轮询和短轮询:

    • 长轮询:服务端收到请求后,如果有数据,那么就立即返回,否则线程进入等待状态,直到有数据到达或超时,浏览器收到响应后立即重新发送相同的请求。

    • 短轮询:服务端收到请求后无论是否有数据都立即返回,浏览器收到响应后间隔一段时间后重新发送相同的请求。

    由于长轮询相比短轮询能够得到实时的响应,且更加节约资源,因此项目中我们考虑使用 ReentrantLock 来实现长轮询。轮询的目的是为了查看二维码状态的变化:

    @RequestMapping(path = "/getQrCodeStatus", method = RequestMethod.GET)
    @ResponseBody
    public Response getQrCodeStatus(@RequestParam String uuid, @RequestParam int currentStatus) throws InterruptedException {
       JSONObject data = loginService.getQrCodeStatus(uuid, currentStatus);
       return Response.createResponse(null, data);
    }

    getQrCodeStatus 方法的主要逻辑如下:

    public JSONObject getQrCodeStatus(String uuid, int currentStatus) throws InterruptedException {
       lock.lock();
       try {
          JSONObject data = new JSONObject();
          String ticketKey = CommonUtil.buildTicketKey(uuid);
          LoginTicket loginTicket = (LoginTicket) cacheStore.get(ticketKey);
    
          QrCodeStatusEnum statusEnum = loginTicket == null || QrCodeStatusEnum.parse(loginTicket.getStatus()) == QrCodeStatusEnum.INVALID ?
                   QrCodeStatusEnum.INVALID : QrCodeStatusEnum.parse(loginTicket.getStatus());
    
          if (currentStatus == statusEnum.getStatus()) {
                Condition condition = CONDITION_CONTAINER.get(uuid);
                if (condition == null) {
                   condition = lock.newCondition();
                   CONDITION_CONTAINER.put(uuid, condition);
                }
                condition.await(LoginConstant.POLL_WAIT_TIME, TimeUnit.SECONDS);
          }
          // 用户扫码后向 PC 端返回头像信息
          if (statusEnum == QrCodeStatusEnum.SCANNED) {
                User user = userService.getCurrentUser(loginTicket.getUserId());
                data.put("avatar", user.getAvatar());
          }
    
          // 用户确认后为 PC 端生成 access_token
          if (statusEnum == QrCodeStatusEnum.CONFIRMED) {
                String accessToken = CommonUtil.generateUUID();
                cacheStore.put(CommonUtil.buildAccessTokenKey(accessToken), loginTicket.getUserId(), LoginConstant.ACCESS_TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
                data.put("access_token", accessToken);
          }
    
          data.put("status", statusEnum.getStatus());
          data.put("message", statusEnum.getMessage());
          return data;
       } finally {
          lock.unlock();
       }
    }

    该方法接收两个参数,即 uuid 和 currentStatus,其中 uuid 用于查询二维码,currentStatus 用于确认二维码状态是否发生了变化,如果是,那么需要立即向 PC 端反馈。我们规定 PC 端在轮询时,请求的参数中需要携带二维码当前的状态。

    1.首先根据 uuid 查询出二维码的最新状态,并比较其是否与 currentStatus 相同。如果相同,那么当前线程进入阻塞状态,直到被唤醒或者超时。

    2.如果二维码状态为 "待确认",那么服务端向 PC 端返回扫码用户的头像信息(处于 "待确认" 状态时,二维码已与用户信息绑定在一起,因此可以查询出用户的头像)。

    3.如果二维码状态为 "已确认",那么服务端为 PC 端生成一个 token,在之后的请求中,PC 端可通过该 token 表明自己的身份。

    上述代码中的加锁操作是为了能够令当前处理请求的线程进入阻塞状态,当二维码的状态发生变化时,我们再将其唤醒,因此上文中的扫码操作和确认登录操作完成后,还会有一个唤醒线程的过程。

    实际上,加锁操作设计得不太合理,因为我们只设置了一把锁。因此对不同二维码的查询或修改操作都会抢占同一把锁。按理来说,不同二维码的操作之间应该是相互独立的,即使加锁,也应该是为每个二维码均配一把锁,但这样做代码会更加复杂,或许有其它更好的实现长轮询的方式?或者干脆直接短轮询。当然,也可以使用 WebSocket 实现长连接。

    7. 拦截器配置

    项目中配置了两个拦截器,一个用于确认用户的身份,即验证 token 是否有效:

    @Component
    public class LoginInterceptor implements HandlerInterceptor {
    
        @Autowired
        private HostHolder hostHolder;
    
        @Autowired
        private CacheStore cacheStore;
    
        @Autowired
        private UserService userService;
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
            String accessToken = request.getHeader("access_token");
            // access_token 存在
            if (StringUtils.isNotEmpty(accessToken)) {
                String userId = (String) cacheStore.get(CommonUtil.buildAccessTokenKey(accessToken));
                User user = userService.getCurrentUser(userId);
                hostHolder.setUser(user);
            }
            return true;
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            hostHolder.clear();
        }
    }

    如果 token 有效,那么服务端根据 token 获取用户的信息,并将用户信息存储到 ThreadLocal 容器。手机端和 PC 端的请求都由该拦截器处理,如 PC 端的 "查询用户信息" 请求,手机端的 "扫码" 请求。由于我们忽略了手机端验证时所需要的的设备信息,因此 PC 端和手机端 token 可以使用同一套验证逻辑。

    另一个拦截器用于拦截 "确认登录" 请求,即验证一次性 token 是否有效:

    @Component
    public class ConfirmInterceptor implements HandlerInterceptor {
    
        @Autowired
        private CacheStore cacheStore;
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    
            String onceToken = request.getHeader("once_token");
            if (StringUtils.isEmpty(onceToken)) {
                return false;
            }
            if (StringUtils.isNoneEmpty(onceToken)) {
                String onceTokenKey = CommonUtil.buildOnceTokenKey(onceToken);
                String uuidFromCache = (String) cacheStore.get(onceTokenKey);
                String uuidFromRequest = request.getParameter("uuid");
                if (!StringUtils.equals(uuidFromCache, uuidFromRequest)) {
                    throw new RuntimeException("非法的一次性 token");
                }
                // 一次性 token 检查完成后将其删除
                cacheStore.delete(onceTokenKey);
            }
            return true;
        }
    }

    该拦截器主要拦截 "确认登录" 请求,需要注意的是,一次性 token 验证通过后要立即将其删除。

    编码过程中,我们简化了许多操作,例如:1. 忽略掉了手机端的设备信息;2. 手机端确认登录后并没有直接为用户生成 PC 端 token,而是在轮询时生成。

    效果演示

    1. 工具准备

    • 浏览器:PC 端操作

    • Postman:模仿手机端操作。

    2. 数据准备

    由于我们没有实现真实的手机端扫码的功能,因此使用 Postman 模仿手机端向服务端发送请求。首先我们需要确保服务端存储着用户的信息,即在 Test 类中执行如下代码:

    @Test
    void insertUser() {
       User user = new User();
       user.setUserId("1");
       user.setUserName("John同学");
       user.setAvatar("/avatar.jpg");
       cacheStore.put("user:1", user);
    }

    手机端发送请求时需要携带手机端 token,这里我们为 useId 为 "1" 的用户生成一个 token(手机端 token):

    @Test
    void loginByPhone() {
       String accessToken = CommonUtil.generateUUID();
       System.out.println(accessToken);
       cacheStore.put(CommonUtil.buildAccessTokenKey(accessToken), "1");
    }

    手机端 token(accessToken)为 "aae466837d0246d486f644a3bcfaa9e1"(随机值),之后发送 "扫码" 请求时需要携带这个 token。

    3. 扫码登录流程展示

    启动项目,访问 localhost:8080/index

    How to implement code scanning login based on Java

    点击登录,并在开发者工具中找到二维码 id(uuid):

    How to implement code scanning login based on Java

    打开 Postman,发送localhost:8080/login/scan 请求,Query 参数中携带 uuid,Header 中携带手机端 token:

    How to implement code scanning login based on Java

    上述请求返回 "扫码成功" 的响应,同时还返回了一次性 token。此时 PC 端显示出扫码用户的头像:

    How to implement code scanning login based on Java

    在 Postman 中发送 localhost:8080/login/confirm 请求,Query 参数中携带 uuid,Header 中携带一次性 token:

    How to implement code scanning login based on Java

    "确认登录" 请求发送完成后,PC 端随即获取到 PC 端 token,并成功查询用户信息:

    How to implement code scanning login based on Java

    The above is the detailed content of How to implement code scanning login based on Java. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete