瀏覽代碼

uspa登录,获得登录菜单

wangchao 4 年之前
父節點
當前提交
d1cb15d9a5
共有 15 個文件被更改,包括 864 次插入8 次删除
  1. 84 0
      location-rescue-service/src/main/java/com/ai/bss/location/rescue/controller/LoginController.java
  2. 24 0
      location-rescue-service/src/main/java/com/ai/bss/location/rescue/model/User.java
  3. 115 0
      location-rescue-service/src/main/java/com/ai/bss/location/rescue/service/impl/LoginServiceImpl.java
  4. 22 0
      location-rescue-service/src/main/java/com/ai/bss/location/rescue/service/interfaces/LoginService.java
  5. 6 1
      location-rescue-service/src/main/resources/application.properties
  6. 5 6
      security-protection-service/pom.xml
  7. 60 0
      security-protection-service/src/main/java/com/ai/bss/security/protection/config/MyCorsFilter.java
  8. 4 1
      security-protection-service/src/main/java/com/ai/bss/security/protection/controller/AiAlarmManageController.java
  9. 81 0
      security-protection-service/src/main/java/com/ai/bss/security/protection/controller/LoginController.java
  10. 2 0
      security-protection-service/src/main/java/com/ai/bss/security/protection/model/AiQuery.java
  11. 24 0
      security-protection-service/src/main/java/com/ai/bss/security/protection/model/User.java
  12. 115 0
      security-protection-service/src/main/java/com/ai/bss/security/protection/service/impl/LoginServiceImpl.java
  13. 22 0
      security-protection-service/src/main/java/com/ai/bss/security/protection/service/interfaces/LoginService.java
  14. 295 0
      security-protection-service/src/main/java/com/ai/bss/security/protection/utils/HttpServiceUtil.java
  15. 5 0
      security-protection-service/src/main/resources/application.properties

+ 84 - 0
location-rescue-service/src/main/java/com/ai/bss/location/rescue/controller/LoginController.java

@ -0,0 +1,84 @@
1
package com.ai.bss.location.rescue.controller;
2
3
import com.ai.abc.api.model.CommonResponse;
4
import com.ai.bss.location.rescue.model.User;
5
import com.ai.bss.location.rescue.service.interfaces.LoginService;
6
import org.springframework.beans.factory.annotation.Autowired;
7
import org.springframework.stereotype.Controller;
8
import org.springframework.web.bind.annotation.RequestBody;
9
import org.springframework.web.bind.annotation.RequestMapping;
10
import org.springframework.web.bind.annotation.ResponseBody;
11
12
import javax.servlet.http.Cookie;
13
import javax.servlet.http.HttpServletRequest;
14
import javax.servlet.http.HttpServletResponse;
15
import java.util.ArrayList;
16
import java.util.HashMap;
17
import java.util.List;
18
import java.util.Map;
19
20
/**
21
 * @Auther: 王超
22
 * @Date: 2020/12/24 14:05
23
 * @Description:
24
 */
25
@RequestMapping("/login")
26
@Controller
27
public class LoginController {
28
29
    @Autowired
30
    LoginService loginService;
31
32
    /**
33
     * 登录
34
     *
35
     * @return
36
     * @throws Exception
37
     */
38
    @ResponseBody
39
    @RequestMapping("/login")
40
    public Map<String, Object> login(@RequestBody User user,HttpServletResponse response){
41
        Map<String, Object> login = loginService.login(user);
42
43
        if(login!=null&&login.size()>0){
44
45
            Map result = (Map)login.get("RESULT");
46
            if(result!=null&&result.size()>0){
47
                Cookie userCookie1=new Cookie("session_id",(String) result.get("GLOBAL_SESSION_ID"));
48
                userCookie1.setMaxAge(30*60);   //存活期为30分钟
49
                userCookie1.setPath("/");
50
                response.addCookie(userCookie1);
51
52
                Cookie userCookie2=new Cookie("sign",(String) result.get("GLOBAL_SIGN"));
53
                userCookie2.setMaxAge(30*60);   //存活期为30分钟
54
                userCookie2.setPath("/");
55
                response.addCookie(userCookie2);
56
57
                Cookie userCookie3=new Cookie("sign_key",(String) result.get("TENANT_CODE"));
58
                userCookie3.setMaxAge(30*60);   //存活期为30分钟
59
                userCookie3.setPath("/");
60
                response.addCookie(userCookie3);
61
            }
62
        }
63
        return login;
64
    }
65
66
67
    /**
68
     *  获取菜单
69
     *
70
     * @return
71
     * @throws Exception
72
     */
73
    @ResponseBody
74
    @RequestMapping("/findMenus")
75
    public Map<String, Object> findMenus(@RequestBody User user, HttpServletRequest request){
76
77
        Map<String, Object> menus = loginService.findMenus(user,request);
78
        return menus;
79
    }
80
81
82
83
84
}

