v2.9.0 FIX

This commit is contained in:
MaxKey 2021-08-23 11:12:49 +08:00
parent 68d462003a
commit bc91908667
14 changed files with 197 additions and 162 deletions

View File

@ -134,6 +134,7 @@ public abstract class AbstractAuthenticationProvider {
HashMap<String,Object> sessionAttributeMap = new HashMap<String,Object>();
for(String attributeName : WebContext.sessionAttributeNameList) {
sessionAttributeMap.put(attributeName, WebContext.getAttribute(attributeName));
WebContext.removeAttribute(attributeName);
}
//new Session
@ -143,7 +144,9 @@ public abstract class AbstractAuthenticationProvider {
WebContext.setAttribute(attributeName, sessionAttributeMap.get(attributeName));
}
_logger.debug("Login Success Session {}.", WebContext.getSession().getId());
_logger.debug("Login Success Session {} Mapping to user Session {}.",
WebContext.getSession().getId(),
WebContext.getAttribute(WebConstants.CURRENT_USER_SESSION_ID));
}

View File

@ -185,8 +185,8 @@ public class LoginCredential implements Authentication {
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("BasicAuthentication [username=").append(username)
.append(", password=").append(password)
builder.append("LoginCredential [username=").append(username)
.append(", password=").append("******")
.append(", sessionId=").append(sessionId)
.append(", captcha=").append(captcha)
.append(", otpCaptcha=").append(otpCaptcha)

View File

@ -24,6 +24,7 @@ import javax.servlet.http.HttpServletResponse;
import org.maxkey.authn.support.rememberme.AbstractRemeberMeService;
import org.maxkey.entity.Groups;
import org.maxkey.entity.HistoryLogin;
import org.maxkey.entity.UserInfo;
import org.maxkey.persistence.db.LoginHistoryService;
import org.maxkey.persistence.db.PasswordPolicyValidator;
@ -134,55 +135,32 @@ public abstract class AbstractAuthenticationRealm {
* @param message
*/
public boolean insertLoginHistory(UserInfo userInfo, String type, String provider, String code, String message) {
String sessionId = WebContext.genId();
int sessionStatus = 7;
HistoryLogin historyLogin = new HistoryLogin();
historyLogin.setSessionId(WebContext.genId());
historyLogin.setSessionStatus(7);
if(WebContext.getAttribute(WebConstants.CURRENT_USER_SESSION_ID) !=null) {
sessionStatus = 1;
sessionId = WebContext.getAttribute(WebConstants.CURRENT_USER_SESSION_ID).toString();
historyLogin.setSessionStatus(1);
historyLogin.setSessionId(WebContext.getAttribute(WebConstants.CURRENT_USER_SESSION_ID).toString());
}
_logger.debug("user session id is {} . ",sessionId);
_logger.debug("user session id is {} . ",historyLogin.getSessionId());
userInfo.setLastLoginTime(DateUtils.formatDateTime(new Date()));
userInfo.setLastLoginIp(WebContext.getRequestIpAddress());
String platform = "";
String browser = "";
String userAgent = WebContext.getRequest().getHeader("User-Agent");
String[] arrayUserAgent = null;
if (userAgent.indexOf("MSIE") > 0) {
arrayUserAgent = userAgent.split(";");
browser = arrayUserAgent[1].trim();
platform = arrayUserAgent[2].trim();
} else if (userAgent.indexOf("Trident") > 0) {
arrayUserAgent = userAgent.split(";");
browser = "MSIE/" + arrayUserAgent[3].split("\\)")[0];
;
platform = arrayUserAgent[0].split("\\(")[1];
} else if (userAgent.indexOf("Chrome") > 0) {
arrayUserAgent = userAgent.split(" ");
// browser=arrayUserAgent[8].trim();
for (int i = 0; i < arrayUserAgent.length; i++) {
if (arrayUserAgent[i].contains("Chrome")) {
browser = arrayUserAgent[i].trim();
browser = browser.substring(0, browser.indexOf('.'));
}
}
platform = (arrayUserAgent[1].substring(1) + " " + arrayUserAgent[2] + " "
+ arrayUserAgent[3].substring(0, arrayUserAgent[3].length() - 1)).trim();
} else if (userAgent.indexOf("Firefox") > 0) {
arrayUserAgent = userAgent.split(" ");
for (int i = 0; i < arrayUserAgent.length; i++) {
if (arrayUserAgent[i].contains("Firefox")) {
browser = arrayUserAgent[i].trim();
browser = browser.substring(0, browser.indexOf('.'));
}
}
platform = (arrayUserAgent[1].substring(1) + " " + arrayUserAgent[2] + " "
+ arrayUserAgent[3].substring(0, arrayUserAgent[3].length() - 1)).trim();
}
loginHistoryService.login(userInfo,sessionId, type, message, code, provider, browser, platform,sessionStatus);
Browser browser = resolveBrowser();
historyLogin.setBrowser(browser.getName());
historyLogin.setPlatform(browser.getPlatform());
historyLogin.setSourceIp(userInfo.getLastLoginIp());
historyLogin.setProvider(provider);
historyLogin.setCode(code);
historyLogin.setLoginType(type);
historyLogin.setMessage(message);
historyLogin.setUserId(userInfo.getId());
historyLogin.setUsername(userInfo.getUsername());
historyLogin.setDisplayName(userInfo.getDisplayName());
loginHistoryService.login(historyLogin);
loginService.setLastLoginInfo(userInfo);
@ -218,4 +196,67 @@ public abstract class AbstractAuthenticationRealm {
}
public Browser resolveBrowser() {
Browser browser =new Browser();
String userAgent = WebContext.getRequest().getHeader("User-Agent");
String[] arrayUserAgent = null;
if (userAgent.indexOf("MSIE") > 0) {
arrayUserAgent = userAgent.split(";");
browser.setName(arrayUserAgent[1].trim());
browser.setPlatform(arrayUserAgent[2].trim());
} else if (userAgent.indexOf("Trident") > 0) {
arrayUserAgent = userAgent.split(";");
browser.setName( "MSIE/" + arrayUserAgent[3].split("\\)")[0]);
browser.setPlatform( arrayUserAgent[0].split("\\(")[1]);
} else if (userAgent.indexOf("Chrome") > 0) {
arrayUserAgent = userAgent.split(" ");
// browser=arrayUserAgent[8].trim();
for (int i = 0; i < arrayUserAgent.length; i++) {
if (arrayUserAgent[i].contains("Chrome")) {
browser.setName( arrayUserAgent[i].trim());
browser.setName( browser.getName().substring(0, browser.getName().indexOf('.')));
}
}
browser.setPlatform( (arrayUserAgent[1].substring(1) + " " + arrayUserAgent[2] + " "
+ arrayUserAgent[3].substring(0, arrayUserAgent[3].length() - 1)).trim());
} else if (userAgent.indexOf("Firefox") > 0) {
arrayUserAgent = userAgent.split(" ");
for (int i = 0; i < arrayUserAgent.length; i++) {
if (arrayUserAgent[i].contains("Firefox")) {
browser.setName( arrayUserAgent[i].trim());
browser.setName(browser.getName().substring(0, browser.getName().indexOf('.')));
}
}
browser.setPlatform( (arrayUserAgent[1].substring(1) + " " + arrayUserAgent[2] + " "
+ arrayUserAgent[3].substring(0, arrayUserAgent[3].length() - 1)).trim());
}
return browser;
}
public class Browser{
private String platform;
private String name;
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public String getName() {
return name;
}
public void setName(String browser) {
this.name = browser;
}
}
}

View File

@ -1,87 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.authn.realm.jdbc;
import org.maxkey.authn.realm.AbstractAuthenticationRealm;
import org.maxkey.constants.ConstantsLoginType;
import org.maxkey.crypto.password.PasswordReciprocal;
import org.maxkey.entity.UserInfo;
import org.maxkey.web.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* same as JdbcAuthenticationRealm.
*
* @author Crystal.Sea
*
*/
public class DefaultJdbcAuthenticationRealm extends AbstractAuthenticationRealm {
private static Logger _logger = LoggerFactory.getLogger(DefaultJdbcAuthenticationRealm.class);
protected PasswordEncoder passwordEncoder;
public DefaultJdbcAuthenticationRealm() {
}
public DefaultJdbcAuthenticationRealm(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/**
* passwordMatches.
*/
public boolean passwordMatches(UserInfo userInfo, String password) {
boolean passwordMatches = false;
//jdbc password check
_logger.trace("password : "
+ PasswordReciprocal.getInstance().rawPassword(userInfo.getUsername(), password));
passwordMatches = passwordEncoder.matches(password,userInfo.getPassword());
//passwordMatches == false and ldapSupport ==true
//validate password with LDAP
if(!passwordMatches && ldapSupport) {
passwordMatches =this.ldapAuthenticationRealm.passwordMatches(userInfo, password);
if(passwordMatches) {
//init password to local Realm
UserInfo changePasswordUser = new UserInfo();
changePasswordUser.setId(userInfo.getId());
changePasswordUser.setUsername(userInfo.getUsername());
changePasswordUser.setPassword(password);
userInfoService.changePassword(changePasswordUser, false);
}
}
_logger.debug("passwordvalid : " + passwordMatches);
if (!passwordMatches) {
passwordPolicyValidator.plusBadPasswordCount(userInfo);
insertLoginHistory(userInfo, ConstantsLoginType.LOCAL, "", "xe00000004", "password error");
throw new BadCredentialsException(WebContext.getI18nValue("login.error.password"));
}
return passwordMatches;
}
}

View File

@ -19,13 +19,17 @@ package org.maxkey.authn.realm.jdbc;
import org.maxkey.authn.realm.AbstractAuthenticationRealm;
import org.maxkey.authn.support.rememberme.AbstractRemeberMeService;
import org.maxkey.constants.ConstantsLoginType;
import org.maxkey.entity.UserInfo;
import org.maxkey.persistence.db.LoginHistoryService;
import org.maxkey.persistence.db.LoginService;
import org.maxkey.persistence.db.PasswordPolicyValidator;
import org.maxkey.persistence.service.UserInfoService;
import org.maxkey.web.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
@ -33,9 +37,11 @@ import org.springframework.security.crypto.password.PasswordEncoder;
* @author Crystal.Sea
*
*/
public class JdbcAuthenticationRealm extends DefaultJdbcAuthenticationRealm {
public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm {
private static Logger _logger = LoggerFactory.getLogger(JdbcAuthenticationRealm.class);
protected PasswordEncoder passwordEncoder;
public JdbcAuthenticationRealm() {
_logger.debug("init . ");
}
@ -86,6 +92,37 @@ public class JdbcAuthenticationRealm extends DefaultJdbcAuthenticationRealm {
this.ldapSupport = ldapSupport;
}
/**
* passwordMatches.
*/
public boolean passwordMatches(UserInfo userInfo, String password) {
boolean passwordMatches = false;
//jdbc password check
//_logger.trace("password : "
// + PasswordReciprocal.getInstance().rawPassword(userInfo.getUsername(), password));
passwordMatches = passwordEncoder.matches(password,userInfo.getPassword());
//passwordMatches == false and ldapSupport ==true
//validate password with LDAP
if(!passwordMatches && ldapSupport) {
passwordMatches =this.ldapAuthenticationRealm.passwordMatches(userInfo, password);
if(passwordMatches) {
//init password to local Realm
UserInfo changePasswordUser = new UserInfo();
changePasswordUser.setId(userInfo.getId());
changePasswordUser.setUsername(userInfo.getUsername());
changePasswordUser.setPassword(password);
userInfoService.changePassword(changePasswordUser, false);
}
}
_logger.debug("passwordvalid : " + passwordMatches);
if (!passwordMatches) {
passwordPolicyValidator.plusBadPasswordCount(userInfo);
insertLoginHistory(userInfo, ConstantsLoginType.LOCAL, "", "xe00000004", "password error");
throw new BadCredentialsException(WebContext.getI18nValue("login.error.password"));
}
return passwordMatches;
}
}

View File

@ -25,6 +25,9 @@ import javax.servlet.Filter;
import org.maxkey.constants.ConstantsProperties;
import org.maxkey.constants.ConstantsTimeInterval;
import org.maxkey.persistence.db.LoginHistoryService;
import org.maxkey.persistence.db.LoginService;
import org.maxkey.web.SessionListenerAdapter;
import org.maxkey.web.WebXssRequestFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -286,6 +289,17 @@ public class MvcAutoConfiguration implements InitializingBean {
return registrationBean;
}
@Bean(name = "sessionListenerAdapter")
public SessionListenerAdapter sessionListenerAdapter(
LoginService loginService,
LoginHistoryService loginHistoryService
) {
SessionListenerAdapter sessionListenerAdapter =new SessionListenerAdapter();
sessionListenerAdapter.setLoginService(loginService);
sessionListenerAdapter.setLoginHistoryService(loginHistoryService);
return sessionListenerAdapter;
}
@Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub

View File

@ -76,6 +76,8 @@ public class HistoryLogin extends JpaBaseEntity implements Serializable{
@Column
String logoutTime;
int sessionStatus;
String startDate;
String endDate;
@ -227,7 +229,15 @@ public class HistoryLogin extends JpaBaseEntity implements Serializable{
this.endDate = endDate;
}
@Override
public int getSessionStatus() {
return sessionStatus;
}
public void setSessionStatus(int sessionStatus) {
this.sessionStatus = sessionStatus;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("HistoryLogin [id=");

View File

@ -1267,10 +1267,6 @@ public class UserInfo extends JpaBaseEntity {
builder.append(id);
builder.append(", username=");
builder.append(username);
builder.append(", password=");
builder.append(password);
builder.append(", decipherable=");
builder.append(decipherable);
builder.append(", sharedSecret=");
builder.append(sharedSecret);
builder.append(", sharedCounter=");

View File

@ -19,6 +19,7 @@ package org.maxkey.persistence.db;
import java.sql.Types;
import org.maxkey.entity.HistoryLogin;
import org.maxkey.entity.UserInfo;
import org.maxkey.web.WebContext;
import org.slf4j.Logger;
@ -38,23 +39,54 @@ public class LoginHistoryService {
this.jdbcTemplate = jdbcTemplate;
}
@Deprecated
public void login(UserInfo userInfo,String sessionId,
String type, String message, String code, String provider,String browser, String platform,int sessionStatus) {
jdbcTemplate.update(HISTORY_LOGIN_INSERT_STATEMENT,
new Object[] { WebContext.genId(), sessionId, userInfo.getId(), userInfo.getUsername(),
userInfo.getDisplayName(), type, message, code, provider, userInfo.getLastLoginIp(), browser, platform,
"Browser", WebContext.getRequest().getRequestURI() , sessionStatus},
new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR ,Types.INTEGER});
new int[] {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR ,Types.INTEGER
});
}
public void login(HistoryLogin historyLogin) {
historyLogin.setId(WebContext.genId());
historyLogin.setLoginUrl(WebContext.getRequest().getRequestURI());
_logger.debug(" historyLogin " + historyLogin);
jdbcTemplate.update(HISTORY_LOGIN_INSERT_STATEMENT,
new Object[] {
historyLogin.getId(), historyLogin.getSessionId(), historyLogin.getUserId(), historyLogin.getUsername(),
historyLogin.getDisplayName(), historyLogin.getLoginType(), historyLogin.getMessage(), historyLogin.getCode(),
historyLogin.getProvider(), historyLogin.getSourceIp(), historyLogin.getBrowser(), historyLogin.getPlatform(),
"Browser", historyLogin.getLoginUrl() , historyLogin.getSessionStatus()
},
new int[] {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR ,Types.INTEGER
});
}
public void logoff(String lastLogoffTime,String sessionId) {
_logger.debug(" sessionId " +sessionId +" , lastlogofftime " + lastLogoffTime);
jdbcTemplate.update(HISTORY_LOGOUT_UPDATE_STATEMENT,
new Object[] { lastLogoffTime, sessionId },
new int[] { Types.VARCHAR, Types.VARCHAR });
}
public void logoff(HistoryLogin historyLogin) {
_logger.debug(" sessionId " +historyLogin.getSessionId() +" , LogoutTime " + historyLogin.getLogoutTime());
jdbcTemplate.update(HISTORY_LOGOUT_UPDATE_STATEMENT,
new Object[] { historyLogin.getLogoutTime(), historyLogin.getSessionId() },
new int[] { Types.VARCHAR, Types.VARCHAR });
}
}

View File

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.web.interceptor;
package org.maxkey.web;
import java.util.Date;
@ -27,7 +27,6 @@ import org.maxkey.entity.UserInfo;
import org.maxkey.persistence.db.LoginHistoryService;
import org.maxkey.persistence.db.LoginService;
import org.maxkey.util.DateUtils;
import org.maxkey.web.WebConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -76,6 +76,8 @@ public final class WebContext {
sessionAttributeNameList.add(WebConstants.CURRENT_USER_SESSION_ID);
sessionAttributeNameList.add(WebConstants.FIRST_SAVED_REQUEST_PARAMETER);
sessionAttributeNameList.add(WebConstants.REMEBER_ME_SESSION);
}
/**
@ -451,7 +453,7 @@ public final class WebContext {
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
}
LogFactory.getLog(WebContext.class).debug(
LogFactory.getLog(WebContext.class).trace(
"getRequestIpAddress() RequestIpAddress:" + ipAddress);
return ipAddress;
}

View File

@ -26,19 +26,15 @@ import org.maxkey.authn.support.rememberme.AbstractRemeberMeService;
import org.maxkey.authn.support.rememberme.HttpRemeberMeEntryPoint;
import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.constants.ConstantsProperties;
import org.maxkey.persistence.db.LoginHistoryService;
import org.maxkey.persistence.db.LoginService;
import org.maxkey.web.interceptor.HistoryLoginAppAdapter;
import org.maxkey.web.interceptor.HistoryLogsAdapter;
import org.maxkey.web.interceptor.PermissionAdapter;
import org.maxkey.web.interceptor.PreLoginAppAdapter;
import org.maxkey.web.interceptor.SessionListenerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@ -234,16 +230,4 @@ public class MaxKeyMvcConfig implements WebMvcConfigurer {
}
@Bean(name = "sessionListenerAdapter")
public SessionListenerAdapter sessionListenerAdapter(
LoginService loginService,
LoginHistoryService loginHistoryService
) {
SessionListenerAdapter sessionListenerAdapter =new SessionListenerAdapter();
sessionListenerAdapter.setLoginService(loginService);
sessionListenerAdapter.setLoginHistoryService(loginHistoryService);
return sessionListenerAdapter;
}
}

View File

@ -18,6 +18,8 @@
#server port
server.port=8080
#session default 1800
#1800s =30m
#28800s=8h
server.servlet.session.timeout=1800
#server context path
server.servlet.context-path=/maxkey

View File

@ -18,6 +18,8 @@
#server port
server.port=443
#session default 1800
#1800s =30m
#28800s=8h
server.servlet.session.timeout=1800
#server context path
server.servlet.context-path=/maxkey