ludc
2023-09-12 7f9d6840cc01c25ac9816df60dbac3d040594fa3
Source/UBCS/ubcs-service/ubcs-code/src/main/java/com/vci/ubcs/code/service/impl/PasswordFreeLoginServiceImpl.java
@@ -1,8 +1,12 @@
package com.vci.ubcs.code.service.impl;
import com.vci.ubcs.code.service.IPasswordFreeLoginService;
import com.vci.ubcs.code.util.HttpUtils;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
@@ -13,6 +17,9 @@
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.List;
/**
 * 免密登录服务
 * @author ludc
@@ -21,8 +28,22 @@
@Service
public class PasswordFreeLoginServiceImpl implements IPasswordFreeLoginService {
   private RestTemplate restTemplate;
   // 通过服务注册中心获取网关的端口号
   @Autowired
   private DiscoveryClient discoveryClient;
   /**
    * 获取网关端口
    * @return
    */
   public String getGatewayPort() {
      List<ServiceInstance> instances = discoveryClient.getInstances("ubcs-gateway");
      if (!instances.isEmpty()) {
         ServiceInstance gatewayInstance = instances.get(0);
         return String.valueOf(gatewayInstance.getPort());
      }
      return "80";
   }
   /**
    * 免密登录
@@ -32,7 +53,7 @@
   @Override
   public boolean passwordFreeLogin(String account) {
      // 免密登录接口地址
      String loginUrl = "http://ubcs-auth/auth/login";
      String loginUrl = "http://localhost:"+this.getGatewayPort()+"/ubcs-auth/oauth/passwordFreeLogin?username=admin&grant_type=captcha&scope=all&type=account";
      // 设置请求头
      HttpHeaders headers = new HttpHeaders();
@@ -42,13 +63,9 @@
      MultiValueMap<String,String> bodyParams = new LinkedMultiValueMap<String,String>();
      bodyParams.add("account",account);
      // 创建请求实体
      HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(bodyParams, headers);
      // 发送POST请求
      ResponseEntity<String> responseEntity = restTemplate.exchange(loginUrl, HttpMethod.POST, requestEntity, String.class);
      String responseBody = responseEntity.getBody();
      String responseBody = HttpUtils.post(loginUrl, bodyParams);
      System.out.println(responseBody);
      //拿到响应体将token存入到redis中,以account作为存储的key
      // 解析响应体获取令牌