Commit bc078cbc by chenzx

元曜集成元年单点登录

parent 2969605b
...@@ -66,10 +66,10 @@ ...@@ -66,10 +66,10 @@
<artifactId>jedis</artifactId> <artifactId>jedis</artifactId>
<version>2.9.0</version> <version>2.9.0</version>
</dependency> </dependency>
<dependency> <!--<dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId> <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> </dependency>-->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
...@@ -79,6 +79,25 @@ ...@@ -79,6 +79,25 @@
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId> <artifactId>spring-cloud-config-client</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.4.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
</dependencies> </dependencies>
<dependencyManagement> <dependencyManagement>
...@@ -100,6 +119,26 @@ ...@@ -100,6 +119,26 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.21.0</version>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins> </plugins>
<resources>
<resource>
<directory>src/main/webapp/WEB-INF/jsp</directory>
<!--如果使用springboot自带的tomcat启动,则使用如下配置jsp路径-->
<targetPath>META-INF/resources</targetPath>
<!--如果使用maven启动本地tomcat启动,则使用如下配置-->
<!--<targetPath>/WEB-INF/jsp</targetPath>-->
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
</build> </build>
</project> </project>
...@@ -2,8 +2,10 @@ package com.keymobile.proxy; ...@@ -2,8 +2,10 @@ package com.keymobile.proxy;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication @SpringBootApplication
@EnableFeignClients
public class LoginApplication { public class LoginApplication {
public static void main(String[] args) { public static void main(String[] args) {
......
...@@ -7,6 +7,7 @@ public class Constants { ...@@ -7,6 +7,7 @@ public class Constants {
public static final String Session_UserDName = "userDName"; public static final String Session_UserDName = "userDName";
public static final String Session_Roles = "roles"; public static final String Session_Roles = "roles";
public static final String Session_Lang = "lang"; public static final String Session_Lang = "lang";
public static final String ROLE_PREFIX = "ROLE_";
} }
...@@ -19,17 +19,20 @@ public class LoginManagement { ...@@ -19,17 +19,20 @@ public class LoginManagement {
@RequestMapping(value = "/sessionInfo", method = RequestMethod.POST) @RequestMapping(value = "/sessionInfo", method = RequestMethod.POST)
public @ResponseBody Map<String,Object> verifyLogin(HttpServletRequest request, HttpServletResponse response) { public @ResponseBody Map<String,Object> verifyLogin(HttpServletRequest request, HttpServletResponse response) {
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// String userNameWithIdAttached = userDetails.getUsername( );
// rs.put(Constants.Session_UserName, userNameWithIdAttached.split(":")[0]);
// rs.put(Constants.Session_UserId, userNameWithIdAttached.split(":")[1]);
// rs.put(Constants.Session_UserDName, userNameWithIdAttached.split(":")[2]);
// List<String> roles = new ArrayList<>();
// userDetails.getAuthorities().forEach(auth -> roles.add(auth.getAuthority()));
// rs.put(Constants.Session_Roles, roles);
Map<String,Object> rs = new HashMap<>(); Map<String,Object> rs = new HashMap<>();
String userNameWithIdAttached = userDetails.getUsername();
rs.put(Constants.Session_UserName, userNameWithIdAttached.split(":")[0]);
rs.put(Constants.Session_UserId, userNameWithIdAttached.split(":")[1]);
rs.put(Constants.Session_UserDName, userNameWithIdAttached.split(":")[2]);
List<String> roles = new ArrayList<>();
userDetails.getAuthorities().forEach(auth -> roles.add(auth.getAuthority()));
rs.put(Constants.Session_Roles, roles);
HttpSession session = request.getSession(); HttpSession session = request.getSession();
rs.put(Constants.Session_UserId, session.getAttribute(Constants.Session_UserId));
rs.put(Constants.Session_UserDName, session.getAttribute(Constants.Session_UserDName));
rs.put(Constants.Session_UserDName, session.getAttribute(Constants.Session_UserDName));
rs.put(Constants.Session_Roles, session.getAttribute(Constants.Session_Roles));
Object lang = session.getAttribute(Constants.Session_Lang); Object lang = session.getAttribute(Constants.Session_Lang);
rs.put(Constants.Session_Lang, lang != null ? lang.toString() : "cn"); rs.put(Constants.Session_Lang, lang != null ? lang.toString() : "cn");
return rs; return rs;
......
package com.keymobile.proxy.api;
import com.alibaba.fastjson.JSONObject;
import com.keymobile.proxy.service.AuthService;
import com.keymobile.proxy.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
@Controller
public class SSOCtrl {
private Logger logger = LoggerFactory.getLogger(SSOCtrl.class);
@Value("${sso.url}")
private String ssoUrl;
@Value("${redirect-url.data-platform}")
private String dataPlatformURL;
@Autowired
private UserService userService;
@GetMapping("/main")
public String getDataPlatformMainView(Map<String, Object> model,
@RequestParam(value = "token",required = false) String token) {
model.put("success", true);
model.put("redirect-url", dataPlatformURL);
model.put("msg", "验证成功");
if(null == token ||"".equals(token)){
model.put("success", false);
model.put("msg", "缺少token参数,验证失败");
return "main";
}
this.logger.info("单点登录验证token:"+token);
String flag = checkToken(ssoUrl+"?token="+token,HttpMethod.POST,null);
if("".equals(flag)){
model.put("success", false);
model.put("msg", "Token验证异常,请重试");
}else{
try {
JSONObject jo = JSONObject.parseObject(flag);
boolean success = jo.getBoolean("success");
String message = jo.getString("message");
if(!success){
model.put("success", false);
model.put("msg", message);
return "main";
}
JSONObject data = jo.getJSONObject("data");
String loginName = data.getString("loginName");
String userName = data.getString("userName");
this.userService.setSessionInfo(loginName,userName);
this.logger.info(loginName+"单点登录成功");
}catch (Exception e){
e.printStackTrace();
model.put("success", false);
model.put("msg", "单点登录异常,请联系管理员");
return "main";
}
}
return "main";
}
private String checkToken(String url, HttpMethod method, MultiValueMap<String, String> params) {
try{
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(10*1000);
requestFactory.setReadTimeout(10*1000);
RestTemplate client = new RestTemplate(requestFactory);
HttpHeaders headers = new HttpHeaders();
// 请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
// 执行HTTP请求
ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
return response.getBody();
}catch (Exception e){
e.printStackTrace();
this.logger.info("checkToken异常:",e.getMessage());
return "";
}
}
}
package com.keymobile.proxy.api;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
@RestController
public class TestCtrl {
@RequestMapping("/sso")
public String sso() {
return "{" +
" \"data\": {" +
" \"clientIp\": \"192.168.58.10\"," +
" \"clientName\": \"\"," +
" \"clientType\": \"\"," +
" \"consoleMenuId\": [" +
" \"580e04789a7b11eaad6745965231c0b2\"," +
" \"be35d754754611e8a06c7f1e4c9a49f4\"," +
" \"be35d755754611e8a06cb9cf608eeab1\"," +
" \"e39e9a7d27d911ea8fd7af93faecd120\"," +
" \"be35b042754611e8a06c33d913e43302\"," +
" \"9dc97da6dcb111e88b43eb0df4392e87\"" +
" ]," +
" \"createTime\": null," +
" \"failedCount\": 0," +
" \"forceLock\": false," +
" \"instanc\": \"\"," +
" \"languageCode\": \"zh_CN\"," +
" \"lastTime\": \"2020-10-26 18:41:57\"," +
" \"lockTime\": null," +
" \"loginName\": \"czx\"," +
" \"loginStatusId\": \"4f1e3997177711eba2dc2d94a378ce32\"," +
" \"loginTime\": \"2020-10-26 18:37:56\"," +
" \"products\": \"CONSOLE\"," +
" \"requestProducts\": \"\"," +
" \"serverIpPort\": \"\"," +
" \"token\": \"4f1e3998177711eba2dc690cb77c1cf0\"," +
" \"userId\": \"352ba07b0dc211eba68cf5d2709f91c5\"," +
" \"userName\": \"测试\"," +
" \"validTime\": 120" +
" }," +
" \"message\": \"\"," +
" \"messageList\": null," +
" \"messageType\": \"ERROR\"," +
" \"success\": true" +
"}";
}
}
package com.keymobile.proxy.conf;
import feign.auth.BasicAuthRequestInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignClientConfig {
@Value("${security.authUser}")
private String authUser;
@Value("${security.authPwd}")
private String authPwd;
@Bean
public BasicAuthRequestInterceptor getBasicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor(authUser, authPwd);
}
}
\ No newline at end of file
package com.keymobile.proxy.model;
public class Author {
private Long id;
private String name;
public Author() {}
public Long getAuthorId() {
return id;
}
public void setAuthorId(Long id) {
this.id = id;
}
public String getAuthorName() {
return name;
}
public void setAuthorName(String name) {
this.name = name;
}
}
package com.keymobile.proxy.model;
public class Domain {
private Long id;
private String name;
public Domain() {}
public Domain(String name) {
this.name = name;
}
public Long getDomainId() {
return id;
}
public void setDomainId(Long id) {
this.id = id;
}
public String getDomainName() {
return name;
}
public void setDomainName(String name) {
this.name = name;
}
}
package com.keymobile.proxy.model;
public class Role {
private Long id;
private String name;
private String dname;
public Role() {}
public Long getRoleId() {
return id;
}
public void setRoleId(Long id) {
this.id = id;
}
public String getRoleName() {
return name;
}
public void setRoleName(String name) {
this.name = name;
}
public String getRoleDName() {
return dname;
}
public void setRoleDName(String dname) {
this.dname = dname;
}
}
package com.keymobile.proxy.model;
import java.util.List;
public class User {
private Long id;
private String name;
private String dname;
private String password;
private List<Role> roles;
private List<Domain> domains;
public User() {}
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDName() {
return dname;
}
public void setDName(String dname) {
this.dname = dname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
System.out.println(password);
this.password = password;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public List<Domain> getDomains() {
return domains;
}
public void setDomains(List<Domain> domains) {
this.domains = domains;
}
}
\ No newline at end of file
package com.keymobile.proxy.service;
import com.keymobile.proxy.model.Author;
import com.keymobile.proxy.model.Domain;
import com.keymobile.proxy.model.Role;
import com.keymobile.proxy.model.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@FeignClient(value = "authService")
public interface AuthService {
@RequestMapping(value = "/user")
User getUserByName(@RequestParam(value = "name") String name);
@PostMapping(value = "/users/{userId}")
User updateUser(@PathVariable(value = "userId") Long userId, @RequestBody User user);
@RequestMapping(value = "/users", method = RequestMethod.POST)
User addUser(@RequestParam(value = "roleIds", required = false) Long[] roleIds
, @RequestParam(value = "domainIds", required = false) Long[] domainIds, @RequestBody User user);
@RequestMapping(value = "/roles/{roleId}/authors", method = RequestMethod.GET)
List<Author> getAuthorsOfRole(@PathVariable(value = "roleId") Long roleId);
@RequestMapping(value = "/users/{userId}/roles", method = RequestMethod.GET)
List<Role> getRolesOfUser(@PathVariable(value = "userId") Long userId);
@RequestMapping(value = "/users/{userId}/domains", method = RequestMethod.GET)
List<Domain> getDomainsOfUser(@PathVariable(value = "userId") Long userId);
}
package com.keymobile.proxy.service;
import com.keymobile.proxy.api.Constants;
import com.keymobile.proxy.model.Author;
import com.keymobile.proxy.model.Domain;
import com.keymobile.proxy.model.Role;
import com.keymobile.proxy.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserService {
private Logger logger = LoggerFactory.getLogger(UserService.class);
@Autowired
private AuthService authService;
public void setSessionInfo(String name,String dName) {
HttpSession session = HttpUtil.getSession();
if (session != null) {
com.keymobile.proxy.model.User u = this.authService.getUserByName(name);
if (u == null) {
u = new com.keymobile.proxy.model.User();
u.setName(name);
u.setPassword("37fa265330ad83eaa879efb1e2db6380896cf639");
u.setDName(dName);
u = this.authService.addUser(new Long[] { (long) 4 }, new Long[] {}, u);
this.logger.info("单点登录新增用户:"+name);
}
List<GrantedAuthority> authorities = new ArrayList<>();
String userDomainFilterStr = "*";
List<String> userDomainList = new ArrayList<>();
List<Domain> domainsOfUser = authService.getDomainsOfUser(u.getId());
domainsOfUser.forEach(d -> userDomainList.add(d.getDomainId().toString()));
if (userDomainList.size() > 0) {
userDomainFilterStr = String.join(",", userDomainList);
}
List<Role> rolesOfUser = authService.getRolesOfUser(u.getId());
for (Role role : rolesOfUser) {
List<Author> authors = authService.getAuthorsOfRole(role.getRoleId());
for (Author author: authors) {
GrantedAuthority authorityInfo = new SimpleGrantedAuthority(Constants.ROLE_PREFIX + author.getAuthorName() + ":" + userDomainFilterStr);
authorities.add(authorityInfo);
}
}
List<String> roles = new ArrayList<>();
authorities.forEach(auth -> roles.add(auth.getAuthority()));
session.setAttribute(Constants.Session_UserId, u.getId());
session.setAttribute(Constants.Session_UserName, u.getName());
session.setAttribute(Constants.Session_UserDName, u.getDName());
session.setAttribute(Constants.Session_Roles, roles);
this.logger.info(name+"用户session设置成功");
}
}
}
server: server:
port: 8764 port: 8764
redirect-url:
data-platform: http://192.168.0.41:9090/center-home/view/index
system-management: http://localhost
spring: spring:
application: application:
name: auth name: auth
session: session:
store-type: redis store-type: redis
redis: redis:
namespace: dataplatformtest namespace: sdrcb
redis: redis:
cluster: cluster:
nodes: localhost:6379 nodes: 192.168.0.192:6379
max-redirects: 6 max-redirects: 6
timeout: 10000 #客户端超时时间单位是毫秒 默认是2000 timeout: 10000 #客户端超时时间单位是毫秒 默认是2000
maxIdle: 300 #最大空闲数 maxIdle: 300 #最大空闲数
...@@ -23,11 +27,15 @@ spring: ...@@ -23,11 +27,15 @@ spring:
testWhileIdle: true #在空闲时检查有效性, 默认false testWhileIdle: true #在空闲时检查有效性, 默认false
password: #密码 password: #密码
datasource: datasource:
url: jdbc:mysql://localhost:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8 url: jdbc:mysql://192.168.0.192:3306/sdrcb?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8
username: test username: test
password: dataSharing password: test
hikari: hikari:
maximum-pool-size: 3 maximum-pool-size: 3
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
eureka: eureka:
client: client:
...@@ -35,7 +43,7 @@ eureka: ...@@ -35,7 +43,7 @@ eureka:
region: default region: default
registryFetchIntervalSeconds: 5 registryFetchIntervalSeconds: 5
serviceUrl: serviceUrl:
defaultZone: http://localhost:8081/eureka/ defaultZone: http://192.168.0.41:8081/eureka/
zuul: zuul:
prefix: /api prefix: /api
...@@ -43,4 +51,12 @@ zuul: ...@@ -43,4 +51,12 @@ zuul:
logging: logging:
level: level:
org.springframework.security: DEBUG org.springframework.security: DEBUG
\ No newline at end of file
security:
permit: true
authUser: root
authPwd: pwd
sso:
url: http://192.168.0.113:8764/sso
\ No newline at end of file
<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page pageEncoding = "gb2312" %>
<%@ page contentType = "text/html;charset=gb2312" %>
<% request.setCharacterEncoding("gb2312"); %>
<html lang="en">
<c:choose>
<c:when test="${requestScope.success}">
<%
response.sendRedirect((String) request.getAttribute("redirect-url"));
%>
</c:when>
<c:otherwise>
${requestScope.msg}
</c:otherwise>
</c:choose>
</html>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment