Commit 4a840a45 by linxu

sso login using spring security

parent 9cf0d62b
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
<groupId>LV77</groupId> <groupId>LV77</groupId>
<artifactId>ads-mds-login</artifactId> <artifactId>ads-mds-login</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>war</packaging>
<name>mdslogin</name> <name>mdslogin</name>
<description>mdslogin</description> <description>mdslogin</description>
...@@ -119,26 +119,6 @@ ...@@ -119,26 +119,6 @@
<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>
...@@ -14,27 +14,26 @@ import java.util.List; ...@@ -14,27 +14,26 @@ import java.util.List;
import java.util.Map; import java.util.Map;
@RestController @RestController
@RequestMapping(value = "/")
public class LoginManagement { public class LoginManagement {
@RequestMapping(value = "/sessionInfo", method = RequestMethod.POST) @GetMapping("/sso")
public void doJump() {
System.out.println("GO");
}
@RequestMapping(value = "/sessionInfo", method = {RequestMethod.POST, RequestMethod.GET})
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();
// 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<>();
HttpSession session = request.getSession();
rs.put(Constants.Session_UserId, session.getAttribute(Constants.Session_UserId)); UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
rs.put(Constants.Session_UserDName, session.getAttribute(Constants.Session_UserDName)); String userNameWithIdAttached = userDetails.getUsername();
rs.put(Constants.Session_UserDName, session.getAttribute(Constants.Session_UserDName)); rs.put(Constants.Session_UserName, userNameWithIdAttached.split(":")[0]);
rs.put(Constants.Session_Roles, session.getAttribute(Constants.Session_Roles)); rs.put(Constants.Session_UserId, userNameWithIdAttached.split(":")[1]);
Object lang = session.getAttribute(Constants.Session_Lang); rs.put(Constants.Session_UserDName, userNameWithIdAttached.split(":")[2]);
rs.put(Constants.Session_Lang, lang != null ? lang.toString() : "cn"); List<String> roles = new ArrayList<>();
userDetails.getAuthorities().forEach(auth -> roles.add(auth.getAuthority()));
rs.put(Constants.Session_Roles, roles);
return rs; return rs;
} }
......
package com.keymobile.proxy.api; package com.keymobile.proxy.api;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.keymobile.proxy.service.AuthService;
import com.keymobile.proxy.service.UserService; import com.keymobile.proxy.service.UserService;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -10,15 +10,12 @@ import org.springframework.beans.factory.annotation.Value; ...@@ -10,15 +10,12 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*; import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map; import java.util.Map;
@Controller @Controller
...@@ -35,6 +32,14 @@ public class SSOCtrl { ...@@ -35,6 +32,14 @@ public class SSOCtrl {
@Autowired @Autowired
private UserService userService; private UserService userService;
@GetMapping("/go")
public String doJump(Map<String, Object> model) {
model.put("success", true);
model.put("redirect-url", dataPlatformURL);
model.put("msg", "验证成功");
return "main";
}
@GetMapping("/main") @GetMapping("/main")
public String getDataPlatformMainView(Map<String, Object> model, public String getDataPlatformMainView(Map<String, Object> model,
@RequestParam(value = "token",required = false) String token) { @RequestParam(value = "token",required = false) String token) {
......
package com.keymobile.proxy.conf; package com.keymobile.proxy.conf;
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.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
@Configuration @Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter { public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String usersQuery = "select concat(user_name, ':', user_id, ':', user_dname), password, true \n" +
"from auth_user where user_name = ?";
private static final String rolesQuery = "select t1.user_name, concat(concat('ROLE_', t1.author_name), ':', GROUP_CONCAT(COALESCE(t2.domain_id, '*'))) as role_name \n" +
"from \n" +
" (select a.user_name, d.author_name\n" +
" from auth_user a, auth_user_roles b, auth_role_authors c, auth_author d\n" +
" where a.user_id = b.user_id and b.role_id = c.role_id and c.author_id = d.author_id\n" +
" and a.user_name = substring_index(?, ':', 1)) t1\n" +
" left join\n" +
" (select a.user_name, c.domain_id\n" +
" from auth_user a, auth_user_domains b, auth_domain c\n" +
" where a.user_id = b.user_id and b.domain_id = c.domain_id) t2\n" +
"on t1.user_name = t2.user_name \n" +
"group by t1.author_name";
@Autowired
private DataSource dataSource;
@Autowired @Autowired
private RESTAuthenticationEntryPoint authenticationEntryPoint; private RESTAuthenticationEntryPoint authenticationEntryPoint;
@Autowired @Autowired
...@@ -39,22 +39,54 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { ...@@ -39,22 +39,54 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
private RESTLogoutSuccessHandler logoutSuccessHandler; private RESTLogoutSuccessHandler logoutSuccessHandler;
@Autowired @Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception { private AuthService authService;
auth.jdbcAuthentication().usersByUsernameQuery(usersQuery).authoritiesByUsernameQuery(rolesQuery)
.dataSource(dataSource).passwordEncoder(NoOpPasswordEncoder.getInstance());
}
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll();
http.csrf().disable(); http.csrf().disable();
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint); }
http.formLogin().successHandler(authenticationSuccessHandler);
http.formLogin().failureHandler(authenticationFailureHandler); @Bean
http.formLogin().loginPage("/login"); public AbstractAuthenticationProcessingFilter authenticationFilter() throws Exception {
http.formLogin().loginProcessingUrl("/signin"); AbstractAuthenticationProcessingFilter authenticationFilter = new AbstractAuthenticationProcessingFilter("/sso") {
http.logout().logoutUrl("/signout"); @Override
http.logout().logoutSuccessHandler(logoutSuccessHandler); public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
String name = "adminA";
com.keymobile.proxy.model.User u = authService.getUserByName(name);
if (u == null) {
// todo:
}
List<GrantedAuthority> authorities = new ArrayList<>();
String userName = u.getName() + ":" + u.getId() + ":" + u.getDName();
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);
}
}
Authentication auth = new UsernamePasswordAuthenticationToken(new User(userName, "whatever", authorities), null, authorities);
return auth;
}
};
authenticationFilter.setAuthenticationManager(authenticationManager());
authenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
return authenticationFilter;
} }
} }
...@@ -25,7 +25,7 @@ spring: ...@@ -25,7 +25,7 @@ spring:
timeBetweenEvictionRunsMillis: 30000 #逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1 timeBetweenEvictionRunsMillis: 30000 #逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
testOnBorrow: true #是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个 testOnBorrow: true #是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
testWhileIdle: true #在空闲时检查有效性, 默认false testWhileIdle: true #在空闲时检查有效性, 默认false
password: #密码 password:
datasource: datasource:
url: jdbc:mysql://192.168.0.192:3306/sdrcb?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
...@@ -39,7 +39,7 @@ spring: ...@@ -39,7 +39,7 @@ spring:
eureka: eureka:
client: client:
registerWithEureka: false registerWithEureka: true
region: default region: default
registryFetchIntervalSeconds: 5 registryFetchIntervalSeconds: 5
serviceUrl: serviceUrl:
...@@ -49,14 +49,13 @@ zuul: ...@@ -49,14 +49,13 @@ zuul:
prefix: /api prefix: /api
sensitive-headers: sensitive-headers:
logging: #logging:
level: # level:
org.springframework.security: DEBUG # org.springframework.security: DEBUG
security: security:
permit: true
authUser: root authUser: root
authPwd: pwd authPwd: pwd
sso: sso:
url: http://192.168.0.113:8764/sso url: http://localhost:8764/sso
\ No newline at end of file \ No newline at end of file
...@@ -3,6 +3,6 @@ spring: ...@@ -3,6 +3,6 @@ spring:
name: auth name: auth
profiles: profiles:
active: test active: test
cloud: # cloud:
config: # config:
uri: http://localhost:8082 # uri: http://localhost:8082
\ No newline at end of file \ 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