+ 24 - 0
location-rescue-service/src/main/java/com/ai/bss/location/rescue/model/User.java

@ -0,0 +1,24 @@
1
package com.ai.bss.location.rescue.model;
2
3
import lombok.Data;
4
5
/**
6
 * @Auther: 王超
7
 * @Date: 2020/12/24 15:07
8
 * @Description:
9
 */
10
11
@Data
12
public class User {
13
    //用户名
14
    private String userName;
15
16
    //用户编码
17
    private String userCode;
18
19
    //密码
20
    private String passWord;
21
22
    //根模块
23
    private String root_module;
24
}

+ 115 - 0
location-rescue-service/src/main/java/com/ai/bss/location/rescue/service/impl/LoginServiceImpl.java

@ -0,0 +1,115 @@
1
package com.ai.bss.location.rescue.service.impl;
2
3
import com.ai.abc.api.model.CommonResponse;
4
import com.ai.bss.location.rescue.model.User;
5
import com.ai.bss.location.rescue.service.interfaces.LoginService;
6
import com.ai.bss.location.rescue.util.HttpServiceUtil;
7
import com.alibaba.fastjson.JSON;
8
import org.slf4j.Logger;
9
import org.slf4j.LoggerFactory;
10
import org.springframework.beans.factory.annotation.Value;
11
import org.springframework.stereotype.Service;
12
13
import javax.servlet.http.Cookie;
14
import javax.servlet.http.HttpServletRequest;
15
import java.nio.charset.Charset;
16
import java.util.HashMap;
17
import java.util.List;
18
import java.util.Map;
19
20
/**
21
 * @Auther: 王超
22
 * @Date: 2020/12/24 15:13
23
 * @Description:
24
 */
25
26
@Service
27
public class LoginServiceImpl implements LoginService {
28
29
    Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);
30
31
    @Value("${uspa.login.vercode}")
32
    private String verCode;
33
34
    @Value("${uspa.login.url}")
35
    private String url;
36
37
    @Value("${uspa.login.menuUrl}")
38
    private String menuUrl;
39
40
    @Override
41
    public Map<String, Object> login(User user) {
42
        Map resultMap=null;
43
44
        try {
45
            HashMap<String, Object> paramsMap = new HashMap<>();
46
            paramsMap.put("userCode",user.getUserCode());
47
            paramsMap.put("passWord",user.getPassWord());
48
            paramsMap.put("vercode",verCode);
49
50
            // (1)设置字符集
51
            Charset charset = Charset.forName("utf-8");
52
53
            String result = HttpServiceUtil.sendPost(url, paramsMap, charset);
54
55
            resultMap = JSON.parseObject(result, Map.class);
56
57
        } catch (Exception e) {
58
            logger.error("调用uspa登录接口失败: " + e.getMessage());
59
            return resultMap;
60
        }
61
62
63
        return resultMap;
64
    }
65
66
    @Override
67
    public Map<String, Object> findMenus(User user, HttpServletRequest request) {
68
        Map resultMap=null;
69
70
        try {
71
            HashMap<String, Object> paramsMap = new HashMap<>();
72
            paramsMap.put("root_module","0000");
73
            paramsMap.put("userCode",user.getUserCode());
74
75
            Map<String, String> headerMap=new HashMap<>();
76
            // 取得cookie
77
            Cookie[] cookies = request.getCookies();
78
            if (cookies != null) {
79
                for (Cookie cookie : cookies) {
80
                    if (cookie.getName().equals("session_id")) {
81
                        headerMap.put("session_id", cookie.getValue());
82
                    }
83
                    if (cookie.getName().equals("sign")) {
84
                        headerMap.put("sign", cookie.getValue());
85
                    }
86
                    if (cookie.getName().equals("sign_key")) {
87
                        headerMap.put("sign_key", cookie.getValue());
88
                    }
89
                }
90
            }
91
            Map<String, String> headerMap1=new HashMap<>();
92
            //将设置拼接cookie
93
            headerMap1.put("Cookie","session_id="+headerMap.get("session_id")+";"+"sign="+headerMap.get("sign")+";"+"sign_key="+headerMap.get("sign_key"));
94
            // (1)设置字符集
95
            Charset charset = Charset.forName("utf-8");
96
97
            String result = HttpServiceUtil.sendPost(menuUrl, paramsMap, charset,headerMap1 );
98
            //将返回结果转为map
99
            resultMap = JSON.parseObject(result, Map.class);
100
101
            String result1 = (String)resultMap.get("RESULT");
102
            if(null!=result1&&!"".equals(result1)){
103
                //如果result有值返回正确,将返回结果转为List
104
                List<Map<String,List<Map>>> list = JSON.parseObject(result1, List.class);
105
                resultMap.put("RESULT",list);
106
            }
107
        } catch (Exception e) {
108
            logger.error("调用uspa获取菜单接口失败: " + e.getMessage());
109
110
            return resultMap;
111
        }
112
        return resultMap;
113
    }
