From b7db556e23d0e2d49aeb1a1159c82c2034fdae63 Mon Sep 17 00:00:00 2001 From: shimingxy Date: Wed, 1 Apr 2020 21:34:46 +0800 Subject: [PATCH] v1.3 RC --- .../authn/AbstractAuthenticationProvider.java | 154 ++-- .../org/maxkey/authn/BasicAuthentication.java | 113 +-- .../authn/RealmAuthenticationProvider.java | 43 +- .../realm/AbstractAuthenticationRealm.java | 626 ++++++++--------- .../jdbc/DefaultJdbcAuthenticationRealm.java | 57 +- .../realm/jdbc/JdbcAuthenticationRealm.java | 21 +- .../rememberme/AbstractRemeberMeService.java | 8 +- .../main/java/org/maxkey/web/WebContext.java | 659 ++++++++++-------- .../cas/endpoint/Cas10AuthorizeEndpoint.java | 2 +- .../cas/endpoint/Cas20AuthorizeEndpoint.java | 2 +- .../cas/endpoint/Cas30AuthorizeEndpoint.java | 4 +- .../OAuth20AccessConfirmationController.java | 2 +- .../TokenEndpointAuthenticationFilter.java | 2 +- .../main/resources/templates/views/login.ftl | 10 +- .../main/resources/templates/views/login.ftl | 24 +- 15 files changed, 887 insertions(+), 840 deletions(-) diff --git a/maxkey-core/src/main/java/org/maxkey/authn/AbstractAuthenticationProvider.java b/maxkey-core/src/main/java/org/maxkey/authn/AbstractAuthenticationProvider.java index 20b080b8c..bc378f846 100644 --- a/maxkey-core/src/main/java/org/maxkey/authn/AbstractAuthenticationProvider.java +++ b/maxkey-core/src/main/java/org/maxkey/authn/AbstractAuthenticationProvider.java @@ -20,14 +20,14 @@ import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; /** - * login Authentication abstract class + * login Authentication abstract class. * * @author Crystal.Sea * */ public abstract class AbstractAuthenticationProvider { - - private static final Logger _logger = LoggerFactory.getLogger(AbstractAuthenticationProvider.class); + private static final Logger _logger = + LoggerFactory.getLogger(AbstractAuthenticationProvider.class); @Autowired @Qualifier("applicationConfig") @@ -39,7 +39,7 @@ public abstract class AbstractAuthenticationProvider { @Autowired @Qualifier("tfaOTPAuthn") - protected AbstractOTPAuthn tfaOTPAuthn; + protected AbstractOTPAuthn tfaOptAuthn; @Autowired @Qualifier("remeberMeService") @@ -54,21 +54,22 @@ public abstract class AbstractAuthenticationProvider { return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)); } - /* - * authenticate (non-Javadoc) + /** + * authenticate . * - * @see org.springframework.security.authentication.AuthenticationProvider# - * authenticate(org.springframework.security.core.Authentication) */ - public Authentication authenticate(Authentication authentication) throws AuthenticationException { - _logger.debug("Trying to authenticate user '{}' via {}", authentication.getPrincipal(), getProviderName()); + public Authentication authenticate(Authentication authentication) + throws AuthenticationException { + _logger.debug("Trying to authenticate user '{}' via {}", + authentication.getPrincipal(), getProviderName()); try { authentication = doInternalAuthenticate(authentication); } catch (AuthenticationException e) { e.printStackTrace(); _logger.error("Failed to authenticate user {} via {}: {}", - new Object[] { authentication.getPrincipal(), getProviderName(), e.getMessage() }); + new Object[] { + authentication.getPrincipal(), getProviderName(), e.getMessage() }); throw e; } catch (Exception e) { e.printStackTrace(); @@ -81,39 +82,45 @@ public abstract class AbstractAuthenticationProvider { } // user authenticated - _logger.debug("'{}' authenticated successfully by {}.", authentication.getPrincipal(), getProviderName()); + _logger.debug("'{}' authenticated successfully by {}.", + authentication.getPrincipal(), getProviderName()); - UserInfo userInfo = WebContext.getUserInfo(); - Object password_set_type = WebContext.getSession() + final UserInfo userInfo = WebContext.getUserInfo(); + final Object passwordSetType = WebContext.getSession() .getAttribute(WebConstants.CURRENT_LOGIN_USER_PASSWORD_SET_TYPE); // 登录完成后切换SESSION _logger.debug("Login Session {}.", WebContext.getSession().getId()); WebContext.getSession().invalidate(); - WebContext.setAttribute(WebConstants.CURRENT_USER_SESSION_ID, WebContext.getSession().getId()); + WebContext.setAttribute( + WebConstants.CURRENT_USER_SESSION_ID, WebContext.getSession().getId()); _logger.debug("Login Success Session {}.", WebContext.getSession().getId()); - authenticationRealm.insertLoginHistory(userInfo, LOGINTYPE.LOCAL, "", "xe00000004", "success"); + authenticationRealm.insertLoginHistory( + userInfo, LOGINTYPE.LOCAL, "", "xe00000004", "success"); // 认证设置 WebContext.setAuthentication(authentication); WebContext.setUserInfo(userInfo); - WebContext.getSession().setAttribute(WebConstants.CURRENT_LOGIN_USER_PASSWORD_SET_TYPE, password_set_type); + WebContext.getSession().setAttribute( + WebConstants.CURRENT_LOGIN_USER_PASSWORD_SET_TYPE, passwordSetType); // create new authentication response containing the user and it's authorities - UsernamePasswordAuthenticationToken simpleUserAuthentication = new UsernamePasswordAuthenticationToken( - userInfo.getUsername(), authentication.getCredentials(), authentication.getAuthorities()); + UsernamePasswordAuthenticationToken simpleUserAuthentication = + new UsernamePasswordAuthenticationToken( + userInfo.getUsername(), + authentication.getCredentials(), + authentication.getAuthorities() + ); return simpleUserAuthentication; } /** - * session validate + * session validate. * - * @param j_username - * @param j_cname - * @param sessionId + * @param sessionId String */ - protected void sessionValid(String j_sessionId) { - if (j_sessionId == null || !j_sessionId.equals(WebContext.getSession().getId())) { + protected void sessionValid(String sessionId) { + if (sessionId == null || !sessionId.equals(WebContext.getSession().getId())) { String message = WebContext.getI18nValue("login.error.session"); _logger.debug("login session valid error."); throw new BadCredentialsException(message); @@ -121,15 +128,13 @@ public abstract class AbstractAuthenticationProvider { } /** - * session validate + * session validate. * - * @param j_username - * @param j_cname - * @param sessionId + * @param jwtToken String */ - protected void jwtTokenValid(String j_jwtToken) { + protected void jwtTokenValid(String jwtToken) { /* - * if(j_jwtToken!=null && ! j_jwtToken.equals("")){ + * if(jwtToken!=null && ! jwtToken.equals("")){ * if(jwtLoginService.jwtTokenValidation(j_jwtToken)){ return; } } */ String message = WebContext.getI18nValue("login.error.session"); @@ -137,8 +142,8 @@ public abstract class AbstractAuthenticationProvider { throw new BadCredentialsException(message); } - protected void authTypeValid(String j_auth_type) { - if (j_auth_type == null) { + protected void authTypeValid(String authType) { + if (authType == null) { String message = WebContext.getI18nValue("login.error.authtype"); _logger.debug("login AuthN type can not been null ."); throw new BadCredentialsException(message); @@ -146,19 +151,21 @@ public abstract class AbstractAuthenticationProvider { } /** - * captcha validate + * captcha validate . * - * @param j_username - * @param j_cname - * @param captcha + * @param authType String + * @param captcha String */ - protected void captchaValid(String j_captcha, String j_auth_type) { - if (applicationConfig.getLoginConfig().isCaptcha()) {// for basic - if (j_auth_type.equalsIgnoreCase("common")) { + protected void captchaValid(String captcha, String authType) { + if (applicationConfig.getLoginConfig().isCaptcha()) { + // for basic + if (authType.equalsIgnoreCase("common")) { _logger.info("captcha : " - + WebContext.getSession().getAttribute(WebConstants.KAPTCHA_SESSION_KEY).toString()); - if (j_captcha == null || !j_captcha - .equals(WebContext.getSession().getAttribute(WebConstants.KAPTCHA_SESSION_KEY).toString())) { + + WebContext.getSession().getAttribute( + WebConstants.KAPTCHA_SESSION_KEY).toString()); + if (captcha == null || !captcha + .equals(WebContext.getSession().getAttribute( + WebConstants.KAPTCHA_SESSION_KEY).toString())) { String message = WebContext.getI18nValue("login.error.captcha"); _logger.debug("login captcha valid error."); throw new BadCredentialsException(message); @@ -168,22 +175,24 @@ public abstract class AbstractAuthenticationProvider { } /** - * captcha validate + * captcha validate. * - * @param j_username - * @param j_cname - * @param j_otp_captcha + * @param otpCaptcha String + * @param authType String + * @param userInfo UserInfo */ - protected void tftcaptchaValid(String j_otp_captcha, String j_auth_type, UserInfo userInfo) { - if (applicationConfig.getLoginConfig().isOneTimePwd()) {// for one time password 2 factor - if (j_auth_type.equalsIgnoreCase("tfa")) { + protected void tftcaptchaValid(String otpCaptcha, String authType, UserInfo userInfo) { + // for one time password 2 factor + if (applicationConfig.getLoginConfig().isOneTimePwd()) { + if (authType.equalsIgnoreCase("tfa")) { UserInfo validUserInfo = new UserInfo(); validUserInfo.setUsername(userInfo.getUsername()); - String sharedSecret = PasswordReciprocal.getInstance().decoder(userInfo.getSharedSecret()); + String sharedSecret = + PasswordReciprocal.getInstance().decoder(userInfo.getSharedSecret()); validUserInfo.setSharedSecret(sharedSecret); validUserInfo.setSharedCounter(userInfo.getSharedCounter()); validUserInfo.setId(userInfo.getId()); - if (j_otp_captcha == null || !tfaOTPAuthn.validate(validUserInfo, j_otp_captcha)) { + if (otpCaptcha == null || !tfaOptAuthn.validate(validUserInfo, otpCaptcha)) { String message = WebContext.getI18nValue("login.error.captcha"); _logger.debug("login captcha valid error."); throw new BadCredentialsException(message); @@ -195,14 +204,14 @@ public abstract class AbstractAuthenticationProvider { /** * login user by j_username and j_cname first query user by j_cname if first - * step userinfo is null,query user from system + * step userinfo is null,query user from system. * - * @param j_username - * @param j_cname + * @param username String + * @param password String * @return */ - protected UserInfo loadUserInfo(String j_username, String j_password) { - UserInfo userInfo = authenticationRealm.loadUserInfo(j_username, j_password); + protected UserInfo loadUserInfo(String username, String password) { + UserInfo userInfo = authenticationRealm.loadUserInfo(username, password); if (userInfo != null) { if (userInfo.getUserType() == "SYSTEM") { @@ -216,50 +225,49 @@ public abstract class AbstractAuthenticationProvider { } /** - * check input password empty + * check input password empty. * - * @param password + * @param password String * @return */ - protected boolean emptyPasswordValid(String j_password) { - if (null == j_password || "".equals(j_password)) { + protected boolean emptyPasswordValid(String password) { + if (null == password || "".equals(password)) { throw new BadCredentialsException(WebContext.getI18nValue("login.error.password.null")); } return true; } /** - * check input username or password empty + * check input username or password empty. * - * @param j_username - * @param password + * @param email String * @return */ - protected boolean emptyEmailValid(String j_email) { - if (null == j_email || "".equals(j_email)) { + protected boolean emptyEmailValid(String email) { + if (null == email || "".equals(email)) { throw new BadCredentialsException("login.error.email.null"); } return true; } /** - * check input username empty + * check input username empty. * - * @param j_username + * @param username String * @return */ - protected boolean emptyUsernameValid(String j_username) { - if (null == j_username || "".equals(j_username)) { + protected boolean emptyUsernameValid(String username) { + if (null == username || "".equals(username)) { throw new BadCredentialsException(WebContext.getI18nValue("login.error.username.null")); } return true; } - protected boolean userinfoValid(UserInfo userInfo, String j_username) { + protected boolean userinfoValid(UserInfo userInfo, String username) { if (null == userInfo) { String message = WebContext.getI18nValue("login.error.username"); - _logger.debug("login user " + j_username + " not in this System ." + message); - UserInfo loginUser = new UserInfo(j_username); + _logger.debug("login user " + username + " not in this System ." + message); + UserInfo loginUser = new UserInfo(username); loginUser.setId(loginUser.generateId()); loginUser.setDisplayName("not exist"); loginUser.setLoginCount(0); diff --git a/maxkey-core/src/main/java/org/maxkey/authn/BasicAuthentication.java b/maxkey-core/src/main/java/org/maxkey/authn/BasicAuthentication.java index 364903dea..c213387be 100644 --- a/maxkey-core/src/main/java/org/maxkey/authn/BasicAuthentication.java +++ b/maxkey-core/src/main/java/org/maxkey/authn/BasicAuthentication.java @@ -6,22 +6,23 @@ import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; + public class BasicAuthentication implements Authentication { - /** - * - */ private static final long serialVersionUID = -110742975439268030L; - String j_username; - String j_password; - String j_sessionid; - String j_captcha; - String j_otp_captcha; - String j_remeberme; - String j_auth_type; - String j_jwt_token; + String username; + String password; + String sessionId; + String captcha; + String otpCaptcha; + String remeberMe; + String authType; + String jwtToken; ArrayList grantedAuthority; boolean authenticated; + /** + * BasicAuthentication. + */ public BasicAuthentication() { grantedAuthority = new ArrayList(); grantedAuthority.add(new SimpleGrantedAuthority("ROLE_USER")); @@ -40,7 +41,7 @@ public class BasicAuthentication implements Authentication { @Override public Object getCredentials() { - return this.getJ_password(); + return this.getPassword(); } @Override @@ -50,7 +51,7 @@ public class BasicAuthentication implements Authentication { @Override public Object getPrincipal() { - return this.getJ_username(); + return this.getUsername(); } @Override @@ -64,76 +65,69 @@ public class BasicAuthentication implements Authentication { } - public String getJ_username() { - return j_username; - } public String getUsername() { - return j_username; + return username; } - public void setJ_username(String j_username) { - this.j_username = j_username; + public void setUsername(String username) { + this.username = username; } - public String getJ_password() { - return j_password; + public String getPassword() { + return password; } - public void setJ_password(String j_password) { - this.j_password = j_password; + public void setPassword(String password) { + this.password = password; } - public String getJ_sessionid() { - return j_sessionid; + public String getSessionId() { + return sessionId; } - public String getSessionid() { - return j_sessionid; + public void setSessionId(String sessionId) { + this.sessionId = sessionId; } - public void setJ_sessionid(String j_sessionid) { - this.j_sessionid = j_sessionid; + public String getCaptcha() { + return captcha; } - public String getJ_captcha() { - return j_captcha; + public void setCaptcha(String captcha) { + this.captcha = captcha; } - public void setJ_captcha(String j_captcha) { - this.j_captcha = j_captcha; + public String getOtpCaptcha() { + return otpCaptcha; } - public String getJ_otp_captcha() { - return j_otp_captcha; + public void setOtpCaptcha(String otpCaptcha) { + this.otpCaptcha = otpCaptcha; } - public void setJ_otp_captcha(String j_otp_captcha) { - this.j_otp_captcha = j_otp_captcha; + public String getRemeberMe() { + return remeberMe; } - public String getJ_remeberme() { - return j_remeberme; + public void setRemeberMe(String remeberMe) { + this.remeberMe = remeberMe; } - public void setJ_remeberme(String j_remeberme) { - this.j_remeberme = j_remeberme; + public String getAuthType() { + return authType; } - public String getJ_auth_type() { - return j_auth_type; + public void setAuthType(String authType) { + this.authType = authType; } - public void setJ_auth_type(String j_auth_type) { - this.j_auth_type = j_auth_type; + public String getJwtToken() { + return jwtToken; } - public String getJ_jwt_token() { - return j_jwt_token; - } - - public void setJ_jwt_token(String j_jwt_token) { - this.j_jwt_token = j_jwt_token; + public void setJwtToken(String jwtToken) { + this.jwtToken = jwtToken; } public ArrayList getGrantedAuthority() { @@ -146,9 +140,18 @@ public class BasicAuthentication implements Authentication { @Override public String toString() { - return "BasicAuthentication [j_username=" + j_username + ", j_sessionId=" + j_sessionid + ", j_captcha=" - + j_captcha + ", j_otp_captcha=" + j_otp_captcha + ", j_remeberMe=" + j_remeberme + ", j_auth_type=" - + j_auth_type + ", j_jwtToken=" + j_jwt_token + ", authenticated=" + authenticated + "]"; + StringBuilder builder = new StringBuilder(); + builder.append("BasicAuthentication [username=").append(username) + .append(", password=").append(password) + .append(", sessionId=").append(sessionId) + .append(", captcha=").append(captcha) + .append(", otpCaptcha=").append(otpCaptcha) + .append(", remeberMe=").append(remeberMe) + .append(", authType=").append(authType) + .append(", jwtToken=").append(jwtToken) + .append(", grantedAuthority=").append(grantedAuthority) + .append(", authenticated=").append(authenticated) + .append("]"); + return builder.toString(); } - } diff --git a/maxkey-core/src/main/java/org/maxkey/authn/RealmAuthenticationProvider.java b/maxkey-core/src/main/java/org/maxkey/authn/RealmAuthenticationProvider.java index c20d7818b..ee54a0c98 100644 --- a/maxkey-core/src/main/java/org/maxkey/authn/RealmAuthenticationProvider.java +++ b/maxkey-core/src/main/java/org/maxkey/authn/RealmAuthenticationProvider.java @@ -13,13 +13,13 @@ import org.springframework.web.context.request.ServletRequestAttributes; /** - * database Authentication provider + * database Authentication provider. * @author Crystal.Sea * */ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider { - - private static final Logger _logger = LoggerFactory.getLogger(RealmAuthenticationProvider.class); + private static final Logger _logger = + LoggerFactory.getLogger(RealmAuthenticationProvider.class); protected String getProviderName() { return "RealmAuthenticationProvider"; @@ -31,53 +31,58 @@ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider _logger.debug("authentication " + auth); - sessionValid(auth.getJ_sessionid()); + sessionValid(auth.getSessionId()); //jwtTokenValid(j_jwtToken); - authTypeValid(auth.getJ_auth_type()); + authTypeValid(auth.getAuthType()); - captchaValid(auth.getJ_captcha(),auth.getJ_auth_type()); + captchaValid(auth.getCaptcha(),auth.getAuthType()); - emptyPasswordValid(auth.getJ_password()); + emptyPasswordValid(auth.getPassword()); UserInfo userInfo = null; - emptyUsernameValid(auth.getJ_username()); + emptyUsernameValid(auth.getUsername()); - userInfo= loadUserInfo(auth.getJ_username(),auth.getJ_password()); + userInfo = loadUserInfo(auth.getUsername(),auth.getPassword()); - userinfoValid(userInfo, auth.getJ_password()); + userinfoValid(userInfo, auth.getPassword()); - tftcaptchaValid(auth.getJ_otp_captcha(),auth.getJ_auth_type(),userInfo); + tftcaptchaValid(auth.getOtpCaptcha(),auth.getAuthType(),userInfo); authenticationRealm.passwordPolicyValid(userInfo); - authenticationRealm.passwordMatches(userInfo, auth.getJ_password()); + authenticationRealm.passwordMatches(userInfo, auth.getPassword()); authenticationRealm.grantAuthority(userInfo); - /** + /* * put userInfo to current session context */ WebContext.setUserInfo(userInfo); auth.setAuthenticated(true); - if(auth.isAuthenticated()&&applicationConfig.getLoginConfig().isRemeberMe()){ - if(auth.getJ_remeberme()!=null&&auth.getJ_remeberme().equals("remeberMe")){ - WebContext.getSession().setAttribute(WebConstants.REMEBER_ME_SESSION,auth.getJ_username()); + if (auth.isAuthenticated() && applicationConfig.getLoginConfig().isRemeberMe()) { + if (auth.getRemeberMe() != null && auth.getRemeberMe().equals("remeberMe")) { + WebContext.getSession().setAttribute( + WebConstants.REMEBER_ME_SESSION,auth.getUsername()); _logger.debug("do Remeber Me"); remeberMeService.createRemeberMe( userInfo.getUsername(), WebContext.getRequest(), - ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse()); + ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()) + .getResponse() + ); } } - UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =new UsernamePasswordAuthenticationToken( + UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = + new UsernamePasswordAuthenticationToken( auth, "PASSWORD", authenticationRealm.grantAuthority(userInfo)); - usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetails(WebContext.getRequest())); + usernamePasswordAuthenticationToken.setDetails( + new WebAuthenticationDetails(WebContext.getRequest())); return usernamePasswordAuthenticationToken; } diff --git a/maxkey-core/src/main/java/org/maxkey/authn/realm/AbstractAuthenticationRealm.java b/maxkey-core/src/main/java/org/maxkey/authn/realm/AbstractAuthenticationRealm.java index ce9ccbf74..f3d941dee 100644 --- a/maxkey-core/src/main/java/org/maxkey/authn/realm/AbstractAuthenticationRealm.java +++ b/maxkey-core/src/main/java/org/maxkey/authn/realm/AbstractAuthenticationRealm.java @@ -35,352 +35,330 @@ import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; - /** + * AbstractAuthenticationRealm. * @author Crystal.Sea * */ -public abstract class AbstractAuthenticationRealm{ - private static Logger _logger = LoggerFactory.getLogger(AbstractAuthenticationRealm.class); - - private static final String LOCK_USER_UPDATE_STATEMENT = "UPDATE USERINFO SET ISLOCKED = ? , UNLOCKTIME = ? WHERE ID = ?"; - - private static final String UNLOCK_USER_UPDATE_STATEMENT = "UPDATE USERINFO SET ISLOCKED = ? , UNLOCKTIME = ? WHERE ID = ?"; - - private static final String BADPASSWORDCOUNT_UPDATE_STATEMENT = "UPDATE USERINFO SET BADPASSWORDCOUNT = ? , BADPASSWORDTIME = ? WHERE ID = ?"; - - private static final String BADPASSWORDCOUNT_RESET_UPDATE_STATEMENT = "UPDATE USERINFO SET BADPASSWORDCOUNT = ? , ISLOCKED = ? ,UNLOCKTIME = ? WHERE ID = ?"; - - private static final String HISTORY_LOGIN_INSERT_STATEMENT = "INSERT INTO HISTORY_LOGIN (ID , SESSIONID , UID , USERNAME , DISPLAYNAME , LOGINTYPE , MESSAGE , CODE , PROVIDER , SOURCEIP , BROWSER , PLATFORM , APPLICATION , LOGINURL )VALUES( ? , ? , ? , ? , ?, ? , ? , ?, ? , ? , ?, ? , ? , ?)"; - - private static final String LOGIN_USERINFO_UPDATE_STATEMENT = "UPDATE USERINFO SET LASTLOGINTIME = ? , LASTLOGINIP = ? , LOGINCOUNT = ?, ONLINE = "+UserInfo.ONLINE.ONLINE+" WHERE ID = ?"; - - private static final String LOGOUT_USERINFO_UPDATE_STATEMENT = "UPDATE USERINFO SET LASTLOGOFFTIME = ? , ONLINE = "+UserInfo.ONLINE.OFFLINE+" WHERE ID = ?"; - - private static final String HISTORY_LOGOUT_UPDATE_STATEMENT = "UPDATE HISTORY_LOGIN SET LOGOUTTIME = ? WHERE SESSIONID = ?"; - - private static final String GROUPS_SELECT_STATEMENT = "SELECT DISTINCT G.ID,G.NAME FROM USERINFO U,GROUPS G,GROUP_MEMBER GM WHERE U.ID = ? AND U.ID=GM.MEMBERID AND GM.GROUPID=G.ID "; - - private static final String DEFAULT_USERINFO_SELECT_STATEMENT = "SELECT * FROM USERINFO WHERE USERNAME = ?"; - - private static final String PASSWORD_POLICY_SELECT_STATEMENT = "SELECT ID,MINLENGTH,MAXLENGTH,LOWERCASE,UPPERCASE,DIGITS,SPECIALCHAR,ATTEMPTS,DURATION,EXPIRATION,USERNAME,SIMPLEPASSWORDS FROM PASSWORD_POLICY "; - - protected PasswordPolicy passwordPolicy; - - protected JdbcTemplate jdbcTemplate; - - protected boolean provisioning; - - - @Autowired - @Qualifier("remeberMeService") - protected AbstractRemeberMeService remeberMeService; +public abstract class AbstractAuthenticationRealm { + private static Logger _logger = LoggerFactory.getLogger(AbstractAuthenticationRealm.class); + private static final String LOCK_USER_UPDATE_STATEMENT = "UPDATE USERINFO SET ISLOCKED = ? , UNLOCKTIME = ? WHERE ID = ?"; - /** - * - */ - public AbstractAuthenticationRealm() { - - } - - - public AbstractAuthenticationRealm(JdbcTemplate jdbcTemplate) { - this.jdbcTemplate=jdbcTemplate; - } + private static final String UNLOCK_USER_UPDATE_STATEMENT = "UPDATE USERINFO SET ISLOCKED = ? , UNLOCKTIME = ? WHERE ID = ?"; - public PasswordPolicy getPasswordPolicy() { - if(passwordPolicy==null){ - passwordPolicy=jdbcTemplate.queryForObject( - PASSWORD_POLICY_SELECT_STATEMENT, - new PasswordPolicyRowMapper()); - _logger.debug("query PasswordPolicy : "+passwordPolicy); - } - return passwordPolicy; - } - - public boolean passwordPolicyValid(UserInfo userInfo){ - /* - * check login attempts fail times - */ - if(userInfo.getBadPasswordCount()>=getPasswordPolicy().getAttempts()){ - _logger.debug("PasswordPolicy : "+passwordPolicy); - _logger.debug("login Attempts is "+userInfo.getBadPasswordCount()); - lockUser(userInfo); - - throw new BadCredentialsException(WebContext.getI18nValue("login.error.attempts") +" "+userInfo.getBadPasswordCount()); - } - - if(userInfo.getPasswordSetType()!=PASSWORDSETTYPE.PASSWORD_NORMAL){ - WebContext.getSession().setAttribute(WebConstants.CURRENT_LOGIN_USER_PASSWORD_SET_TYPE, userInfo.getPasswordSetType()); - return true; - }else{ - WebContext.getSession().setAttribute(WebConstants.CURRENT_LOGIN_USER_PASSWORD_SET_TYPE, PASSWORDSETTYPE.PASSWORD_NORMAL); - } - - /* - * check password is Expired,if Expiration equals 0,not need check - */ - if(getPasswordPolicy().getExpiration()>0){ - - String passwordLastSetTimeString=userInfo.getPasswordLastSetTime().substring(0, 19); - _logger.info("last password set date 锛�" + passwordLastSetTimeString); - - DateTime currentdateTime = new DateTime(); - DateTime changePwdDateTime=DateTime.parse(passwordLastSetTimeString, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")); - Duration duration = new Duration(changePwdDateTime, currentdateTime); - int intDuration=Integer.parseInt(duration.getStandardDays()+""); - _logger.debug("validate duration "+intDuration); - _logger.debug("validate result "+(intDuration<=getPasswordPolicy().getExpiration())); - if(intDuration>getPasswordPolicy().getExpiration()){ - WebContext.getSession().setAttribute(WebConstants.CURRENT_LOGIN_USER_PASSWORD_SET_TYPE, PASSWORDSETTYPE.PASSWORD_EXPIRED); - } - } - - return true; - } - - public UserInfo loadUserInfo(String username,String password) { - List listUserInfo=jdbcTemplate.query( - DEFAULT_USERINFO_SELECT_STATEMENT, - new UserInfoRowMapper(), - username); - UserInfo userInfo=null; - if(listUserInfo!=null&&listUserInfo.size()>0){ - userInfo=listUserInfo.get(0); - } - _logger.debug("load UserInfo : "+userInfo); - return userInfo; - } + private static final String BADPASSWORDCOUNT_UPDATE_STATEMENT = "UPDATE USERINFO SET BADPASSWORDCOUNT = ? , BADPASSWORDTIME = ? WHERE ID = ?"; - public abstract boolean passwordMatches(UserInfo userInfo,String password); - + private static final String BADPASSWORDCOUNT_RESET_UPDATE_STATEMENT = "UPDATE USERINFO SET BADPASSWORDCOUNT = ? , ISLOCKED = ? ,UNLOCKTIME = ? WHERE ID = ?"; - public static boolean isAuthenticated(){ - if(WebContext.getUserInfo()!=null){ - return true; - }else{ - return false; - } - } - - /** - * 閿佸畾鐢ㄦ埛锛歩slock锛�1 鐢ㄦ埛瑙i攣 2 鐢ㄦ埛閿佸畾 - * @param userInfo - */ - public void lockUser(UserInfo userInfo) { - try { - if(userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) { - jdbcTemplate.update(LOCK_USER_UPDATE_STATEMENT, - new Object[] { - STATUS.LOCK, - new Date(), - userInfo.getId()}, - new int[] {Types.VARCHAR, Types.TIMESTAMP ,Types.VARCHAR}); - } - } catch(Exception e) { - e.printStackTrace(); - } - } - - /** - * 閿佸畾鐢ㄦ埛锛歩slock锛�1 鐢ㄦ埛瑙i攣 2 鐢ㄦ埛閿佸畾 - * @param userInfo - */ - public void unlockUser(UserInfo userInfo) { - try { - if(userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) { - jdbcTemplate.update(UNLOCK_USER_UPDATE_STATEMENT, - new Object[] { - STATUS.ACTIVE, - new Date(), - userInfo.getId()}, - new int[] {Types.VARCHAR, Types.TIMESTAMP ,Types.VARCHAR}); - } - } catch(Exception e) { - e.printStackTrace(); - } - } + private static final String HISTORY_LOGIN_INSERT_STATEMENT = "INSERT INTO HISTORY_LOGIN (ID , SESSIONID , UID , USERNAME , DISPLAYNAME , LOGINTYPE , MESSAGE , CODE , PROVIDER , SOURCEIP , BROWSER , PLATFORM , APPLICATION , LOGINURL )VALUES( ? , ? , ? , ? , ?, ? , ? , ?, ? , ? , ?, ? , ? , ?)"; - /** - * 閲嶇疆閿欒瀵嗙爜娆℃暟鍜岃В閿佺敤鎴� - * @param userInfo - */ - public void resetBadPasswordCountAndLockout(UserInfo userInfo) { - try { - if(userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) { - jdbcTemplate.update(BADPASSWORDCOUNT_RESET_UPDATE_STATEMENT, - new Object[] { - 0, - STATUS.ACTIVE, - new Date(), - userInfo.getId()}, - new int[] {Types.INTEGER,Types.INTEGER, Types.TIMESTAMP ,Types.VARCHAR}); - } - } catch(Exception e) { - e.printStackTrace(); - _logger.error(e.getMessage()); - } - } + private static final String LOGIN_USERINFO_UPDATE_STATEMENT = "UPDATE USERINFO SET LASTLOGINTIME = ? , LASTLOGINIP = ? , LOGINCOUNT = ?, ONLINE = " + + UserInfo.ONLINE.ONLINE + " WHERE ID = ?"; - /** - * 鏇存柊閿欒瀵嗙爜娆℃暟 - * @param userInfo - */ - public void setBadPasswordCount(UserInfo userInfo) { - try { - if(userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) { - int badPasswordCount = userInfo.getBadPasswordCount() + 1; - userInfo.setBadPasswordCount(badPasswordCount); - jdbcTemplate.update(BADPASSWORDCOUNT_UPDATE_STATEMENT, - new Object[] { - badPasswordCount, - new Date(), - userInfo.getId()}, - new int[] {Types.INTEGER, Types.TIMESTAMP ,Types.VARCHAR}); - insertLoginHistory(userInfo,LOGINTYPE.LOCAL,"","xe00000004","password error"); - } - } catch(Exception e) { - e.printStackTrace(); - _logger.error(e.getMessage()); - } - } - - public List queryGroups(UserInfo userInfo) { - List listGroups=jdbcTemplate.query(GROUPS_SELECT_STATEMENT, new RowMapper() { - public Groups mapRow(ResultSet rs, int rowNum) throws SQLException { - Groups group=new Groups(rs.getString("ID"),rs.getString("NAME"),0); + private static final String LOGOUT_USERINFO_UPDATE_STATEMENT = "UPDATE USERINFO SET LASTLOGOFFTIME = ? , ONLINE = " + + UserInfo.ONLINE.OFFLINE + " WHERE ID = ?"; + + private static final String HISTORY_LOGOUT_UPDATE_STATEMENT = "UPDATE HISTORY_LOGIN SET LOGOUTTIME = ? WHERE SESSIONID = ?"; + + private static final String GROUPS_SELECT_STATEMENT = "SELECT DISTINCT G.ID,G.NAME FROM USERINFO U,GROUPS G,GROUP_MEMBER GM WHERE U.ID = ? AND U.ID=GM.MEMBERID AND GM.GROUPID=G.ID "; + + private static final String DEFAULT_USERINFO_SELECT_STATEMENT = "SELECT * FROM USERINFO WHERE USERNAME = ?"; + + private static final String PASSWORD_POLICY_SELECT_STATEMENT = "SELECT ID,MINLENGTH,MAXLENGTH,LOWERCASE,UPPERCASE,DIGITS,SPECIALCHAR,ATTEMPTS,DURATION,EXPIRATION,USERNAME,SIMPLEPASSWORDS FROM PASSWORD_POLICY "; + + protected PasswordPolicy passwordPolicy; + + protected JdbcTemplate jdbcTemplate; + + protected boolean provisioning; + + @Autowired + @Qualifier("remeberMeService") + protected AbstractRemeberMeService remeberMeService; + + /** + * + */ + public AbstractAuthenticationRealm() { + + } + + public AbstractAuthenticationRealm(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + public PasswordPolicy getPasswordPolicy() { + if (passwordPolicy == null) { + passwordPolicy = jdbcTemplate.queryForObject(PASSWORD_POLICY_SELECT_STATEMENT, + new PasswordPolicyRowMapper()); + _logger.debug("query PasswordPolicy : " + passwordPolicy); + } + return passwordPolicy; + } + + public boolean passwordPolicyValid(UserInfo userInfo) { + /* + * check login attempts fail times + */ + if (userInfo.getBadPasswordCount() >= getPasswordPolicy().getAttempts()) { + _logger.debug("PasswordPolicy : " + passwordPolicy); + _logger.debug("login Attempts is " + userInfo.getBadPasswordCount()); + lockUser(userInfo); + + throw new BadCredentialsException( + WebContext.getI18nValue("login.error.attempts") + " " + userInfo.getBadPasswordCount()); + } + + if (userInfo.getPasswordSetType() != PASSWORDSETTYPE.PASSWORD_NORMAL) { + WebContext.getSession().setAttribute(WebConstants.CURRENT_LOGIN_USER_PASSWORD_SET_TYPE, + userInfo.getPasswordSetType()); + return true; + } else { + WebContext.getSession().setAttribute(WebConstants.CURRENT_LOGIN_USER_PASSWORD_SET_TYPE, + PASSWORDSETTYPE.PASSWORD_NORMAL); + } + + /* + * check password is Expired,if Expiration equals 0,not need check + */ + if (getPasswordPolicy().getExpiration() > 0) { + + String passwordLastSetTimeString = userInfo.getPasswordLastSetTime().substring(0, 19); + _logger.info("last password set date 锛�" + passwordLastSetTimeString); + + DateTime currentdateTime = new DateTime(); + DateTime changePwdDateTime = DateTime.parse(passwordLastSetTimeString, + DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")); + Duration duration = new Duration(changePwdDateTime, currentdateTime); + int intDuration = Integer.parseInt(duration.getStandardDays() + ""); + _logger.debug("validate duration " + intDuration); + _logger.debug("validate result " + (intDuration <= getPasswordPolicy().getExpiration())); + if (intDuration > getPasswordPolicy().getExpiration()) { + WebContext.getSession().setAttribute(WebConstants.CURRENT_LOGIN_USER_PASSWORD_SET_TYPE, + PASSWORDSETTYPE.PASSWORD_EXPIRED); + } + } + + return true; + } + + public UserInfo loadUserInfo(String username, String password) { + List listUserInfo = jdbcTemplate.query(DEFAULT_USERINFO_SELECT_STATEMENT, new UserInfoRowMapper(), + username); + UserInfo userInfo = null; + if (listUserInfo != null && listUserInfo.size() > 0) { + userInfo = listUserInfo.get(0); + } + _logger.debug("load UserInfo : " + userInfo); + return userInfo; + } + + public abstract boolean passwordMatches(UserInfo userInfo, String password); + + public static boolean isAuthenticated() { + if (WebContext.getUserInfo() != null) { + return true; + } else { + return false; + } + } + + /** + * 閿佸畾鐢ㄦ埛锛歩slock锛�1 鐢ㄦ埛瑙i攣 2 鐢ㄦ埛閿佸畾 + * + * @param userInfo + */ + public void lockUser(UserInfo userInfo) { + try { + if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) { + jdbcTemplate.update(LOCK_USER_UPDATE_STATEMENT, + new Object[] { STATUS.LOCK, new Date(), userInfo.getId() }, + new int[] { Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR }); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 閿佸畾鐢ㄦ埛锛歩slock锛�1 鐢ㄦ埛瑙i攣 2 鐢ㄦ埛閿佸畾 + * + * @param userInfo + */ + public void unlockUser(UserInfo userInfo) { + try { + if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) { + jdbcTemplate.update(UNLOCK_USER_UPDATE_STATEMENT, + new Object[] { STATUS.ACTIVE, new Date(), userInfo.getId() }, + new int[] { Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR }); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 閲嶇疆閿欒瀵嗙爜娆℃暟鍜岃В閿佺敤鎴� + * + * @param userInfo + */ + public void resetBadPasswordCountAndLockout(UserInfo userInfo) { + try { + if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) { + jdbcTemplate.update(BADPASSWORDCOUNT_RESET_UPDATE_STATEMENT, + new Object[] { 0, STATUS.ACTIVE, new Date(), userInfo.getId() }, + new int[] { Types.INTEGER, Types.INTEGER, Types.TIMESTAMP, Types.VARCHAR }); + } + } catch (Exception e) { + e.printStackTrace(); + _logger.error(e.getMessage()); + } + } + + /** + * 鏇存柊閿欒瀵嗙爜娆℃暟 + * + * @param userInfo + */ + public void setBadPasswordCount(UserInfo userInfo) { + try { + if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) { + int badPasswordCount = userInfo.getBadPasswordCount() + 1; + userInfo.setBadPasswordCount(badPasswordCount); + jdbcTemplate.update(BADPASSWORDCOUNT_UPDATE_STATEMENT, + new Object[] { badPasswordCount, new Date(), userInfo.getId() }, + new int[] { Types.INTEGER, Types.TIMESTAMP, Types.VARCHAR }); + insertLoginHistory(userInfo, LOGINTYPE.LOCAL, "", "xe00000004", "password error"); + } + } catch (Exception e) { + e.printStackTrace(); + _logger.error(e.getMessage()); + } + } + + public List queryGroups(UserInfo userInfo) { + List listGroups = jdbcTemplate.query(GROUPS_SELECT_STATEMENT, new RowMapper() { + public Groups mapRow(ResultSet rs, int rowNum) throws SQLException { + Groups group = new Groups(rs.getString("ID"), rs.getString("NAME"), 0); + + return group; + } + }, userInfo.getId()); + + _logger.debug("list Groups " + listGroups); + return listGroups; + } - return group; - } - },userInfo.getId()); - - _logger.debug("list Groups "+listGroups); - return listGroups; - } - /** * grant Authority by userinfo + * * @param userInfo - * @return ArrayList + * @return ArrayList */ - public ArrayList grantAuthority(UserInfo userInfo){ - //query roles for user - List listGroups=queryGroups(userInfo); - - //set role for spring security - ArrayList grantedAuthority = new ArrayList(); - grantedAuthority.add(new SimpleGrantedAuthority("ROLE_USER")); - for(Groups group :listGroups){ - grantedAuthority.add(new SimpleGrantedAuthority(group.getId())); - } - _logger.debug("Authority : "+grantedAuthority); - - return grantedAuthority; + public ArrayList grantAuthority(UserInfo userInfo) { + // query roles for user + List listGroups = queryGroups(userInfo); + + // set role for spring security + ArrayList grantedAuthority = new ArrayList(); + grantedAuthority.add(new SimpleGrantedAuthority("ROLE_USER")); + for (Groups group : listGroups) { + grantedAuthority.add(new SimpleGrantedAuthority(group.getId())); + } + _logger.debug("Authority : " + grantedAuthority); + + return grantedAuthority; } - - /** + + /** * login log write to log db + * * @param uid * @param j_username * @param type * @param code * @param message */ - public boolean insertLoginHistory(UserInfo userInfo,String type,String provider,String code,String message){ - Date loginDate=new Date(); - String sessionId=WebContext.genId(); - WebContext.setAttribute(WebConstants.CURRENT_USER_SESSION_ID, sessionId); - String ipAddress=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;i0){ - arrayUserAgent=userAgent.split(" "); - for(int i=0;i 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(); + + } + + jdbcTemplate.update(HISTORY_LOGIN_INSERT_STATEMENT, + new Object[] { WebContext.genId(), sessionId, userInfo.getId(), userInfo.getUsername(), + userInfo.getDisplayName(), type, message, code, provider, ipAddress, browser, platform, + "Browser", loginDate }, + 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.TIMESTAMP }); + + userInfo.setLastLoginTime(DateUtils.formatDateTime(loginDate)); + + jdbcTemplate.update(LOGIN_USERINFO_UPDATE_STATEMENT, + new Object[] { loginDate, ipAddress, userInfo.getLoginCount() + 1, userInfo.getId() }, + new int[] { Types.TIMESTAMP, Types.VARCHAR, Types.INTEGER, Types.VARCHAR }); + + return true; + } + + public boolean logout(HttpServletResponse response) { + if (isAuthenticated()) { + Object sessionIdAttribute = WebContext.getAttribute(WebConstants.CURRENT_USER_SESSION_ID); + UserInfo userInfo = WebContext.getUserInfo(); + Date logoutDateTime = new Date(); + if (sessionIdAttribute != null) { + remeberMeService.removeRemeberMe(response); + + jdbcTemplate.update(HISTORY_LOGOUT_UPDATE_STATEMENT, + new Object[] { logoutDateTime, sessionIdAttribute.toString() }, + new int[] { Types.TIMESTAMP, Types.VARCHAR }); + } + + jdbcTemplate.update(LOGOUT_USERINFO_UPDATE_STATEMENT, new Object[] { logoutDateTime, userInfo.getId() }, + new int[] { Types.TIMESTAMP, Types.VARCHAR }); + + _logger.debug("Session " + WebContext.getAttribute(WebConstants.CURRENT_USER_SESSION_ID) + ", user " + + userInfo.getUsername() + " Logout, datetime " + DateUtils.toUtc(logoutDateTime) + " ."); + } + return true; + + } } diff --git a/maxkey-core/src/main/java/org/maxkey/authn/realm/jdbc/DefaultJdbcAuthenticationRealm.java b/maxkey-core/src/main/java/org/maxkey/authn/realm/jdbc/DefaultJdbcAuthenticationRealm.java index cccc1bd71..1a7faee0c 100644 --- a/maxkey-core/src/main/java/org/maxkey/authn/realm/jdbc/DefaultJdbcAuthenticationRealm.java +++ b/maxkey-core/src/main/java/org/maxkey/authn/realm/jdbc/DefaultJdbcAuthenticationRealm.java @@ -11,38 +11,41 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.crypto.password.PasswordEncoder; - /** - * same as JdbcAuthenticationRealm + * same as JdbcAuthenticationRealm. + * * @author Crystal.Sea * */ -public class DefaultJdbcAuthenticationRealm extends AbstractAuthenticationRealm{ - private static Logger _logger = LoggerFactory.getLogger(DefaultJdbcAuthenticationRealm.class); - - @Autowired - private PasswordEncoder passwordEncoder; - +public class DefaultJdbcAuthenticationRealm extends AbstractAuthenticationRealm { + private static Logger _logger = LoggerFactory.getLogger(DefaultJdbcAuthenticationRealm.class); - public DefaultJdbcAuthenticationRealm() { - - } - - public DefaultJdbcAuthenticationRealm(JdbcTemplate jdbcTemplate) { - this.jdbcTemplate=jdbcTemplate; - } + @Autowired + private PasswordEncoder passwordEncoder; + public DefaultJdbcAuthenticationRealm() { - public boolean passwordMatches(UserInfo userInfo, String j_password) { - boolean passwordMatches=false; - - _logger.info("password : "+PasswordReciprocal.getInstance().rawPassword(userInfo.getUsername(), j_password)); - passwordMatches= passwordEncoder.matches(PasswordReciprocal.getInstance().rawPassword(userInfo.getUsername(), j_password), userInfo.getPassword()); - _logger.debug("passwordvalid : "+passwordMatches); - if(!passwordMatches){ - setBadPasswordCount(userInfo); - throw new BadCredentialsException(WebContext.getI18nValue("login.error.password")); - } - return passwordMatches; - } + } + + public DefaultJdbcAuthenticationRealm(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + /** + * passwordMatches. + */ + public boolean passwordMatches(UserInfo userInfo, String password) { + boolean passwordMatches = false; + _logger.info("password : " + + PasswordReciprocal.getInstance().rawPassword(userInfo.getUsername(), password)); + passwordMatches = passwordEncoder.matches( + PasswordReciprocal.getInstance().rawPassword(userInfo.getUsername(), password), + userInfo.getPassword()); + _logger.debug("passwordvalid : " + passwordMatches); + if (!passwordMatches) { + setBadPasswordCount(userInfo); + throw new BadCredentialsException(WebContext.getI18nValue("login.error.password")); + } + return passwordMatches; + } } diff --git a/maxkey-core/src/main/java/org/maxkey/authn/realm/jdbc/JdbcAuthenticationRealm.java b/maxkey-core/src/main/java/org/maxkey/authn/realm/jdbc/JdbcAuthenticationRealm.java index 26641ad6b..d25cbf957 100644 --- a/maxkey-core/src/main/java/org/maxkey/authn/realm/jdbc/JdbcAuthenticationRealm.java +++ b/maxkey-core/src/main/java/org/maxkey/authn/realm/jdbc/JdbcAuthenticationRealm.java @@ -4,21 +4,20 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; - /** + * JdbcAuthenticationRealm. * @author Crystal.Sea * */ -public class JdbcAuthenticationRealm extends DefaultJdbcAuthenticationRealm{ - private static Logger _logger = LoggerFactory.getLogger(JdbcAuthenticationRealm.class); - +public class JdbcAuthenticationRealm extends DefaultJdbcAuthenticationRealm { + private static Logger _logger = LoggerFactory.getLogger(JdbcAuthenticationRealm.class); - public JdbcAuthenticationRealm() { - _logger.debug("init . "); - } - - public JdbcAuthenticationRealm(JdbcTemplate jdbcTemplate) { - this.jdbcTemplate=jdbcTemplate; - } + public JdbcAuthenticationRealm() { + _logger.debug("init . "); + } + + public JdbcAuthenticationRealm(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } } diff --git a/maxkey-core/src/main/java/org/maxkey/authn/support/rememberme/AbstractRemeberMeService.java b/maxkey-core/src/main/java/org/maxkey/authn/support/rememberme/AbstractRemeberMeService.java index 9be6efc76..521e8f9cf 100644 --- a/maxkey-core/src/main/java/org/maxkey/authn/support/rememberme/AbstractRemeberMeService.java +++ b/maxkey-core/src/main/java/org/maxkey/authn/support/rememberme/AbstractRemeberMeService.java @@ -94,7 +94,13 @@ public abstract class AbstractRemeberMeService { DateTime expiryDate = loginDate.plusSeconds(getRemeberMeValidity()); DateTime now = new DateTime(); if (now.isBefore(expiryDate)) { - if (WebContext.setAuthentication(storeRemeberMe.getUsername(), LOGINTYPE.REMEBER_ME, "", "", "success")) { + if (WebContext.setAuthentication( + storeRemeberMe.getUsername(), + LOGINTYPE.REMEBER_ME, + "", + "", + "success") + ) { return updateRemeberMe(remeberMeCookie, response); } } diff --git a/maxkey-core/src/main/java/org/maxkey/web/WebContext.java b/maxkey-core/src/main/java/org/maxkey/web/WebContext.java index a54f0702a..e5bca1949 100644 --- a/maxkey-core/src/main/java/org/maxkey/web/WebContext.java +++ b/maxkey-core/src/main/java/org/maxkey/web/WebContext.java @@ -1,10 +1,8 @@ package org.maxkey.web; import java.util.Locale; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; - import org.apache.commons.logging.LogFactory; import org.maxkey.authn.BasicAuthentication; import org.maxkey.authn.realm.AbstractAuthenticationRealm; @@ -24,323 +22,370 @@ import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.support.RequestContextUtils; /** - * Application is common class for Web Application Context + * Application is common class for Web Application Context. * * @author Crystal.Sea * @since 1.5 */ public final class WebContext { - - /** - * set Current login user to session - * @see WebConstants.CURRENT_USER - */ - public static void setUserInfo(UserInfo userInfo) { - setAttribute(WebConstants.CURRENT_USER,userInfo); - } - - /** - * get Current login user from session - * @see WebConstants.CURRENT_USER - * @return UserInfo - */ - public static UserInfo getUserInfo() { - return ((UserInfo)getAttribute(WebConstants.CURRENT_USER)); - } - - - /** - * set Message to session,session id is Constants.MESSAGE - * @see WebConstants.MESSAGE - * @param message - */ - public static void setMessage(Message message) { - setAttribute(WebConstants.CURRENT_MESSAGE,message); - } - - /** - * get message from session,session id is Constants.MESSAGE - * @see WebConstants.MESSAGE - * @return Message - */ - public static Message getMessage() { - return ((Message)getAttribute(WebConstants.CURRENT_MESSAGE)); - } - - /** - * clear session Message ,session id is Constants.MESSAGE - * @see WebConstants.MESSAGE - */ - public static void clearMessage() { - removeAttribute(WebConstants.CURRENT_MESSAGE); - } - - public static boolean setAuthentication(String username, String type, String provider, String code, String message){ - AbstractAuthenticationRealm authenticationRealm = (AbstractAuthenticationRealm)getBean("authenticationRealm"); - UserInfo loadeduserInfo = authenticationRealm.loadUserInfo(username,""); - if (loadeduserInfo != null) - { - setUserInfo(loadeduserInfo); - BasicAuthentication authentication =new BasicAuthentication(); - authentication.setJ_username(loadeduserInfo.getUsername()); - UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =new UsernamePasswordAuthenticationToken( - authentication, - "PASSWORD", - authenticationRealm.grantAuthority(loadeduserInfo)); - - authentication.setAuthenticated(true); - WebContext.setAuthentication(usernamePasswordAuthenticationToken); - WebContext.setUserInfo(loadeduserInfo); - - authenticationRealm.insertLoginHistory(loadeduserInfo, type, provider, code, message); - } - return true; - } - - public static void setAuthentication(Authentication authentication) { - setAttribute(WebConstants.AUTHENTICATION,authentication); - } - - public static Authentication getAuthentication() { - Authentication authentication = (Authentication)getAttribute(WebConstants.AUTHENTICATION); - return authentication; - } - - public static boolean isAuthenticated(){ - if (getUserInfo() != null) { - return true; - } - return false; - } - - - /** - * get ApplicationContext from web ServletContext configuration - * @return ApplicationContext - */ - public static ApplicationContext getApplicationContext(){ - return WebApplicationContextUtils.getWebApplicationContext(getSession().getServletContext()); - } - - /** - * get bean from spring configuration by bean id - * @param id - * @return Object - */ - public static Object getBean(String id){ - return getApplicationContext().getBean(id); - } - - - //below method is common HttpServlet method - /** - * get Spring HttpServletRequest - * @return HttpServletRequest - */ - public static HttpServletRequest getRequest(){ - return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); - } - - /** - * get Http Context full Path,if port equals 80 is omitted - * @return String - * eg:http://192.168.1.20:9080/webcontext or http://www.website.com/webcontext - */ - public static String getHttpContextPath(){ - HttpServletRequest httpServletRequest = WebContext.getRequest(); - ApplicationConfig applicationConfig=(ApplicationConfig)WebContext.getBean("applicationConfig"); - - if(applicationConfig.getServerPrefix()!=null&&!applicationConfig.getServerPrefix().equals("")){ - return applicationConfig.getServerPrefix(); - }else{ - String httpContextPath=httpServletRequest.getScheme()+"://"+applicationConfig.getDomainName(); - int port =httpServletRequest.getServerPort(); - if(port==443 && httpServletRequest.getScheme().equalsIgnoreCase("https")){ - - }else if(port==80 && httpServletRequest.getScheme().equalsIgnoreCase("http")){ - - }else{ - httpContextPath += ":"+port; - } - httpContextPath += httpServletRequest.getContextPath()+""; - return httpContextPath; - } - - } - - /** - * get current Session - * @return HttpSession - */ - public static HttpSession getSession(){ - return getRequest().getSession(); - } - - /** - * get current Session,if no session ,new Session created - * @return HttpSession - */ - public static HttpSession getSession(boolean create) { - return getRequest().getSession(create); - } - - /** - * set Attribute to session ,Attribute name is name,value is value - * @param name - * @param value - */ - public static void setAttribute(String name,Object value){ - getSession().setAttribute(name, value); - } - - /** - * get Attribute from session by name - * @param name - * @return - */ - public static Object getAttribute(String name){ - return getSession().getAttribute(name); - } - - /** - * remove Attribute from session by name - * @param name - */ - public static void removeAttribute(String name){ - getSession().removeAttribute(name); - } - - - /** - * get Request Parameter by name - * @param name - * @return String - */ - public static String getParameter(String name){ - return getRequest().getParameter(name); - } - - /** - * encoding encodingString by ApplicationConfig - * @param encodingString - * @return encoded String - */ - public static String encoding(String encodingString){ - ApplicationConfig applicationConfig = (ApplicationConfig)getBean("applicationConfig"); - return applicationConfig.getCharacterEncodingConfig().encoding(encodingString); - } - - - /** - * get locale from Spring Resolver,if locale is null,get locale from Spring SessionLocaleResolver - * this is from internationalization - * @return Locale - */ - public static Locale getLocale(){ - Locale locale=null; - try{ - CookieLocaleResolver cookieLocaleResolver=(CookieLocaleResolver) getBean("localeResolver"); - locale= cookieLocaleResolver.resolveLocale(getRequest()); - - }catch(Exception e){ - LogFactory.getLog(WebContext.class).debug("getLocale() error . "); - e.printStackTrace(); - locale= RequestContextUtils.getLocale(getRequest()); - } - - return locale; - } - - - - - /** - * get Current Date,eg 2012-07-10 - * @return String - */ - public static String getCurrentDate(){ - return DateUtils.getCurrentDateAsString(DateUtils.FORMAT_DATE_YYYY_MM_DD); - } - - /** - * get System Menu RootId,root id is constant - * @return String - */ - public static String getSystemNavRootId(){ - return "100000000000"; - } - - /** - * get Request IpAddress,for current Request - * @return String,100.167.216.100 - */ - public static final String getRequestIpAddress(){ - return getRequestIpAddress(getRequest()); - } - - /** - * get Request IpAddress by request - * @param request - * @return String - */ - public static final String getRequestIpAddress(HttpServletRequest request){ - String ipAddress = request.getHeader("x-forwarded-for"); - if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getHeader("Proxy-Client-IP"); - } - if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getHeader("WL-Proxy-Client-IP"); - } - if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getRemoteAddr(); - } - LogFactory.getLog(WebContext.class).debug("getRequestIpAddress() RequestIpAddress:"+ipAddress); - return ipAddress; - } - - - public static boolean captchaValid(String j_captcha){ - if(j_captcha==null - || !j_captcha.equals(WebContext.getSession().getAttribute(WebConstants.KAPTCHA_SESSION_KEY).toString())){ - return false; - } - return true; - } - /** - * TODO: - * @param code + * set Current login user to session. + * + * @see WebConstants.CURRENT_USER + */ + public static void setUserInfo(UserInfo userInfo) { + setAttribute(WebConstants.CURRENT_USER, userInfo); + } + + /** + * get Current login user from session. + * + * @see WebConstants.CURRENT_USER + * @return UserInfo + */ + public static UserInfo getUserInfo() { + return ((UserInfo) getAttribute(WebConstants.CURRENT_USER)); + } + + /** + * set Message to session,session id is Constants.MESSAGE + * + * @see WebConstants.MESSAGE + * @param message Message + */ + public static void setMessage(Message message) { + setAttribute(WebConstants.CURRENT_MESSAGE, message); + } + + /** + * get message from session,session id is Constants.MESSAGE + * + * @see WebConstants.MESSAGE + * @return Message + */ + public static Message getMessage() { + return ((Message) getAttribute(WebConstants.CURRENT_MESSAGE)); + } + + /** + * clear session Message ,session id is Constants.MESSAGE + * + * @see WebConstants.MESSAGE + */ + public static void clearMessage() { + removeAttribute(WebConstants.CURRENT_MESSAGE); + } + + /** + * setAuthentication. + * @param username String + * @param type String + * @param provider String + * @param code String + * @param message String + * @return boolean + */ + public static boolean setAuthentication(String username, + String type, + String provider, + String code, + String message) { + AbstractAuthenticationRealm authenticationRealm = + (AbstractAuthenticationRealm) getBean("authenticationRealm"); + UserInfo loadeduserInfo = authenticationRealm.loadUserInfo(username, ""); + if (loadeduserInfo != null) { + setUserInfo(loadeduserInfo); + BasicAuthentication authentication = new BasicAuthentication(); + authentication.setUsername(loadeduserInfo.getUsername()); + UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = + new UsernamePasswordAuthenticationToken( + authentication, + "PASSWORD", + authenticationRealm.grantAuthority(loadeduserInfo) + ); + + authentication.setAuthenticated(true); + WebContext.setAuthentication(usernamePasswordAuthenticationToken); + WebContext.setUserInfo(loadeduserInfo); + + authenticationRealm.insertLoginHistory(loadeduserInfo, type, provider, code, message); + } + return true; + } + + public static void setAuthentication(Authentication authentication) { + setAttribute(WebConstants.AUTHENTICATION, authentication); + } + + public static Authentication getAuthentication() { + Authentication authentication = (Authentication) getAttribute(WebConstants.AUTHENTICATION); + return authentication; + } + + /** + * isAuthenticated. + * @return isAuthenticated + */ + public static boolean isAuthenticated() { + if (getUserInfo() != null) { + return true; + } + return false; + } + + /** + * get ApplicationContext from web ServletContext configuration. + * + * @return ApplicationContext + */ + public static ApplicationContext getApplicationContext() { + return WebApplicationContextUtils.getWebApplicationContext( + getSession().getServletContext()); + } + + /** + * get bean from spring configuration by bean id. + * + * @param id String + * @return Object + */ + public static Object getBean(String id) { + return getApplicationContext().getBean(id); + } + + // below method is common HttpServlet method + /** + * get Spring HttpServletRequest. + * + * @return HttpServletRequest + */ + public static HttpServletRequest getRequest() { + return ((ServletRequestAttributes) + RequestContextHolder.getRequestAttributes()).getRequest(); + } + + /** + * get Http Context full Path,if port equals 80 is omitted. + * + * @return String eg:http://192.168.1.20:9080/webcontext or + * http://www.website.com/webcontext + */ + public static String getHttpContextPath() { + HttpServletRequest httpServletRequest = WebContext.getRequest(); + ApplicationConfig applicationConfig = ( + ApplicationConfig) WebContext.getBean("applicationConfig"); + + if (applicationConfig.getServerPrefix() != null + && !applicationConfig.getServerPrefix().equals("")) { + return applicationConfig.getServerPrefix(); + } else { + String httpContextPath = + httpServletRequest.getScheme() + "://" + applicationConfig.getDomainName(); + int port = httpServletRequest.getServerPort(); + if (port == 443 && httpServletRequest.getScheme().equalsIgnoreCase("https")) { + // + } else if (port == 80 && httpServletRequest.getScheme().equalsIgnoreCase("http")) { + // + } else { + httpContextPath += ":" + port; + } + httpContextPath += httpServletRequest.getContextPath() + ""; + return httpContextPath; + } + + } + + /** + * get current Session. + * + * @return HttpSession + */ + public static HttpSession getSession() { + return getRequest().getSession(); + } + + /** + * get current Session,if no session ,new Session created. + * + * @return HttpSession + */ + public static HttpSession getSession(boolean create) { + return getRequest().getSession(create); + } + + /** + * set Attribute to session ,Attribute name is name,value is value. + * + * @param name String + * @param value String + */ + public static void setAttribute(String name, Object value) { + getSession().setAttribute(name, value); + } + + /** + * get Attribute from session by name. + * + * @param name String * @return */ - public static String getI18nValue(String code) { - return code; + public static Object getAttribute(String name) { + return getSession().getAttribute(name); } - - public static String getI18nValue(String code,Object[] filedValues) { - return code; - } - + /** - * TODO: + * remove Attribute from session by name. + * + * @param name String + */ + public static void removeAttribute(String name) { + getSession().removeAttribute(name); + } + + /** + * get Request Parameter by name. + * + * @param name String + * @return String + */ + public static String getParameter(String name) { + return getRequest().getParameter(name); + } + + /** + * encoding encodingString by ApplicationConfig. + * + * @param encodingString String + * @return encoded String + */ + public static String encoding(String encodingString) { + ApplicationConfig applicationConfig = (ApplicationConfig) getBean("applicationConfig"); + return applicationConfig.getCharacterEncodingConfig().encoding(encodingString); + } + + /** + * get locale from Spring Resolver,if locale is null,get locale from Spring. + * SessionLocaleResolver this is from internationalization + * + * @return Locale + */ + public static Locale getLocale() { + Locale locale = null; + try { + CookieLocaleResolver cookieLocaleResolver = + (CookieLocaleResolver) getBean("localeResolver"); + locale = cookieLocaleResolver.resolveLocale(getRequest()); + + } catch (Exception e) { + LogFactory.getLog(WebContext.class).debug("getLocale() error . "); + e.printStackTrace(); + locale = RequestContextUtils.getLocale(getRequest()); + } + + return locale; + } + + /** + * get Current Date,eg 2012-07-10. + * + * @return String + */ + public static String getCurrentDate() { + return DateUtils.getCurrentDateAsString(DateUtils.FORMAT_DATE_YYYY_MM_DD); + } + + /** + * get System Menu RootId,root id is constant. + * + * @return String + */ + public static String getSystemNavRootId() { + return "100000000000"; + } + + /** + * get Request IpAddress,for current Request. + * + * @return String,100.167.216.100 + */ + public static final String getRequestIpAddress() { + return getRequestIpAddress(getRequest()); + } + + /** + * get Request IpAddress by request. + * + * @param request HttpServletRequest + * @return String + */ + public static final String getRequestIpAddress(HttpServletRequest request) { + String ipAddress = request.getHeader("x-forwarded-for"); + if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { + ipAddress = request.getHeader("Proxy-Client-IP"); + } + if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { + ipAddress = request.getHeader("WL-Proxy-Client-IP"); + } + if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { + ipAddress = request.getRemoteAddr(); + } + LogFactory.getLog(WebContext.class).debug( + "getRequestIpAddress() RequestIpAddress:" + ipAddress); + return ipAddress; + } + + /** + * captchaValid. + * @param captcha String * @return */ - public static String getRequestLocale() { - return ""; + public static boolean captchaValid(String captcha) { + if (captcha == null || !captcha + .equals(WebContext.getSession().getAttribute( + WebConstants.KAPTCHA_SESSION_KEY).toString())) { + return false; + } + return true; + } + + //TODO: + /** + * getI18nValue. + * @param code String + * @return + */ + public static String getI18nValue(String code) { + return code; + } + + public static String getI18nValue(String code, Object[] filedValues) { + return code; + } + + //TODO: + /** + * getRequestLocale. + * @return + */ + public static String getRequestLocale() { + return ""; + } + + /** + * generate random Universally Unique Identifier,delete -. + * + * @return String + */ + public static String genId() { + return (new StringGenerator()).uuidGenerate(); + } + + public static ModelAndView redirect(String redirectUrl) { + return new ModelAndView("redirect:" + redirectUrl); + } + + public static ModelAndView forward(String forwardUrl) { + return new ModelAndView("forward:" + forwardUrl); } - /** - * generate random Universally Unique Identifier,delete - - * @return String - */ - public static String genId() { - return (new StringGenerator()).uuidGenerate(); - } - - public static ModelAndView redirect(String redirectUrl){ - return new ModelAndView("redirect:"+redirectUrl); - } - - public static ModelAndView forward(String forwardUrl){ - return new ModelAndView("forward:"+forwardUrl); - } } \ No newline at end of file diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/Cas10AuthorizeEndpoint.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/Cas10AuthorizeEndpoint.java index 0d8d7bf20..e29153af3 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/Cas10AuthorizeEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/Cas10AuthorizeEndpoint.java @@ -90,7 +90,7 @@ renew [OPTIONAL] - if this parameter is set, ticket validation will only succeed } if(storedTicket!=null){ - String principal=((BasicAuthentication)storedTicket.getAuthentication().getPrincipal()).getJ_username(); + String principal=((BasicAuthentication)storedTicket.getAuthentication().getPrincipal()).getUsername(); _logger.debug("principal "+principal); return new Service10ResponseBuilder().success() .setUser(principal) diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/Cas20AuthorizeEndpoint.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/Cas20AuthorizeEndpoint.java index 2a10665ff..b7398fa03 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/Cas20AuthorizeEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/Cas20AuthorizeEndpoint.java @@ -190,7 +190,7 @@ For all error codes, it is RECOMMENDED that CAS provide a more detailed message ServiceResponseBuilder serviceResponseBuilder=new ServiceResponseBuilder(); if(storedTicket!=null){ - String principal=((BasicAuthentication)storedTicket.getAuthentication().getPrincipal()).getJ_username(); + String principal=((BasicAuthentication)storedTicket.getAuthentication().getPrincipal()).getUsername(); _logger.debug("principal "+principal); serviceResponseBuilder.success().setUser(principal); diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/Cas30AuthorizeEndpoint.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/Cas30AuthorizeEndpoint.java index 994eeebdd..b95a03f1d 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/Cas30AuthorizeEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/Cas30AuthorizeEndpoint.java @@ -71,7 +71,7 @@ public class Cas30AuthorizeEndpoint extends AuthorizeBaseEndpoint{ ServiceResponseBuilder serviceResponseBuilder=new ServiceResponseBuilder(); if(storedTicket!=null){ - String principal=((BasicAuthentication)storedTicket.getAuthentication().getPrincipal()).getJ_username(); + String principal=((BasicAuthentication)storedTicket.getAuthentication().getPrincipal()).getUsername(); serviceResponseBuilder.success().setUser(principal); if(BOOLEAN.isTrue(storedTicket.getCasDetails().getIsAdapter())){ @@ -111,7 +111,7 @@ public class Cas30AuthorizeEndpoint extends AuthorizeBaseEndpoint{ ServiceResponseBuilder serviceResponseBuilder=new ServiceResponseBuilder(); if(storedTicket!=null){ - String principal=((BasicAuthentication)storedTicket.getAuthentication().getPrincipal()).getJ_username(); + String principal=((BasicAuthentication)storedTicket.getAuthentication().getPrincipal()).getUsername(); serviceResponseBuilder.success().setUser(principal); if(BOOLEAN.isTrue(storedTicket.getCasDetails().getIsAdapter())){ diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/approval/controller/OAuth20AccessConfirmationController.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/approval/controller/OAuth20AccessConfirmationController.java index 1787c7d74..9c2ee7ed5 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/approval/controller/OAuth20AccessConfirmationController.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/approval/controller/OAuth20AccessConfirmationController.java @@ -52,7 +52,7 @@ public class OAuth20AccessConfirmationController { for(Object key:model.keySet()){ modelRequest.put(key.toString(), model.get(key).toString()); } - String principal=((BasicAuthentication)WebContext.getAuthentication().getPrincipal()).getJ_username(); + String principal=((BasicAuthentication)WebContext.getAuthentication().getPrincipal()).getUsername(); //Map model AuthorizationRequest clientAuth = (AuthorizationRequest) WebContext.getAttribute("authorizationRequest"); ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId()); diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/endpoint/TokenEndpointAuthenticationFilter.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/endpoint/TokenEndpointAuthenticationFilter.java index e17666e52..f2e37cab9 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/endpoint/TokenEndpointAuthenticationFilter.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/endpoint/TokenEndpointAuthenticationFilter.java @@ -132,7 +132,7 @@ public class TokenEndpointAuthenticationFilter implements Filter { }else { Authentication authentication=ClientCredentials(request,response); BasicAuthentication auth =new BasicAuthentication(); - auth.setJ_username(((User)authentication.getPrincipal()).getUsername()); + auth.setUsername(((User)authentication.getPrincipal()).getUsername()); auth.setAuthenticated(true); UsernamePasswordAuthenticationToken simpleUserAuthentication = new UsernamePasswordAuthenticationToken(auth, authentication.getCredentials(), authentication.getAuthorities()); WebContext.setAuthentication(simpleUserAuthentication); diff --git a/maxkey-web-manage/src/main/resources/templates/views/login.ftl b/maxkey-web-manage/src/main/resources/templates/views/login.ftl index dc4a0f75a..df302ec7e 100644 --- a/maxkey-web-manage/src/main/resources/templates/views/login.ftl +++ b/maxkey-web-manage/src/main/resources/templates/views/login.ftl @@ -29,19 +29,19 @@
- "> + ">
- "> + ">
- "> + ">
- - + + diff --git a/maxkey-web-maxkey/src/main/resources/templates/views/login.ftl b/maxkey-web-maxkey/src/main/resources/templates/views/login.ftl index 4a5fd20be..acf36ad71 100644 --- a/maxkey-web-maxkey/src/main/resources/templates/views/login.ftl +++ b/maxkey-web-maxkey/src/main/resources/templates/views/login.ftl @@ -186,20 +186,20 @@ $(function(){
- + - + - + <#if true==isCaptcha> - + @@ -210,7 +210,7 @@ $(function(){ @@ -222,7 +222,7 @@ $(function(){ - + @@ -235,15 +235,15 @@ $(function(){
- +
- + - + <#if true==isOneTimePwd> @@ -255,7 +255,7 @@ $(function(){ @@ -274,7 +274,7 @@ $(function(){ @@ -286,7 +286,7 @@ $(function(){ - +