瀏覽代碼

添加授权登录, 但还没做用户同步功能

wuweihao 3 年之前
父節點
當前提交
1771146dc6

+ 41 - 0
gis_admin/src/main/java/com/gis/admin/controller/LoginController.java

@@ -1,5 +1,9 @@
 package com.gis.admin.controller;
 
+import cn.hutool.http.HttpResponse;
+import cn.hutool.http.HttpUtil;
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
 import com.gis.common.base.entity.po.LogEntity;
 import com.gis.common.base.exception.BaseRuntimeException;
 import com.gis.common.base.service.LogService;
@@ -57,6 +61,8 @@ public class LoginController {
     // 超级管理员角色key
     private static String ROLE_SYS_ADMIN = "sys_admin";
 
+    final static String HOST = "http://127.0.0.1:8024/admin/authorize";
+
 
 
     // 目前是24h
@@ -89,6 +95,41 @@ public class LoginController {
     }
 
 
+    /**
+     * by owen 2022-06-14
+     * 已测试完成
+     * @param param
+     * @param pwdEncrypt 非必传
+     * @return
+     */
+//    @ApiOperation("授权登录")
+//    @PostMapping(value = "/admin/login")
+//    public Result login(@Valid @RequestBody LoginDto param, String pwdEncrypt)  {
+//        String api = HOST + "?pwdEncrypt=" + pwdEncrypt;
+//        HashMap<Object, Object> querys = new HashMap<>();
+//        querys.put("pwdEncrypt", pwdEncrypt);
+//
+//        JSONObject json = new JSONObject();
+//        json.put("userName", param.getUserName());
+//        json.put("password", param.getPassword());
+//        String s = HttpUtil.createPost(api)
+//                .body(json.toJSONString(), "application/json;charset=UTF-8")
+//                .execute().body();
+//        log.info("授权返回值: {}", s);
+//
+//        Result result = JSON.parseObject(s, Result.class);
+//        if (result.getCode() != 0){
+//            return result;
+//        }
+//
+//        SysUserEntity entity = JSON.parseObject(result.getData().toString(), SysUserEntity.class);
+//
+//
+//        return createToken(entity, "loginCms");
+//
+//    }
+
+
     private Result createToken(SysUserEntity entity, String loginType){
         // 创建新token
         HashMap<String, Object> tokenMap = new HashMap<>();

+ 8 - 0
gis_common/pom.xml

@@ -126,6 +126,14 @@
             <artifactId>mybatis-plus-boot-starter</artifactId>
         </dependency>
 
+
+        <!--httpclient-->
+        <dependency>
+            <groupId>org.apache.httpcomponents</groupId>
+            <artifactId>httpclient</artifactId>
+        </dependency>
+
+
     </dependencies>
 
 

+ 418 - 0
gis_common/src/main/java/com/gis/common/util/HttpUtils.java

@@ -0,0 +1,418 @@
+package com.gis.common.util;
+
+import com.alibaba.fastjson.JSONObject;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.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 org.apache.http.util.EntityUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+import java.io.IOException;
+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;
+
+@Slf4j
+public class HttpUtils {
+
+    protected static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);
+
+    /**
+     * get
+     *
+     * @param host
+     * @param path
+     * @param headers
+     * @param querys
+     * @return
+     * @throws Exception
+     */
+    public static String doGet(String host, String path,
+                                     Map<String, String> headers,
+                                     Map<String, String> querys) {
+        HttpClient httpClient = wrapClient(host);
+        log.info("url : " + host + path);
+        try {
+            HttpGet request = new HttpGet(buildUrl(host, path, querys));
+            for (Map.Entry<String, String> e : headers.entrySet()) {
+                request.addHeader(e.getKey(), e.getValue());
+            }
+            HttpResponse execute = httpClient.execute(request);
+            String str = EntityUtils.toString(execute.getEntity(), "UTF-8");
+            log.info("返回值:{}", str);
+            return str;
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return null;
+
+    }
+
+    /**
+     * post form
+     *
+     * @param host
+     * @param path
+     * @param headers
+     * @param querys
+     * @param bodys
+     * @return
+     * @throws Exception
+     */
+    public static HttpResponse doPost(String host, String path, 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);
+    }
+
+    /**
+     * 2021-02-23
+     * post 有请求头,有headers
+     *
+     * @param host
+     * @param path
+     * @param headers
+     * @param querys
+     * @param body
+     * @return
+     * @throws Exception
+     */
+    public static HttpResponse doPost(String host, String path, Map<String, String> headers, Map<String, String> querys, JSONObject 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) {
+            StringEntity stringEntity = new StringEntity(body.toJSONString(), "utf-8");
+            stringEntity.setContentType("application/json;charset=UTF-8");
+            request.setEntity(stringEntity);
+        }
+        return httpClient.execute(request);
+    }
+
+
+    /**
+     * 2022-05-16
+     * post 有请求头,有headers
+     *
+     * @param headers
+     * @param body
+     * @param api
+     * @return
+     * @throws Exception
+     */
+    public static String doPost(String api, Map<String, String> headers, JSONObject body) {
+        HttpClient httpClient = new DefaultHttpClient();
+        LOGGER.info("url : " + api);
+        HttpPost request = new HttpPost(api);
+        for (Map.Entry<String, String> e : headers.entrySet()) {
+            request.addHeader(e.getKey(), e.getValue());
+        }
+
+        // 请求体
+        if (body != null) {
+            log.info("请求参数:{}", body);
+            StringEntity stringEntity = new StringEntity(body.toJSONString(), "utf-8");
+            stringEntity.setContentType("application/json;charset=UTF-8");
+            request.setEntity(stringEntity);
+        }
+
+        HttpResponse execute = null;
+        try {
+            execute = httpClient.execute(request);
+            String str = EntityUtils.toString(execute.getEntity(), "UTF-8");
+            log.info("返回值:{}", str);
+            return str;
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+//    /**
+//     * 2022-05-17
+//     * post 有请求头,有headers
+//     *
+//     * @param headers
+//     * @param bodyJsonStr jsonString
+//     * @param api
+//     * @return
+//     * @throws Exception
+//     */
+//    public static String doPost(String api, Map<String, String> headers, String bodyJsonStr) {
+//        HttpClient httpClient = new DefaultHttpClient();
+//        LOGGER.info("url : " + api);
+//        HttpPost request = new HttpPost(api);
+//        for (Map.Entry<String, String> e : headers.entrySet()) {
+//            request.addHeader(e.getKey(), e.getValue());
+//        }
+//
+//        // 请求体
+//        if (bodyJsonStr != null) {
+//            log.info("请求参数:{}", bodyJsonStr);
+//            StringEntity stringEntity = new StringEntity(bodyJsonStr, "utf-8");
+//            stringEntity.setContentType("application/json;charset=UTF-8");
+//            request.setEntity(stringEntity);
+//        }
+//
+//        HttpResponse execute = null;
+//        try {
+//            execute = httpClient.execute(request);
+//            String str = EntityUtils.toString(execute.getEntity(), "UTF-8");
+//            log.info("返回值:{}", str);
+//            return str;
+//        } catch (IOException e) {
+//            e.printStackTrace();
+//        }
+//        return null;
+//    }
+
+
+    public static HttpResponse doPost(String host, String path, Map<String, String> headers, Map<String, String> querys)
+            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());
+        }
+
+        return httpClient.execute(request);
+    }
+
+    /**
+     * Post stream
+     *
+     * @param host
+     * @param path
+     * @param headers
+     * @param querys
+     * @param body
+     * @return
+     * @throws Exception
+     */
+    public static HttpResponse doPost(String host, String path,
+                                      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);
+    }
+
+    public 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);
+        }
+        LOGGER.info("request api: " + sbUrl.toString());
+        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() {
+                public X509Certificate[] getAcceptedIssuers() {
+                    return null;
+                }
+
+                public void checkClientTrusted(X509Certificate[] xcs, String str) {
+
+                }
+
+                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);
+        }
+    }
+
+
+
+}