【单点登录】兼容自己的登录逻辑
This commit is contained in:
parent
1ca0606cc3
commit
6be1ab699e
Binary file not shown.
|
@ -228,7 +228,7 @@
|
|||
<directory>src/main/resources</directory>
|
||||
<excludes>
|
||||
<!-- 排除生产环境配置 -->
|
||||
<exclude>application-prod.yml</exclude>
|
||||
<!-- <exclude>application-prod.yml</exclude>-->
|
||||
</excludes>
|
||||
</resource>
|
||||
<resource>
|
||||
|
|
|
@ -9,6 +9,9 @@ import org.springframework.http.converter.StringHttpMessageConverter;
|
|||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Proxy;
|
||||
import java.net.SocketAddress;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Collections;
|
||||
|
||||
|
@ -27,6 +30,10 @@ public class RestTemplateConfig {
|
|||
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
|
||||
factory.setReadTimeout(30000);//单位为ms
|
||||
factory.setConnectTimeout(30000);//单位为ms
|
||||
|
||||
// SocketAddress address = new InetSocketAddress("127.0.0.1", 8888);
|
||||
// Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
|
||||
// factory.setProxy(proxy);
|
||||
return factory;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,112 +0,0 @@
|
|||
package io.renren.common.interceptor;
|
||||
|
||||
import com.yawei.pso.PSORequest;
|
||||
import com.yawei.pso.SSOResponse;
|
||||
import com.yawei.pso.TicketManager;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
/**
|
||||
* 亚微 sso拦截
|
||||
*/
|
||||
@Component
|
||||
public class IdentityInterceptor implements HandlerInterceptor {
|
||||
private static Logger logger = LoggerFactory.getLogger(IdentityInterceptor.class);
|
||||
|
||||
public final static String SEESION_USER = "seesion_user";
|
||||
|
||||
@Autowired
|
||||
private YaweiSSOProperties yaweiSSOProperties;
|
||||
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||
logger.info("==============执行顺序: 1、preHandle================");
|
||||
// 获取当前请求的url
|
||||
String requestUri = request.getRequestURI();
|
||||
|
||||
Validator validator = Validator.getInstance();
|
||||
|
||||
String strResponse = request.getParameter(yaweiSSOProperties.getSsoKey());
|
||||
if (StringUtils.isEmpty(strResponse)) {
|
||||
TicketManager tm = new TicketManager();
|
||||
if (!tm.LoadTicket(request)) {
|
||||
PSORequest psoRequest = new PSORequest(request);
|
||||
String requeststr = psoRequest.CreateHash();
|
||||
|
||||
String keeperUrl = yaweiSSOProperties.getKeeperUrl();
|
||||
keeperUrl = keeperUrl + "?" + yaweiSSOProperties.getSsoKey() + "="
|
||||
+ URLEncoder.encode(requeststr, "UTF-8");
|
||||
response.addHeader("REDIRECT", keeperUrl);
|
||||
response.sendRedirect(keeperUrl);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// 如果服务器端通过认证后,会返回后执行改操作,然后写入cookie
|
||||
SSOResponse ssoResp = new SSOResponse(strResponse);
|
||||
TicketManager tm = ssoResp.CreatePSOTicket();
|
||||
if (tm == null) {
|
||||
PSORequest psoRequest = new PSORequest(request);
|
||||
String requeststr = psoRequest.CreateHash();
|
||||
|
||||
String keeperUrl = yaweiSSOProperties.getKeeperUrl();
|
||||
keeperUrl = keeperUrl + "?" + yaweiSSOProperties.getSsoKey() + "="
|
||||
+ URLEncoder.encode(requeststr, "UTF-8");
|
||||
response.sendRedirect(keeperUrl);
|
||||
} else {
|
||||
String domainName = yaweiSSOProperties.getDomain();
|
||||
tm.SaveTicket(response, domainName);
|
||||
Iterator<Entry<String, String[]>> iterator = request
|
||||
.getParameterMap().entrySet().iterator();
|
||||
StringBuffer param = new StringBuffer();
|
||||
int i = 0;
|
||||
while (iterator.hasNext()) {
|
||||
Entry<String, String[]> entry = (Entry<String, String[]>) iterator
|
||||
.next();
|
||||
if (entry.getKey().equals(yaweiSSOProperties.getSsoKey()))
|
||||
continue;
|
||||
else {
|
||||
i++;
|
||||
if (i == 1)
|
||||
param.append("?").append(entry.getKey())
|
||||
.append("=");
|
||||
else
|
||||
param.append("&").append(entry.getKey())
|
||||
.append("=");
|
||||
|
||||
if (entry.getValue() instanceof String[]) {
|
||||
param.append(((String[]) entry.getValue())[0]);
|
||||
} else {
|
||||
param.append(entry.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
response.sendRedirect(requestUri + param.toString());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
validator.SetUserTicket(request);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
|
||||
logger.info("==============执行顺序: 2、postHandle================");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
|
||||
logger.info("==============执行顺序: 3、afterCompletion================");
|
||||
}
|
||||
}
|
|
@ -1,83 +0,0 @@
|
|||
package io.renren.common.interceptor;
|
||||
|
||||
import com.yawei.pso.TicketManager;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
/**
|
||||
* 验证器
|
||||
*/
|
||||
public class Validator {
|
||||
private static Logger logger = LoggerFactory.getLogger(Validator.class);
|
||||
private static ThreadLocal<Validator> validatorHolder = new ThreadLocal<Validator>() {
|
||||
|
||||
protected Validator initialValue() {
|
||||
return new Validator();
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
// 当前请求的session
|
||||
private HttpSession session = null;
|
||||
|
||||
// 当前的请求
|
||||
private HttpServletRequest request = null;
|
||||
|
||||
private Validator() {
|
||||
|
||||
}
|
||||
|
||||
public static Validator getInstance() {
|
||||
return validatorHolder.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行初始化
|
||||
*
|
||||
* @param httpRequest
|
||||
*/
|
||||
public void init(HttpServletRequest httpRequest) {
|
||||
this.request = httpRequest;
|
||||
this.session = request.getSession();
|
||||
}
|
||||
|
||||
/**
|
||||
* 将凭证身份加入到session
|
||||
*
|
||||
* @param httpRequest
|
||||
*/
|
||||
public void SetUserTicket(HttpServletRequest httpRequest) {
|
||||
try {
|
||||
if (httpRequest.getSession()
|
||||
.getAttribute(IdentityInterceptor.SEESION_USER) == null) {
|
||||
TicketManager ticket = new TicketManager();
|
||||
if (ticket.LoadTicket(httpRequest)) {
|
||||
// 登录用户姓名
|
||||
String userName = ticket.getUserName();
|
||||
// 登录用户账号
|
||||
String userAccount = ticket.getUserID();
|
||||
// 登录用户标识
|
||||
String userGuid = ticket.getADGUID();
|
||||
logger.info("===userName===" + userName);
|
||||
logger.info("===userAccount===" + userAccount);
|
||||
logger.info("===userGuid===" + userGuid);
|
||||
}
|
||||
} else {
|
||||
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
logger.error("", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除session
|
||||
*/
|
||||
public void cancel() {
|
||||
this.session = null;
|
||||
}
|
||||
|
||||
}
|
|
@ -21,7 +21,7 @@ import org.springframework.stereotype.Service;
|
|||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
|
@ -61,7 +61,7 @@ public class ApiGatewayService {
|
|||
throw new IllegalArgumentException(String.format("未找到对应的资源id:%s", resourceId));
|
||||
}
|
||||
String apiUrl = resourceEntity.getApiUrl();
|
||||
String methods = resourceEntity.getApiMethodType();
|
||||
String methods = resourceEntity.getApiMethodType().toUpperCase();
|
||||
|
||||
if (StringUtils.isBlank(apiUrl) || StringUtils.isBlank(methods)){
|
||||
String msg = String.format("注册api参数为空,跳过 apiUrl:%s, methods:%s, resourceId:%s", apiUrl, methods, resourceId);
|
||||
|
@ -69,7 +69,7 @@ public class ApiGatewayService {
|
|||
log.info(msg);
|
||||
return;
|
||||
}
|
||||
methods = methods.toUpperCase(Locale.ROOT);
|
||||
|
||||
//建group
|
||||
String domain = getIP(apiUrl);
|
||||
String uris = apiUrl.substring(apiUrl.indexOf(domain) + domain.length());
|
||||
|
@ -83,6 +83,11 @@ public class ApiGatewayService {
|
|||
groupEntity.put("stripPrefixPattern",String.format("^%s/(.*)", apiPrefix));
|
||||
groupEntity.put("serviceName",domain );
|
||||
|
||||
//加这个才能code认证
|
||||
Map plugins = new HashMap();
|
||||
plugins.put("key-auth", new HashMap(0));
|
||||
groupEntity.put("plugins", plugins);
|
||||
|
||||
String groupUrl = gatewayUrl + "/apiops/api/groups";
|
||||
ResponseEntity<HashMap> responseEntity = restTemplate.postForEntity(groupUrl, groupEntity, HashMap.class);
|
||||
if (responseEntity.getStatusCode() == HttpStatus.OK && responseEntity.hasBody()) {
|
||||
|
|
|
@ -124,11 +124,11 @@ public class ResourceEntity extends BaseEntity {
|
|||
/**
|
||||
* 下架理由
|
||||
*/
|
||||
private String undercarriageReason;
|
||||
// private String undercarriageReason;
|
||||
|
||||
|
||||
/**
|
||||
* 提起下架人员
|
||||
*/
|
||||
private String undercarriageUserName;
|
||||
// private String undercarriageUserName;
|
||||
}
|
|
@ -4,7 +4,6 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
|
|||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
import io.renren.common.interceptor.IdentityInterceptor;
|
||||
import io.renren.common.utils.DateUtils;
|
||||
import io.renren.modules.pay.Interceptor.AliPayInterceptor;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
@ -27,9 +26,6 @@ import java.util.TimeZone;
|
|||
@Configuration
|
||||
public class WebMvcConfig implements WebMvcConfigurer {
|
||||
|
||||
@Autowired
|
||||
private IdentityInterceptor identityInterceptor;
|
||||
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
|
|
|
@ -6,12 +6,13 @@ import io.renren.common.exception.RenException;
|
|||
import io.renren.common.utils.IpUtils;
|
||||
import io.renren.common.utils.Result;
|
||||
import io.renren.common.validator.AssertUtils;
|
||||
import io.renren.common.validator.ValidatorUtils;
|
||||
import io.renren.modules.log.entity.SysLogLoginEntity;
|
||||
import io.renren.modules.log.enums.LoginOperationEnum;
|
||||
import io.renren.modules.log.enums.LoginStatusEnum;
|
||||
import io.renren.modules.log.service.SysLogLoginService;
|
||||
import io.renren.modules.security.dto.LoginDTO;
|
||||
import io.renren.modules.security.oauth2.Oauth2Filter;
|
||||
import io.renren.modules.security.oauth2.YaWeiCookieManage;
|
||||
import io.renren.modules.security.password.PasswordUtils;
|
||||
import io.renren.modules.security.service.CaptchaService;
|
||||
import io.renren.modules.security.service.SysUserTokenService;
|
||||
|
@ -71,7 +72,7 @@ public class LoginController {
|
|||
@ApiImplicitParam(name = "uuid", value = "UUID", paramType = "query",required = true, dataType="String"),
|
||||
})
|
||||
// public Result login(HttpServletRequest request, @RequestBody LoginDTO login) {
|
||||
public Result login(HttpServletRequest request, @ApiIgnore @RequestParam Map<String, Object> params) {
|
||||
public Result login(HttpServletRequest request, HttpServletResponse response, @ApiIgnore @RequestParam Map<String, Object> params) throws Exception {
|
||||
|
||||
LoginDTO login = new LoginDTO();
|
||||
login.setUsername(String.valueOf(params.get("username")));
|
||||
|
@ -132,16 +133,21 @@ public class LoginController {
|
|||
log.setCreatorName(user.getUsername());
|
||||
sysLogLoginService.save(log);
|
||||
|
||||
return sysUserTokenService.createToken(user.getId());
|
||||
Result<Map> token = sysUserTokenService.createToken(user.getId());
|
||||
request.setAttribute(Constant.TOKEN_HEADER, token.getData().get(Constant.TOKEN_HEADER));
|
||||
new Oauth2Filter().login(request, response);
|
||||
return token;
|
||||
}
|
||||
|
||||
@PostMapping("logout")
|
||||
@ApiOperation(value = "退出")
|
||||
public Result logout(HttpServletRequest request) {
|
||||
public Result logout(HttpServletRequest request, HttpServletResponse response) {
|
||||
UserDetail user = SecurityUser.getUser();
|
||||
|
||||
//退出
|
||||
sysUserTokenService.logout(user.getId());
|
||||
//清理亚威登录状态
|
||||
YaWeiCookieManage.clearnTicket(request, response);
|
||||
|
||||
//用户信息
|
||||
SysLogLoginEntity log = new SysLogLoginEntity();
|
||||
|
|
|
@ -1,14 +1,19 @@
|
|||
package io.renren.modules.security.oauth2;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.google.gson.Gson;
|
||||
import com.yawei.pso.PSORequest;
|
||||
import com.yawei.pso.SSOResponse;
|
||||
import com.yawei.pso.TicketManager;
|
||||
import io.renren.common.constant.Constant;
|
||||
import io.renren.common.interceptor.Validator;
|
||||
import io.renren.common.interceptor.YaweiSSOProperties;
|
||||
import io.renren.common.utils.HttpContextUtils;
|
||||
import io.renren.common.utils.Result;
|
||||
import io.renren.modules.security.service.SysUserTokenService;
|
||||
import io.renren.modules.security.user.SecurityUser;
|
||||
import io.renren.modules.sys.dao.SysUserDao;
|
||||
import io.renren.modules.sys.entity.SysUserEntity;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.apache.shiro.authc.AuthenticationException;
|
||||
|
@ -21,32 +26,40 @@ import org.springframework.web.bind.annotation.RequestMethod;
|
|||
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.net.URL;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* oauth2过滤器
|
||||
*
|
||||
*/
|
||||
@Component()
|
||||
@Scope("prototype")
|
||||
public class Oauth2Filter extends AuthenticatingFilter {
|
||||
|
||||
public final static String SEESION_USER = "seesion_user";
|
||||
public class Oauth2Filter extends AuthenticatingFilter {
|
||||
|
||||
@Autowired
|
||||
private YaweiSSOProperties yaweiSSOProperties;
|
||||
|
||||
@Autowired
|
||||
private SysUserTokenService sysUserTokenService;
|
||||
|
||||
@Autowired
|
||||
private SysUserDao sysUserDao;
|
||||
|
||||
@Override
|
||||
protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
|
||||
//获取请求token
|
||||
String token = getRequestToken((HttpServletRequest) request);
|
||||
|
||||
if (StringUtils.isBlank(token)) {
|
||||
if(StringUtils.isBlank(token)){
|
||||
return null;
|
||||
}
|
||||
|
||||
|
@ -55,37 +68,77 @@ public class Oauth2Filter extends AuthenticatingFilter {
|
|||
|
||||
@Override
|
||||
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
|
||||
if (((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())) {
|
||||
return true;
|
||||
}
|
||||
// if(((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())){
|
||||
// return true;
|
||||
// }
|
||||
String currentToken = getRequestToken((HttpServletRequest) request);
|
||||
if (StringUtils.isBlank(currentToken) || SecurityUser.getUser().getUsername() == null)
|
||||
return false;
|
||||
|
||||
return false;
|
||||
//亚威没有测试环境,不验证他了
|
||||
// if (currentToken == null || !(new TicketManager().LoadTicket((HttpServletRequest) request)))
|
||||
// return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
|
||||
|
||||
boolean yaweiHandle = yaweiHandle((HttpServletRequest) request, (HttpServletResponse) response);
|
||||
if (yaweiHandle){
|
||||
//处理成功肯定从cookie或写cookie拿到了认证信息
|
||||
//亚威认证通过,为自己添加上token
|
||||
TicketManager tm = new TicketManager();
|
||||
String currentUser = null;
|
||||
if (tm.LoadTicket((HttpServletRequest) request)) {
|
||||
currentUser = tm.getUserID();
|
||||
}else {
|
||||
currentUser = getYaweiUserIdCookieInResponse((HttpServletResponse) response);
|
||||
currentUser = tm.DecData(currentUser);
|
||||
}
|
||||
|
||||
//获取请求token,如果token不存在,直接返回401
|
||||
String token = getRequestToken((HttpServletRequest) request);
|
||||
if (StringUtils.isBlank(token)) {
|
||||
if (currentUser != null ) {
|
||||
LambdaQueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<SysUserEntity>().lambda()
|
||||
.eq(SysUserEntity::getUsername, currentUser);
|
||||
SysUserEntity sysUserEntity = sysUserDao.selectOne(queryWrapper);
|
||||
if (sysUserEntity != null) {
|
||||
String currentToken = getRequestToken((HttpServletRequest) request);
|
||||
HttpServletResponse httpresponse = (HttpServletResponse)response;
|
||||
if (StringUtils.isBlank(currentToken)){
|
||||
Result<Map> result = sysUserTokenService.createToken(sysUserEntity.getId());
|
||||
Object token = result.getData().get(Constant.TOKEN_HEADER);
|
||||
currentToken = (String) token;
|
||||
Cookie cookie = new Cookie(Constant.TOKEN_HEADER, currentToken);
|
||||
cookie.setPath("/");
|
||||
httpresponse.addCookie(cookie);
|
||||
httpresponse.addHeader(Constant.TOKEN_HEADER, currentToken);
|
||||
httpresponse.addHeader("REDIRECT", ((HttpServletRequest) request).getHeader("REQUESTURI"));
|
||||
}
|
||||
|
||||
yaweiHandle((HttpServletRequest) request, (HttpServletResponse) response);
|
||||
request.setAttribute(Constant.TOKEN_HEADER, currentToken);
|
||||
// return executeLogin(request, response);
|
||||
boolean success = executeLogin(request, response);
|
||||
if (success){
|
||||
// httpresponse.addHeader("REDIRECT", ((HttpServletRequest) request).getHeader("REQUESTURI"));
|
||||
// httpresponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
|
||||
// httpresponse.getWriter().write(HttpStatus.SC_UNAUTHORIZED);
|
||||
}
|
||||
return success;
|
||||
}
|
||||
}
|
||||
|
||||
// HttpServletResponse httpResponse = (HttpServletResponse) response;
|
||||
// httpResponse.setContentType("application/json;charset=utf-8");
|
||||
// httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
|
||||
// httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
|
||||
//
|
||||
// String json = new Gson().toJson(new Result().error(ErrorCode.UNAUTHORIZED));
|
||||
//
|
||||
// httpResponse.getWriter().print(json);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean executeLogin = executeLogin(request, response);
|
||||
return executeLogin;
|
||||
return false;
|
||||
}
|
||||
|
||||
private String getYaweiUserIdCookieInResponse(HttpServletResponse response){
|
||||
String userIdKey = "UserID=";
|
||||
for (String header : response.getHeaders("set-cookie")) {
|
||||
if (header.startsWith(userIdKey)) return header.substring(userIdKey.length());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -108,47 +161,63 @@ public class Oauth2Filter extends AuthenticatingFilter {
|
|||
return false;
|
||||
}
|
||||
|
||||
public boolean login(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
return executeLogin(request, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取请求的token
|
||||
*/
|
||||
private String getRequestToken(HttpServletRequest httpRequest) {
|
||||
private String getRequestToken(HttpServletRequest httpRequest){
|
||||
//从header中获取token
|
||||
String token = httpRequest.getHeader(Constant.TOKEN_HEADER);
|
||||
|
||||
if(StringUtils.isBlank(token)){
|
||||
token = (String) httpRequest.getAttribute(Constant.TOKEN_HEADER);
|
||||
}
|
||||
|
||||
//如果header中不存在token,则从参数中获取token
|
||||
if (StringUtils.isBlank(token)) {
|
||||
if(StringUtils.isBlank(token)){
|
||||
token = httpRequest.getParameter(Constant.TOKEN_HEADER);
|
||||
}
|
||||
|
||||
|
||||
if(StringUtils.isBlank(token)){
|
||||
Cookie[] cookies = httpRequest.getCookies();
|
||||
if (cookies != null){
|
||||
for (Cookie cookie : cookies) {
|
||||
if (Constant.TOKEN_HEADER.equalsIgnoreCase(cookie.getName())) {
|
||||
token = cookie.getValue();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
public boolean yaweiHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
private boolean yaweiHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
// 获取当前请求的url
|
||||
String requestUri = request.getHeader("REQUESTURI");
|
||||
if (requestUri == null) {
|
||||
if (requestUri == null){
|
||||
requestUri = request.getRequestURI();
|
||||
}
|
||||
|
||||
Validator validator = Validator.getInstance();
|
||||
|
||||
String strResponse = request.getParameter(yaweiSSOProperties.getSsoKey());
|
||||
|
||||
if (strResponse == null && requestUri != null && requestUri.indexOf(yaweiSSOProperties.getSsoKey()) > 0) {
|
||||
String ssoMatchKey = yaweiSSOProperties.getSsoKey() + "=";
|
||||
int startIndex = requestUri.indexOf(ssoMatchKey) + ssoMatchKey.length();
|
||||
int indexOf = requestUri.indexOf("&", startIndex);
|
||||
|
||||
strResponse = indexOf > 0 ? requestUri.substring(startIndex, indexOf) : requestUri.substring(startIndex);
|
||||
}
|
||||
if (org.apache.commons.lang.StringUtils.isEmpty(strResponse)) {
|
||||
TicketManager tm = new TicketManager();
|
||||
if (!tm.LoadTicket(request)) {
|
||||
PSORequest psoRequest = new PSORequest(request);
|
||||
//不建新类了,直接反射解决
|
||||
Field returnUrl = psoRequest.getClass().getDeclaredField("returnUrl");
|
||||
returnUrl.setAccessible(true);
|
||||
returnUrl.set(psoRequest, requestUri);
|
||||
String requeststr = psoRequest.CreateHash();
|
||||
|
||||
String keeperUrl = yaweiSSOProperties.getKeeperUrl();
|
||||
keeperUrl = keeperUrl + "?" + yaweiSSOProperties.getSsoKey() + "="
|
||||
+ URLEncoder.encode(requeststr, "UTF-8");
|
||||
response.addHeader("REDIRECT", keeperUrl);
|
||||
response.setStatus(HttpStatus.SC_UNAUTHORIZED);
|
||||
response.getWriter().write(HttpStatus.SC_UNAUTHORIZED);
|
||||
redirectToYaweiLogin(request, response);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
|
@ -156,53 +225,37 @@ public class Oauth2Filter extends AuthenticatingFilter {
|
|||
SSOResponse ssoResp = new SSOResponse(strResponse);
|
||||
TicketManager tm = ssoResp.CreatePSOTicket();
|
||||
if (tm == null) {
|
||||
PSORequest psoRequest = new PSORequest(request);
|
||||
String requeststr = psoRequest.CreateHash();
|
||||
|
||||
String keeperUrl = yaweiSSOProperties.getKeeperUrl();
|
||||
keeperUrl = keeperUrl + "?" + yaweiSSOProperties.getSsoKey() + "="
|
||||
+ URLEncoder.encode(requeststr, "UTF-8");
|
||||
response.sendRedirect(keeperUrl);
|
||||
} else {
|
||||
String domainName = yaweiSSOProperties.getDomain();
|
||||
tm.SaveTicket(response, domainName);
|
||||
|
||||
//同时添加自己的token
|
||||
// Cookie cookie = new Cookie(Constant.TOKEN_HEADER, createToken(request, response).toString());
|
||||
// response.addCookie(cookie);
|
||||
|
||||
Iterator<Map.Entry<String, String[]>> iterator = request
|
||||
.getParameterMap().entrySet().iterator();
|
||||
StringBuffer param = new StringBuffer();
|
||||
int i = 0;
|
||||
while (iterator.hasNext()) {
|
||||
Map.Entry<String, String[]> entry = (Map.Entry<String, String[]>) iterator
|
||||
.next();
|
||||
if (entry.getKey().equals(yaweiSSOProperties.getSsoKey()))
|
||||
continue;
|
||||
else {
|
||||
i++;
|
||||
if (i == 1)
|
||||
param.append("?").append(entry.getKey())
|
||||
.append("=");
|
||||
else
|
||||
param.append("&").append(entry.getKey())
|
||||
.append("=");
|
||||
|
||||
if (entry.getValue() instanceof String[]) {
|
||||
param.append(((String[]) entry.getValue())[0]);
|
||||
} else {
|
||||
param.append(entry.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
response.sendRedirect(requestUri + param.toString());
|
||||
redirectToYaweiLogin(request, response);
|
||||
return false;
|
||||
} else {
|
||||
// String domainName = yaweiSSOProperties.getDomain();
|
||||
// tm.SaveTicket(response, domainName);
|
||||
YaWeiCookieManage.saveTicket(response, tm);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
validator.SetUserTicket(request);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void redirectToYaweiLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, IllegalAccessException, NoSuchFieldException {
|
||||
String requestUri = request.getHeader("REQUESTURI");
|
||||
if (requestUri == null){
|
||||
requestUri = request.getRequestURI();
|
||||
}
|
||||
PSORequest psoRequest = new PSORequest(request);
|
||||
//不建新类了,直接反射解决
|
||||
Field returnUrl = psoRequest.getClass().getDeclaredField("returnUrl");
|
||||
returnUrl.setAccessible(true);
|
||||
returnUrl.set(psoRequest, requestUri);
|
||||
String requeststr = psoRequest.CreateHash();
|
||||
|
||||
String keeperUrl = yaweiSSOProperties.getKeeperUrl();
|
||||
keeperUrl = keeperUrl + "?" + yaweiSSOProperties.getSsoKey() + "="
|
||||
+ URLEncoder.encode(requeststr, "UTF-8");
|
||||
response.addHeader("REDIRECT", keeperUrl);
|
||||
response.setStatus(HttpStatus.SC_UNAUTHORIZED);
|
||||
response.getWriter().write(HttpStatus.SC_UNAUTHORIZED);
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
package io.renren.modules.security.oauth2;
|
||||
|
||||
import com.yawei.pso.TicketManager;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class YaWeiCookieManage {
|
||||
|
||||
public final static HashSet<String> yaweCookieNames = new HashSet();
|
||||
static {
|
||||
String[] names = {"UserID","UserPass","ADGuid","UserName","TicketData","CreateDate","OrigGUID","OrigName"};
|
||||
Collections.addAll(yaweCookieNames, names);
|
||||
}
|
||||
public static void saveTicket(HttpServletResponse response, TicketManager ticketManager){
|
||||
|
||||
for (String cookieName : yaweCookieNames) {
|
||||
try {
|
||||
Field declaredField = ticketManager.getClass().getDeclaredField(cookieName);
|
||||
declaredField.setAccessible(true);
|
||||
Cookie cookie = new Cookie(cookieName, (String) declaredField.get(ticketManager));
|
||||
cookie.setPath("/");
|
||||
response.addCookie(cookie);
|
||||
} catch (Exception e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void clearnTicket(HttpServletRequest request, HttpServletResponse response){
|
||||
|
||||
for (Cookie cookie : request.getCookies()) {
|
||||
if (yaweCookieNames.contains(cookie.getName())){
|
||||
cookie.setPath("/");
|
||||
cookie.setMaxAge(0);
|
||||
response.addCookie(cookie);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -55,4 +55,7 @@ logging:
|
|||
engine:
|
||||
impl:
|
||||
persistence:
|
||||
entity: debug
|
||||
entity: debug
|
||||
mybatis-plus:
|
||||
configuration:
|
||||
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
|
|
@ -46,4 +46,4 @@ big_date:
|
|||
|
||||
hisense:
|
||||
gateway:
|
||||
url: http://devtest-security-app.hismarttv.com:8080
|
||||
url: http://15.72.184.7:8080
|
|
@ -1,3 +1,3 @@
|
|||
sso.domain=127.0.0.1:8080
|
||||
sso.domain=jhoa.qd.gov.cn
|
||||
sso.ssoKey=SSOToken
|
||||
sso.keeperUrl=http://jhoa.qd.gov.cn
|
||||
sso.keeperUrl=http://jhoa.qd.gov.cn/Keeper.aspx
|
|
@ -1,8 +1,12 @@
|
|||
package io.renren;
|
||||
|
||||
import cn.hutool.core.lang.UUID;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import io.renren.common.redis.RedisUtils;
|
||||
import io.renren.modules.processForm.service.ApiGatewayService;
|
||||
import io.renren.modules.resource.dao.ResourceDao;
|
||||
import io.renren.modules.resource.entity.ResourceEntity;
|
||||
import io.renren.modules.sys.entity.SysUserEntity;
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
import org.junit.Test;
|
||||
|
@ -11,15 +15,34 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
public class ApiGatewayServiceTest {
|
||||
@Autowired
|
||||
private ApiGatewayService apiGatewayService;
|
||||
|
||||
@Autowired
|
||||
private ResourceDao resourceDao;
|
||||
|
||||
@Test
|
||||
public void registerApi2Gateway() {
|
||||
apiGatewayService.registerApi2Gateway("1522550194523152385");
|
||||
// String[] resourceIds = {"1522550194833530884","1522550194535735298","1522550194544123906"};
|
||||
// for (String resourceId : resourceIds) {
|
||||
// apiGatewayService.registerApi2Gateway(resourceId);
|
||||
// }
|
||||
|
||||
LambdaQueryWrapper<ResourceEntity> select = new QueryWrapper<ResourceEntity>().lambda()
|
||||
.select(ResourceEntity::getId)
|
||||
.eq(ResourceEntity::getType, "组件服务")
|
||||
.in(ResourceEntity::getApiMethodType, new String[]{"POST", "GET"})
|
||||
.like(ResourceEntity::getApiUrl,"http%");
|
||||
List<ResourceEntity> resourceEntities = resourceDao.selectList(select);
|
||||
resourceEntities.forEach(item -> {
|
||||
apiGatewayService.registerApi2Gateway(String.valueOf(item.getId()));
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
Loading…
Reference in New Issue