114
115
}

+ 22 - 0
location-rescue-service/src/main/java/com/ai/bss/location/rescue/service/interfaces/LoginService.java

@ -0,0 +1,22 @@
1
package com.ai.bss.location.rescue.service.interfaces;
2
3
import com.ai.abc.api.model.CommonResponse;
4
import com.ai.bss.location.rescue.model.User;
5
6
import javax.servlet.http.HttpServletRequest;
7
import java.util.List;
8
import java.util.Map;
9
10
/**
11
 * @Auther: 王超
12
 * @Date: 2020/12/24 15:12
13
 * @Description:
14
 */
15
public interface LoginService {
16
17
18
    Map<String, Object> findMenus(User user, HttpServletRequest request);
19
20
21
    Map<String, Object> login(User user);
22
}

+ 6 - 1
location-rescue-service/src/main/resources/application.properties

@ -64,4 +64,9 @@ logging.level.com.ai=debug
64 64
logging.level.org.springframework.data=debug
65 65
66 66
# \u5f15\u5165gis\u548ciot\u7684\u914d\u7f6e\u6587\u4ef6
67
spring.profiles.active=iot,gis
67
spring.profiles.active=iot,gis
68
69
uspa.login.url=http://10.19.90.34:20000/usermng/login
70
uspa.login.vercode=Hiz#8uAqkjhoPmXu8%aaa
71
72
uspa.login.menuUrl=http://10.19.90.34:20000/usermng/process/com.wframe.usermanager.services.impl.QueryMenuByUser

+ 5 - 6
security-protection-service/pom.xml

@ -134,12 +134,11 @@
134 134
		</dependency>
135 135
136 136
        <!-- uspa登录拦截效验-->
137
138
<!--        <dependency>-->
139
<!--            <groupId>com.wframe</groupId>-->
140
<!--            <artifactId>sso-util</artifactId>-->
141
<!--            <version>1.2</version>-->
142
<!--        </dependency>-->
137
        <dependency>
138
            <groupId>com.wframe</groupId>
139
            <artifactId>sso-util</artifactId>
140
            <version>1.2</version>
141
        </dependency>
143 142
144 143
        <!-- 缓存 -->
145 144
        <dependency>

+ 60 - 0
security-protection-service/src/main/java/com/ai/bss/security/protection/config/MyCorsFilter.java

@ -0,0 +1,60 @@
1
package com.ai.bss.security.protection.config;
2
3
import com.ai.sso.filter.SessionUserFilter;
4
import org.springframework.boot.web.servlet.FilterRegistrationBean;
5
import org.springframework.context.annotation.Bean;
6
import org.springframework.context.annotation.Configuration;
7
import org.springframework.web.cors.CorsConfiguration;
8
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
9
import org.springframework.web.filter.CorsFilter;
10
11
import java.util.Arrays;
12
import java.util.HashMap;
13
import java.util.Map;
14
15
/**
16
 * 解决接口跨域问题
17
 *
18
 * @Auther: lihousheng
19
 * @Date: 2018/8/17 14:05
20
 */
21
22
@Configuration
23
public class MyCorsFilter {
24
25
    /**
26
     * attention:简单跨域就是GET,HEAD和POST请求,但是POST请求的"Content-Type"只能是application/x-www-form-urlencoded, multipart/form-data 或 text/plain
27
     * 反之,就是非简单跨域,此跨域有一个预检机制,说直白点,就是会发两次请求,一次OPTIONS请求,一次真正的请求
28
     */
29
    @Bean
30
    public CorsFilter corsFilter() {
31
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
32
        final CorsConfiguration config = new CorsConfiguration();
33
        config.setAllowCredentials(true); // 允许cookies跨域
34
        config.addAllowedOrigin("*");// #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin
35
        config.addAllowedHeader("*");// #允许访问的头信息,*表示全部
36
        config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
37
        config.addAllowedMethod("OPTIONS");// 允许提交请求的方法,*表示全部允许
38
        config.addAllowedMethod("HEAD");
39
        config.addAllowedMethod("GET");// 允许Get的请求方法
40
        config.addAllowedMethod("PUT");
41
        config.addAllowedMethod("POST");
42
        config.addAllowedMethod("DELETE");
43
        config.addAllowedMethod("PATCH");
44
        source.registerCorsConfiguration("/**", config);
45
        return new CorsFilter(source);
46
    }
47
48
49
    @Bean
50
    public FilterRegistrationBean mySessionUserFilter(){
51
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
52
        registrationBean.setFilter(new SessionUserFilter());
53
        registrationBean.setUrlPatterns(Arrays.asList("/mySessionUserFilter"));
54
        Map<String, String> initParameters = new HashMap<String,String>();
55
        initParameters.put("impl-classname","com.ai.sso.external.DefaultPopedomImpl");
56
        initParameters.put("ALLOWPATH","gif;jpg;jpeg;png;login;checkLogin;genVerificationCode;logout;");
57
        registrationBean.setInitParameters(initParameters);
58
        return registrationBean;
59
    }
60
}

