Commit 35121208 by chenzx

单点登录认证代码整理

parent 4a840a45
......@@ -2,6 +2,7 @@ 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;
......@@ -30,7 +31,7 @@ public class SSOCtrl {
private String dataPlatformURL;
@Autowired
private UserService userService;
private AuthService authService;
@GetMapping("/go")
public String doJump(Map<String, Object> model) {
......@@ -40,66 +41,26 @@ public class SSOCtrl {
return "main";
}
@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);
@GetMapping("/refuse")
public String refuse(Map<String, Object> model,
@RequestParam(value = "code",required = false) String code) {
model.put("success", false);
switch (code){
case "401":
model.put("msg", "缺少token参数,验证失败");
break;
case "402":
model.put("msg", "Token验证异常,请重试");
break;
case "403":
model.put("msg", "单点登录异常,请联系管理员");
return "main";
}
break;
case "405":
model.put("msg", "Token验证失败,请联系管理员");
break;
}
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() {
@RequestMapping("/token")
public String token() {
return "{" +
" \"data\": {" +
" \"clientIp\": \"192.168.58.10\"," +
......@@ -38,7 +28,7 @@ public class TestCtrl {
" \"languageCode\": \"zh_CN\"," +
" \"lastTime\": \"2020-10-26 18:41:57\"," +
" \"lockTime\": null," +
" \"loginName\": \"czx\"," +
" \"loginName\": \"adminA\"," +
" \"loginStatusId\": \"4f1e3997177711eba2dc2d94a378ce32\"," +
" \"loginTime\": \"2020-10-26 18:37:56\"," +
" \"products\": \"CONSOLE\"," +
......
......@@ -29,12 +29,16 @@ public class RESTAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuc
clearAuthenticationAttributes(request);
String returnStatus = "ok";
//check if allow root login
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
String userNameWithIdAttached = userDetails.getUsername();
if (userNameWithIdAttached.split(":")[0].equalsIgnoreCase("root")
&& !rootAllowLogin)
returnStatus = "root not allow login";
//单点登录认证成功直接跳转首页
response.sendRedirect("/go");
PrintWriter writer = response.getWriter();
writer.write(returnStatus);
writer.flush();
......
package com.keymobile.proxy.conf;
import com.alibaba.fastjson.JSONObject;
import com.keymobile.proxy.api.Constants;
import com.keymobile.proxy.api.SSOCtrl;
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.Value;
import org.springframework.context.annotation.Bean;
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.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
......@@ -17,6 +22,8 @@ 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 org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
......@@ -41,6 +48,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthService authService;
@Value("${sso.url}")
private String ssoUrl;
@Override
protected void configure(HttpSecurity http) throws Exception {
......@@ -52,13 +61,50 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
AbstractAuthenticationProcessingFilter authenticationFilter = new AbstractAuthenticationProcessingFilter("/sso") {
@Override
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:
String loginName = "";
String token = httpServletRequest.getParameter("token");
if(null == token){
httpServletResponse.sendRedirect("/refuse?code=401");
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<>();
String userName = u.getName() + ":" + u.getId() + ":" + u.getDName();
......@@ -89,4 +135,23 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
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:
spring:
application:
name: auth
name: ssologin
session:
store-type: redis
redis:
......@@ -58,4 +58,4 @@ security:
authPwd: pwd
sso:
url: http://localhost:8764/sso
\ No newline at end of file
url: http://localhost:8764/token
\ 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