Commit 35121208 by chenzx

单点登录认证代码整理

parent 4a840a45
...@@ -2,6 +2,7 @@ package com.keymobile.proxy.api; ...@@ -2,6 +2,7 @@ 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;
...@@ -30,7 +31,7 @@ public class SSOCtrl { ...@@ -30,7 +31,7 @@ public class SSOCtrl {
private String dataPlatformURL; private String dataPlatformURL;
@Autowired @Autowired
private UserService userService; private AuthService authService;
@GetMapping("/go") @GetMapping("/go")
public String doJump(Map<String, Object> model) { public String doJump(Map<String, Object> model) {
...@@ -40,66 +41,26 @@ public class SSOCtrl { ...@@ -40,66 +41,26 @@ public class SSOCtrl {
return "main"; return "main";
} }
@GetMapping("/main") @GetMapping("/refuse")
public String getDataPlatformMainView(Map<String, Object> model, public String refuse(Map<String, Object> model,
@RequestParam(value = "token",required = false) String token) { @RequestParam(value = "code",required = false) String code) {
model.put("success", true); model.put("success", false);
model.put("redirect-url", dataPlatformURL); switch (code){
model.put("msg", "验证成功"); case "401":
if(null == token ||"".equals(token)){ model.put("msg", "缺少token参数,验证失败");
model.put("success", false); break;
model.put("msg", "缺少token参数,验证失败"); case "402":
return "main"; model.put("msg", "Token验证异常,请重试");
} break;
this.logger.info("单点登录验证token:"+token); case "403":
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", "单点登录异常,请联系管理员"); model.put("msg", "单点登录异常,请联系管理员");
return "main"; break;
} case "405":
model.put("msg", "Token验证失败,请联系管理员");
break;
} }
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; 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.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
@RestController @RestController
public class TestCtrl { public class TestCtrl {
@RequestMapping("/sso") @RequestMapping("/token")
public String sso() { public String token() {
return "{" + return "{" +
" \"data\": {" + " \"data\": {" +
" \"clientIp\": \"192.168.58.10\"," + " \"clientIp\": \"192.168.58.10\"," +
...@@ -38,7 +28,7 @@ public class TestCtrl { ...@@ -38,7 +28,7 @@ public class TestCtrl {
" \"languageCode\": \"zh_CN\"," + " \"languageCode\": \"zh_CN\"," +
" \"lastTime\": \"2020-10-26 18:41:57\"," + " \"lastTime\": \"2020-10-26 18:41:57\"," +
" \"lockTime\": null," + " \"lockTime\": null," +
" \"loginName\": \"czx\"," + " \"loginName\": \"adminA\"," +
" \"loginStatusId\": \"4f1e3997177711eba2dc2d94a378ce32\"," + " \"loginStatusId\": \"4f1e3997177711eba2dc2d94a378ce32\"," +
" \"loginTime\": \"2020-10-26 18:37:56\"," + " \"loginTime\": \"2020-10-26 18:37:56\"," +
" \"products\": \"CONSOLE\"," + " \"products\": \"CONSOLE\"," +
......
...@@ -29,12 +29,16 @@ public class RESTAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuc ...@@ -29,12 +29,16 @@ public class RESTAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuc
clearAuthenticationAttributes(request); clearAuthenticationAttributes(request);
String returnStatus = "ok"; String returnStatus = "ok";
//check if allow root login //check if allow root login
UserDetails userDetails = (UserDetails) authentication.getPrincipal(); UserDetails userDetails = (UserDetails) authentication.getPrincipal();
String userNameWithIdAttached = userDetails.getUsername(); String userNameWithIdAttached = userDetails.getUsername();
if (userNameWithIdAttached.split(":")[0].equalsIgnoreCase("root") if (userNameWithIdAttached.split(":")[0].equalsIgnoreCase("root")
&& !rootAllowLogin) && !rootAllowLogin)
returnStatus = "root not allow login"; returnStatus = "root not allow login";
//单点登录认证成功直接跳转首页
response.sendRedirect("/go");
PrintWriter writer = response.getWriter(); PrintWriter writer = response.getWriter();
writer.write(returnStatus); writer.write(returnStatus);
writer.flush(); writer.flush();
......
package com.keymobile.proxy.conf; package com.keymobile.proxy.conf;
import com.alibaba.fastjson.JSONObject;
import com.keymobile.proxy.api.Constants; import com.keymobile.proxy.api.Constants;
import com.keymobile.proxy.api.SSOCtrl;
import com.keymobile.proxy.model.Author; import com.keymobile.proxy.model.Author;
import com.keymobile.proxy.model.Domain; import com.keymobile.proxy.model.Domain;
import com.keymobile.proxy.model.Role; import com.keymobile.proxy.model.Role;
import com.keymobile.proxy.service.AuthService; import com.keymobile.proxy.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 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;
...@@ -17,6 +22,8 @@ import org.springframework.security.core.GrantedAuthority; ...@@ -17,6 +22,8 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
...@@ -41,6 +48,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { ...@@ -41,6 +48,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired @Autowired
private AuthService authService; private AuthService authService;
@Value("${sso.url}")
private String ssoUrl;
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
...@@ -52,13 +61,50 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { ...@@ -52,13 +61,50 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
AbstractAuthenticationProcessingFilter authenticationFilter = new AbstractAuthenticationProcessingFilter("/sso") { AbstractAuthenticationProcessingFilter authenticationFilter = new AbstractAuthenticationProcessingFilter("/sso") {
@Override @Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException { public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
String name = "adminA"; String loginName = "";
String token = httpServletRequest.getParameter("token");
com.keymobile.proxy.model.User u = authService.getUserByName(name); if(null == token){
if (u == null) { httpServletResponse.sendRedirect("/refuse?code=401");
// todo: return null;
}
String flag = checkToken(ssoUrl+"?token="+token,HttpMethod.POST,null);
if("".equals(flag)){
httpServletResponse.sendRedirect("/refuse?code=402");
return null;
}else{
try {
JSONObject jo = JSONObject.parseObject(flag);
boolean success = jo.getBoolean("success");
String message = jo.getString("message");
if(!success){
httpServletResponse.sendRedirect("/refuse?code=405");
return null;
}
JSONObject data = jo.getJSONObject("data");
loginName = data.getString("loginName");
String userName = data.getString("userName");
com.keymobile.proxy.model.User u = authService.getUserByName(loginName);
if (u == null) {
u = new com.keymobile.proxy.model.User();
u.setName(loginName);
u.setPassword("37fa265330ad83eaa879efb1e2db6380896cf639");
u.setDName(userName);
u = authService.addUser(new Long[] { (long) 4 }, new Long[] {}, u);
this.logger.info("单点登录新增用户:"+loginName);
}
this.logger.info(loginName+"单点登录成功");
}catch (Exception e){
e.printStackTrace();
httpServletResponse.sendRedirect("/refuse?code=403");
return null;
}
} }
com.keymobile.proxy.model.User u = authService.getUserByName(loginName);
// if (u == null) {
// // todo:
// }
List<GrantedAuthority> authorities = new ArrayList<>(); List<GrantedAuthority> authorities = new ArrayList<>();
String userName = u.getName() + ":" + u.getId() + ":" + u.getDName(); String userName = u.getName() + ":" + u.getId() + ":" + u.getDName();
...@@ -89,4 +135,23 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { ...@@ -89,4 +135,23 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
return authenticationFilter; return authenticationFilter;
} }
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();
return "";
}
}
} }
...@@ -7,7 +7,7 @@ redirect-url: ...@@ -7,7 +7,7 @@ redirect-url:
spring: spring:
application: application:
name: auth name: ssologin
session: session:
store-type: redis store-type: redis
redis: redis:
...@@ -58,4 +58,4 @@ security: ...@@ -58,4 +58,4 @@ security:
authPwd: pwd authPwd: pwd
sso: sso:
url: http://localhost:8764/sso url: http://localhost:8764/token
\ 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