+ 4 - 1
security-protection-service/src/main/java/com/ai/bss/security/protection/controller/AiAlarmManageController.java

@ -1,5 +1,6 @@
1 1
package com.ai.bss.security.protection.controller;
2 2
3
import java.util.ArrayList;
3 4
import java.util.Date;
4 5
import java.util.HashMap;
5 6
import java.util.Map;
@ -55,6 +56,8 @@ public class AiAlarmManageController {
55 56
		// 每页条数
56 57
		int pageSize = aiQuery.getPageSize() < 1 ? EbcConstant.DEFAULT_PAGE_SIZE : aiQuery.getPageSize();
57 58
59
		ArrayList<Object> statusList = new ArrayList<>();
60
		statusList.add(aiQuery.getStatusList());
58 61
		Map<String, Object> params = new HashMap<>();
59 62
		params.put("workOrgRoleId", aiQuery.getWorkOrgRoleId());
60 63
		params.put("alarmTypeCode", aiQuery.getAlarmTypeCode());
@ -62,7 +65,7 @@ public class AiAlarmManageController {
62 65
		params.put("workEmployeeRoleId", aiQuery.getWorkEmployeeRoleId());
63 66
		params.put("beginTime", aiQuery.getBeginTime());
64 67
		params.put("endTime", aiQuery.getEndTime());
65
		params.put("statusList", aiQuery.getStatusList());
68
		params.put("statusList",statusList);
66 69
67 70
		CommonResponse<PageBean<Map<String, Object>>> commonResponse = aiAlarmManageService.queryPageAiAlarm(params,
68 71
				pageNumber, pageSize);

+ 81 - 0
security-protection-service/src/main/java/com/ai/bss/security/protection/controller/LoginController.java

@ -0,0 +1,81 @@
1
package com.ai.bss.security.protection.controller;
2
3
4
import com.ai.bss.security.protection.model.User;
5
import com.ai.bss.security.protection.service.interfaces.LoginService;
6
import org.springframework.beans.factory.annotation.Autowired;
7
import org.springframework.stereotype.Controller;
8
import org.springframework.web.bind.annotation.RequestBody;
9
import org.springframework.web.bind.annotation.RequestMapping;
10
import org.springframework.web.bind.annotation.ResponseBody;
11
12
import javax.servlet.http.Cookie;
13
import javax.servlet.http.HttpServletRequest;
14
import javax.servlet.http.HttpServletResponse;
15
import java.util.Map;
16
17
/**
18
 * @Auther: 王超
19
 * @Date: 2020/12/24 14:05
20
 * @Description:
21
 */
22
@RequestMapping("/login")
23
@Controller
24
public class LoginController {
25
26
    @Autowired
27
    LoginService loginService;
28
29
    /**
30
     * 登录
31
     *
32
     * @return
33
     * @throws Exception
34
     */
35
    @ResponseBody
36
    @RequestMapping("/login")
37
    public Map<String, Object> login(@RequestBody User user, HttpServletResponse response){
38
        Map<String, Object> login = loginService.login(user);
39
40
        if(login!=null&&login.size()>0){
41
42
            Map result = (Map)login.get("RESULT");
43
            if(result!=null&&result.size()>0){
44
                Cookie userCookie1=new Cookie("session_id",(String) result.get("GLOBAL_SESSION_ID"));
45
                userCookie1.setMaxAge(30*60);   //存活期为30分钟
46
                userCookie1.setPath("/");
47
                response.addCookie(userCookie1);
48
49
                Cookie userCookie2=new Cookie("sign",(String) result.get("GLOBAL_SIGN"));
50
                userCookie2.setMaxAge(30*60);   //存活期为30分钟
51
                userCookie2.setPath("/");
52
                response.addCookie(userCookie2);
53
54
                Cookie userCookie3=new Cookie("sign_key",(String) result.get("TENANT_CODE"));
55
                userCookie3.setMaxAge(30*60);   //存活期为30分钟
56
                userCookie3.setPath("/");
57
                response.addCookie(userCookie3);
58
            }
59
        }
60
        return login;
61
    }
62
63
64
    /**
65
     *  获取菜单
66
     *
67
     * @return
68
     * @throws Exception
69
     */
70
    @ResponseBody
71
    @RequestMapping("/findMenus")
72
    public Map<String, Object> findMenus(@RequestBody User user, HttpServletRequest request){
73
74
        Map<String, Object> menus = loginService.findMenus(user,request);
75
        return menus;
76
    }
77
78
79
80
81
}

+ 2 - 0
security-protection-service/src/main/java/com/ai/bss/security/protection/model/AiQuery.java

@ -5,6 +5,8 @@ import lombok.Getter;
5 5
import lombok.NoArgsConstructor;
6 6
import lombok.Setter;
7 7
8
import java.util.List;
9
8 10
/**
9 11
 * @Auther: 王超
10 12
 * @Date: 2020/12/8 17:37

+ 24 - 0
security-protection-service/src/main/java/com/ai/bss/security/protection/model/User.java

@ -0,0 +1,24 @@
1
package com.ai.bss.security.protection.model;
2
3
import lombok.Data;
4
5
/**
6
 * @Auther: 王超
7
 * @Date: 2020/12/24 15:07
8
 * @Description:
9
 */
10
11
@Data
12
public class User {
13
    //用户名
14
    private String userName;
15
16
    //用户编码
17
    private String userCode;
18
19
    //密码
20
    private String passWord;
21
22
    //根模块
23
    private String root_module;
24
}

+ 115 - 0
security-protection-service/src/main/java/com/ai/bss/security/protection/service/impl/LoginServiceImpl.java

@ -0,0 +1,115 @@
1
package com.ai.bss.security.protection.service.impl;
2
3
4
import com.ai.bss.security.protection.model.User;
5
import com.ai.bss.security.protection.service.interfaces.LoginService;
6
import com.ai.bss.security.protection.utils.HttpServiceUtil;
7
import com.alibaba.fastjson.JSON;
8
import org.slf4j.Logger;
9
import org.slf4j.LoggerFactory;
10
import org.springframework.beans.factory.annotation.Value;
11
import org.springframework.stereotype.Service;
12
13
import javax.servlet.http.Cookie;
14
import javax.servlet.http.HttpServletRequest;
15
import java.nio.charset.Charset;
16
import java.util.HashMap;
17
import java.util.List;
18
import java.util.Map;
19
20
/**
21
 * @Auther: 王超
22
 * @Date: 2020/12/24 15:13
23
 * @Description:
24
 */
25
26
@Service
27
public class LoginServiceImpl implements LoginService {
28
29
    Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);
30
31
    @Value("${uspa.login.vercode}")
32
    private String verCode;
33
34
    @Value("${uspa.login.url}")
35
    private String url;
36
37
    @Value("${uspa.login.menuUrl}")
38
    private String menuUrl;
39
40
    @Override
41
    public Map<String, Object> login(User user) {
42
        Map resultMap=null;
43
44
        try {
45
            HashMap<String, Object> paramsMap = new HashMap<>();
46
            paramsMap.put("userCode",user.getUserCode());
47
            paramsMap.put("passWord",user.getPassWord());
48
            paramsMap.put("vercode",verCode);
49
50
            // (1)设置字符集
51
            Charset charset = Charset.forName("utf-8");
52
53
            String result = HttpServiceUtil.sendPost(url, paramsMap, charset);
54
55
            resultMap = JSON.parseObject(result, Map.class);
56
57
        } catch (Exception e) {
58
            logger.error("调用uspa登录接口失败: " + e.getMessage());
59
            return resultMap;
60
        }
61
62
63
        return resultMap;
64
    }
65
66
    @Override
67
    public Map<String, Object> findMenus(User user, HttpServletRequest request) {
68
        Map resultMap=null;
69
70
        try {
71
            HashMap<String, Object> paramsMap = new HashMap<>();
72
            paramsMap.put("root_module","0000");
73
            paramsMap.put("userCode",user.getUserCode());
74
75
            Map<String, String> headerMap=new HashMap<>();
76
            // 取得cookie
77
            Cookie[] cookies = request.getCookies();
78
            if (cookies != null) {
79
                for (Cookie cookie : cookies) {
80
                    if (cookie.getName().equals("session_id")) {
81
                        headerMap.put("session_id", cookie.getValue());
82
                    }
83
                    if (cookie.getName().equals("sign")) {
84
                        headerMap.put("sign", cookie.getValue());
85
                    }
86
                    if (cookie.getName().equals("sign_key")) {
87
                        headerMap.put("sign_key", cookie.getValue());
88
                    }
89
                }
90
            }
91
            Map<String, String> headerMap1=new HashMap<>();
92
            //将设置拼接cookie
93
            headerMap1.put("Cookie","session_id="+headerMap.get("session_id")+";"+"sign="+headerMap.get("sign")+";"+"sign_key="+headerMap.get("sign_key"));
94
            // (1)设置字符集
95
            Charset charset = Charset.forName("utf-8");
96
97
            String result = HttpServiceUtil.sendPost(menuUrl, paramsMap, charset,headerMap1 );
98
            //将返回结果转为map
99
            resultMap = JSON.parseObject(result, Map.class);
100
101
            String result1 = (String)resultMap.get("RESULT");
102
            if(null!=result1&&!"".equals(result1)){
103
                //如果result有值返回正确,将返回结果转为List
104
                List<Map<String,List<Map>>> list = JSON.parseObject(result1, List.class);
105
                resultMap.put("RESULT",list);
106
            }
107
        } catch (Exception e) {
108
            logger.error("调用uspa获取菜单接口失败: " + e.getMessage());
109
110
            return resultMap;
111
        }
112
        return resultMap;
113
    }
114
115
}

+ 22 - 0
security-protection-service/src/main/java/com/ai/bss/security/protection/service/interfaces/LoginService.java

@ -0,0 +1,22 @@
1
package com.ai.bss.security.protection.service.interfaces;
2
3
4
5
import com.ai.bss.security.protection.model.User;
6
7
import javax.servlet.http.HttpServletRequest;
8
import java.util.Map;
9
10
/**
11
 * @Auther: 王超
12
 * @Date: 2020/12/24 15:12
13
 * @Description:
14
 */
15
public interface LoginService {
16
17
18
    Map<String, Object> findMenus(User user, HttpServletRequest request);
19
20
21
    Map<String, Object> login(User user);
22
}

+ 295 - 0
security-protection-service/src/main/java/com/ai/bss/security/protection/utils/HttpServiceUtil.java

@ -0,0 +1,295 @@
1
package com.ai.bss.security.protection.utils;
2
3
import com.alibaba.fastjson.JSONObject;
4
import org.apache.http.HttpEntity;
5
import org.apache.http.HttpStatus;
6
import org.apache.http.client.ClientProtocolException;
7
import org.apache.http.client.HttpClient;
8
import org.apache.http.client.config.RequestConfig;
9
import org.apache.http.client.methods.CloseableHttpResponse;
10
import org.apache.http.client.methods.HttpGet;
11
import org.apache.http.client.methods.HttpPost;
12
import org.apache.http.client.methods.HttpPut;
13
import org.apache.http.entity.StringEntity;
14
import org.apache.http.entity.mime.MultipartEntityBuilder;
15
import org.apache.http.impl.client.CloseableHttpClient;
16
import org.apache.http.impl.client.HttpClients;
17
import org.apache.http.protocol.HTTP;
18
import org.apache.http.util.EntityUtils;
19
import org.slf4j.Logger;
20
import org.slf4j.LoggerFactory;
21
import org.springframework.util.CollectionUtils;
22
23
import java.io.*;
24
import java.net.HttpURLConnection;
25
import java.net.URL;
26
import java.net.URLEncoder;
27
import java.nio.charset.Charset;
28
import java.util.Iterator;
29
import java.util.Map;
30
import java.util.Set;
31
32
/**
33
 * http服务请求工具类
34
 *
35
 * @author chencai
36
 */
37
public class HttpServiceUtil {
38
	static Logger log = LoggerFactory.getLogger(HttpServiceUtil.class);
39
40
	private static final String HTTP_CONTENT_TYPE_JSON = "application/json; charset=utf-8";
41
42
	public static String buildUrl(Map<String, String> paramMap, String serviceUrl) {
43
		String url = null;
44
		StringBuffer urlString = new StringBuffer();
45
		urlString.append(serviceUrl);
46
47
		if (!paramMap.isEmpty()) {
48
			// 参数列表不为空,地址尾部增加'?'
49
			urlString.append('?');
50
			// 拼接参数
51
			Set<Map.Entry<String, String>> entrySet = paramMap.entrySet();
52
			for (Map.Entry<String, String> entry : entrySet) {
53
				try {
54
					urlString.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), "UTF-8"))
55
							.append('&');
56
				} catch (UnsupportedEncodingException e) {
57
					log.error(" Exception: " + e);
58
				}
59
			}
60
			// 去掉最后一个字符“&”
61
			url = urlString.substring(0, urlString.length() - 1);
62
		}
