Commit c3ab6c83 by chenzx

单点登录方式改造,植入中软拦截认证

parent 52cdc784
......@@ -23,6 +23,8 @@
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
<hutool.version>5.6.3</hutool.version>
<bcprov-jdk.version>1.66</bcprov-jdk.version>
</properties>
<dependencies>
......@@ -110,6 +112,37 @@
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.portal.sso</groupId>
<artifactId>portal-sso-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/portal-sso-client-0.0.1-SNAPSHOT.jar</systemPath>
</dependency>
<dependency>
<groupId>com.portal.sso</groupId>
<artifactId>portal-sso-core</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/portal-sso-core-0.0.1-SNAPSHOT.jar</systemPath>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
<!--国密算法支持包-->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15to18</artifactId>
<version>${bcprov-jdk.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
</dependencies>
<dependencyManagement>
......
package com.keymobile.proxy.conf;
import com.keymobile.proxy.model.SsoServerProcesssor;
import com.portal.sso.client.filter.WebAppFilter;
import com.portal.sso.core.config.SsoConfig;
import com.portal.sso.core.server.JwtServerHander;
import com.portal.sso.core.server.RequestServerHandler;
import com.portal.sso.core.server.VerificationTgtServer;
import com.portal.sso.core.server.impl.JwtServerHanderImpl;
import com.portal.sso.core.server.impl.RequestServerHandlerImpl;
import com.portal.sso.core.server.impl.VerificationTgtServerImpl;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ClientSsoConfig implements DisposableBean {
@Autowired
SsoServerProcesssor ssoServerProcesssor;
@Value("${portal.sso.server}")
private String ssoServer;
@Value("${portal.sso.logout.path}")
private String ssoLogoutPath;
@Value("${portal.sso.excluded.paths}")
private String ssoExcludedPaths;
@Bean
public WebAppFilter webAppFilter(){
return new WebAppFilter();
}
@Bean
public RequestServerHandler requestServerHandler(){
return new RequestServerHandlerImpl();
}
@Bean
public VerificationTgtServer verificationTgtServer(){
VerificationTgtServer server = new VerificationTgtServerImpl();
server.setClientAppId(ssoServerProcesssor.getClientAppId());
server.setClientSecret(ssoServerProcesssor.getClientSecret());
server.setJwtServerHander(jwtServerHanderImpl());
return server;
}
@Bean
public JwtServerHander jwtServerHanderImpl(){
return new JwtServerHanderImpl();
}
@Bean
public FilterRegistrationBean PortalSsoFilterRegistration() {
// 注册拦截器
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setName("WebAppFilter");
registration.setOrder(1);
registration.addUrlPatterns("/*");
registration.setFilter(webAppFilter());
registration.addInitParameter(SsoConfig.SSO_CLIENT_SERVER, ssoServer);
registration.addInitParameter(SsoConfig.SSO_CLIENT_LOGOUT_PATH, ssoLogoutPath);
registration.addInitParameter(SsoConfig.SSO_CLIENT_EXCLUDED_PATHS, ssoExcludedPaths);
registration.addInitParameter(SsoConfig.SSO_APP_ID, ssoServerProcesssor.getClientAppId());
registration.addInitParameter(SsoConfig.SSO_SERVER_LOGIN_PATHS, ssoServerProcesssor.getLoginPath());
return registration;
}
@Override
public void destroy() throws Exception {
System.out.println("拦截器已执行完毕");
}
}
......@@ -2,57 +2,50 @@ package com.keymobile.proxy.conf;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import com.keymobile.proxy.api.Constants;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@Component
public class RESTAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
@Value("${security.allowRootLogin:true}")
private boolean rootAllowLogin = true;
@Value("${redirect-url.data-platform}")
private String go;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
clearAuthenticationAttributes(request);
String data = (String) request.getSession().getAttribute("ssoLogin");
System.out.println("come onAuthenticationSuccess here");
if(null == data){
System.out.println("getAttribute('ssoLogin') is null");
data = "ok";
}
String returnStatus = data;
//check if allow root login
String sso = (String) request.getSession().getAttribute("ssologin");
if(null == request.getSession()){
System.out.println("RESTAuthenticationSuccessHandler--SessionID-->null");
}else{
System.out.println("RESTAuthenticationSuccessHandler--SessionID-->"+request.getSession().getId());
}
String data = "ok";
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
String userNameWithIdAttached = userDetails.getUsername();
if (userNameWithIdAttached.split(":")[0].equalsIgnoreCase("root")
&& !rootAllowLogin)
returnStatus = "root not allow login";
&& !rootAllowLogin)
data = "root not allow login";
response.sendRedirect("/go");
if(null==sso || "".equals(sso.trim())){
System.out.println("走登录页面登录");
}else{
System.out.println("走单点登录");
response.sendRedirect(go);
}
PrintWriter writer = response.getWriter();
writer.write(returnStatus);
writer.write(data);
writer.flush();
writer.close();
}
......
......@@ -5,7 +5,7 @@ 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 com.keymobile.proxy.util.Des;
import com.portal.sso.core.config.SsoConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -23,10 +23,6 @@ import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
......@@ -34,7 +30,6 @@ import javax.sql.DataSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
......@@ -95,24 +90,15 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
AbstractAuthenticationProcessingFilter authenticationFilter = new AbstractAuthenticationProcessingFilter("/ssoauth") {
@Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
String portal_actionURL = httpServletRequest.getParameter("portal_actionURL");
String username = httpServletRequest.getParameter("portal_username");
String portal_password = httpServletRequest.getParameter("portal_password");
String CallBack = httpServletRequest.getParameter("CallBack");
String key = httpServletRequest.getParameter("key");
if(null == username || null == portal_password ||
null == CallBack ||null == key){
httpServletResponse.sendError(500,"sso login url missing request param");
System.out.println("开始进入单点登录......");
httpServletRequest.getSession().setAttribute("ssologin","ssoauth");
String username = httpServletRequest.getAttribute(SsoConfig.SSO_USER_ID).toString();
//String username = "icsssj";
if(null == username || "".equals(username.trim())){
httpServletResponse.sendError(500,"单点登录异常,无法获取到用户信息");
return null;
}
Des des = new Des();
String pwd = des.strDec(portal_password, key);
logger.info("sso login param->userName:"+username+" pwd:"+pwd);
if(!authenticate(username,pwd)){
httpServletResponse.sendError(500,CallBack+"({'query':{'results':{'postresult':'portal_ssologin_fali'}}});");
return null;
}
httpServletRequest.getSession().setAttribute("ssoLogin",CallBack+"({'query':{'results':{'postresult':'portal_ssologin_succeed'}}});");
System.out.println("单点用户:"+username);
com.keymobile.proxy.model.User u = authService.getUserByName(username);
if (u == null) {
u = new com.keymobile.proxy.model.User();
......@@ -120,7 +106,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
u.setPassword("37fa265330ad83eaa879efb1e2db6380896cf639");//pwd
u.setDName(username);
u = authService.addUser(new Long[] { (long) 4 }, new Long[] {}, u);
this.logger.info("单点登录新增用户:"+authService);
this.logger.info("单点登录新增用户:"+u);
System.out.println("单点登录新增用户名称:"+username);
}
List<GrantedAuthority> authorities = new ArrayList<>();
......@@ -144,6 +131,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
}
}
System.out.println("单点登录认证完成......");
Authentication auth = new UsernamePasswordAuthenticationToken(new User(userName, "whatever", authorities), null, authorities);
return auth;
}
......@@ -153,48 +141,4 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
return authenticationFilter;
}
/**
* 验证用户登录
*
* @param userName
* String 用户名格式为 username或者username@hntobacco.com
湖南内网的domain必须是@hntobacco.com,不是hnyc.com
* @param password
* String
* @return boolean
*/
public boolean authenticate(String userName, String password) {
if (password != null && !"".equals(password.trim())) {
DirContext ctx1;
try {
String domain = "@hntobacco.com";
Properties ldapEnv = new Properties();
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
ldapEnv.put(Context.PROVIDER_URL, "ldap://hntobacco.com:389");//服务器必须配置DNS,否则无法解析hntobacc.com
ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
String user = userName.indexOf(domain) > 0 ? userName : userName
+ domain;
ldapEnv.put(Context.SECURITY_PRINCIPAL, user);
ldapEnv.put(Context.SECURITY_CREDENTIALS, password);
ctx1 = new InitialDirContext(ldapEnv);
ctx1.close();
logger.info("登录验证成功!");
return true;
} catch (javax.naming.AuthenticationException e) {
logger.info("登录失败!"+e.getLocalizedMessage());
e.printStackTrace();
return false;
} catch (NamingException e) {
logger.info("登录失败!"+e.getLocalizedMessage());
e.printStackTrace();
return false;
}
} else {
logger.info("登录验证失败!");
return false;
}
}
}
\ No newline at end of file
package com.keymobile.proxy.model;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class SsoServerProcesssor {
@Value("${portal.sso.appid}")
private String clientAppId;
@Value("${portal.sso.secret}")
private String clientSecret;
@Value("${portal.sso.login.path}")
private String loginPath;
public String getClientAppId() {
return clientAppId;
}
public void setClientAppId(String clientAppId) {
this.clientAppId = clientAppId;
}
public String getClientSecret() {
return clientSecret;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public String getLoginPath() {
return loginPath;
}
public void setLoginPath(String loginPath) {
this.loginPath = loginPath;
}
}
......@@ -61,4 +61,16 @@ redirect-url:
security:
permit: false
authUser: root
authPwd: pwd
\ No newline at end of file
authPwd: pwd
portal:
sso:
server: http://10.72.66.65/sso-server
appid: sj_sjzt
secret: b14ec16eac588f44cdb95aae477652db
logout:
path: /logout
login:
path: http://login.hntobacco.com
excluded:
paths: /api/auth/sessionInfo
\ No newline at end of file
......@@ -5,11 +5,11 @@ import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
//@RunWith(SpringRunner.class)
//@SpringBootTest
public class ProxyApplicationTests {
@Test
// @Test
public void contextLoads() {
}
......
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