63
		return url;
64
	}
65
66
	public static String sendRequest(String url) {
67
		InputStream inputStream = null;
68
		BufferedReader bufferedReader = null;
69
		HttpURLConnection httpURLConnection = null;
70
		try {
71
			log.error("It's not error. request url: " + url);
72
			URL requestURL = new URL(url);
73
			// 获取连接
74
			httpURLConnection = (HttpURLConnection) requestURL.openConnection();
75
			httpURLConnection.setConnectTimeout(10000); // 建立连接的超时时间,毫秒
76
			httpURLConnection.setReadTimeout(25000); // 获得返回的超时时间,毫秒
77
			httpURLConnection.setRequestMethod("GET");
78
			httpURLConnection.setRequestProperty("Content-type", "text/html;charset=UTF-8");
79
			httpURLConnection.setRequestProperty("Accept",
80
					"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
81
			// 通过输入流获取请求的内容
82
			inputStream = httpURLConnection.getInputStream();
83
			bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
84
			String temp = null;
85
			StringBuffer stringBuffer = new StringBuffer();
86
			// 循环读取返回的结果
87
			while ((temp = bufferedReader.readLine()) != null) {
88
				stringBuffer.append(temp);
89
			}
90
91
			return stringBuffer.toString();
92
		} catch (Exception e) {
93
			log.error("sendRequest Exception: " + e);
94
		} finally {
95
			// 断开连接
96
			if (httpURLConnection != null) {
97
				httpURLConnection.disconnect();
98
			}
99
			// 关闭流
100
			if (bufferedReader != null) {
101
				try {
102
					bufferedReader.close();
103
				} catch (IOException e) {
104
					log.error("bufferedReader Exception: " + e);
105
				}
106
			}
107
			if (inputStream != null) {
108
				try {
109
					inputStream.close();
110
				} catch (IOException e) {
111
					log.error("inputStream Exception: " + e);
112
				}
113
			}
114
		}
115
		return null;
116
	}
117
118
	public static String sendPostRequest(String url, Map<String, String> map, String encoding) {
119
		String retStr = "";
120
		try {
121
			retStr = sendPostRequest(url, map, encoding, 0, 0);
122
		} catch (Exception ex) {
123
			log.error("sendPostRequest error: " + ex);
124
		}
125
126
		return retStr;
127
	}
128
129
	public static String sendPostRequest(String url, Map<String, String> map, String encoding, int ebossConnectTimeout,
130
			int ebossServiceTimeout) {
131
		CloseableHttpClient httpClient = HttpClients.createDefault();
132
		HttpPost httpPost = new HttpPost(url);
133
		String body = "";
134
135
		try {
136
			MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
137
			if (map != null) {
138
				for (Map.Entry<String, String> entry : map.entrySet()) {
139
					multipartEntityBuilder.addTextBody(entry.getKey(), entry.getValue());
140
				}
141
			}
142
143
			log.debug("ebossConnectTimeout:" + ebossConnectTimeout);
144
			log.debug("ebossServiceTimeout:" + ebossServiceTimeout);
145
146
			httpPost.setEntity(multipartEntityBuilder.build());
147
			if (ebossConnectTimeout != 0 && ebossServiceTimeout != 0) {
148
				RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(ebossServiceTimeout)
149
						.setConnectTimeout(ebossConnectTimeout).build();// 设置请求和传输超时时间
150
				httpPost.setConfig(requestConfig);
151
			}
152
153
			CloseableHttpResponse response = httpClient.execute(httpPost);
154
155
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
156
				HttpEntity entity = response.getEntity();
157
				if (entity != null) {
158
					// 按指定编码转换结果实体为String类型
159
					body = EntityUtils.toString(entity, encoding);
160
				}
161
				EntityUtils.consume(entity);
162
			}
163
		} catch (ClientProtocolException e) {
164
			log.error("ClientProtocolException Exception: " + e);
165
		} catch (UnsupportedEncodingException e) {
166
			log.error("UnsupportedEncodingException Exception: " + e);
167
		} catch (IOException e) {
168
			log.error("IOException Exception: " + e);
169
			// throw new BaseException("10", "调用Eboss超时");
170
		} finally {
171
			// 关闭连接,释放资源
172
			try {
173
				httpClient.close();
174
			} catch (IOException e) {
175
				log.error("httpClient Exception: " + e);
176
			}
177
		}
178
179
		return body;
180
	}
181
182
	public static String sendGet(String url, Charset encoding, Map<String, String> headerMap) {
183
		HttpClient httpClient = HttpClients.createDefault();
184
		HttpGet httpGet = new HttpGet(url);
185
		httpGet.addHeader(HTTP.CONTENT_TYPE, HTTP_CONTENT_TYPE_JSON);
186
		CloseableHttpResponse response = null;
187
		try {
188
			log.debug("执行GET请求:url= " + url);
189
			response = (CloseableHttpResponse) httpClient.execute(httpGet);
190
		} catch (Exception e) {
191
			log.error("sendGet Exception: " + e.getMessage());
192
			return "{}";
193
		}
194
		return responseEx(httpClient, response, encoding);
195
	}
196
197
	public static String sendPost(String url, Map<String, Object> paramsMap, Charset encoding) {
198
		HttpClient httpClient = HttpClients.createDefault();
199
		HttpPost httpPost = new HttpPost(url);
200
		httpPost.addHeader(HTTP.CONTENT_TYPE, HTTP_CONTENT_TYPE_JSON);
201
		if (!CollectionUtils.isEmpty(paramsMap)) {
202
			StringEntity se = new StringEntity(JSONObject.toJSONString(paramsMap), encoding);
203
			httpPost.setEntity(se);
204
		}
205
		CloseableHttpResponse response = null;
206
		try {
207
			log.debug("执行POST无参请求:url= " + url);
208
			response = (CloseableHttpResponse) httpClient.execute(httpPost);
209
		} catch (Exception e) {
210
			log.error("sendPost Exception: " + e.getMessage());
211
			return "{}";
212
		}
213
		return responseEx(httpClient, response, encoding);
214
	}
215
216
	public static String sendPost(String url, Map<String, Object> paramsMap, Charset encoding,
217
			Map<String, String> headerMap) {
218
		HttpClient httpClient = HttpClients.createDefault();
219
		HttpPost httpPost = new HttpPost(url);
220
221
		Iterator<String> iter = headerMap.keySet().iterator();
222
		String key = "";
223
		String value = "";
224
		while (iter.hasNext()) {
225
			key = iter.next();
226
			value = headerMap.get(key);
227
			httpPost.setHeader(key, value);
228
		}
229
230
		httpPost.addHeader(HTTP.CONTENT_TYPE, HTTP_CONTENT_TYPE_JSON);
231
		if (!CollectionUtils.isEmpty(paramsMap)) {
232
			log.debug("执行POST请求:url= " + url + ",参数= " + JSONObject.toJSONString(paramsMap));
233
			StringEntity se = new StringEntity(JSONObject.toJSONString(paramsMap), encoding);
234
			httpPost.setEntity(se);
235
		}
236
		CloseableHttpResponse response = null;
237
		try {
238
			response = (CloseableHttpResponse) httpClient.execute(httpPost);
239
		} catch (Exception e) {
240
			log.error("sendPost Exception: " + e.getMessage());
241
			return "{}";
242
		}
243
		return responseEx(httpClient, response, encoding);
244
	}
245
246
	public static String sendPut(String url, Map<String, Object> paramsMap, Charset encoding) {
247
		HttpClient httpClient = HttpClients.createDefault();
248
		String resp = "";
249
		HttpPut httpPut = new HttpPut(url);
250
		httpPut.addHeader(HTTP.CONTENT_TYPE, HTTP_CONTENT_TYPE_JSON);
251
		if (!CollectionUtils.isEmpty(paramsMap)) {
252
			StringEntity se = new StringEntity(JSONObject.toJSONString(paramsMap), encoding);
253
			httpPut.setEntity(se);
254
		}
255
		CloseableHttpResponse response = null;
256
		try {
257
			log.debug("执行PUT请求:url= " + url + ",参数= " + JSONObject.toJSONString(paramsMap));
258
			response = (CloseableHttpResponse) httpClient.execute(httpPut);
259
		} catch (Exception e) {
260
			log.error("sendPut Exception: " + e.getMessage());
261
			return "{}";
262
		}
263
264
		return responseEx(httpClient, response, encoding);
265
	}
266
267
	private static String responseEx(HttpClient httpClient, CloseableHttpResponse response, Charset encoding) {
268
		String resp = "";
269
		try {
270
			if (response == null) {
271
				resp = "{}";
272
				log.error("请求执行失败,无返回信息");
273
			} else if (200 != response.getStatusLine().getStatusCode()) {
274
				resp = "{}";
275
				log.error("请求执行失败,状态码=" + response.getStatusLine().getStatusCode() + ",返回信息="
276
						+ EntityUtils.toString(response.getEntity(), encoding));
277
			} else {
278
				log.debug("请求执行成功");
279
				resp = EntityUtils.toString(response.getEntity(), encoding);
280
			}
281
		} catch (Exception e) {
282
			log.error("responseEx Exception: " + e.getMessage());
283
		} finally {
284
			if (response != null) {
285
				try {
286
					response.close();
287
				} catch (Exception e) {
288
					log.error("responseEx Exception: " + e.getMessage());
289
				}
290
			}
291
		}
292
		return resp;
293
	}
294
295
}

+ 5 - 0
security-protection-service/src/main/resources/application.properties

@ -89,3 +89,8 @@ spring.servlet.multipart.resolve-lazily=false
89 89
# LOGGING
90 90
logging.level.com.ai=debug
91 91
logging.level.org.springframework.data=debug
92
93
uspa.login.url=http://10.19.90.34:20000/usermng/login
94
uspa.login.vercode=Hiz#8uAqkjhoPmXu8%aaa
95
96
uspa.login.menuUrl=http://10.19.90.34:20000/usermng/process/com.wframe.usermanager.services.impl.QueryMenuByUser