From 50bfb3087ec690a330d90c2d8f13c01d7a3117b2 Mon Sep 17 00:00:00 2001 From: MaxKey Date: Tue, 12 Apr 2022 22:31:41 +0800 Subject: [PATCH] AuthorizationUtils --- .../authn/AbstractAuthenticationProvider.java | 7 - .../authn/RealmAuthenticationProvider.java | 22 +-- ...uestAwareAuthenticationSuccessHandler.java | 10 -- .../java/org/maxkey/authn/jwt/AuthJwt.java | 32 ++-- .../realm/AbstractAuthenticationRealm.java | 17 +- .../realm/jdbc/JdbcAuthenticationRealm.java | 14 +- .../authn/support/jwt/HttpJwtEntryPoint.java | 4 +- .../kerberos/HttpKerberosEntryPoint.java | 4 +- .../rememberme/AbstractRemeberMeService.java | 166 ------------------ .../rememberme/HttpRemeberMeEntryPoint.java | 149 ---------------- .../rememberme/InMemoryRemeberMeService.java | 54 ------ .../rememberme/JdbcRemeberMeService.java | 91 ---------- .../rememberme/RedisRemeberMeService.java | 71 -------- .../authn/support/rememberme/RemeberMe.java | 74 -------- .../rememberme/RemeberMeServiceFactory.java | 48 ----- .../HttpWsFederationEntryPoint.java | 4 +- .../maxkey/authn/web/AuthorizationUtils.java | 95 ++++++++++ .../CurrentUserMethodArgumentResolver.java | 2 +- .../SessionSecurityContextHolderStrategy.java | 4 +- ...Point.java => UnauthorizedEntryPoint.java} | 20 +-- .../web/interceptor/PermissionAdapter.java | 115 ------------ .../interceptor/PermissionInterceptor.java | 84 +++++++++ .../AuthenticationAutoConfiguration.java | 16 -- .../socialsignon/SocialSignOnEndpoint.java | 31 +--- .../org/maxkey/entity/ChangePassword.java | 65 +++++-- .../main/java/org/maxkey/entity/UserInfo.java | 6 + .../repository/PasswordPolicyValidator.java | 7 +- .../main/java/org/maxkey/web/WebContext.java | 48 +---- .../org/maxkey/web/tag/ThemeTagDirective.java | 86 --------- .../identity/rest/RestUserInfoController.java | 5 +- .../persistence/mapper/UserInfoMapper.java | 3 +- .../persistence/service/UserInfoService.java | 115 +++++------- .../mapper/xml/mysql/UserInfoMapper.xml | 4 +- .../authz/endpoint/AuthorizeBaseEndpoint.java | 5 +- .../endpoint/AuthorizeCredentialEndpoint.java | 20 ++- .../endpoint/AuthorizeProtectedEndpoint.java | 8 +- .../cas/endpoint/CasAuthorizeEndpoint.java | 6 +- .../authz/cas/endpoint/CasRestV1Endpoint.java | 8 +- .../endpoint/ExtendApiAuthorizeEndpoint.java | 16 +- .../endpoint/FormBasedAuthorizeEndpoint.java | 14 +- .../token/endpoint/JwtAuthorizeEndpoint.java | 11 +- .../OAuth20AccessConfirmationEndpoint.java | 5 +- .../endpoint/AuthorizationEndpoint.java | 6 +- .../provider/endpoint/TokenEndpoint.java | 4 +- .../TokenEndpointAuthenticationFilter.java | 5 +- .../oidc/idtoken/OIDCIdTokenEnhancer.java | 4 +- .../provider/endpoint/AssertionEndpoint.java | 15 +- .../provider/xml/AssertionGenerator.java | 18 +- .../xml/AttributeStatementGenerator.java | 19 +- .../provider/xml/AuthnResponseGenerator.java | 7 +- .../saml20/provider/xml/SubjectGenerator.java | 4 +- .../endpoint/TokenBasedAuthorizeEndpoint.java | 11 +- .../main/java/org/maxkey/MaxKeyConfig.java | 3 - .../main/java/org/maxkey/MaxKeyMvcConfig.java | 84 +++------ .../web/contorller/AppListController.java | 2 +- .../contorller/ChangePasswodController.java | 74 ++++++++ .../contorller/ForgotPasswordContorller.java | 3 +- .../web/contorller/ProfileController.java | 61 +++---- .../maxkey/web/contorller/SafeController.java | 124 ++----------- .../maxkey/web/endpoint/LoginEntryPoint.java | 8 +- .../maxkey/web/endpoint/LogoutEndpoint.java | 6 +- .../maxkey/web/filter/SingleSignOnFilter.java | 69 -------- ...apter.java => HistoryLogsInterceptor.java} | 16 +- ....java => HistorySignOnAppInterceptor.java} | 42 +++-- .../web/interceptor/PreLoginAppAdapter.java | 70 -------- .../interceptor/SingleSignOnInterceptor.java | 70 ++++++++ .../main/java/org/maxkey/MaxKeyMgtConfig.java | 3 - .../java/org/maxkey/MaxKeyMgtMvcConfig.java | 22 +-- .../contorller/LocalizationController.java | 12 +- .../web/contorller/LoginEntryPoint.java | 2 +- .../contorller/OrganizationsController.java | 11 +- .../web/contorller/UserAdjointController.java | 26 ++- .../web/contorller/UserInfoController.java | 29 +-- .../web/interceptor/HistoryLogsAdapter.java | 4 +- .../interceptor/RestApiPermissionAdapter.java | 4 +- 75 files changed, 766 insertions(+), 1638 deletions(-) delete mode 100644 maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/AbstractRemeberMeService.java delete mode 100644 maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/HttpRemeberMeEntryPoint.java delete mode 100644 maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/InMemoryRemeberMeService.java delete mode 100644 maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/JdbcRemeberMeService.java delete mode 100644 maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/RedisRemeberMeService.java delete mode 100644 maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/RemeberMe.java delete mode 100644 maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/RemeberMeServiceFactory.java create mode 100644 maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/AuthorizationUtils.java rename maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/{AuthEntryPoint.java => UnauthorizedEntryPoint.java} (60%) delete mode 100644 maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/interceptor/PermissionAdapter.java create mode 100644 maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/interceptor/PermissionInterceptor.java delete mode 100644 maxkey-core/src/main/java/org/maxkey/web/tag/ThemeTagDirective.java create mode 100644 maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/ChangePasswodController.java delete mode 100644 maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/filter/SingleSignOnFilter.java rename maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/{HistoryLogsAdapter.java => HistoryLogsInterceptor.java} (82%) rename maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/{HistoryLoginAppAdapter.java => HistorySignOnAppInterceptor.java} (68%) delete mode 100644 maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/PreLoginAppAdapter.java create mode 100644 maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/SingleSignOnInterceptor.java diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/AbstractAuthenticationProvider.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/AbstractAuthenticationProvider.java index 960c8a192..741e016a7 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/AbstractAuthenticationProvider.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/AbstractAuthenticationProvider.java @@ -22,7 +22,6 @@ import java.util.HashMap; import org.maxkey.authn.online.OnlineTicketService; import org.maxkey.authn.realm.AbstractAuthenticationRealm; -import org.maxkey.authn.support.rememberme.AbstractRemeberMeService; import org.maxkey.configuration.ApplicationConfig; import org.maxkey.constants.ConstsLoginType; import org.maxkey.constants.ConstsStatus; @@ -62,8 +61,6 @@ public abstract class AbstractAuthenticationProvider { protected OtpAuthnService otpAuthnService; - protected AbstractRemeberMeService remeberMeService; - protected OnlineTicketService onlineTicketServices; public static ArrayList grantedAdministratorsAuthoritys = new ArrayList(); @@ -372,10 +369,6 @@ public abstract class AbstractAuthenticationProvider { this.tfaOtpAuthn = tfaOtpAuthn; } - public void setRemeberMeService(AbstractRemeberMeService remeberMeService) { - this.remeberMeService = remeberMeService; - } - public void setOnlineTicketServices(OnlineTicketService onlineTicketServices) { this.onlineTicketServices = onlineTicketServices; } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/RealmAuthenticationProvider.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/RealmAuthenticationProvider.java index d6d431574..d6e58a9e0 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/RealmAuthenticationProvider.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/RealmAuthenticationProvider.java @@ -22,7 +22,7 @@ import java.util.ArrayList; import org.maxkey.authn.online.OnlineTicket; import org.maxkey.authn.online.OnlineTicketService; import org.maxkey.authn.realm.AbstractAuthenticationRealm; -import org.maxkey.authn.support.rememberme.AbstractRemeberMeService; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.configuration.ApplicationConfig; import org.maxkey.entity.Institutions; import org.maxkey.entity.UserInfo; @@ -37,8 +37,6 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.web.authentication.WebAuthenticationDetails; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; /** @@ -65,13 +63,11 @@ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider ApplicationConfig applicationConfig, AbstractOtpAuthn tfaOtpAuthn, OtpAuthnService otpAuthnService, - AbstractRemeberMeService remeberMeService, OnlineTicketService onlineTicketServices) { this.authenticationRealm = authenticationRealm; this.applicationConfig = applicationConfig; this.tfaOtpAuthn = tfaOtpAuthn; this.otpAuthnService = otpAuthnService; - this.remeberMeService = remeberMeService; this.onlineTicketServices = onlineTicketServices; } @@ -115,20 +111,6 @@ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider authenticationRealm.getPasswordPolicyValidator().applyPasswordPolicy(userInfo); UsernamePasswordAuthenticationToken authenticationToken = createOnlineSession(loginCredential,userInfo); - //RemeberMe Config check then set RemeberMe cookies - if (applicationConfig.getLoginConfig().isRemeberMe()) { - if (loginCredential.getRemeberMe() != null && loginCredential.getRemeberMe().equals("remeberMe")) { - WebContext.getSession().setAttribute( - WebConstants.REMEBER_ME_SESSION,loginCredential.getUsername()); - _logger.debug("do Remeber Me"); - remeberMeService.createRemeberMe( - userInfo.getUsername(), - WebContext.getRequest(), - ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()) - .getResponse() - ); - } - } return authenticationToken; } @@ -225,7 +207,7 @@ public class RealmAuthenticationProvider extends AbstractAuthenticationProvider /* * put Authentication to current session context */ - WebContext.setAuthentication(authenticationToken); + AuthorizationUtils.setAuthentication(authenticationToken); return authenticationToken; } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/SavedRequestAwareAuthenticationSuccessHandler.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/SavedRequestAwareAuthenticationSuccessHandler.java index 4a6b5a370..51dea2b1b 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/SavedRequestAwareAuthenticationSuccessHandler.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/SavedRequestAwareAuthenticationSuccessHandler.java @@ -22,13 +22,10 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.maxkey.authn.support.rememberme.AbstractRemeberMeService; import org.maxkey.web.WebConstants; import org.maxkey.web.WebContext; 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.security.core.Authentication; import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; import org.springframework.security.web.savedrequest.HttpSessionRequestCache; @@ -74,10 +71,6 @@ public class SavedRequestAwareAuthenticationSuccessHandler protected final Logger _logger = LoggerFactory.getLogger( SavedRequestAwareAuthenticationSuccessHandler.class); - @Autowired - @Qualifier("remeberMeService") - protected AbstractRemeberMeService remeberMeService; - private RequestCache requestCache = new HttpSessionRequestCache(); @Override @@ -85,9 +78,6 @@ public class SavedRequestAwareAuthenticationSuccessHandler Authentication authentication) throws ServletException, IOException { SavedRequest savedRequest = requestCache.getRequest(request, response); - remeberMeService.createRemeberMe( - authentication.getPrincipal().toString(), request, response); - if (savedRequest == null) { super.onAuthenticationSuccess(request, response, authentication); diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/jwt/AuthJwt.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/jwt/AuthJwt.java index 4fbc8c3e4..0045726c0 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/jwt/AuthJwt.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/jwt/AuthJwt.java @@ -8,16 +8,17 @@ import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; public class AuthJwt { - private String token; - private String type = "Bearer"; - private String id; - private String name; - private String username; - private String displayName; - private String email; - private String instId; - private String instName; - private List authorities; + private String ticket; + private String token; + private String type = "Bearer"; + private String id; + private String name; + private String username; + private String displayName; + private String email; + private String instId; + private String instName; + private List authorities; public AuthJwt(String token, String id, String username, String displayName, String email, String instId, @@ -37,6 +38,8 @@ public class AuthJwt { SigninPrincipal signinPrincipal = ((SigninPrincipal)authentication.getPrincipal()); this.token = token; + this.ticket = signinPrincipal.getOnlineTicket().getTicketId().substring(3); + this.id = signinPrincipal.getUserInfo().getId(); this.username = signinPrincipal.getUserInfo().getUsername(); this.name = this.username; @@ -115,6 +118,15 @@ public class AuthJwt { public void setAuthorities(List authorities) { this.authorities = authorities; } + + public String getTicket() { + return ticket; + } + + public void setTicket(String ticket) { + this.ticket = ticket; + } + @Override public String toString() { StringBuilder builder = new StringBuilder(); diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/realm/AbstractAuthenticationRealm.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/realm/AbstractAuthenticationRealm.java index dbf7ba193..b4836e06c 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/realm/AbstractAuthenticationRealm.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/realm/AbstractAuthenticationRealm.java @@ -24,7 +24,6 @@ import javax.servlet.http.HttpServletResponse; import org.maxkey.authn.SigninPrincipal; import org.maxkey.authn.realm.ldap.LdapAuthenticationRealmService; -import org.maxkey.authn.support.rememberme.AbstractRemeberMeService; import org.maxkey.entity.Groups; import org.maxkey.entity.HistoryLogin; import org.maxkey.entity.UserInfo; @@ -57,8 +56,6 @@ public abstract class AbstractAuthenticationRealm { protected LoginRepository loginRepository; protected LoginHistoryRepository loginHistoryRepository; - - protected AbstractRemeberMeService remeberMeService; protected UserInfoService userInfoService; @@ -90,16 +87,6 @@ public abstract class AbstractAuthenticationRealm { public abstract boolean passwordMatches(UserInfo userInfo, String password); - - public static boolean isAuthenticated() { - if (WebContext.getUserInfo() != null) { - return true; - } else { - return false; - } - } - - public List queryGroups(UserInfo userInfo) { return loginRepository.queryGroups(userInfo); } @@ -183,9 +170,7 @@ public abstract class AbstractAuthenticationRealm { SigninPrincipal signinPrincipal = ((SigninPrincipal) authentication.getPrincipal()); UserInfo userInfo = signinPrincipal.getUserInfo(); userInfo.setLastLogoffTime(DateUtils.formatDateTime(new Date())); - - remeberMeService.removeRemeberMe(response); - + loginHistoryRepository.logoff(userInfo.getLastLogoffTime(), signinPrincipal.getOnlineTicket().getTicketId()); diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/realm/jdbc/JdbcAuthenticationRealm.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/realm/jdbc/JdbcAuthenticationRealm.java index 22c5d3b12..fa1ff305b 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/realm/jdbc/JdbcAuthenticationRealm.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/realm/jdbc/JdbcAuthenticationRealm.java @@ -20,8 +20,8 @@ package org.maxkey.authn.realm.jdbc; import org.maxkey.authn.realm.AbstractAuthenticationRealm; import org.maxkey.authn.realm.ldap.LdapAuthenticationRealm; import org.maxkey.authn.realm.ldap.LdapAuthenticationRealmService; -import org.maxkey.authn.support.rememberme.AbstractRemeberMeService; import org.maxkey.constants.ConstsLoginType; +import org.maxkey.entity.ChangePassword; import org.maxkey.entity.PasswordPolicy; import org.maxkey.entity.UserInfo; import org.maxkey.persistence.repository.LoginHistoryRepository; @@ -59,7 +59,6 @@ public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm { PasswordPolicyValidator passwordPolicyValidator, LoginRepository loginRepository, LoginHistoryRepository loginHistoryRepository, - AbstractRemeberMeService remeberMeService, UserInfoService userInfoService, JdbcTemplate jdbcTemplate) { @@ -67,7 +66,6 @@ public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm { this.passwordPolicyValidator=passwordPolicyValidator; this.loginRepository = loginRepository; this.loginHistoryRepository = loginHistoryRepository; - this.remeberMeService = remeberMeService; this.userInfoService = userInfoService; this.jdbcTemplate = jdbcTemplate; } @@ -77,7 +75,6 @@ public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm { PasswordPolicyValidator passwordPolicyValidator, LoginRepository loginRepository, LoginHistoryRepository loginHistoryRepository, - AbstractRemeberMeService remeberMeService, UserInfoService userInfoService, JdbcTemplate jdbcTemplate, LdapAuthenticationRealmService ldapAuthenticationRealmService) { @@ -85,7 +82,6 @@ public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm { this.passwordPolicyValidator = passwordPolicyValidator; this.loginRepository = loginRepository; this.loginHistoryRepository = loginHistoryRepository; - this.remeberMeService = remeberMeService; this.userInfoService = userInfoService; this.jdbcTemplate = jdbcTemplate; this.ldapAuthenticationRealmService = ldapAuthenticationRealmService; @@ -109,11 +105,9 @@ public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm { passwordMatches = ldapRealm.passwordMatches(userInfo, password); if(passwordMatches) { //write password to database Realm - UserInfo changePasswordUser = new UserInfo(); - changePasswordUser.setId(userInfo.getId()); - changePasswordUser.setUsername(userInfo.getUsername()); - changePasswordUser.setPassword(password); - userInfoService.changePassword(changePasswordUser, false); + ChangePassword changePassword = new ChangePassword(userInfo); + changePassword.setPassword(password); + userInfoService.changePassword(changePassword, false); } } } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/jwt/HttpJwtEntryPoint.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/jwt/HttpJwtEntryPoint.java index b10c4428f..6f6c0d16b 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/jwt/HttpJwtEntryPoint.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/jwt/HttpJwtEntryPoint.java @@ -22,10 +22,10 @@ import javax.servlet.http.HttpServletResponse; import org.maxkey.authn.AbstractAuthenticationProvider; import org.maxkey.authn.LoginCredential; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.configuration.ApplicationConfig; import org.maxkey.constants.ConstsLoginType; import org.maxkey.web.WebConstants; -import org.maxkey.web.WebContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.AsyncHandlerInterceptor; @@ -46,7 +46,7 @@ public class HttpJwtEntryPoint implements AsyncHandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { - boolean isAuthenticated= WebContext.isAuthenticated(); + boolean isAuthenticated= AuthorizationUtils.isAuthenticated(); String jwt = request.getParameter(WebConstants.JWT_TOKEN_PARAMETER); if(!enable diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/kerberos/HttpKerberosEntryPoint.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/kerberos/HttpKerberosEntryPoint.java index ae35be10d..2ce0e2385 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/kerberos/HttpKerberosEntryPoint.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/kerberos/HttpKerberosEntryPoint.java @@ -22,13 +22,13 @@ import javax.servlet.http.HttpServletResponse; import org.joda.time.DateTime; import org.maxkey.authn.AbstractAuthenticationProvider; import org.maxkey.authn.LoginCredential; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.configuration.ApplicationConfig; import org.maxkey.constants.ConstsLoginType; import org.maxkey.crypto.ReciprocalUtils; import org.maxkey.util.DateUtils; import org.maxkey.util.JsonUtils; import org.maxkey.web.WebConstants; -import org.maxkey.web.WebContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.AsyncHandlerInterceptor; @@ -47,7 +47,7 @@ public class HttpKerberosEntryPoint implements AsyncHandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { - boolean isAuthenticated= WebContext.isAuthenticated(); + boolean isAuthenticated= AuthorizationUtils.isAuthenticated(); String kerberosTokenString = request.getParameter(WebConstants.KERBEROS_TOKEN_PARAMETER); String kerberosUserDomain = request.getParameter(WebConstants.KERBEROS_USERDOMAIN_PARAMETER); diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/AbstractRemeberMeService.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/AbstractRemeberMeService.java deleted file mode 100644 index e14bacba3..000000000 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/AbstractRemeberMeService.java +++ /dev/null @@ -1,166 +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.support.rememberme; - -import java.util.Date; -import java.util.regex.Pattern; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.maxkey.configuration.ApplicationConfig; -import org.maxkey.constants.ConstsTimeInterval; -import org.maxkey.crypto.Base64Utils; -import org.maxkey.crypto.password.PasswordReciprocal; -import org.maxkey.util.JsonUtils; -import org.maxkey.web.WebConstants; -import org.maxkey.web.WebContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; - -public abstract class AbstractRemeberMeService { - private static final Logger _logger = LoggerFactory.getLogger(AbstractRemeberMeService.class); - - protected Integer remeberMeValidity = ConstsTimeInterval.TWO_WEEK; - - protected String validity; - - @Autowired - @Qualifier("applicationConfig") - protected ApplicationConfig applicationConfig; - - // follow function is for persist - public abstract void save(RemeberMe remeberMe); - - public abstract void update(RemeberMe remeberMe); - - public abstract RemeberMe read(RemeberMe remeberMe); - - public abstract void remove(String username); - // end persist - - public boolean createRemeberMe(String username, HttpServletRequest request, HttpServletResponse response) { - if (request.getSession().getAttribute(WebConstants.REMEBER_ME_SESSION) != null - && applicationConfig.getLoginConfig().isRemeberMe()) { - _logger.debug("Remeber Me ..."); - RemeberMe remeberMe = new RemeberMe(); - remeberMe.setAuthKey(WebContext.genId()); - remeberMe.setId(WebContext.genId()); - remeberMe.setUsername(WebContext.getUserInfo().getUsername()); - remeberMe.setLastLogin(new Date()); - save(remeberMe); - _logger.debug("Remeber Me " + remeberMe); - _logger.debug("Cookie Name : " + WebConstants.REMEBER_ME_COOKIE); - - String jsonRemeberMe = JsonUtils.object2Json(remeberMe); - _logger.debug("Remeber Me JSON " + jsonRemeberMe); - - jsonRemeberMe = PasswordReciprocal.getInstance().encode(jsonRemeberMe); - - String cookieValue = Base64Utils.base64UrlEncode(jsonRemeberMe.getBytes()); - - _logger.debug("Remeber Me JSON " + cookieValue); - Cookie cookie = new Cookie(WebConstants.REMEBER_ME_COOKIE, cookieValue); - - Integer maxAge = getRemeberMeValidity(); - _logger.debug("Cookie Max Age :" + maxAge + " seconds."); - cookie.setMaxAge(maxAge); - - // cookie.setPath("/"); - cookie.setDomain(applicationConfig.getDomainName()); - response.addCookie(cookie); - request.getSession().removeAttribute(WebConstants.REMEBER_ME_SESSION); - } - return true; - } - - public boolean updateRemeberMe(RemeberMe remeberMe, HttpServletResponse response) { - remeberMe.setAuthKey(WebContext.genId()); - remeberMe.setLastLogin(new Date()); - update(remeberMe); - _logger.debug("update Remeber Me " + remeberMe); - _logger.debug("Cookie Name : " + WebConstants.REMEBER_ME_COOKIE); - - String jsonRemeberMe = JsonUtils.object2Json(remeberMe); - _logger.debug("Remeber Me JSON " + jsonRemeberMe); - - _logger.debug("Encode Remeber Me JSON ..."); - jsonRemeberMe = PasswordReciprocal.getInstance().encode(jsonRemeberMe); - _logger.debug("Encode Remeber Me JSON " + jsonRemeberMe); - - String cookieValue = Base64Utils.base64UrlEncode(jsonRemeberMe.getBytes()); - - Cookie cookie = new Cookie(WebConstants.REMEBER_ME_COOKIE, cookieValue); - - Integer maxAge = getRemeberMeValidity(); - _logger.debug("Cookie Max Age :" + maxAge + " seconds."); - cookie.setMaxAge(maxAge); - - // cookie.setPath("/"); - cookie.setDomain(applicationConfig.getDomainName()); - response.addCookie(cookie); - return true; - } - - public boolean removeRemeberMe(HttpServletResponse response) { - Cookie cookie = new Cookie(WebConstants.REMEBER_ME_COOKIE, null); - cookie.setMaxAge(0); - - cookie.setDomain(applicationConfig.getDomainName()); - response.addCookie(cookie); - - remove(WebContext.getUserInfo().getUsername()); - - return true; - } - - public Integer getRemeberMeValidity() { - return remeberMeValidity; - } - - public void setRemeberMeValidity(Integer remeberMeValidity) { - this.remeberMeValidity = remeberMeValidity; - } - - public String getValidity() { - return validity; - } - - public void setApplicationConfig(ApplicationConfig applicationConfig) { - this.applicationConfig = applicationConfig; - } - - public void setValidity(String validity) { - _logger.debug("validity : " + validity); - this.validity = validity; - if (Pattern.matches("[0-9]+", validity)) { - remeberMeValidity = Integer.parseInt(validity); - } else if (validity.equalsIgnoreCase("ONE_DAY")) { - remeberMeValidity = ConstsTimeInterval.ONE_DAY; - } else if (validity.equalsIgnoreCase("ONE_WEEK")) { - remeberMeValidity = ConstsTimeInterval.ONE_WEEK; - } else if (validity.equalsIgnoreCase("TWO_WEEK")) { - remeberMeValidity = ConstsTimeInterval.TWO_WEEK; - } else if (validity.equalsIgnoreCase("ONE_YEAR")) { - remeberMeValidity = ConstsTimeInterval.ONE_YEAR; - } - - _logger.debug("Remeber Me Validity : " + remeberMeValidity); - } -} diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/HttpRemeberMeEntryPoint.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/HttpRemeberMeEntryPoint.java deleted file mode 100644 index 432764c25..000000000 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/HttpRemeberMeEntryPoint.java +++ /dev/null @@ -1,149 +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.support.rememberme; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.joda.time.DateTime; -import org.maxkey.authn.AbstractAuthenticationProvider; -import org.maxkey.authn.LoginCredential; -import org.maxkey.configuration.ApplicationConfig; -import org.maxkey.constants.ConstsLoginType; -import org.maxkey.crypto.Base64Utils; -import org.maxkey.crypto.password.PasswordReciprocal; -import org.maxkey.util.JsonUtils; -import org.maxkey.web.WebConstants; -import org.maxkey.web.WebContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.servlet.AsyncHandlerInterceptor; - - -public class HttpRemeberMeEntryPoint implements AsyncHandlerInterceptor { - private static final Logger _logger = LoggerFactory.getLogger(HttpRemeberMeEntryPoint.class); - - boolean enable; - - ApplicationConfig applicationConfig; - - AbstractAuthenticationProvider authenticationProvider ; - - AbstractRemeberMeService remeberMeService; - - @Override - public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { - boolean isAuthenticated= WebContext.isAuthenticated(); - Cookie readRemeberMeCookie = WebContext.readCookieByName(request,WebConstants.REMEBER_ME_COOKIE); - - if(!enable - || isAuthenticated - || readRemeberMeCookie==null - || !applicationConfig.getLoginConfig().isRemeberMe()){ - return true; - } - - _logger.trace("RemeberMe Login Start ..."); - _logger.trace("Request url : "+ request.getRequestURL()); - _logger.trace("Request URI : "+ request.getRequestURI()); - _logger.trace("Request ContextPath : "+ request.getContextPath()); - _logger.trace("Request ServletPath : "+ request.getServletPath()); - _logger.trace("RequestSessionId : "+ request.getRequestedSessionId()); - _logger.trace("isRequestedSessionIdValid : "+ request.isRequestedSessionIdValid()); - _logger.trace("getSession : "+ request.getSession(false)); - - // session not exists,session timeout,recreate new session - if(request.getSession(false) == null) { - _logger.info("recreate new session ."); - request.getSession(true); - } - - _logger.trace("getSession.getId : "+ request.getSession().getId()); - - _logger.debug("Try RemeberMe login "); - String remeberMe = readRemeberMeCookie.getValue(); - _logger.debug("RemeberMe : " + remeberMe); - - remeberMe = new String(Base64Utils.base64UrlDecode(remeberMe)); - - remeberMe = PasswordReciprocal.getInstance().decoder(remeberMe); - - _logger.debug("decoder RemeberMe : " + remeberMe); - RemeberMe remeberMeCookie = new RemeberMe(); - remeberMeCookie = (RemeberMe) JsonUtils.json2Object(remeberMe, remeberMeCookie); - _logger.debug("Remeber Me Cookie : " + remeberMeCookie); - - RemeberMe storeRemeberMe = remeberMeService.read(remeberMeCookie); - if (storeRemeberMe != null) { - DateTime loginDate = new DateTime(storeRemeberMe.getLastLogin()); - DateTime expiryDate = loginDate.plusSeconds(remeberMeService.getRemeberMeValidity()); - DateTime now = new DateTime(); - if (now.isBefore(expiryDate)) { - LoginCredential loginCredential = - new LoginCredential(storeRemeberMe.getUsername(),"",ConstsLoginType.REMEBER_ME); - authenticationProvider.authentication(loginCredential,true); - remeberMeService.updateRemeberMe(remeberMeCookie, response); - _logger.debug("RemeberMe Logined in , username " + storeRemeberMe.getUsername()); - } - } - - return true; - } - - public HttpRemeberMeEntryPoint() { - super(); - } - - public HttpRemeberMeEntryPoint (boolean enable) { - super(); - this.enable = enable; - } - - public HttpRemeberMeEntryPoint( - AbstractAuthenticationProvider authenticationProvider, AbstractRemeberMeService remeberMeService, - ApplicationConfig applicationConfig,boolean enable) { - super(); - this.enable = enable; - this.applicationConfig = applicationConfig; - this.authenticationProvider = authenticationProvider; - this.remeberMeService = remeberMeService; - } - - public boolean isEnable() { - return enable; - } - - public void setEnable(boolean enable) { - this.enable = enable; - } - - public void setApplicationConfig(ApplicationConfig applicationConfig) { - this.applicationConfig = applicationConfig; - } - - public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) { - this.authenticationProvider = authenticationProvider; - } - - public void setRemeberMeService(AbstractRemeberMeService remeberMeService) { - this.remeberMeService = remeberMeService; - } - - -} diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/InMemoryRemeberMeService.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/InMemoryRemeberMeService.java deleted file mode 100644 index 7e66a7e48..000000000 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/InMemoryRemeberMeService.java +++ /dev/null @@ -1,54 +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.support.rememberme; - -import java.util.concurrent.TimeUnit; - -import org.maxkey.constants.ConstsTimeInterval; - -import com.github.benmanes.caffeine.cache.Cache; -import com.github.benmanes.caffeine.cache.Caffeine; - -public class InMemoryRemeberMeService extends AbstractRemeberMeService { - - protected static final Cache remeberMeStore = - Caffeine.newBuilder() - .expireAfterWrite(ConstsTimeInterval.TWO_WEEK, TimeUnit.SECONDS) - .build(); - - @Override - public void save(RemeberMe remeberMe) { - remeberMeStore.put(remeberMe.getUsername(), remeberMe); - } - - @Override - public void update(RemeberMe remeberMe) { - remeberMeStore.put(remeberMe.getUsername(), remeberMe); - } - - @Override - public RemeberMe read(RemeberMe remeberMe) { - return remeberMeStore.getIfPresent(remeberMe.getUsername()); - } - - @Override - public void remove(String username) { - remeberMeStore.invalidate(username); - } - -} diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/JdbcRemeberMeService.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/JdbcRemeberMeService.java deleted file mode 100644 index 60a84a5f9..000000000 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/JdbcRemeberMeService.java +++ /dev/null @@ -1,91 +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.support.rememberme; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; - -public class JdbcRemeberMeService extends AbstractRemeberMeService { - private static final Logger _logger = LoggerFactory.getLogger(JdbcRemeberMeService.class); - - private static final String DEFAULT_DEFAULT_INSERT_STATEMENT = - "INSERT INTO REMEMBER_ME(ID, USERNAME,AUTHKEY,LASTLOGIN)VALUES( ? , ? , ? , ?)"; - - private static final String DEFAULT_DEFAULT_SELECT_STATEMENT = - "SELECT ID, USERNAME,AUTHKEY,LASTLOGIN FROM REMEMBER_ME " - + " WHERE ID = ? AND USERNAME = ? AND AUTHKEY = ?"; - - private static final String DEFAULT_DEFAULT_DELETE_STATEMENT = - "DELETE FROM REMEMBER_ME WHERE USERNAME = ?"; - - private static final String DEFAULT_DEFAULT_UPDATE_STATEMENT = - "UPDATE REMEMBER_ME SET AUTHKEY = ? , LASTLOGIN = ? WHERE ID = ?"; - - private final JdbcTemplate jdbcTemplate; - - public JdbcRemeberMeService(JdbcTemplate jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; - } - - @Override - public void save(RemeberMe remeberMe) { - jdbcTemplate.update(DEFAULT_DEFAULT_INSERT_STATEMENT, - new Object[] { remeberMe.getId(), remeberMe.getUsername(), remeberMe.getAuthKey(), - remeberMe.getLastLogin() }, - new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.TIMESTAMP }); - } - - @Override - public void update(RemeberMe remeberMe) { - jdbcTemplate.update(DEFAULT_DEFAULT_UPDATE_STATEMENT, - new Object[] { - remeberMe.getAuthKey(), - remeberMe.getLastLogin(), - remeberMe.getId() - }); - } - - @Override - public RemeberMe read(RemeberMe remeberMe) { - List listRemeberMe = jdbcTemplate.query(DEFAULT_DEFAULT_SELECT_STATEMENT, - new RowMapper() { - public RemeberMe mapRow(ResultSet rs, int rowNum) throws SQLException { - RemeberMe remeberMe = new RemeberMe(); - remeberMe.setId(rs.getString(1)); - remeberMe.setUsername(rs.getString(2)); - remeberMe.setAuthKey(rs.getString(3)); - remeberMe.setLastLogin(rs.getDate(4)); - return remeberMe; - } - }, remeberMe.getId(), remeberMe.getUsername(), remeberMe.getAuthKey()); - _logger.debug("listRemeberMe " + listRemeberMe); - return (listRemeberMe.size() > 0) ? listRemeberMe.get(0) : null; - } - - @Override - public void remove(String username) { - jdbcTemplate.update(DEFAULT_DEFAULT_DELETE_STATEMENT, username); - } - -} diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/RedisRemeberMeService.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/RedisRemeberMeService.java deleted file mode 100644 index 64bef8e13..000000000 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/RedisRemeberMeService.java +++ /dev/null @@ -1,71 +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.support.rememberme; - -import org.maxkey.constants.ConstsTimeInterval; -import org.maxkey.persistence.redis.RedisConnection; -import org.maxkey.persistence.redis.RedisConnectionFactory; - -public class RedisRemeberMeService extends AbstractRemeberMeService { - - protected int serviceTicketValiditySeconds = ConstsTimeInterval.TWO_WEEK; - - RedisConnectionFactory connectionFactory; - - public static String PREFIX = "REDIS_REMEBER_ME_SERVICE_"; - - @Override - public void save(RemeberMe remeberMe) { - RedisConnection conn = connectionFactory.getConnection(); - conn.setexObject(PREFIX + remeberMe.getUsername(), serviceTicketValiditySeconds, remeberMe); - conn.close(); - } - - @Override - public void update(RemeberMe remeberMe) { - RedisConnection conn = connectionFactory.getConnection(); - conn.setexObject(PREFIX + remeberMe.getUsername(), serviceTicketValiditySeconds, remeberMe); - conn.close(); - } - - @Override - public RemeberMe read(RemeberMe remeberMe) { - RedisConnection conn = connectionFactory.getConnection(); - RemeberMe readRemeberMe = (RemeberMe)conn.getObject(PREFIX + remeberMe.getUsername()); - conn.close(); - return readRemeberMe; - } - - @Override - public void remove(String username) { - RedisConnection conn = connectionFactory.getConnection(); - conn.delete(PREFIX + username); - conn.close(); - } - - public RedisRemeberMeService(RedisConnectionFactory connectionFactory) { - super(); - this.connectionFactory = connectionFactory; - } - - public void setConnectionFactory(RedisConnectionFactory connectionFactory) { - this.connectionFactory = connectionFactory; - } - - -} diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/RemeberMe.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/RemeberMe.java deleted file mode 100644 index 8b20e50dc..000000000 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/RemeberMe.java +++ /dev/null @@ -1,74 +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.support.rememberme; - -import java.io.Serializable; -import java.util.Date; - -public class RemeberMe implements Serializable { - - private static final long serialVersionUID = 8010496585233991785L; - - String id; - - String username; - - String authKey; - - Date lastLogin; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getAuthKey() { - return authKey; - } - - public void setAuthKey(String authKey) { - this.authKey = authKey; - } - - public Date getLastLogin() { - return lastLogin; - } - - public void setLastLogin(Date lastLogin) { - this.lastLogin = lastLogin; - } - - @Override - public String toString() { - return "RemeberMe [id=" + id - + ", username=" + username - + ", authKey=" + authKey + ", lastLogin=" + lastLogin - + "]"; - } -} diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/RemeberMeServiceFactory.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/RemeberMeServiceFactory.java deleted file mode 100644 index 25199aee8..000000000 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/RemeberMeServiceFactory.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright [2021] [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.support.rememberme; - -import org.maxkey.constants.ConstsPersistence; -import org.maxkey.persistence.redis.RedisConnectionFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.jdbc.core.JdbcTemplate; - -public class RemeberMeServiceFactory { - private static final Logger _logger = - LoggerFactory.getLogger(RemeberMeServiceFactory.class); - - public AbstractRemeberMeService getService( - int persistence, - JdbcTemplate jdbcTemplate, - RedisConnectionFactory redisConnFactory){ - - AbstractRemeberMeService remeberMeService = null; - if (persistence == ConstsPersistence.INMEMORY) { - remeberMeService = new InMemoryRemeberMeService(); - _logger.debug("InMemoryRemeberMeService"); - } else if (persistence == ConstsPersistence.JDBC) { - //remeberMeService = new JdbcRemeberMeService(jdbcTemplate); - _logger.debug("JdbcRemeberMeService not support "); - } else if (persistence == ConstsPersistence.REDIS) { - remeberMeService = new RedisRemeberMeService(redisConnFactory); - _logger.debug("RedisRemeberMeService"); - } - return remeberMeService; - } -} diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/wsfederation/HttpWsFederationEntryPoint.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/wsfederation/HttpWsFederationEntryPoint.java index 2f274dfbf..886301edd 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/wsfederation/HttpWsFederationEntryPoint.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/wsfederation/HttpWsFederationEntryPoint.java @@ -21,10 +21,10 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.maxkey.authn.AbstractAuthenticationProvider; import org.maxkey.authn.LoginCredential; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.configuration.ApplicationConfig; import org.maxkey.constants.ConstsLoginType; import org.maxkey.util.StringUtils; -import org.maxkey.web.WebContext; import org.opensaml.saml1.core.impl.AssertionImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,7 +44,7 @@ public class HttpWsFederationEntryPoint implements AsyncHandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { - boolean isAuthenticated= WebContext.isAuthenticated(); + boolean isAuthenticated= AuthorizationUtils.isAuthenticated(); String wsFederationWA = request.getParameter(WsFederationConstants.WA); String wsFederationWResult = request.getParameter(WsFederationConstants.WRESULT); diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/AuthorizationUtils.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/AuthorizationUtils.java new file mode 100644 index 000000000..dd7bc9b44 --- /dev/null +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/AuthorizationUtils.java @@ -0,0 +1,95 @@ +package org.maxkey.authn.web; + +import java.text.ParseException; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; + +import org.maxkey.authn.SigninPrincipal; +import org.maxkey.authn.jwt.AuthJwtService; +import org.maxkey.authn.online.OnlineTicket; +import org.maxkey.authn.online.OnlineTicketService; +import org.maxkey.entity.UserInfo; +import org.maxkey.util.AuthorizationHeaderUtils; +import org.maxkey.web.WebConstants; +import org.maxkey.web.WebContext; +import org.springframework.security.core.Authentication; + +public class AuthorizationUtils { + + static final String Authorization = "Authorization"; + + public static void authenticateWithCookie( + HttpServletRequest request, + AuthJwtService authJwtService, + OnlineTicketService onlineTicketService + ) throws ParseException{ + if(getAuthentication() == null) { + Cookie authCookie = WebContext.getCookie(request, Authorization); + if(authCookie != null ) { + String authorization = authCookie.getValue(); + doAuthenticate(authorization,authJwtService,onlineTicketService); + } + } + } + + public static void authenticate( + HttpServletRequest request, + AuthJwtService authJwtService, + OnlineTicketService onlineTicketService + ) throws ParseException{ + if(getAuthentication() == null) { + String authorization = AuthorizationHeaderUtils.resolveBearer(request); + if(authorization != null ) { + doAuthenticate(authorization,authJwtService,onlineTicketService); + } + } + } + + public static void doAuthenticate( + String authorization, + AuthJwtService authJwtService, + OnlineTicketService onlineTicketService) throws ParseException { + if(authJwtService.validateJwtToken(authorization)) { + String ticket = authJwtService.resolveTicket(authorization); + OnlineTicket onlineTicket = onlineTicketService.get(ticket); + if(onlineTicket != null) { + setAuthentication(onlineTicket.getAuthentication()); + } + } + } + + + public static void setAuthentication(Authentication authentication) { + WebContext.setAttribute(WebConstants.AUTHENTICATION, authentication); + } + + public static Authentication getAuthentication() { + Authentication authentication = (Authentication) WebContext.getAttribute(WebConstants.AUTHENTICATION); + return authentication; + } + + public static boolean isAuthenticated() { + return getAuthentication() != null; + } + + public static boolean isNotAuthenticated() { + return getAuthentication() == null; + } + + public static SigninPrincipal getPrincipal() { + Authentication authentication = getAuthentication(); + return authentication == null ? null :(SigninPrincipal) authentication.getPrincipal(); + } + + public static UserInfo getUserInfo() { + Authentication authentication = getAuthentication(); + UserInfo userInfo = null; + if(isAuthenticated() && (authentication.getPrincipal() instanceof SigninPrincipal)) { + SigninPrincipal signinPrincipal = ((SigninPrincipal) authentication.getPrincipal()); + userInfo = signinPrincipal.getUserInfo(); + } + return userInfo; + } + +} diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/CurrentUserMethodArgumentResolver.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/CurrentUserMethodArgumentResolver.java index 8cefcc173..cf025c2ca 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/CurrentUserMethodArgumentResolver.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/CurrentUserMethodArgumentResolver.java @@ -24,7 +24,7 @@ public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentR public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { UserInfo userInfo = null; Authentication authentication = (Authentication ) webRequest.getAttribute(WebConstants.AUTHENTICATION, RequestAttributes.SCOPE_SESSION); - if(authentication.getPrincipal() instanceof SigninPrincipal) { + if((authentication != null) && (authentication.getPrincipal() instanceof SigninPrincipal)) { SigninPrincipal signinPrincipal = ((SigninPrincipal) authentication.getPrincipal()); userInfo = signinPrincipal.getUserInfo(); if (userInfo != null) { diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/SessionSecurityContextHolderStrategy.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/SessionSecurityContextHolderStrategy.java index ad6f17915..8729204bd 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/SessionSecurityContextHolderStrategy.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/SessionSecurityContextHolderStrategy.java @@ -45,7 +45,7 @@ public class SessionSecurityContextHolderStrategy implements SecurityContextHold SecurityContext ctx = createEmptyContext(); Authentication authentication = null; try { - authentication = (Authentication)WebContext.getAuthentication(); + authentication = (Authentication)AuthorizationUtils.getAuthentication(); if (authentication != null) { ctx.setAuthentication(authentication); } @@ -59,7 +59,7 @@ public class SessionSecurityContextHolderStrategy implements SecurityContextHold @Override public void setContext(SecurityContext context) { - WebContext.setAuthentication(context.getAuthentication()); + AuthorizationUtils.setAuthentication(context.getAuthentication()); } @Override diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/AuthEntryPoint.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/UnauthorizedEntryPoint.java similarity index 60% rename from maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/AuthEntryPoint.java rename to maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/UnauthorizedEntryPoint.java index 400bd98d2..13c2f99b0 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/AuthEntryPoint.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/UnauthorizedEntryPoint.java @@ -18,24 +18,24 @@ import com.fasterxml.jackson.databind.DatabindException; import com.fasterxml.jackson.databind.ObjectMapper; @Controller -public class AuthEntryPoint { - private static final Logger _logger = LoggerFactory.getLogger(AuthEntryPoint.class); +public class UnauthorizedEntryPoint { + private static final Logger _logger = LoggerFactory.getLogger(UnauthorizedEntryPoint.class); @RequestMapping(value={"/auth/entrypoint"}) public void entryPoint( HttpServletRequest request, HttpServletResponse response) throws StreamWriteException, DatabindException, IOException { - _logger.trace("AuthEntryPoint /entrypoint."); - response.setContentType(MediaType.APPLICATION_JSON_VALUE); + _logger.trace("UnauthorizedEntryPoint /entrypoint."); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - final Map body = new HashMap<>(); - body.put("status", HttpServletResponse.SC_UNAUTHORIZED); - body.put("error", "Unauthorized"); - body.put("message", "Unauthorized"); - body.put("path", request.getServletPath()); + final Map responseBody = new HashMap<>(); + responseBody.put("status", HttpServletResponse.SC_UNAUTHORIZED); + responseBody.put("error", "Unauthorized"); + responseBody.put("message", "Unauthorized"); + responseBody.put("path", request.getServletPath()); final ObjectMapper mapper = new ObjectMapper(); - mapper.writeValue(response.getOutputStream(), body); + mapper.writeValue(response.getOutputStream(), responseBody); } } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/interceptor/PermissionAdapter.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/interceptor/PermissionAdapter.java deleted file mode 100644 index 1caca3603..000000000 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/interceptor/PermissionAdapter.java +++ /dev/null @@ -1,115 +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.web.interceptor; - -import javax.servlet.RequestDispatcher; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.maxkey.authn.SigninPrincipal; -import org.maxkey.authn.jwt.AuthJwtService; -import org.maxkey.authn.online.OnlineTicket; -import org.maxkey.authn.online.OnlineTicketService; -import org.maxkey.configuration.ApplicationConfig; -import org.maxkey.util.AuthorizationHeaderUtils; -import org.maxkey.web.WebContext; -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.stereotype.Component; -import org.springframework.web.servlet.AsyncHandlerInterceptor; -/** - * 权限Interceptor处理 - * 权限处理需在servlet.xml中配置 - * mvc:interceptors permission - * @author Crystal.Sea - * - */ -@Component -public class PermissionAdapter implements AsyncHandlerInterceptor { - private static final Logger _logger = LoggerFactory.getLogger(PermissionAdapter.class); - //无需Interceptor url - @Autowired - @Qualifier("applicationConfig") - private ApplicationConfig applicationConfig; - - @Autowired - @Qualifier("onlineTicketService") - OnlineTicketService onlineTicketService; - - @Autowired - @Qualifier("authJwtService") - AuthJwtService authJwtService ; - - /* - * 请求前处理 - * (non-Javadoc) - * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) - */ - @Override - public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { - _logger.trace("PermissionAdapter preHandle"); - String authorization = AuthorizationHeaderUtils.resolveBearer(request); - - if(authJwtService.validateJwtToken(authorization)) { - String ticket = authJwtService.resolveTicket(authorization); - if(WebContext.getAuthentication()==null) { - OnlineTicket onlineTicket = onlineTicketService.get(ticket); - if(onlineTicket != null) { - WebContext.setAuthentication(onlineTicket.getAuthentication()); - } - } - //判断用户是否登录 - if(WebContext.getAuthentication()==null - ||WebContext.getAuthentication().getAuthorities()==null){//判断用户和角色,判断用户是否登录用户 - _logger.trace("No Authentication ... forward to /auth/entrypoint"); - RequestDispatcher dispatcher = request.getRequestDispatcher("/auth/entrypoint"); - dispatcher.forward(request, response); - return false; - } - - //非管理员用户直接注销 - if (!((SigninPrincipal) WebContext.getAuthentication().getPrincipal()).isRoleAdministrators()) { - _logger.debug("Not ADMINISTRATORS Authentication ."); - RequestDispatcher dispatcher = request.getRequestDispatcher("/logout"); - dispatcher.forward(request, response); - return false; - } - } - - boolean hasAccess=true; - - - /* - boolean preHandler = super.preHandle(request, response, handler); - - if(preHandler) { - preHandler = false; - - - if(!preHandler){//无权限转向 - log.debug("You do not have permission to access "+accessUrl); - RequestDispatcher dispatcher = request.getRequestDispatcher("/accessdeny"); - dispatcher.forward(request, response); - return false; - } - }*/ - return hasAccess; - } -} diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/interceptor/PermissionInterceptor.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/interceptor/PermissionInterceptor.java new file mode 100644 index 000000000..8cea35061 --- /dev/null +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/interceptor/PermissionInterceptor.java @@ -0,0 +1,84 @@ +/* + * 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.web.interceptor; + +import javax.servlet.RequestDispatcher; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.maxkey.authn.SigninPrincipal; +import org.maxkey.authn.jwt.AuthJwtService; +import org.maxkey.authn.online.OnlineTicketService; +import org.maxkey.authn.web.AuthorizationUtils; +import org.maxkey.configuration.ApplicationConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.AsyncHandlerInterceptor; +/** + * 权限Interceptor处理 + * 权限处理需在servlet.xml中配置 + * mvc:interceptors permission + * @author Crystal.Sea + * + */ +@Component +public class PermissionInterceptor implements AsyncHandlerInterceptor { + private static final Logger _logger = LoggerFactory.getLogger(PermissionInterceptor.class); + //无需Interceptor url + @Autowired + ApplicationConfig applicationConfig; + + @Autowired + OnlineTicketService onlineTicketService; + + @Autowired + AuthJwtService authJwtService ; + + /* + * 请求前处理 + * (non-Javadoc) + * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) + */ + @Override + public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { + _logger.trace("PermissionAdapter preHandle"); + AuthorizationUtils.authenticate(request, authJwtService, onlineTicketService); + //判断用户是否登录 + if(AuthorizationUtils.getAuthentication()==null + ||AuthorizationUtils.getAuthentication().getAuthorities()==null){//判断用户和角色,判断用户是否登录用户 + _logger.trace("No Authentication ... forward to /auth/entrypoint"); + RequestDispatcher dispatcher = request.getRequestDispatcher("/auth/entrypoint"); + dispatcher.forward(request, response); + return false; + } + + //非管理员用户直接注销 + if (!((SigninPrincipal) AuthorizationUtils.getAuthentication().getPrincipal()).isRoleAdministrators()) { + _logger.debug("Not ADMINISTRATORS Authentication ."); + RequestDispatcher dispatcher = request.getRequestDispatcher("/logout"); + dispatcher.forward(request, response); + return false; + } + + boolean hasAccess=true; + + return hasAccess; + } +} diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/autoconfigure/AuthenticationAutoConfiguration.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/autoconfigure/AuthenticationAutoConfiguration.java index 40645a2a9..fdce3c1f9 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/autoconfigure/AuthenticationAutoConfiguration.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/autoconfigure/AuthenticationAutoConfiguration.java @@ -24,8 +24,6 @@ import org.maxkey.authn.jwt.AuthJwtService; import org.maxkey.authn.online.OnlineTicketService; import org.maxkey.authn.online.OnlineTicketServiceFactory; import org.maxkey.authn.realm.AbstractAuthenticationRealm; -import org.maxkey.authn.support.rememberme.AbstractRemeberMeService; -import org.maxkey.authn.support.rememberme.RemeberMeServiceFactory; import org.maxkey.authn.web.SessionListenerAdapter; import org.maxkey.configuration.ApplicationConfig; import org.maxkey.configuration.AuthJwkConfig; @@ -69,7 +67,6 @@ public class AuthenticationAutoConfiguration implements InitializingBean { ApplicationConfig applicationConfig, AbstractOtpAuthn tfaOtpAuthn, OtpAuthnService otpAuthnService, - AbstractRemeberMeService remeberMeService, OnlineTicketService onlineTicketServices ) { @@ -79,7 +76,6 @@ public class AuthenticationAutoConfiguration implements InitializingBean { applicationConfig, tfaOtpAuthn, otpAuthnService, - remeberMeService, onlineTicketServices ); @@ -125,18 +121,6 @@ public class AuthenticationAutoConfiguration implements InitializingBean { return new LoginHistoryRepository(jdbcTemplate); } - /** - * remeberMeService . - * @return - */ - @Bean(name = "remeberMeService") - public AbstractRemeberMeService remeberMeService( - @Value("${maxkey.server.persistence}") int persistence, - @Value("${maxkey.login.remeberme.validity}") int validity, - JdbcTemplate jdbcTemplate, - RedisConnectionFactory redisConnFactory) { - return new RemeberMeServiceFactory().getService(persistence, jdbcTemplate, redisConnFactory); - } @Bean(name = "onlineTicketService") public OnlineTicketService onlineTicketService( diff --git a/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/authn/support/socialsignon/SocialSignOnEndpoint.java b/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/authn/support/socialsignon/SocialSignOnEndpoint.java index a46e0dc88..32031af98 100644 --- a/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/authn/support/socialsignon/SocialSignOnEndpoint.java +++ b/maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/authn/support/socialsignon/SocialSignOnEndpoint.java @@ -23,9 +23,11 @@ package org.maxkey.authn.support.socialsignon; import javax.servlet.http.HttpServletRequest; import org.maxkey.authn.LoginCredential; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.constants.ConstsLoginType; import org.maxkey.entity.SocialsAssociate; import org.maxkey.entity.SocialsProvider; +import org.maxkey.entity.UserInfo; import org.maxkey.web.WebContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -71,30 +73,6 @@ public class SocialSignOnEndpoint extends AbstractSocialSignOnEndpoint{ return socialSignOnAuthorize(request,provider); } - @RequestMapping(value={"/unbind/{provider}"}, method = RequestMethod.GET) - public ModelAndView unbind(HttpServletRequest request, - @PathVariable String provider) { - WebContext.setAttribute(SOCIALSIGNON_SESSION_REDIRECT_URI, request.getParameter(SOCIALSIGNON_REDIRECT_URI)); - SocialsAssociate socialSignOnUser =new SocialsAssociate(); - socialSignOnUser.setProvider(provider); - socialSignOnUser.setUserId(WebContext.getUserInfo().getId()); - socialSignOnUser.setUsername(WebContext.getUserInfo().getUsername()); - _logger.debug("Social Sign On unbind {} from user {}", - provider, - WebContext.getUserInfo().getUsername() - ); - - socialsAssociateService.delete(socialSignOnUser); - - Object redirect_uri = WebContext.getAttribute(SOCIALSIGNON_SESSION_REDIRECT_URI); - if(redirect_uri != null){ - return WebContext.redirect(redirect_uri.toString()); - }else{ - return WebContext.forward("/socialsignon/list"); - } - - } - @RequestMapping(value={"/authorize/{provider}/{appid}"}, method = RequestMethod.GET) public ModelAndView authorize2AppId(HttpServletRequest request, @PathVariable("provider") String provider, @@ -177,9 +155,10 @@ public class SocialSignOnEndpoint extends AbstractSocialSignOnEndpoint{ return false; } + UserInfo userInfo = AuthorizationUtils.getUserInfo(); socialsAssociate.setSocialUserInfo(accountJsonString); - socialsAssociate.setUserId(WebContext.getUserInfo().getId()); - socialsAssociate.setUsername(WebContext.getUserInfo().getUsername()); + socialsAssociate.setUserId(userInfo.getId()); + socialsAssociate.setUsername(userInfo.getUsername()); //socialsAssociate.setAccessToken(JsonUtils.object2Json(accessToken)); //socialsAssociate.setExAttribute(JsonUtils.object2Json(accessToken.getResponseObject())); _logger.debug("Social Bind : "+socialsAssociate); diff --git a/maxkey-core/src/main/java/org/maxkey/entity/ChangePassword.java b/maxkey-core/src/main/java/org/maxkey/entity/ChangePassword.java index 666e94bdd..8ba531d18 100644 --- a/maxkey-core/src/main/java/org/maxkey/entity/ChangePassword.java +++ b/maxkey-core/src/main/java/org/maxkey/entity/ChangePassword.java @@ -36,9 +36,11 @@ public class ChangePassword extends JpaBaseEntity{ private String displayName; private String oldPassword; private String password; - private String confirmpassword; + private String confirmPassword; private String decipherable; private String instId; + private int passwordSetType; + private String passwordLastSetTime; /** * @@ -46,7 +48,24 @@ public class ChangePassword extends JpaBaseEntity{ public ChangePassword() { } - + + public ChangePassword(String username,String password) { + this.username = username; + this.password = password; + } + + public ChangePassword(UserInfo userInfo) { + this.setId(userInfo.getId()); + this.setUserId(userInfo.getId()); + this.setUsername(userInfo.getUsername()); + this.setWindowsAccount(userInfo.getWindowsAccount()); + this.setMobile(userInfo.getMobile()); + this.setEmail(userInfo.getEmail()); + this.setEmployeeNumber(userInfo.getEmployeeNumber()); + this.setDecipherable(userInfo.getDecipherable()); + this.setPassword(userInfo.getPassword()); + this.setInstId(userInfo.getInstId()); + } /** * @return the id @@ -127,23 +146,14 @@ public class ChangePassword extends JpaBaseEntity{ this.password = password; } - - /** - * @return the confirmpassword - */ - public String getConfirmpassword() { - return confirmpassword; + public String getConfirmPassword() { + return confirmPassword; } - - /** - * @param confirmpassword the confirmpassword to set - */ - public void setConfirmpassword(String confirmpassword) { - this.confirmpassword = confirmpassword; + public void setConfirmPassword(String confirmPassword) { + this.confirmPassword = confirmPassword; } - /** * @return the decipherable */ @@ -217,6 +227,27 @@ public class ChangePassword extends JpaBaseEntity{ this.instId = instId; } + + public int getPasswordSetType() { + return passwordSetType; + } + + + public void setPasswordSetType(int passwordSetType) { + this.passwordSetType = passwordSetType; + } + + + public String getPasswordLastSetTime() { + return passwordLastSetTime; + } + + + public void setPasswordLastSetTime(String passwordLastSetTime) { + this.passwordLastSetTime = passwordLastSetTime; + } + + @Override public String toString() { StringBuilder builder = new StringBuilder(); @@ -232,8 +263,8 @@ public class ChangePassword extends JpaBaseEntity{ builder.append(oldPassword); builder.append(", password="); builder.append(password); - builder.append(", confirmpassword="); - builder.append(confirmpassword); + builder.append(", confirmPassword="); + builder.append(confirmPassword); builder.append(", decipherable="); builder.append(decipherable); builder.append("]"); diff --git a/maxkey-core/src/main/java/org/maxkey/entity/UserInfo.java b/maxkey-core/src/main/java/org/maxkey/entity/UserInfo.java index 5de31bdf9..9c9d9aca3 100644 --- a/maxkey-core/src/main/java/org/maxkey/entity/UserInfo.java +++ b/maxkey-core/src/main/java/org/maxkey/entity/UserInfo.java @@ -1360,6 +1360,12 @@ public class UserInfo extends JpaBaseEntity { public void setOriginId2(String originId2) { this.originId2 = originId2; } + + public void trans() { + this.setPassword(""); + this.setDecipherable(""); + this.transPictureBase64(); + } @Override public String toString() { diff --git a/maxkey-core/src/main/java/org/maxkey/persistence/repository/PasswordPolicyValidator.java b/maxkey-core/src/main/java/org/maxkey/persistence/repository/PasswordPolicyValidator.java index 7343f1aed..a47f897b8 100644 --- a/maxkey-core/src/main/java/org/maxkey/persistence/repository/PasswordPolicyValidator.java +++ b/maxkey-core/src/main/java/org/maxkey/persistence/repository/PasswordPolicyValidator.java @@ -25,6 +25,7 @@ import org.joda.time.format.DateTimeFormat; import org.maxkey.constants.ConstsPasswordSetType; import org.maxkey.constants.ConstsStatus; import org.maxkey.crypto.password.PasswordGen; +import org.maxkey.entity.ChangePassword; import org.maxkey.entity.PasswordPolicy; import org.maxkey.entity.UserInfo; import org.maxkey.util.StringUtils; @@ -73,11 +74,11 @@ public class PasswordPolicyValidator { * @param userInfo * @return boolean */ - public boolean validator(UserInfo userInfo) { + public boolean validator(ChangePassword changePassword) { - String password = userInfo.getPassword(); - String username = userInfo.getUsername(); + String password = changePassword.getPassword(); + String username = changePassword.getUsername(); if(password.equals("") || password==null){ _logger.debug("password is Empty "); 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 2e8aaeeeb..91849095a 100644 --- a/maxkey-core/src/main/java/org/maxkey/web/WebContext.java +++ b/maxkey-core/src/main/java/org/maxkey/web/WebContext.java @@ -33,7 +33,6 @@ import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.LogFactory; import org.maxkey.configuration.ApplicationConfig; import org.maxkey.entity.Institutions; -import org.maxkey.entity.UserInfo; import org.maxkey.util.DateUtils; import org.maxkey.util.IdGenerator; import org.maxkey.web.message.Message; @@ -42,7 +41,6 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.core.env.StandardEnvironment; -import org.springframework.security.core.Authentication; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.support.WebApplicationContextUtils; @@ -107,25 +105,7 @@ 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)); - } - + public static String getInst(HttpServletRequest request) { String instId = "1"; //from session @@ -133,7 +113,7 @@ public final class WebContext { instId = ((Institutions)request.getSession().getAttribute(WebConstants.CURRENT_INST)).getId(); }else { //from cookie - instId = WebContext.readCookieByName(request, WebConstants.INST_COOKIE_NAME).getValue(); + instId = WebContext.getCookie(request, WebConstants.INST_COOKIE_NAME).getValue(); } return StringUtils.isBlank(instId) ? "1" : instId; } @@ -167,25 +147,7 @@ public final class WebContext { removeAttribute(WebConstants.CURRENT_MESSAGE); } - 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 @@ -413,8 +375,8 @@ public final class WebContext { * @param name cookie名字 * @return Cookie */ - public static Cookie readCookieByName(HttpServletRequest request, String name) { - Map cookieMap = readCookieAll(request); + public static Cookie getCookie(HttpServletRequest request, String name) { + Map cookieMap = getCookieAll(request); if (cookieMap.containsKey(name)) { Cookie cookie = (Cookie) cookieMap.get(name); return cookie; @@ -429,7 +391,7 @@ public final class WebContext { * @param request HttpServletRequest * @return Map */ - private static Map readCookieAll(HttpServletRequest request) { + private static Map getCookieAll(HttpServletRequest request) { Map cookieMap = new HashMap(); Cookie[] cookies = request.getCookies(); if (null != cookies) { diff --git a/maxkey-core/src/main/java/org/maxkey/web/tag/ThemeTagDirective.java b/maxkey-core/src/main/java/org/maxkey/web/tag/ThemeTagDirective.java deleted file mode 100644 index bfdec11a1..000000000 --- a/maxkey-core/src/main/java/org/maxkey/web/tag/ThemeTagDirective.java +++ /dev/null @@ -1,86 +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.web.tag; - -import freemarker.core.Environment; -import freemarker.template.TemplateDirectiveBody; -import freemarker.template.TemplateDirectiveModel; -import freemarker.template.TemplateException; -import freemarker.template.TemplateModel; -import java.io.IOException; -import java.util.Map; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.maxkey.constants.ConstsTimeInterval; -import org.maxkey.web.WebConstants; -import org.maxkey.web.WebContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - - - -/** - * 获取主题标签 .<@theme/> - * - * @author Crystal.Sea - * - */ - -@FreemarkerTag("theme") -public class ThemeTagDirective implements TemplateDirectiveModel { - private static final Logger _logger = LoggerFactory.getLogger(ThemeTagDirective.class); - @Autowired - private HttpServletRequest request; - - @Autowired - HttpServletResponse response; - - @SuppressWarnings("rawtypes") - @Override - public void execute(Environment env, - Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) - throws TemplateException, IOException { - String theme = null; - if (null != WebContext.getUserInfo()) { - theme = WebContext.getUserInfo().getTheme(); - _logger.trace("read theme form login user session , theme is " + theme); - } - - if (null == theme) { - Cookie themeCookie = - WebContext.readCookieByName(request, WebConstants.THEME_COOKIE_NAME); - if (themeCookie != null) { - theme = themeCookie.getValue(); - _logger.trace("read theme form cookie , theme is " + theme); - } - } - - //每次登陆完成设置一次COOKIE - if (request.getAttribute(WebConstants.THEME_COOKIE_NAME) == null - && null != WebContext.getUserInfo()) { - request.setAttribute(WebConstants.THEME_COOKIE_NAME, "theme"); - WebContext.setCookie(response, null, - WebConstants.THEME_COOKIE_NAME, theme, ConstsTimeInterval.ONE_WEEK); - } - - env.getOut().append(theme == null ? "default" : theme); - } - -} diff --git a/maxkey-identitys/maxkey-identity-rest/src/main/java/org/maxkey/identity/rest/RestUserInfoController.java b/maxkey-identitys/maxkey-identity-rest/src/main/java/org/maxkey/identity/rest/RestUserInfoController.java index f02bc9ce5..b52ba906d 100644 --- a/maxkey-identitys/maxkey-identity-rest/src/main/java/org/maxkey/identity/rest/RestUserInfoController.java +++ b/maxkey-identitys/maxkey-identity-rest/src/main/java/org/maxkey/identity/rest/RestUserInfoController.java @@ -19,6 +19,7 @@ package org.maxkey.identity.rest; import java.io.IOException; +import org.maxkey.entity.ChangePassword; import org.maxkey.entity.UserInfo; import org.maxkey.persistence.service.UserInfoService; import org.springframework.beans.factory.annotation.Autowired; @@ -75,9 +76,7 @@ public class RestUserInfoController { UriComponentsBuilder builder) throws IOException { UserInfo loadUserInfo = userInfoService.findByUsername(username); if(loadUserInfo != null) { - UserInfo changePassword = new UserInfo(); - changePassword.setId(loadUserInfo.getId()); - changePassword.setUsername(username); + ChangePassword changePassword = new ChangePassword(loadUserInfo); changePassword.setPassword(password); changePassword.setDecipherable(loadUserInfo.getDecipherable()); userInfoService.changePassword(changePassword,true); diff --git a/maxkey-persistence/src/main/java/org/maxkey/persistence/mapper/UserInfoMapper.java b/maxkey-persistence/src/main/java/org/maxkey/persistence/mapper/UserInfoMapper.java index b2cb6097d..787d4ebfa 100644 --- a/maxkey-persistence/src/main/java/org/maxkey/persistence/mapper/UserInfoMapper.java +++ b/maxkey-persistence/src/main/java/org/maxkey/persistence/mapper/UserInfoMapper.java @@ -23,6 +23,7 @@ import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import org.apache.mybatis.jpa.persistence.IJpaBaseMapper; import org.maxkey.constants.ConstsStatus; +import org.maxkey.entity.ChangePassword; import org.maxkey.entity.Organizations; import org.maxkey.entity.UserInfo; import org.maxkey.entity.UserInfoAdjoint; @@ -53,7 +54,7 @@ public interface UserInfoMapper extends IJpaBaseMapper{ public void updateBadPWDCount(UserInfo userInfo); - public int updatePassword(UserInfo userInfo); + public int changePassword(ChangePassword changePassword); public int updateAppLoginPassword(UserInfo userInfo); diff --git a/maxkey-persistence/src/main/java/org/maxkey/persistence/service/UserInfoService.java b/maxkey-persistence/src/main/java/org/maxkey/persistence/service/UserInfoService.java index fd4e9f15c..4d2608f92 100644 --- a/maxkey-persistence/src/main/java/org/maxkey/persistence/service/UserInfoService.java +++ b/maxkey-persistence/src/main/java/org/maxkey/persistence/service/UserInfoService.java @@ -77,7 +77,7 @@ public class UserInfoService extends JpaBaseService { } public boolean insert(UserInfo userInfo) { - userInfo = passwordEncoder(userInfo); + this.passwordEncoder(userInfo); if (super.insert(userInfo)) { if(mqPersistService.getApplicationConfig().isMessageQueueSupport()) { UserInfo loadUserInfo = findUserRelated(userInfo.getId()); @@ -94,7 +94,7 @@ public class UserInfoService extends JpaBaseService { } public boolean update(UserInfo userInfo) { - userInfo = passwordEncoder(userInfo); + ChangePassword changePassword = this.passwordEncoder(userInfo); if (super.update(userInfo)) { if(mqPersistService.getApplicationConfig().isMessageQueueSupport()) { UserInfo loadUserInfo = findUserRelated(userInfo.getId()); @@ -105,7 +105,7 @@ public class UserInfoService extends JpaBaseService { MqIdentityAction.UPDATE_ACTION); } - changePasswordProvisioning(userInfo); + changePasswordProvisioning(changePassword); return true; } return false; @@ -151,11 +151,11 @@ public class UserInfoService extends JpaBaseService { return loadUserInfo; } - public boolean updateGridList(String gridList) { + public boolean updateGridList(String gridList,UserInfo userInfo) { try { if (gridList != null && !gridList.equals("")) { - WebContext.getUserInfo().setGridList(Integer.parseInt(gridList)); - getMapper().updateGridList(WebContext.getUserInfo()); + userInfo.setGridList(Integer.parseInt(gridList)); + getMapper().updateGridList(userInfo); } }catch(Exception e) { e.printStackTrace(); @@ -180,9 +180,6 @@ public class UserInfoService extends JpaBaseService { public boolean updateProtectedApps(UserInfo userinfo) { try { - if(WebContext.getUserInfo() != null) { - userinfo.setModifiedBy(WebContext.getUserInfo().getId()); - } userinfo.setModifiedDate(DateUtils.getCurrentDateTimeAsString()); return getMapper().updateProtectedApps(userinfo) > 0; } catch (Exception e) { @@ -210,21 +207,32 @@ public class UserInfoService extends JpaBaseService { return null; } - public UserInfo passwordEncoder(UserInfo userInfo) { + public ChangePassword passwordEncoder(UserInfo userInfo) { + ChangePassword changePassword = null; + if(StringUtils.isNotBlank(userInfo.getPassword())) { + changePassword = new ChangePassword(userInfo); + passwordEncoder(changePassword); + userInfo.setPassword(changePassword.getPassword()); + userInfo.setDecipherable(changePassword.getDecipherable()); + userInfo.setPasswordLastSetTime(changePassword.getPasswordLastSetTime()); + } + return changePassword; + } + + public ChangePassword passwordEncoder(ChangePassword changePassword) { //密码不为空,则需要进行加密处理 - if(!StringUtils.isBlank(userInfo.getPassword())) { - String password = passwordEncoder.encode(userInfo.getPassword()); - userInfo.setDecipherable(PasswordReciprocal.getInstance().encode(userInfo.getPassword())); - _logger.debug("decipherable : "+userInfo.getDecipherable()); - userInfo.setPassword(password); - userInfo.setPasswordLastSetTime(DateUtils.getCurrentDateTimeAsString()); + if(StringUtils.isNotBlank(changePassword.getPassword())) { + String password = passwordEncoder.encode(changePassword.getPassword()); + changePassword.setDecipherable(PasswordReciprocal.getInstance().encode(changePassword.getPassword())); + _logger.debug("decipherable : "+changePassword.getDecipherable()); + changePassword.setPassword(password); + changePassword.setPasswordLastSetTime(DateUtils.getCurrentDateTimeAsString()); - userInfo.setModifiedDate(DateUtils.getCurrentDateTimeAsString()); }else { - userInfo.setPassword(null); - userInfo.setDecipherable(null); + changePassword.setPassword(null); + changePassword.setDecipherable(null); } - return userInfo; + return changePassword; } /** @@ -235,32 +243,20 @@ public class UserInfoService extends JpaBaseService { * @param passwordSetType * @return */ - public boolean changePassword( String oldPassword, - String newPassword, - String confirmPassword, - int passwordSetType) { + public boolean changePassword( ChangePassword changePassword) { try { WebContext.setAttribute(PasswordPolicyValidator.PASSWORD_POLICY_VALIDATE_RESULT, ""); - UserInfo userInfo = WebContext.getUserInfo(); - UserInfo changeUserInfo = new UserInfo(); - changeUserInfo.setUsername(userInfo.getUsername()); - changeUserInfo.setPassword(newPassword); - changeUserInfo.setId(userInfo.getId()); - changeUserInfo.setDecipherable(userInfo.getDecipherable()); - changeUserInfo.setPasswordSetType(passwordSetType); - - if(newPassword.equals(confirmPassword)){ - if(oldPassword==null || - passwordEncoder.matches(oldPassword, userInfo.getPassword())){ - if(changePassword(changeUserInfo,true) ){ - userInfo.setPassword(changeUserInfo.getPassword()); - userInfo.setDecipherable(changeUserInfo.getDecipherable()); + UserInfo userInfo = this.findByUsername(changePassword.getUsername()); + if(changePassword.getPassword().equals(changePassword.getConfirmPassword())){ + if(StringUtils.isNotBlank(changePassword.getOldPassword()) || + passwordEncoder.matches(changePassword.getOldPassword(), userInfo.getPassword())){ + if(changePassword(changePassword,true) ){ return true; } return false; }else { - if(oldPassword!=null && - passwordEncoder.matches(newPassword, userInfo.getPassword())) { + if(StringUtils.isNotBlank(changePassword.getOldPassword())&& + passwordEncoder.matches(changePassword.getPassword(), userInfo.getPassword())) { WebContext.setAttribute(PasswordPolicyValidator.PASSWORD_POLICY_VALIDATE_RESULT, WebContext.getI18nValue("PasswordPolicy.OLD_PASSWORD_MATCH")); }else { @@ -285,23 +281,19 @@ public class UserInfoService extends JpaBaseService { * @param passwordPolicy * @return */ - public boolean changePassword(UserInfo changeUserInfo,boolean passwordPolicy) { + public boolean changePassword(ChangePassword changePassword,boolean passwordPolicy) { try { - _logger.debug("decipherable old : " + changeUserInfo.getDecipherable()); - _logger.debug("decipherable new : " + PasswordReciprocal.getInstance().encode(changeUserInfo.getPassword())); + _logger.debug("decipherable old : " + changePassword.getDecipherable()); + _logger.debug("decipherable new : " + PasswordReciprocal.getInstance().encode(changePassword.getDecipherable())); - if (passwordPolicy && passwordPolicyValidator.validator(changeUserInfo) == false) { + if (passwordPolicy && passwordPolicyValidator.validator(changePassword) == false) { return false; } - if (WebContext.getUserInfo() != null) { - changeUserInfo.setModifiedBy(WebContext.getUserInfo().getId()); - } + changePassword = passwordEncoder(changePassword); - changeUserInfo = passwordEncoder(changeUserInfo); - - if (getMapper().updatePassword(changeUserInfo) > 0) { - changePasswordProvisioning(changeUserInfo); + if (getMapper().changePassword(changePassword) > 0) { + changePasswordProvisioning(changePassword); return true; } return false; @@ -317,20 +309,10 @@ public class UserInfoService extends JpaBaseService { return passwordPolicyValidator.generateRandomPassword(); } - public void changePasswordProvisioning(UserInfo userInfo) { - if(StringUtils.isNotBlank(userInfo.getPassword())) { - UserInfo loadUserInfo = findByUsername(userInfo.getUsername()); - ChangePassword changePassword=new ChangePassword(); - changePassword.setId(loadUserInfo.getId()); - changePassword.setUserId(loadUserInfo.getId()); - changePassword.setUsername(loadUserInfo.getUsername()); - changePassword.setWindowsAccount(loadUserInfo.getWindowsAccount()); - changePassword.setMobile(loadUserInfo.getMobile()); - changePassword.setEmail(loadUserInfo.getEmail()); - changePassword.setEmployeeNumber(loadUserInfo.getEmployeeNumber()); - changePassword.setDecipherable(loadUserInfo.getDecipherable()); - changePassword.setPassword(loadUserInfo.getPassword()); - changePassword.setInstId(loadUserInfo.getInstId()); + public void changePasswordProvisioning(ChangePassword changePassworded) { + if(changePassworded !=null && StringUtils.isNotBlank(changePassworded.getPassword())) { + UserInfo loadUserInfo = findByUsername(changePassworded.getUsername()); + ChangePassword changePassword = new ChangePassword(loadUserInfo); mqPersistService.send( MqIdentityTopic.PASSWORD_TOPIC, changePassword, @@ -340,9 +322,6 @@ public class UserInfoService extends JpaBaseService { public boolean updateAppLoginPassword(UserInfo userinfo) { try { - if(WebContext.getUserInfo() != null) { - userinfo.setModifiedBy(WebContext.getUserInfo().getId()); - } userinfo.setModifiedDate(DateUtils.getCurrentDateTimeAsString()); return getMapper().updateAppLoginPassword(userinfo) > 0; } catch (Exception e) { diff --git a/maxkey-persistence/src/main/resources/org/maxkey/persistence/mapper/xml/mysql/UserInfoMapper.xml b/maxkey-persistence/src/main/resources/org/maxkey/persistence/mapper/xml/mysql/UserInfoMapper.xml index f7a910a84..a54fa745a 100644 --- a/maxkey-persistence/src/main/resources/org/maxkey/persistence/mapper/xml/mysql/UserInfoMapper.xml +++ b/maxkey-persistence/src/main/resources/org/maxkey/persistence/mapper/xml/mysql/UserInfoMapper.xml @@ -84,7 +84,7 @@ id = #{id} - + update mxk_userinfo set password = #{password}, @@ -93,7 +93,7 @@ passwordlastsettime = current_timestamp where - id = #{id} + id = #{userId} diff --git a/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/maxkey/authz/endpoint/AuthorizeBaseEndpoint.java b/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/maxkey/authz/endpoint/AuthorizeBaseEndpoint.java index 361ef9db3..4aae39619 100644 --- a/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/maxkey/authz/endpoint/AuthorizeBaseEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/maxkey/authz/endpoint/AuthorizeBaseEndpoint.java @@ -73,8 +73,7 @@ public class AuthorizeBaseEndpoint { return app; } - protected Accounts getAccounts(Apps app){ - UserInfo userInfo = WebContext.getUserInfo(); + protected Accounts getAccounts(Apps app,UserInfo userInfo){ Apps loadApp = getApp(app.getId()); Accounts account = new Accounts(userInfo.getId(),loadApp.getId()); @@ -97,7 +96,7 @@ public class AuthorizeBaseEndpoint { ); //decoder database stored encode password account.setRelatedPassword( - PasswordReciprocal.getInstance().decoder(WebContext.getUserInfo().getDecipherable())); + PasswordReciprocal.getInstance().decoder(userInfo.getDecipherable())); }else if(loadApp.getCredential()==Apps.CREDENTIALS.NONE){ account.setUsername(userInfo.getUsername()); account.setRelatedPassword(userInfo.getUsername()); diff --git a/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/maxkey/authz/endpoint/AuthorizeCredentialEndpoint.java b/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/maxkey/authz/endpoint/AuthorizeCredentialEndpoint.java index e779480f1..3fcfcd8b7 100644 --- a/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/maxkey/authz/endpoint/AuthorizeCredentialEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/maxkey/authz/endpoint/AuthorizeCredentialEndpoint.java @@ -21,6 +21,8 @@ package org.maxkey.authz.endpoint; import javax.servlet.http.HttpServletRequest; + +import org.maxkey.authn.annotation.CurrentUser; import org.maxkey.crypto.password.PasswordReciprocal; import org.maxkey.entity.Accounts; import org.maxkey.entity.UserInfo; @@ -41,12 +43,13 @@ public class AuthorizeCredentialEndpoint extends AuthorizeBaseEndpoint{ @RequestMapping("/authz/credential/forward") public ModelAndView authorizeCredentialForward( @RequestParam("appId") String appId, - @RequestParam("redirect_uri") String redirect_uri){ + @RequestParam("redirect_uri") String redirect_uri, + @CurrentUser UserInfo currentUser){ ModelAndView modelAndView=new ModelAndView("authorize/init_sso_credential"); modelAndView.addObject("username", ""); modelAndView.addObject("password", ""); modelAndView.addObject("setpassword", true); - modelAndView.addObject("userId", WebContext.getUserInfo().getId()); + modelAndView.addObject("userId", currentUser.getId()); modelAndView.addObject("appId", appId); modelAndView.addObject("appName",getApp(appId).getName()); modelAndView.addObject("redirect_uri", redirect_uri); @@ -60,16 +63,17 @@ public class AuthorizeCredentialEndpoint extends AuthorizeBaseEndpoint{ @RequestParam("appId") String appId, @RequestParam("identity_username") String identity_username, @RequestParam("identity_password") String identity_password, - @RequestParam("redirect_uri") String redirect_uri){ + @RequestParam("redirect_uri") String redirect_uri, + @CurrentUser UserInfo currentUser){ if(StringUtils.isNotEmpty(identity_username)&&StringUtils.isNotEmpty(identity_password)){ Accounts appUser =new Accounts (); - UserInfo userInfo=WebContext.getUserInfo(); + appUser.setId(appUser.generateId()); - appUser.setUserId(userInfo.getId()); - appUser.setUsername(userInfo.getUsername()); - appUser.setDisplayName(userInfo.getDisplayName()); + appUser.setUserId(currentUser.getId()); + appUser.setUsername(currentUser.getUsername()); + appUser.setDisplayName(currentUser.getDisplayName()); appUser.setAppId(appId); appUser.setAppName(getApp(appId).getName()); @@ -77,7 +81,7 @@ public class AuthorizeCredentialEndpoint extends AuthorizeBaseEndpoint{ appUser.setRelatedUsername(identity_username); appUser.setRelatedPassword(PasswordReciprocal.getInstance().encode(identity_password)); - appUser.setInstId(WebContext.getUserInfo().getInstId()); + appUser.setInstId(currentUser.getInstId()); if(accountsService.insert(appUser)){ diff --git a/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/maxkey/authz/endpoint/AuthorizeProtectedEndpoint.java b/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/maxkey/authz/endpoint/AuthorizeProtectedEndpoint.java index a3a4b5177..0cd931956 100644 --- a/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/maxkey/authz/endpoint/AuthorizeProtectedEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/maxkey/authz/endpoint/AuthorizeProtectedEndpoint.java @@ -21,6 +21,8 @@ package org.maxkey.authz.endpoint; import javax.servlet.http.HttpServletRequest; + +import org.maxkey.authn.annotation.CurrentUser; import org.maxkey.crypto.password.PasswordReciprocal; import org.maxkey.entity.UserInfo; import org.maxkey.web.WebConstants; @@ -49,9 +51,9 @@ public class AuthorizeProtectedEndpoint{ @RequestMapping("/authz/protected") public ModelAndView authorizeProtected( @RequestParam("password") String password, - @RequestParam("redirect_uri") String redirect_uri){ - UserInfo userInfo=WebContext.getUserInfo(); - if( userInfo.getAppLoginPassword().equals(PasswordReciprocal.getInstance().encode(password))){ + @RequestParam("redirect_uri") String redirect_uri, + @CurrentUser UserInfo currentUser){ + if( currentUser.getAppLoginPassword().equals(PasswordReciprocal.getInstance().encode(password))){ WebContext.setAttribute(WebConstants.CURRENT_SINGLESIGNON_URI, redirect_uri); return WebContext.redirect(redirect_uri); } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/CasAuthorizeEndpoint.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/CasAuthorizeEndpoint.java index 021030930..d3f4b23db 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/CasAuthorizeEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/CasAuthorizeEndpoint.java @@ -26,8 +26,8 @@ import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.maxkey.authn.SigninPrincipal; import org.maxkey.authn.online.OnlineTicket; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.authz.cas.endpoint.ticket.CasConstants; import org.maxkey.authz.cas.endpoint.ticket.ServiceTicketImpl; import org.maxkey.authz.singlelogout.LogoutType; @@ -117,7 +117,7 @@ public class CasAuthorizeEndpoint extends CasBaseAuthorizeEndpoint{ HttpServletRequest request, HttpServletResponse response){ AppsCasDetails casDetails = (AppsCasDetails)WebContext.getAttribute(CasConstants.PARAMETER.ENDPOINT_CAS_DETAILS); - ServiceTicketImpl serviceTicket = new ServiceTicketImpl(WebContext.getAuthentication(),casDetails); + ServiceTicketImpl serviceTicket = new ServiceTicketImpl(AuthorizationUtils.getAuthentication(),casDetails); String ticket = ticketServices.createTicket(serviceTicket,casDetails.getExpires()); @@ -149,7 +149,7 @@ public class CasAuthorizeEndpoint extends CasBaseAuthorizeEndpoint{ } if(casDetails.getLogoutType()==LogoutType.BACK_CHANNEL) { - String onlineTicketId = ((SigninPrincipal)WebContext.getAuthentication().getPrincipal()).getOnlineTicket().getTicketId(); + String onlineTicketId = AuthorizationUtils.getPrincipal().getOnlineTicket().getTicketId(); OnlineTicket onlineTicket = onlineTicketService.get(onlineTicketId); //set cas ticket as OnlineTicketId casDetails.setOnlineTicket(ticket); diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/CasRestV1Endpoint.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/CasRestV1Endpoint.java index dfc54e10e..70be8b8cc 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/CasRestV1Endpoint.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/CasRestV1Endpoint.java @@ -25,6 +25,7 @@ import javax.servlet.http.HttpServletResponse; import org.maxkey.authn.AbstractAuthenticationProvider; import org.maxkey.authn.LoginCredential; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.authz.cas.endpoint.response.ServiceResponseBuilder; import org.maxkey.authz.cas.endpoint.ticket.CasConstants; import org.maxkey.authz.cas.endpoint.ticket.ServiceTicketImpl; @@ -33,7 +34,6 @@ import org.maxkey.entity.UserInfo; import org.maxkey.entity.apps.AppsCasDetails; import org.maxkey.util.StringUtils; import org.maxkey.web.HttpResponseConstants; -import org.maxkey.web.WebContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -85,7 +85,7 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{ authenticationProvider.authentication(loginCredential,false); - TicketGrantingTicketImpl ticketGrantingTicket=new TicketGrantingTicketImpl("Random",WebContext.getAuthentication(),null); + TicketGrantingTicketImpl ticketGrantingTicket=new TicketGrantingTicketImpl("Random",AuthorizationUtils.getAuthentication(),null); String ticket=casTicketGrantingTicketServices.createTicket(ticketGrantingTicket); String location = applicationConfig.getServerPrefix()+CasConstants.ENDPOINT.ENDPOINT_REST_TICKET_V1 +"/" + ticket; @@ -188,8 +188,8 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{ LoginCredential loginCredential =new LoginCredential(username,password,"CASREST"); authenticationProvider.authentication(loginCredential,false); - UserInfo userInfo =WebContext.getUserInfo(); - TicketGrantingTicketImpl ticketGrantingTicket=new TicketGrantingTicketImpl("Random",WebContext.getAuthentication(),null); + UserInfo userInfo = AuthorizationUtils.getUserInfo(); + TicketGrantingTicketImpl ticketGrantingTicket=new TicketGrantingTicketImpl("Random",AuthorizationUtils.getAuthentication(),null); String ticket=casTicketGrantingTicketServices.createTicket(ticketGrantingTicket); String location = applicationConfig.getServerPrefix() + CasConstants.ENDPOINT.ENDPOINT_REST_TICKET_V1 + ticket; diff --git a/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/maxkey/authz/exapi/endpoint/ExtendApiAuthorizeEndpoint.java b/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/maxkey/authz/exapi/endpoint/ExtendApiAuthorizeEndpoint.java index 49d4886c6..43af4321d 100644 --- a/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/maxkey/authz/exapi/endpoint/ExtendApiAuthorizeEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/maxkey/authz/exapi/endpoint/ExtendApiAuthorizeEndpoint.java @@ -22,14 +22,15 @@ package org.maxkey.authz.exapi.endpoint; import javax.servlet.http.HttpServletRequest; -import org.maxkey.authn.SigninPrincipal; +import org.maxkey.authn.annotation.CurrentUser; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.authz.endpoint.AuthorizeBaseEndpoint; import org.maxkey.authz.endpoint.adapter.AbstractAuthorizeAdapter; import org.maxkey.constants.ConstsBoolean; import org.maxkey.entity.Accounts; +import org.maxkey.entity.UserInfo; import org.maxkey.entity.apps.Apps; import org.maxkey.util.Instance; -import org.maxkey.web.WebContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; @@ -51,20 +52,23 @@ public class ExtendApiAuthorizeEndpoint extends AuthorizeBaseEndpoint{ @Operation(summary = "ExtendApi认证地址接口", description = "参数应用ID",method="GET") @RequestMapping("/authz/api/{id}") - public ModelAndView authorize(HttpServletRequest request,@PathVariable("id") String id){ + public ModelAndView authorize( + HttpServletRequest request, + @PathVariable("id") String id, + @CurrentUser UserInfo currentUser){ ModelAndView modelAndView=new ModelAndView("authorize/redirect_sso_submit"); Apps apps = getApp(id); _logger.debug(""+apps); if(ConstsBoolean.isTrue(apps.getIsAdapter())){ AbstractAuthorizeAdapter adapter = (AbstractAuthorizeAdapter)Instance.newInstance(apps.getAdapter()); - Accounts account = getAccounts(apps); + Accounts account = getAccounts(apps,currentUser); if(apps.getCredential()==Apps.CREDENTIALS.USER_DEFINED && account == null) { return generateInitCredentialModelAndView(id,"/authorize/api/"+id); } - adapter.setAuthentication((SigninPrincipal)WebContext.getAuthentication().getPrincipal()); - adapter.setUserInfo(WebContext.getUserInfo()); + adapter.setAuthentication(AuthorizationUtils.getPrincipal()); + adapter.setUserInfo(currentUser); adapter.setApp(apps); adapter.setAccount(account); diff --git a/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/maxkey/authz/formbased/endpoint/FormBasedAuthorizeEndpoint.java b/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/maxkey/authz/formbased/endpoint/FormBasedAuthorizeEndpoint.java index f4630f6a3..0f56328b3 100644 --- a/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/maxkey/authz/formbased/endpoint/FormBasedAuthorizeEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/maxkey/authz/formbased/endpoint/FormBasedAuthorizeEndpoint.java @@ -22,17 +22,18 @@ package org.maxkey.authz.formbased.endpoint; import javax.servlet.http.HttpServletRequest; -import org.maxkey.authn.SigninPrincipal; +import org.maxkey.authn.annotation.CurrentUser; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.authz.endpoint.AuthorizeBaseEndpoint; import org.maxkey.authz.endpoint.adapter.AbstractAuthorizeAdapter; import org.maxkey.authz.formbased.endpoint.adapter.FormBasedDefaultAdapter; import org.maxkey.constants.ConstsBoolean; import org.maxkey.entity.Accounts; +import org.maxkey.entity.UserInfo; import org.maxkey.entity.apps.Apps; import org.maxkey.entity.apps.AppsFormBasedDetails; import org.maxkey.persistence.service.AppsFormBasedDetailsService; import org.maxkey.util.Instance; -import org.maxkey.web.WebContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -62,7 +63,8 @@ public class FormBasedAuthorizeEndpoint extends AuthorizeBaseEndpoint{ @RequestMapping("/authz/formbased/{id}") public ModelAndView authorize( HttpServletRequest request, - @PathVariable("id") String id){ + @PathVariable("id") String id, + @CurrentUser UserInfo currentUser){ AppsFormBasedDetails formBasedDetails = formBasedDetailsService.getAppDetails(id , true); _logger.debug("formBasedDetails {}",formBasedDetails); @@ -71,7 +73,7 @@ public class FormBasedAuthorizeEndpoint extends AuthorizeBaseEndpoint{ formBasedDetails.setIsAdapter(application.getIsAdapter()); ModelAndView modelAndView=null; - Accounts account = getAccounts(formBasedDetails); + Accounts account = getAccounts(formBasedDetails,currentUser); _logger.debug("Accounts {}",account); if(account == null){ @@ -88,8 +90,8 @@ public class FormBasedAuthorizeEndpoint extends AuthorizeBaseEndpoint{ FormBasedDefaultAdapter formBasedDefaultAdapter =new FormBasedDefaultAdapter(); adapter =(AbstractAuthorizeAdapter)formBasedDefaultAdapter; } - adapter.setAuthentication((SigninPrincipal)WebContext.getAuthentication().getPrincipal()); - adapter.setUserInfo(WebContext.getUserInfo()); + adapter.setAuthentication(AuthorizationUtils.getPrincipal()); + adapter.setUserInfo(currentUser); adapter.setApp(formBasedDetails); adapter.setAccount(account); diff --git a/maxkey-protocols/maxkey-protocol-jwt/src/main/java/org/maxkey/authz/token/endpoint/JwtAuthorizeEndpoint.java b/maxkey-protocols/maxkey-protocol-jwt/src/main/java/org/maxkey/authz/token/endpoint/JwtAuthorizeEndpoint.java index 3b1b74d0a..29b944cde 100644 --- a/maxkey-protocols/maxkey-protocol-jwt/src/main/java/org/maxkey/authz/token/endpoint/JwtAuthorizeEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-jwt/src/main/java/org/maxkey/authz/token/endpoint/JwtAuthorizeEndpoint.java @@ -27,7 +27,8 @@ import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.lang3.StringUtils; -import org.maxkey.authn.SigninPrincipal; +import org.maxkey.authn.annotation.CurrentUser; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.authz.endpoint.AuthorizeBaseEndpoint; import org.maxkey.authz.endpoint.adapter.AbstractAuthorizeAdapter; import org.maxkey.authz.jwt.endpoint.adapter.JwtAdapter; @@ -35,6 +36,7 @@ import org.maxkey.configuration.ApplicationConfig; import org.maxkey.constants.ConstsBoolean; import org.maxkey.constants.ContentType; import org.maxkey.crypto.jose.keystore.JWKSetKeyStore; +import org.maxkey.entity.UserInfo; import org.maxkey.entity.apps.Apps; import org.maxkey.entity.apps.AppsJwtDetails; import org.maxkey.persistence.service.AppsJwtDetailsService; @@ -76,7 +78,8 @@ public class JwtAuthorizeEndpoint extends AuthorizeBaseEndpoint{ public ModelAndView authorize( HttpServletRequest request, HttpServletResponse response, - @PathVariable("id") String id){ + @PathVariable("id") String id, + @CurrentUser UserInfo currentUser){ ModelAndView modelAndView=new ModelAndView(); Apps application = getApp(id); AppsJwtDetails jwtDetails = jwtDetailsService.getAppDetails(id , true); @@ -98,8 +101,8 @@ public class JwtAuthorizeEndpoint extends AuthorizeBaseEndpoint{ adapter = (AbstractAuthorizeAdapter)jwtAdapter; } - adapter.setAuthentication((SigninPrincipal)WebContext.getAuthentication().getPrincipal()); - adapter.setUserInfo(WebContext.getUserInfo()); + adapter.setAuthentication(AuthorizationUtils.getPrincipal()); + adapter.setUserInfo(currentUser); adapter.generateInfo(); //sign diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/approval/endpoint/OAuth20AccessConfirmationEndpoint.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/approval/endpoint/OAuth20AccessConfirmationEndpoint.java index 595d90bb7..bb0c2c975 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/approval/endpoint/OAuth20AccessConfirmationEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/approval/endpoint/OAuth20AccessConfirmationEndpoint.java @@ -19,7 +19,7 @@ package org.maxkey.authz.oauth2.provider.approval.endpoint; import java.util.LinkedHashMap; import java.util.Map; -import org.maxkey.authn.SigninPrincipal; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.authz.oauth2.common.OAuth2Constants; import org.maxkey.authz.oauth2.provider.AuthorizationRequest; import org.maxkey.authz.oauth2.provider.ClientDetailsService; @@ -95,8 +95,7 @@ public class OAuth20AccessConfirmationEndpoint { for (String scope : clientAuth.getScope()) { scopes.put(OAuth2Constants.PARAMETER.SCOPE_PREFIX + scope, "false"); } - String principal = - ((SigninPrincipal) WebContext.getAuthentication().getPrincipal()).getUsername(); + String principal = AuthorizationUtils.getPrincipal().getUsername(); for (Approval approval : approvalStore.getApprovals(principal, client.getClientId())) { if (clientAuth.getScope().contains(approval.getScope())) { scopes.put(OAuth2Constants.PARAMETER.SCOPE_PREFIX + approval.getScope(), diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/endpoint/AuthorizationEndpoint.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/endpoint/AuthorizationEndpoint.java index fb4dc2517..9baf16852 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/endpoint/AuthorizationEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/endpoint/AuthorizationEndpoint.java @@ -22,6 +22,8 @@ import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.authz.oauth2.common.OAuth2AccessToken; import org.maxkey.authz.oauth2.common.OAuth2Constants; import org.maxkey.authz.oauth2.common.exceptions.InvalidClientException; @@ -150,7 +152,7 @@ public class AuthorizationEndpoint extends AbstractEndpoint { @RequestParam Map parameters, SessionStatus sessionStatus) { - Principal principal=(Principal)WebContext.getAuthentication(); + Principal principal=(Principal)AuthorizationUtils.getAuthentication(); // Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should // query off of the authorization request instead of referring back to the parameters map. The contents of the // parameters map will be stored without change in the AuthorizationRequest object once it is created. @@ -241,7 +243,7 @@ public class AuthorizationEndpoint extends AbstractEndpoint { Map model, SessionStatus sessionStatus) { - Principal principal=(Principal)WebContext.getAuthentication(); + Principal principal=(Principal)AuthorizationUtils.getAuthentication(); if (!(principal instanceof Authentication)) { sessionStatus.setComplete(); throw new InsufficientAuthenticationException( diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/endpoint/TokenEndpoint.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/endpoint/TokenEndpoint.java index bb2917436..0e0d2fdc7 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/endpoint/TokenEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/endpoint/TokenEndpoint.java @@ -23,6 +23,7 @@ import java.util.Map; import java.util.Set; import org.maxkey.authn.SigninPrincipal; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.authz.oauth2.common.DefaultOAuth2AccessToken; import org.maxkey.authz.oauth2.common.OAuth2AccessToken; import org.maxkey.authz.oauth2.common.OAuth2Constants; @@ -38,7 +39,6 @@ import org.maxkey.authz.oauth2.provider.TokenRequest; import org.maxkey.authz.oauth2.provider.request.DefaultOAuth2RequestValidator; import org.maxkey.entity.apps.oauth2.provider.ClientDetails; import org.maxkey.util.StringGenerator; -import org.maxkey.web.WebContext; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; @@ -114,7 +114,7 @@ public class TokenEndpoint extends AbstractEndpoint { // TokenEndpointAuthenticationFilter OAuth2AccessToken token = null; try { - Object principal = WebContext.getAuthentication(); + Object principal = AuthorizationUtils.getAuthentication(); if (!(principal instanceof Authentication)) { throw new InsufficientAuthenticationException( 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 af9745238..dab7153b3 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 @@ -32,6 +32,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.maxkey.authn.SigninPrincipal; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.authz.oauth2.common.OAuth2Constants; import org.maxkey.authz.oauth2.common.util.OAuth2Utils; import org.maxkey.authz.oauth2.provider.AuthorizationRequest; @@ -154,7 +155,7 @@ public class TokenEndpointAuthenticationFilter implements Filter { } auth.setAuthenticated(true); UsernamePasswordAuthenticationToken simpleUserAuthentication = new UsernamePasswordAuthenticationToken(auth, authentication.getCredentials(), authentication.getAuthorities()); - WebContext.setAuthentication(simpleUserAuthentication); + AuthorizationUtils.setAuthentication(simpleUserAuthentication); } } @@ -208,7 +209,7 @@ public class TokenEndpointAuthenticationFilter implements Filter { OAuth2Request storedOAuth2Request = oAuth2RequestFactory.createOAuth2Request(authorizationRequest); - WebContext.setAuthentication(new OAuth2Authentication(storedOAuth2Request, authResult)); + AuthorizationUtils.setAuthentication(new OAuth2Authentication(storedOAuth2Request, authResult)); onSuccessfulAuthentication(request, response, authResult); diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oidc/idtoken/OIDCIdTokenEnhancer.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oidc/idtoken/OIDCIdTokenEnhancer.java index 561bcbdbc..2948e971e 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oidc/idtoken/OIDCIdTokenEnhancer.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oidc/idtoken/OIDCIdTokenEnhancer.java @@ -30,6 +30,7 @@ import java.util.UUID; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.authz.oauth2.common.DefaultOAuth2AccessToken; import org.maxkey.authz.oauth2.common.OAuth2AccessToken; import org.maxkey.authz.oauth2.provider.ClientDetailsService; @@ -40,7 +41,6 @@ import org.maxkey.configuration.oidc.OIDCProviderMetadata; import org.maxkey.crypto.jwt.encryption.service.impl.DefaultJwtEncryptionAndDecryptionService; import org.maxkey.crypto.jwt.signer.service.impl.DefaultJwtSigningAndValidationService; import org.maxkey.entity.apps.oauth2.provider.ClientDetails; -import org.maxkey.web.WebContext; import com.nimbusds.jose.util.Base64URL; import org.slf4j.Logger; @@ -125,7 +125,7 @@ public class OIDCIdTokenEnhancer implements TokenEnhancer { if (request.getExtensions().containsKey("max_age") || (request.getExtensions().containsKey("idtoken")) // parse the ID Token claims (#473) -- for now assume it could be in there ) { - DateTime loginDate = DateTime.parse(WebContext.getUserInfo().getLastLoginTime(), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")); + DateTime loginDate = DateTime.parse(AuthorizationUtils.getUserInfo().getLastLoginTime(), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")); builder.claim("auth_time", loginDate.getMillis()/1000); } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/endpoint/AssertionEndpoint.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/endpoint/AssertionEndpoint.java index df8f5a735..2cda1fd22 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/endpoint/AssertionEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/endpoint/AssertionEndpoint.java @@ -22,14 +22,15 @@ import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.maxkey.authn.SigninPrincipal; +import org.maxkey.authn.annotation.CurrentUser; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.authz.saml.common.AuthnRequestInfo; import org.maxkey.authz.saml.common.EndpointGenerator; import org.maxkey.authz.saml20.binding.BindingAdapter; import org.maxkey.authz.saml20.provider.xml.AuthnResponseGenerator; +import org.maxkey.entity.UserInfo; import org.maxkey.entity.apps.AppsSAML20Details; import org.maxkey.web.WebConstants; -import org.maxkey.web.WebContext; import org.opensaml.saml2.core.Response; import org.opensaml.saml2.metadata.Endpoint; import org.opensaml.ws.message.encoder.MessageEncodingException; @@ -57,7 +58,10 @@ public class AssertionEndpoint { AuthnResponseGenerator authnResponseGenerator; @RequestMapping(value = "/authz/saml20/assertion") - public ModelAndView assertion(HttpServletRequest request,HttpServletResponse response) throws Exception { + public ModelAndView assertion( + HttpServletRequest request, + HttpServletResponse response, + @CurrentUser UserInfo currentUser) throws Exception { logger.debug("saml20 assertion start."); bindingAdapter = (BindingAdapter) request.getSession().getAttribute( WebConstants.AUTHORIZE_SIGN_ON_APP_SAMLV20_ADAPTER); @@ -74,14 +78,15 @@ public class AssertionEndpoint { logger.debug("AuthnRequestInfo: {}", authnRequestInfo); HashMap attributeMap=new HashMap(); attributeMap.put(WebConstants.ONLINE_TICKET_NAME, - ((SigninPrincipal)WebContext.getAuthentication().getPrincipal()).getOnlineTicket().getTicketId()); + AuthorizationUtils.getPrincipal().getOnlineTicket().getTicketId()); //saml20Details Response authResponse = authnResponseGenerator.generateAuthnResponse( saml20Details, authnRequestInfo, attributeMap, - bindingAdapter); + bindingAdapter, + currentUser); Endpoint endpoint = endpointGenerator.generateEndpoint(saml20Details.getSpAcsUrl()); diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/AssertionGenerator.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/AssertionGenerator.java index 99c1b6817..d74c770c6 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/AssertionGenerator.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/AssertionGenerator.java @@ -21,10 +21,12 @@ import java.util.ArrayList; import java.util.HashMap; import org.joda.time.DateTime; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.authz.saml.service.IDService; import org.maxkey.authz.saml.service.TimeService; import org.maxkey.authz.saml20.binding.BindingAdapter; import org.maxkey.authz.saml20.xml.IssuerGenerator; +import org.maxkey.entity.UserInfo; import org.maxkey.entity.apps.AppsSAML20Details; import org.maxkey.web.WebContext; import org.opensaml.Configuration; @@ -79,7 +81,8 @@ public class AssertionGenerator { String inResponseTo, String audienceUrl, int validInSeconds, - HashMapattributeMap + HashMapattributeMap, + UserInfo userInfo ) { Assertion assertion = new AssertionBuilder().buildObject();; @@ -88,7 +91,8 @@ public class AssertionGenerator { saml20Details, assertionConsumerURL, inResponseTo, - validInSeconds); + validInSeconds, + userInfo); assertion.setSubject(subject); //issuer Issuer issuer = issuerGenerator.generateIssuer(); @@ -100,11 +104,15 @@ public class AssertionGenerator { //AttributeStatements ArrayList grantedAuthoritys = new ArrayList(); grantedAuthoritys.add(new SimpleGrantedAuthority("ROLE_USER")); - for(GrantedAuthority anthGrantedAuthority: ((UsernamePasswordAuthenticationToken)WebContext.getAuthentication()).getAuthorities()){ + for(GrantedAuthority anthGrantedAuthority: ((UsernamePasswordAuthenticationToken)AuthorizationUtils.getAuthentication()).getAuthorities()){ grantedAuthoritys.add(anthGrantedAuthority); } - AttributeStatement attributeStatement =attributeStatementGenerator.generateAttributeStatement( - saml20Details, grantedAuthoritys,attributeMap); + AttributeStatement attributeStatement = + attributeStatementGenerator.generateAttributeStatement( + saml20Details, + grantedAuthoritys, + attributeMap, + userInfo); assertion.getAttributeStatements().add(attributeStatement); //ID assertion.setID(idService.generateID()); diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/AttributeStatementGenerator.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/AttributeStatementGenerator.java index 681346821..86a1befdf 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/AttributeStatementGenerator.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/AttributeStatementGenerator.java @@ -30,7 +30,6 @@ import org.maxkey.entity.ExtraAttr; import org.maxkey.entity.ExtraAttrs; import org.maxkey.entity.UserInfo; import org.maxkey.entity.apps.AppsSAML20Details; -import org.maxkey.web.WebContext; import org.opensaml.Configuration; import org.opensaml.saml2.core.Attribute; import org.opensaml.saml2.core.AttributeStatement; @@ -52,15 +51,20 @@ public class AttributeStatementGenerator { public static String COMMA = ","; public static String COMMA_ISO8859_1 = "#44;"; //#44; ->, - public AttributeStatement generateAttributeStatement(AppsSAML20Details saml20Details,ArrayList grantedAuthoritys) { - return generateAttributeStatement(saml20Details, grantedAuthoritys,null); + public AttributeStatement generateAttributeStatement( + AppsSAML20Details saml20Details, + ArrayList grantedAuthoritys, + UserInfo userInfo) { + return generateAttributeStatement( + saml20Details, grantedAuthoritys,null,userInfo); } public AttributeStatement generateAttributeStatement( AppsSAML20Details saml20Details, ArrayList grantedAuthoritys, - HashMapattributeMap) { + HashMapattributeMap, + UserInfo userInfo) { AttributeStatementBuilder attributeStatementBuilder = (AttributeStatementBuilder) builderFactory.getBuilder(AttributeStatement.DEFAULT_ELEMENT_NAME); AttributeStatement attributeStatement = attributeStatementBuilder.buildObject(); @@ -68,7 +72,7 @@ public class AttributeStatementGenerator { Attribute attributeGrantedAuthority=builderGrantedAuthority(grantedAuthoritys); attributeStatement.getAttributes().add(attributeGrantedAuthority); - putUserAttributes(attributeMap); + putUserAttributes(attributeMap,userInfo); if(null!=attributeMap){ Iterator> iterator = attributeMap.entrySet().iterator(); @@ -137,8 +141,9 @@ public class AttributeStatementGenerator { return xsStringValue; } - public HashMap putUserAttributes(HashMap attributeMap){ - UserInfo userInfo = WebContext.getUserInfo(); + public HashMap putUserAttributes( + HashMap attributeMap, + UserInfo userInfo){ attributeMap.put(ActiveDirectoryUser.USERNAME, userInfo.getUsername()); attributeMap.put(ActiveDirectoryUser.UID, userInfo.getUsername()); diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/AuthnResponseGenerator.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/AuthnResponseGenerator.java index c35fd4c4d..1f7dd68dc 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/AuthnResponseGenerator.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/AuthnResponseGenerator.java @@ -26,6 +26,7 @@ import org.maxkey.authz.saml.service.TimeService; import org.maxkey.authz.saml20.binding.BindingAdapter; import org.maxkey.authz.saml20.xml.IssuerGenerator; import org.maxkey.constants.ConstsBoolean; +import org.maxkey.entity.UserInfo; import org.maxkey.entity.apps.AppsSAML20Details; import org.opensaml.Configuration; import org.opensaml.saml2.core.Assertion; @@ -64,7 +65,8 @@ public class AuthnResponseGenerator { public Response generateAuthnResponse( AppsSAML20Details saml20Details, AuthnRequestInfo authnRequestInfo, HashMapattributeMap, - BindingAdapter bindingAdapter){ + BindingAdapter bindingAdapter, + UserInfo currentUser){ Response authResponse = new ResponseBuilder().buildObject(); //builder Assertion @@ -75,7 +77,8 @@ public class AuthnResponseGenerator { authnRequestInfo.getAuthnRequestID(), saml20Details.getAudience(), Integer.parseInt(saml20Details.getValidityInterval()), - attributeMap); + attributeMap, + currentUser); //Encrypt if(ConstsBoolean.isYes(saml20Details.getEncrypted())) { diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/SubjectGenerator.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/SubjectGenerator.java index dbd9dfdd1..0024ef9ef 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/SubjectGenerator.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/SubjectGenerator.java @@ -47,8 +47,8 @@ public class SubjectGenerator { public Subject generateSubject( AppsSAML20Details saml20Details, String assertionConsumerURL, String inResponseTo, - int validInSeconds) { - UserInfo userInfo = WebContext.getUserInfo(); + int validInSeconds, + UserInfo userInfo) { String nameIdValue = userInfo.getUsername(); if(saml20Details.getNameidFormat().equalsIgnoreCase("persistent")) { diff --git a/maxkey-protocols/maxkey-protocol-tokenbased/src/main/java/org/maxkey/authz/token/endpoint/TokenBasedAuthorizeEndpoint.java b/maxkey-protocols/maxkey-protocol-tokenbased/src/main/java/org/maxkey/authz/token/endpoint/TokenBasedAuthorizeEndpoint.java index fbe69b641..ac278a5dd 100644 --- a/maxkey-protocols/maxkey-protocol-tokenbased/src/main/java/org/maxkey/authz/token/endpoint/TokenBasedAuthorizeEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-tokenbased/src/main/java/org/maxkey/authz/token/endpoint/TokenBasedAuthorizeEndpoint.java @@ -24,12 +24,14 @@ import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.maxkey.authn.SigninPrincipal; +import org.maxkey.authn.annotation.CurrentUser; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.authz.endpoint.AuthorizeBaseEndpoint; import org.maxkey.authz.endpoint.adapter.AbstractAuthorizeAdapter; import org.maxkey.authz.token.endpoint.adapter.TokenBasedDefaultAdapter; import org.maxkey.configuration.ApplicationConfig; import org.maxkey.constants.ConstsBoolean; +import org.maxkey.entity.UserInfo; import org.maxkey.entity.apps.Apps; import org.maxkey.entity.apps.AppsTokenBasedDetails; import org.maxkey.persistence.service.AppsTokenBasedDetailsService; @@ -66,7 +68,8 @@ public class TokenBasedAuthorizeEndpoint extends AuthorizeBaseEndpoint{ public ModelAndView authorize( HttpServletRequest request, HttpServletResponse response, - @PathVariable("id") String id){ + @PathVariable("id") String id, + @CurrentUser UserInfo currentUser){ ModelAndView modelAndView=new ModelAndView(); @@ -84,8 +87,8 @@ public class TokenBasedAuthorizeEndpoint extends AuthorizeBaseEndpoint{ }else{ adapter =(AbstractAuthorizeAdapter)new TokenBasedDefaultAdapter(); } - adapter.setAuthentication((SigninPrincipal)WebContext.getAuthentication().getPrincipal()); - adapter.setUserInfo(WebContext.getUserInfo()); + adapter.setAuthentication(AuthorizationUtils.getPrincipal()); + adapter.setUserInfo(currentUser); adapter.setApp(tokenBasedDetails); adapter.generateInfo(); diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/MaxKeyConfig.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/MaxKeyConfig.java index f11fa3cbc..9d94fe1df 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/MaxKeyConfig.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/MaxKeyConfig.java @@ -28,7 +28,6 @@ import org.maxkey.authn.realm.jdbc.JdbcAuthenticationRealm; import org.maxkey.authn.realm.ldap.LdapAuthenticationRealmService; import org.maxkey.authn.support.kerberos.KerberosProxy; import org.maxkey.authn.support.kerberos.RemoteKerberosService; -import org.maxkey.authn.support.rememberme.AbstractRemeberMeService; import org.maxkey.configuration.EmailConfig; import org.maxkey.constants.ConstsPersistence; import org.maxkey.password.onetimepwd.AbstractOtpAuthn; @@ -103,7 +102,6 @@ public class MaxKeyConfig implements InitializingBean { PasswordPolicyValidator passwordPolicyValidator, LoginRepository loginService, LoginHistoryRepository loginHistoryService, - AbstractRemeberMeService remeberMeService, UserInfoService userInfoService, JdbcTemplate jdbcTemplate, OtpAuthnService otpAuthnService, @@ -114,7 +112,6 @@ public class MaxKeyConfig implements InitializingBean { passwordPolicyValidator, loginService, loginHistoryService, - remeberMeService, userInfoService, jdbcTemplate, ldapRealmService diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/MaxKeyMvcConfig.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/MaxKeyMvcConfig.java index 5d7152ffc..160086f48 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/MaxKeyMvcConfig.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/MaxKeyMvcConfig.java @@ -24,14 +24,12 @@ import org.maxkey.authn.support.basic.BasicEntryPoint; import org.maxkey.authn.support.httpheader.HttpHeaderEntryPoint; import org.maxkey.authn.support.kerberos.HttpKerberosEntryPoint; import org.maxkey.authn.support.kerberos.KerberosService; -import org.maxkey.authn.support.rememberme.AbstractRemeberMeService; -import org.maxkey.authn.support.rememberme.HttpRemeberMeEntryPoint; import org.maxkey.authn.web.CurrentUserMethodArgumentResolver; -import org.maxkey.authn.web.interceptor.PermissionAdapter; +import org.maxkey.authn.web.interceptor.PermissionInterceptor; import org.maxkey.configuration.ApplicationConfig; -import org.maxkey.web.interceptor.HistoryLoginAppAdapter; -import org.maxkey.web.interceptor.HistoryLogsAdapter; -import org.maxkey.web.interceptor.PreLoginAppAdapter; +import org.maxkey.web.interceptor.HistorySignOnAppInterceptor; +import org.maxkey.web.interceptor.HistoryLogsInterceptor; +import org.maxkey.web.interceptor.SingleSignOnInterceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -44,7 +42,6 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; @Configuration @EnableWebMvc @@ -59,28 +56,22 @@ public class MaxKeyMvcConfig implements WebMvcConfigurer { @Qualifier("authenticationProvider") AbstractAuthenticationProvider authenticationProvider ; - @Autowired - @Qualifier("remeberMeService") - AbstractRemeberMeService remeberMeService; - @Autowired @Qualifier("kerberosService") KerberosService kerberosService; @Autowired - PermissionAdapter permissionAdapter; + PermissionInterceptor permissionInterceptor; @Autowired - HistoryLogsAdapter historyLogsAdapter; + HistoryLogsInterceptor historyLogsInterceptor; + @Autowired - LocaleChangeInterceptor localeChangeInterceptor; + SingleSignOnInterceptor singleSignOnInterceptor; @Autowired - PreLoginAppAdapter preLoginAppAdapter; - - @Autowired - HistoryLoginAppAdapter historyLoginAppAdapter; + HistorySignOnAppInterceptor historySignOnAppInterceptor; @Value("${maxkey.login.httpheader.enable:false}") private boolean httpHeaderEnable; @@ -118,10 +109,6 @@ public class MaxKeyMvcConfig implements WebMvcConfigurer { public void addInterceptors(InterceptorRegistry registry) { //addPathPatterns 用于添加拦截规则 , 先把所有路径都加入拦截, 再一个个排除 //excludePathPatterns 表示改路径不用拦截 - _logger.debug("add HttpRemeberMeEntryPoint"); - registry.addInterceptor(new HttpRemeberMeEntryPoint( - authenticationProvider,remeberMeService,applicationConfig,true)) - .addPathPatterns("/login"); _logger.debug("add HttpKerberosEntryPoint"); registry.addInterceptor(new HttpKerberosEntryPoint( @@ -141,11 +128,8 @@ public class MaxKeyMvcConfig implements WebMvcConfigurer { _logger.debug("add BasicEntryPoint"); } - registry.addInterceptor(permissionAdapter) - .addPathPatterns("/index/**") - .addPathPatterns("/logs/**") - .addPathPatterns("/userinfo/**") - .addPathPatterns("/profile/**") + //for frontend + registry.addInterceptor(permissionInterceptor) .addPathPatterns("/config/**") .addPathPatterns("/historys/**") .addPathPatterns("/access/session/**") @@ -153,9 +137,17 @@ public class MaxKeyMvcConfig implements WebMvcConfigurer { .addPathPatterns("/appList") .addPathPatterns("/appList/**") .addPathPatterns("/socialsignon/**") - + ; + _logger.debug("add Permission Interceptor"); + + registry.addInterceptor(historyLogsInterceptor) + .addPathPatterns("/config/changePassword/**") + ; + _logger.debug("add historyLogs Interceptor"); + + //for Single Sign On + registry.addInterceptor(singleSignOnInterceptor) .addPathPatterns("/authz/basic/*") - .addPathPatterns("/authz/ltpa/*") //Form based .addPathPatterns("/authz/formbased/*") //Token based @@ -197,34 +189,10 @@ public class MaxKeyMvcConfig implements WebMvcConfigurer { //online ticket Validate .excludePathPatterns("/onlineticket/ticketValidate") .excludePathPatterns("/onlineticket/ticketValidate/*") - ; - - _logger.debug("add PermissionAdapter"); - - registry.addInterceptor(historyLogsAdapter) - .addPathPatterns("/safe/changePassword/**") - ; - _logger.debug("add HistoryLogsAdapter"); - - registry.addInterceptor(preLoginAppAdapter) - .addPathPatterns("/authz/basic/*") - .addPathPatterns("/authz/ltpa/*") - //Form based - .addPathPatterns("/authz/formbased/*") - //Token based - .addPathPatterns("/authz/tokenbased/*") - //JWT - .addPathPatterns("/authz/jwt/*") - //SAML - .addPathPatterns("/authz/saml20/idpinit/*") - .addPathPatterns("/authz/saml20/assertion") - //CAS - .addPathPatterns("/authz/cas/login") - .addPathPatterns("/authz/cas/granting") ; - _logger.debug("add PreLoginAppAdapter"); + _logger.debug("add Single SignOn Interceptor"); - registry.addInterceptor(historyLoginAppAdapter) + registry.addInterceptor(historySignOnAppInterceptor) .addPathPatterns("/authz/basic/*") .addPathPatterns("/authz/ltpa/*") //Extend api @@ -243,11 +211,7 @@ public class MaxKeyMvcConfig implements WebMvcConfigurer { //OAuth .addPathPatterns("/authz/oauth/v20/approval_confirm") ; - _logger.debug("add HistoryLoginAppAdapter"); - - - registry.addInterceptor(localeChangeInterceptor); - _logger.debug("add LocaleChangeInterceptor"); + _logger.debug("add history SignOn App Interceptor"); } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/AppListController.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/AppListController.java index 0f114f39e..1201b8cd1 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/AppListController.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/AppListController.java @@ -70,7 +70,7 @@ public class AppListController { public ResponseEntity appList( @RequestParam(value = "gridList", required = false) String gridList, @CurrentUser UserInfo currentUser) { - userInfoService.updateGridList(gridList); + userInfoService.updateGridList(gridList,currentUser); UserApps userApps = new UserApps(); userApps.setUsername(currentUser.getUsername()); userApps.setInstId(currentUser.getInstId()); diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/ChangePasswodController.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/ChangePasswodController.java new file mode 100644 index 000000000..aefc4db65 --- /dev/null +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/ChangePasswodController.java @@ -0,0 +1,74 @@ +/* + * 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.web.contorller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.maxkey.authn.annotation.CurrentUser; +import org.maxkey.constants.ConstsOperateMessage; +import org.maxkey.constants.ConstsPasswordSetType; +import org.maxkey.constants.ConstsTimeInterval; +import org.maxkey.entity.ChangePassword; +import org.maxkey.entity.UserInfo; +import org.maxkey.persistence.repository.PasswordPolicyValidator; +import org.maxkey.persistence.service.UserInfoService; +import org.maxkey.web.WebConstants; +import org.maxkey.web.WebContext; +import org.maxkey.web.message.Message; +import org.maxkey.web.message.MessageType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.ModelAndView; + +@Controller +@RequestMapping(value={"/config"}) +public class ChangePasswodController { + final static Logger _logger = LoggerFactory.getLogger(ChangePasswodController.class); + + @Autowired + private UserInfoService userInfoService; + + @ResponseBody + @RequestMapping(value="/changePassword") + public Message changePasswod( + @RequestBody ChangePassword changePassword, + @CurrentUser UserInfo currentUser) { + + changePassword.setUserId(currentUser.getId()); + changePassword.setUsername(currentUser.getUsername()); + changePassword.setInstId(currentUser.getInstId()); + changePassword.setPasswordSetType(ConstsPasswordSetType.PASSWORD_NORMAL); + if(userInfoService.changePassword(changePassword)) { + return new Message(WebContext.getI18nValue(ConstsOperateMessage.UPDATE_SUCCESS),MessageType.success); + }else { + return new Message( + WebContext.getI18nValue(ConstsOperateMessage.UPDATE_ERROR)+"
" + +WebContext.getAttribute(PasswordPolicyValidator.PASSWORD_POLICY_VALIDATE_RESULT), + MessageType.error); + } + } + +} diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/ForgotPasswordContorller.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/ForgotPasswordContorller.java index 5894fd6fc..db1c0c5c7 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/ForgotPasswordContorller.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/ForgotPasswordContorller.java @@ -145,13 +145,14 @@ public class ForgotPasswordContorller { if ((forgotType == ForgotType.EMAIL && mailOtpAuthn.validate(userInfo, captcha)) || (forgotType == ForgotType.MOBILE && smsOtpAuthn.validate(userInfo, captcha)) ) { + /** if(userInfoService.changePassword(userInfo,true)) { modelAndView.addObject("passwordResetResult", PasswordResetResult.SUCCESS); }else { ; modelAndView.addObject("validate_result", WebContext.getAttribute(PasswordPolicyValidator.PASSWORD_POLICY_VALIDATE_RESULT)); modelAndView.addObject("passwordResetResult", PasswordResetResult.PASSWORDERROR); - } + }*/ } else { modelAndView.addObject("passwordResetResult", PasswordResetResult.CAPTCHAERROR); } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/ProfileController.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/ProfileController.java index 0e298c9fb..5e6e9a120 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/ProfileController.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/ProfileController.java @@ -1,5 +1,5 @@ /* - * Copyright [2020] [MaxKey of copyright http://www.maxkey.top] + * Copyright [2022] [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. @@ -17,45 +17,34 @@ package org.maxkey.web.contorller; -import javax.validation.Valid; -import org.maxkey.constants.ConstsOperateMessage; +import org.maxkey.authn.annotation.CurrentUser; +import org.maxkey.entity.Message; import org.maxkey.entity.UserInfo; import org.maxkey.persistence.service.UserInfoService; -import org.maxkey.web.WebContext; -import org.maxkey.web.message.Message; -import org.maxkey.web.message.MessageScope; -import org.maxkey.web.message.MessageType; -import org.maxkey.web.message.OperateType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.bind.annotation.ResponseBody; @Controller -@RequestMapping(value = { "/profile" }) +@RequestMapping(value = { "/config/profile" }) public class ProfileController { static final Logger _logger = LoggerFactory.getLogger(ProfileController.class); @Autowired private UserInfoService userInfoService; - @RequestMapping(value = { "/myProfile" }) - public ModelAndView forwardBasic() { - ModelAndView modelAndView = new ModelAndView("profile/myProfile"); - UserInfo userInfo = userInfoService.findByUsername(WebContext.getUserInfo().getUsername()); - userInfo.transPictureBase64(); - - // HashMapextraAttributeMap=new HashMap(); - // extraAttributeMap=(HashMap)JsonUtils.json2Object(userInfo.getExtraAttribute(),extraAttributeMap); - // modelAndView.addObject("extraAttributeMap", extraAttributeMap); - // _logger.info("extraAttributeMap : "+extraAttributeMap); - // - modelAndView.addObject("model", userInfo); - return modelAndView; + @RequestMapping(value = { "/get" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public ResponseEntity get(@CurrentUser UserInfo currentUser) { + UserInfo userInfo = userInfoService.findByUsername(currentUser.getUsername()); + userInfo.trans(); + return new Message(userInfo).buildResponse(); } /** @@ -65,9 +54,11 @@ public class ProfileController { * @param result * @return */ - @RequestMapping(value = "/update/myProfile") - public ModelAndView updatebasic( - @Valid @ModelAttribute("userInfo") UserInfo userInfo, + @ResponseBody + @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public ResponseEntity update( + @RequestBody UserInfo userInfo, + @CurrentUser UserInfo currentUser, BindingResult result) { _logger.debug(userInfo.toString()); @@ -83,17 +74,11 @@ public class ProfileController { // } if (userInfoService.updateProfile(userInfo) > 0) { - new Message( - WebContext.getI18nValue(ConstsOperateMessage.UPDATE_SUCCESS), - userInfo, MessageType.success, - OperateType.add, MessageScope.DB); - - } else { - new Message(WebContext.getI18nValue(ConstsOperateMessage.UPDATE_ERROR), MessageType.error); - } - - return WebContext.redirect("/profile/myProfile"); - + return new Message(Message.SUCCESS).buildResponse(); + } + + return new Message(Message.FAIL).buildResponse(); + } } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/SafeController.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/SafeController.java index f436e36e1..93696e276 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/SafeController.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/SafeController.java @@ -20,14 +20,11 @@ package org.maxkey.web.contorller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.maxkey.authn.annotation.CurrentUser; import org.maxkey.constants.ConstsOperateMessage; -import org.maxkey.constants.ConstsPasswordSetType; import org.maxkey.constants.ConstsTimeInterval; -import org.maxkey.crypto.password.PasswordReciprocal; import org.maxkey.entity.UserInfo; -import org.maxkey.persistence.repository.PasswordPolicyValidator; import org.maxkey.persistence.service.UserInfoService; -import org.maxkey.util.StringUtils; import org.maxkey.web.WebConstants; import org.maxkey.web.WebContext; import org.maxkey.web.message.Message; @@ -49,109 +46,13 @@ public class SafeController { @Autowired private UserInfoService userInfoService; - @ResponseBody - @RequestMapping(value="/forward/changePasswod") - public ModelAndView fowardChangePasswod() { - ModelAndView modelAndView=new ModelAndView("safe/changePassword"); - modelAndView.addObject("model", WebContext.getUserInfo()); - return modelAndView; - } - - @ResponseBody - @RequestMapping(value="/changePassword") - public Message changePasswod( - @RequestParam(value ="oldPassword",required = true) String oldPassword, - @RequestParam("newPassword") String newPassword, - @RequestParam("confirmPassword") String confirmPassword) { - - if(userInfoService.changePassword(oldPassword,newPassword,confirmPassword,ConstsPasswordSetType.PASSWORD_NORMAL)) { - return new Message(WebContext.getI18nValue(ConstsOperateMessage.UPDATE_SUCCESS),MessageType.success); - }else { - return new Message( - WebContext.getI18nValue(ConstsOperateMessage.UPDATE_ERROR)+"
" - +WebContext.getAttribute(PasswordPolicyValidator.PASSWORD_POLICY_VALIDATE_RESULT), - MessageType.error); - } - } - @RequestMapping(value="/changeExpiredPassword") - public ModelAndView changeExpiredPassword( - @RequestParam(value ="oldPassword" ,required = false) String oldPassword, - @RequestParam(value ="newPassword",required = false) String newPassword, - @RequestParam(value ="confirmPassword",required = false) String confirmPassword) { - ModelAndView modelAndView=new ModelAndView("passwordExpired"); - if(newPassword ==null ||newPassword.equals("")) { - - }else if(userInfoService.changePassword(oldPassword,newPassword,confirmPassword,ConstsPasswordSetType.PASSWORD_NORMAL)){ - WebContext.getSession().setAttribute(WebConstants.CURRENT_USER_PASSWORD_SET_TYPE,ConstsPasswordSetType.PASSWORD_NORMAL); - return WebContext.redirect("/index"); - } - - Object errorMessage=WebContext.getAttribute(PasswordPolicyValidator.PASSWORD_POLICY_VALIDATE_RESULT); - UserInfo userInfo=WebContext.getUserInfo(); - modelAndView.addObject("model", userInfo); - modelAndView.addObject("errorMessage", errorMessage==null?"":errorMessage); - return modelAndView; - } - - - @RequestMapping(value="/changeInitPassword") - public ModelAndView changeInitPassword( - @RequestParam(value ="oldPassword",required = false) String oldPassword, - @RequestParam(value ="newPassword",required = false) String newPassword, - @RequestParam(value ="confirmPassword",required = false) String confirmPassword) { - ModelAndView modelAndView=new ModelAndView("passwordInitial"); - if(newPassword ==null ||newPassword.equals("")) { - - }else if(userInfoService.changePassword(oldPassword,newPassword,confirmPassword,ConstsPasswordSetType.PASSWORD_NORMAL)){ - WebContext.getSession().setAttribute(WebConstants.CURRENT_USER_PASSWORD_SET_TYPE,ConstsPasswordSetType.PASSWORD_NORMAL); - return WebContext.redirect("/index"); - } - - Object errorMessage=WebContext.getAttribute(PasswordPolicyValidator.PASSWORD_POLICY_VALIDATE_RESULT); - modelAndView.addObject("errorMessage", errorMessage==null?"":errorMessage); - UserInfo userInfo=WebContext.getUserInfo(); - modelAndView.addObject("model", userInfo); - return modelAndView; - } - - - @ResponseBody - @RequestMapping(value="/forward/changeAppLoginPasswod") - public ModelAndView fowardChangeAppLoginPasswod() { - ModelAndView modelAndView=new ModelAndView("safe/changeAppLoginPasswod"); - modelAndView.addObject("model", WebContext.getUserInfo()); - return modelAndView; - } - - @ResponseBody - @RequestMapping(value="/changeAppLoginPasswod") - public Message changeAppLoginPasswod( - @RequestParam("oldPassword") String oldPassword, - @RequestParam("newPassword") String newPassword, - @RequestParam("confirmPassword") String confirmPassword) { - - UserInfo userInfo =WebContext.getUserInfo(); - _logger.debug("App Login Password : "+userInfo.getAppLoginPassword()); - _logger.debug("App Login new Password : "+PasswordReciprocal.getInstance().encode(newPassword)); - if(newPassword.equals(confirmPassword)){ - if(StringUtils.isEmpty(userInfo.getAppLoginPassword())||userInfo.getAppLoginPassword().equals(PasswordReciprocal.getInstance().encode(oldPassword))){ - userInfo.setAppLoginPassword(PasswordReciprocal.getInstance().encode(newPassword)); - boolean change= userInfoService.updateAppLoginPassword(userInfo); - _logger.debug(""+change); - return new Message(WebContext.getI18nValue(ConstsOperateMessage.UPDATE_SUCCESS),MessageType.prompt); - } - } - - return new Message(WebContext.getI18nValue(ConstsOperateMessage.UPDATE_ERROR),MessageType.error); - - } @RequestMapping(value="/forward/setting") - public ModelAndView fowardSetting() { + public ModelAndView fowardSetting(@CurrentUser UserInfo currentUser) { ModelAndView modelAndView=new ModelAndView("safe/setting"); - modelAndView.addObject("model", WebContext.getUserInfo()); + modelAndView.addObject("model", currentUser); return modelAndView; } @@ -165,24 +66,25 @@ public class SafeController { @RequestParam("mobileVerify") String mobileVerify, @RequestParam("email") String email, @RequestParam("emailVerify") String emailVerify, - @RequestParam("theme") String theme) { - UserInfo userInfo =WebContext.getUserInfo(); - userInfo.setAuthnType(Integer.parseInt(authnType)); - userInfoService.updateAuthnType(userInfo); + @RequestParam("theme") String theme, + @CurrentUser UserInfo currentUser) { + currentUser.setAuthnType(Integer.parseInt(authnType)); + userInfoService.updateAuthnType(currentUser); - userInfo.setMobile(mobile); - userInfoService.updateMobile(userInfo); + currentUser.setMobile(mobile); + userInfoService.updateMobile(currentUser); - userInfo.setEmail(email); + currentUser.setEmail(email); - userInfo.setTheme(theme); + currentUser.setTheme(theme); WebContext.setCookie(response,null, WebConstants.THEME_COOKIE_NAME, theme, ConstsTimeInterval.ONE_WEEK); - userInfoService.updateEmail(userInfo); + userInfoService.updateEmail(currentUser); return new Message(WebContext.getI18nValue(ConstsOperateMessage.UPDATE_SUCCESS),MessageType.success); } + } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/endpoint/LoginEntryPoint.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/endpoint/LoginEntryPoint.java index 5575c4516..6593a0f1e 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/endpoint/LoginEntryPoint.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/endpoint/LoginEntryPoint.java @@ -30,6 +30,7 @@ import org.maxkey.authn.jwt.AuthJwt; import org.maxkey.authn.jwt.AuthJwtService; import org.maxkey.authn.support.kerberos.KerberosService; import org.maxkey.authn.support.socialsignon.service.SocialSignOnProviderService; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.configuration.ApplicationConfig; import org.maxkey.entity.Institutions; import org.maxkey.entity.Message; @@ -110,7 +111,7 @@ public class LoginEntryPoint { public ModelAndView login(HttpServletRequest request) { _logger.debug("LoginController /login."); - boolean isAuthenticated= WebContext.isAuthenticated(); + boolean isAuthenticated= AuthorizationUtils.isAuthenticated(); if(isAuthenticated){ return WebContext.redirect("/forwardindex"); @@ -153,7 +154,7 @@ public class LoginEntryPoint { authenticationProvider.authenticate(loginCredential); - if (WebContext.isAuthenticated()) { + if (AuthorizationUtils.isAuthenticated()) { return WebContext.redirect("/forwardindex"); } else { return WebContext.redirect("/login"); @@ -193,6 +194,9 @@ public class LoginEntryPoint { @RequestMapping(value={"/signin"}, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity signin( @RequestBody LoginCredential loginCredential) { Authentication authentication = authenticationProvider.authenticate(loginCredential); + if(authentication == null) { + return new Message(Message.FAIL).buildResponse(); + } String jwt = authJwtService.generateToken(authentication); return new Message(new AuthJwt(jwt, authentication)).buildResponse(); } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/endpoint/LogoutEndpoint.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/endpoint/LogoutEndpoint.java index 20c0bc9f5..172dbb7ae 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/endpoint/LogoutEndpoint.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/endpoint/LogoutEndpoint.java @@ -24,10 +24,10 @@ import java.util.Map.Entry; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.maxkey.authn.SigninPrincipal; import org.maxkey.authn.online.OnlineTicket; import org.maxkey.authn.online.OnlineTicketService; import org.maxkey.authn.realm.AbstractAuthenticationRealm; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.authz.singlelogout.SamlSingleLogout; import org.maxkey.authz.singlelogout.DefaultSingleLogout; import org.maxkey.authz.singlelogout.LogoutType; @@ -117,8 +117,8 @@ public class LogoutEndpoint { modelAndView.addObject("reloginUrl",reLoginUrl); //if logined in have onlineTicket ,need remove or logout back - if(WebContext.getAuthentication() != null) { - String onlineTicketId = ((SigninPrincipal)WebContext.getAuthentication().getPrincipal()).getOnlineTicket().getTicketId(); + if(AuthorizationUtils.getAuthentication() != null) { + String onlineTicketId = (AuthorizationUtils.getPrincipal()).getOnlineTicket().getTicketId(); OnlineTicket onlineTicket = onlineTicketService.get(onlineTicketId); if(onlineTicket != null) { Set> entrySet = onlineTicket.getAuthorizedApps().entrySet(); diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/filter/SingleSignOnFilter.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/filter/SingleSignOnFilter.java deleted file mode 100644 index 7144a7776..000000000 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/filter/SingleSignOnFilter.java +++ /dev/null @@ -1,69 +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.web.filter; - -import java.io.IOException; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import org.maxkey.util.StringUtils; -import org.maxkey.web.WebConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * SingleSignOnFilter. - * @author Crystal.Sea - */ - -public class SingleSignOnFilter implements Filter { - private static final Logger _logger = LoggerFactory.getLogger(SingleSignOnFilter.class); - - /** - *doFilter. - */ - public void doFilter(ServletRequest request, - ServletResponse response, FilterChain chain)throws IOException, ServletException { - - HttpServletRequest httpServletRequest = (HttpServletRequest) request; - HttpSession session = httpServletRequest.getSession(); - // 浠巗ession涓幏鍙栧瓨鏀剧殑appid - String appId = (String) session.getAttribute(WebConstants.SINGLE_SIGN_ON_APP_ID); - // 鑾峰彇鏈�鍚庝竴涓�"/"鐨勬暟鎹綔涓篴ppid锛屼繚瀛樺湪session涓� - if (StringUtils.isEmpty(appId)) { - String uir = httpServletRequest.getRequestURI(); - session.setAttribute(WebConstants.SINGLE_SIGN_ON_APP_ID, - uir.substring(uir.lastIndexOf("/") + 1)); - session.setAttribute("protocol", "formbase"); - } - chain.doFilter(request, response); - } - - public void destroy() { - _logger.debug(" destroy."); - } - - public void init(FilterConfig config) throws ServletException { - _logger.debug(" init."); - } -} diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/HistoryLogsAdapter.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/HistoryLogsInterceptor.java similarity index 82% rename from maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/HistoryLogsAdapter.java rename to maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/HistoryLogsInterceptor.java index 1082a697b..a54573ec4 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/HistoryLogsAdapter.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/HistoryLogsInterceptor.java @@ -19,6 +19,8 @@ package org.maxkey.web.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.entity.HistorySystemLogs; import org.maxkey.entity.UserInfo; import org.maxkey.persistence.service.HistorySystemLogsService; @@ -40,9 +42,9 @@ import org.springframework.web.servlet.ModelAndView; * */ @Component -public class HistoryLogsAdapter implements AsyncHandlerInterceptor { +public class HistoryLogsInterceptor implements AsyncHandlerInterceptor { - private static final Logger _logger = LoggerFactory.getLogger(HistoryLogsAdapter.class); + private static final Logger _logger = LoggerFactory.getLogger(HistoryLogsInterceptor.class); @Autowired private HistorySystemLogsService historySystemLogsService; @@ -60,13 +62,13 @@ public class HistoryLogsAdapter implements AsyncHandlerInterceptor { //判断message类型 if (message.getMessageScope() == MessageScope.DB || message.getMessageScope() == MessageScope.DB_CLIENT) { - UserInfo userInfo = WebContext.getUserInfo();//取得当前用户信息 + UserInfo userInfo = AuthorizationUtils.getUserInfo();//取得当前用户信息 //创建日志记录 - HistorySystemLogs historyLogs = new HistorySystemLogs(); - historyLogs.setInstId(userInfo.getInstId()); - _logger.debug("insert db historyLogs content : " + historyLogs); - historySystemLogsService.insert(historyLogs);//日志插入数据库 + HistorySystemLogs historySystemLogs = new HistorySystemLogs(); + historySystemLogs.setInstId(userInfo.getInstId()); + _logger.debug("insert db historyLogs content : " + historySystemLogs); + historySystemLogsService.insert(historySystemLogs);//日志插入数据库 //message类型仅插入数据库 if (message.getMessageScope() == MessageScope.DB) { WebContext.clearMessage();//清除message diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/HistoryLoginAppAdapter.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/HistorySignOnAppInterceptor.java similarity index 68% rename from maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/HistoryLoginAppAdapter.java rename to maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/HistorySignOnAppInterceptor.java index bd1b6e858..93ff9c44d 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/HistoryLoginAppAdapter.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/HistorySignOnAppInterceptor.java @@ -21,6 +21,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.maxkey.authn.SigninPrincipal; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.entity.HistoryLoginApps; import org.maxkey.entity.UserInfo; import org.maxkey.entity.apps.Apps; @@ -39,8 +40,8 @@ import org.springframework.web.servlet.AsyncHandlerInterceptor; import org.springframework.web.servlet.ModelAndView; @Component -public class HistoryLoginAppAdapter implements AsyncHandlerInterceptor { - private static final Logger _logger = LoggerFactory.getLogger(HistoryLoginAppAdapter.class); +public class HistorySignOnAppInterceptor implements AsyncHandlerInterceptor { + private static final Logger _logger = LoggerFactory.getLogger(HistorySignOnAppInterceptor.class); @Autowired HistoryLoginAppsService historyLoginAppsService; @@ -58,7 +59,7 @@ public class HistoryLoginAppAdapter implements AsyncHandlerInterceptor { throws Exception { _logger.debug("preHandle"); final Apps app = (Apps)WebContext.getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP); - Authentication authentication = WebContext.getAuthentication(); + Authentication authentication = AuthorizationUtils.getAuthentication(); if(authentication.getPrincipal() instanceof SigninPrincipal) { SigninPrincipal signinPrincipal = (SigninPrincipal)authentication.getPrincipal() ; if(signinPrincipal.getGrantedAuthorityApps().contains(new SimpleGrantedAuthority(app.getId()))) { @@ -83,19 +84,26 @@ public class HistoryLoginAppAdapter implements AsyncHandlerInterceptor { _logger.debug("postHandle"); final Apps app = (Apps)WebContext.getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP); - String sessionId = "";//(String)WebContext.getAttribute(WebConstants.CURRENT_USER_SESSION_ID); - final UserInfo userInfo = WebContext.getUserInfo(); - _logger.debug("sessionId : " + sessionId + " ,appId : " + app.getId()); - HistoryLoginApps historyLoginApps = new HistoryLoginApps(); - historyLoginApps.setAppId(app.getId()); - historyLoginApps.setSessionId(sessionId); - historyLoginApps.setAppName(app.getName()); - historyLoginApps.setUserId(userInfo.getId()); - historyLoginApps.setUsername(userInfo.getUsername()); - historyLoginApps.setDisplayName(userInfo.getDisplayName()); - historyLoginApps.setInstId(userInfo.getInstId()); - historyLoginAppsService.insert(historyLoginApps); - WebContext.removeAttribute(WebConstants.CURRENT_SINGLESIGNON_URI); - WebContext.removeAttribute(WebConstants.SINGLE_SIGN_ON_APP_ID); + + Authentication authentication = AuthorizationUtils.getAuthentication(); + if((authentication != null) + && (authentication.getPrincipal() instanceof SigninPrincipal)) { + SigninPrincipal signinPrincipal = AuthorizationUtils.getPrincipal(); + final UserInfo userInfo = signinPrincipal.getUserInfo(); + String sessionId = signinPrincipal.getOnlineTicket().getTicketId().substring(3); + _logger.debug("sessionId : " + sessionId + " ,appId : " + app.getId()); + HistoryLoginApps historyLoginApps = new HistoryLoginApps(); + historyLoginApps.setAppId(app.getId()); + historyLoginApps.setSessionId(sessionId); + historyLoginApps.setAppName(app.getName()); + historyLoginApps.setUserId(userInfo.getId()); + historyLoginApps.setUsername(userInfo.getUsername()); + historyLoginApps.setDisplayName(userInfo.getDisplayName()); + historyLoginApps.setInstId(userInfo.getInstId()); + historyLoginAppsService.insert(historyLoginApps); + WebContext.removeAttribute(WebConstants.CURRENT_SINGLESIGNON_URI); + WebContext.removeAttribute(WebConstants.SINGLE_SIGN_ON_APP_ID); + } + } } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/PreLoginAppAdapter.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/PreLoginAppAdapter.java deleted file mode 100644 index e2368ef96..000000000 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/PreLoginAppAdapter.java +++ /dev/null @@ -1,70 +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.web.interceptor; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.maxkey.web.WebConstants; -import org.maxkey.web.WebContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; -import org.springframework.web.servlet.AsyncHandlerInterceptor; - -@Component -public class PreLoginAppAdapter implements AsyncHandlerInterceptor { - - private static final Logger _logger = LoggerFactory.getLogger(PreLoginAppAdapter.class); - - @Override - public boolean preHandle(HttpServletRequest request, - HttpServletResponse response, Object handler) - throws Exception { - _logger.debug("preHandle"); - String redirect_uri = request.getRequestURL().toString(); - String appId = getAppIdFromRequestUrl(request); - _logger.debug("preHandle app Id " + appId); - Object singlesignon_uri = WebContext.getAttribute(WebConstants.CURRENT_SINGLESIGNON_URI); - if (singlesignon_uri != null && singlesignon_uri.equals(redirect_uri)) { - return true; - } - /* - * UserInfo userInfo = WebContext.getUserInfo(); - * if(userInfo.getProtectedAppsMap().get(appId)!=null){ - * - * request.setAttribute("redirect_uri",redirect_uri); - * _logger.debug(""+redirect_uri); RequestDispatcher dispatcher = - * request.getRequestDispatcher("/authorize/protected/forward"); - * dispatcher.forward(request, response); return false; } - */ - - return true; - } - - /** - * Request URL . - * @param request http - * @return . - */ - public static String getAppIdFromRequestUrl(HttpServletRequest request) { - String[] uri = request.getRequestURI().split("/"); - String appId = uri[uri.length - 1]; - return appId; - } -} diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/SingleSignOnInterceptor.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/SingleSignOnInterceptor.java new file mode 100644 index 000000000..22136650a --- /dev/null +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/SingleSignOnInterceptor.java @@ -0,0 +1,70 @@ +/* + * Copyright [2022] [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.web.interceptor; +import javax.servlet.RequestDispatcher; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.maxkey.authn.jwt.AuthJwtService; +import org.maxkey.authn.online.OnlineTicketService; +import org.maxkey.authn.web.AuthorizationUtils; +import org.maxkey.crypto.Base64Utils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.web.util.UrlUtils; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.AsyncHandlerInterceptor; + +@Component +public class SingleSignOnInterceptor implements AsyncHandlerInterceptor { + private static final Logger _logger = LoggerFactory.getLogger(SingleSignOnInterceptor.class); + + + + @Autowired + OnlineTicketService onlineTicketService; + + @Autowired + AuthJwtService authJwtService ; + + @Override + public boolean preHandle(HttpServletRequest request, + HttpServletResponse response, Object handler) + throws Exception { + _logger.debug("Single Sign On Interceptor automatic Auth"); + + AuthorizationUtils.authenticateWithCookie( + request,authJwtService,onlineTicketService); + + if(AuthorizationUtils.isAuthenticated()){ + //http://sso.maxkey.top/sign/ + String loginUrl = "http://sso.maxkey.top:4200/#/passport/login"; + String savedRequestUrl = UrlUtils.buildFullRequestUrl(request); + String base64RequestUrl = Base64Utils.base64UrlEncode(savedRequestUrl.getBytes()); + + _logger.trace("No Authentication ... forward to /auth/entrypoint"); + RequestDispatcher dispatcher = request.getRequestDispatcher(loginUrl + "?redirect_uri=" + base64RequestUrl); + dispatcher.forward(request, response); + return false; + } + + return true; + } + +} diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/MaxKeyMgtConfig.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/MaxKeyMgtConfig.java index df3deaa56..92c4da7a2 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/MaxKeyMgtConfig.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/MaxKeyMgtConfig.java @@ -24,7 +24,6 @@ import org.maxkey.persistence.repository.LoginRepository; import org.maxkey.persistence.repository.PasswordPolicyValidator; import org.maxkey.persistence.service.UserInfoService; import org.maxkey.authn.realm.jdbc.JdbcAuthenticationRealm; -import org.maxkey.authn.support.rememberme.AbstractRemeberMeService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; @@ -44,7 +43,6 @@ public class MaxKeyMgtConfig implements InitializingBean { PasswordPolicyValidator passwordPolicyValidator, LoginRepository loginRepository, LoginHistoryRepository loginHistoryRepository, - AbstractRemeberMeService remeberMeService, UserInfoService userInfoService, JdbcTemplate jdbcTemplate) { @@ -53,7 +51,6 @@ public class MaxKeyMgtConfig implements InitializingBean { passwordPolicyValidator, loginRepository, loginHistoryRepository, - remeberMeService, userInfoService, jdbcTemplate); diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/MaxKeyMgtMvcConfig.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/MaxKeyMgtMvcConfig.java index 569cc9d79..4e95429f9 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/MaxKeyMgtMvcConfig.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/MaxKeyMgtMvcConfig.java @@ -22,17 +22,14 @@ import java.util.List; import org.maxkey.authn.AbstractAuthenticationProvider; import org.maxkey.authn.support.jwt.HttpJwtEntryPoint; import org.maxkey.authn.support.jwt.JwtLoginService; -import org.maxkey.authn.support.rememberme.AbstractRemeberMeService; -import org.maxkey.authn.support.rememberme.HttpRemeberMeEntryPoint; import org.maxkey.authn.web.CurrentUserMethodArgumentResolver; -import org.maxkey.authn.web.interceptor.PermissionAdapter; +import org.maxkey.authn.web.interceptor.PermissionInterceptor; import org.maxkey.configuration.ApplicationConfig; import org.maxkey.web.interceptor.HistoryLogsAdapter; import org.maxkey.web.interceptor.RestApiPermissionAdapter; 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.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @@ -48,23 +45,16 @@ public class MaxKeyMgtMvcConfig implements WebMvcConfigurer { private static final Logger _logger = LoggerFactory.getLogger(MaxKeyMgtMvcConfig.class); @Autowired - @Qualifier("applicationConfig") ApplicationConfig applicationConfig; @Autowired - @Qualifier("authenticationProvider") AbstractAuthenticationProvider authenticationProvider ; @Autowired - @Qualifier("remeberMeService") - AbstractRemeberMeService remeberMeService; - - @Autowired - @Qualifier("jwtLoginService") JwtLoginService jwtLoginService; @Autowired - PermissionAdapter permissionAdapter; + PermissionInterceptor permissionInterceptor; @Autowired HistoryLogsAdapter historyLogsAdapter; @@ -103,18 +93,12 @@ public class MaxKeyMgtMvcConfig implements WebMvcConfigurer { public void addInterceptors(InterceptorRegistry registry) { //addPathPatterns 用于添加拦截规则 , 先把所有路径都加入拦截, 再一个个排除 //excludePathPatterns 表示改路径不用拦截 - - _logger.debug("add HttpRemeberMeEntryPoint"); - registry.addInterceptor(new HttpRemeberMeEntryPoint( - authenticationProvider,remeberMeService,applicationConfig,true)) - .addPathPatterns("/login"); - _logger.debug("add HttpJwtEntryPoint"); registry.addInterceptor(new HttpJwtEntryPoint( authenticationProvider,jwtLoginService,applicationConfig,true)) .addPathPatterns("/login"); - registry.addInterceptor(permissionAdapter) + registry.addInterceptor(permissionInterceptor) .addPathPatterns("/dashboard/**") .addPathPatterns("/orgs/**") .addPathPatterns("/users/**") diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/config/contorller/LocalizationController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/config/contorller/LocalizationController.java index b6eaf853f..adb998a35 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/config/contorller/LocalizationController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/config/contorller/LocalizationController.java @@ -18,8 +18,10 @@ package org.maxkey.web.config.contorller; import org.apache.commons.lang3.StringUtils; +import org.maxkey.authn.annotation.CurrentUser; import org.maxkey.constants.ConstsOperateMessage; import org.maxkey.entity.Localization; +import org.maxkey.entity.UserInfo; import org.maxkey.persistence.repository.LocalizationRepository; import org.maxkey.web.WebContext; import org.maxkey.web.message.Message; @@ -50,11 +52,11 @@ public class LocalizationController { * @return */ @RequestMapping(value={"/forward/{property}"}) - public ModelAndView forward(@PathVariable("property") String property){ - Localization localization = localizationRepository.get(property,WebContext.getUserInfo().getInstId()); + public ModelAndView forward(@PathVariable("property") String property,@CurrentUser UserInfo currentUser){ + Localization localization = localizationRepository.get(property,currentUser.getInstId()); if(localization == null )localization = new Localization(); localization.setProperty(property); - localization.setInstId(WebContext.getUserInfo().getInstId()); + localization.setInstId(currentUser.getInstId()); return new ModelAndView("localization/updateLocalization","model",localization); } @@ -65,9 +67,9 @@ public class LocalizationController { */ @RequestMapping(value={"/update"}) @ResponseBody - public Message updat(@ModelAttribute("localization") Localization localization,BindingResult result) { + public Message updat(@ModelAttribute("localization") Localization localization,@CurrentUser UserInfo currentUser,BindingResult result) { _logger.debug("update localization : "+localization); - localization.setInstId(WebContext.getUserInfo().getInstId()); + localization.setInstId(currentUser.getInstId()); if(StringUtils.isBlank(localization.getId())){ localization.setId(localization.generateId()); if(localizationRepository.insert(localization)) { diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/LoginEntryPoint.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/LoginEntryPoint.java index 62af9d11b..f06b646de 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/LoginEntryPoint.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/LoginEntryPoint.java @@ -68,7 +68,7 @@ public class LoginEntryPoint { public ModelAndView login() { _logger.debug("LoginController /login."); - boolean isAuthenticated= WebContext.isAuthenticated(); + boolean isAuthenticated= false;//WebContext.isAuthenticated(); //for normal login if(isAuthenticated){ return WebContext.redirect("/main"); diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/OrganizationsController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/OrganizationsController.java index 3a184659b..0af59f7ae 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/OrganizationsController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/OrganizationsController.java @@ -35,7 +35,6 @@ import org.maxkey.entity.Organizations; import org.maxkey.entity.UserInfo; import org.maxkey.persistence.service.OrganizationsService; import org.maxkey.util.ExcelUtils; -import org.maxkey.web.WebContext; import org.maxkey.web.component.TreeAttributes; import org.maxkey.web.component.TreeNode; import org.slf4j.Logger; @@ -161,7 +160,9 @@ public class OrganizationsController { } @RequestMapping(value = "/import") - public ResponseEntity importingOrganizations(@ModelAttribute("excelImportFile")ExcelImport excelImportFile) { + public ResponseEntity importingOrganizations( + @ModelAttribute("excelImportFile")ExcelImport excelImportFile, + @CurrentUser UserInfo currentUser) { if (excelImportFile.isExcelNotEmpty() ) { try { List orgsList = Lists.newArrayList(); @@ -176,7 +177,7 @@ public class OrganizationsController { if (row == null || j <3 ) {//略过空行和前3行 continue; } else {//其他行是数据行 - orgsList.add(buildOrganizationsFromSheetRow(row)); + orgsList.add(buildOrganizationsFromSheetRow(row,currentUser)); } } } @@ -200,7 +201,7 @@ public class OrganizationsController { } - public Organizations buildOrganizationsFromSheetRow(Row row) { + public Organizations buildOrganizationsFromSheetRow(Row row,UserInfo currentUser) { Organizations organization = new Organizations(); // 上级编码 organization.setParentId(ExcelUtils.getValue(row, 0)); @@ -248,7 +249,7 @@ public class OrganizationsController { organization.setDescription(ExcelUtils.getValue(row, 20)); organization.setStatus(1); - organization.setInstId(WebContext.getUserInfo().getInstId()); + organization.setInstId(currentUser.getInstId()); return organization; } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/UserAdjointController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/UserAdjointController.java index b645d2a0b..870816650 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/UserAdjointController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/UserAdjointController.java @@ -18,7 +18,9 @@ package org.maxkey.web.contorller; import org.apache.mybatis.jpa.persistence.JpaPageResults; +import org.maxkey.authn.annotation.CurrentUser; import org.maxkey.constants.ConstsOperateMessage; +import org.maxkey.entity.UserInfo; import org.maxkey.entity.UserInfoAdjoint; import org.maxkey.persistence.service.UserInfoAdjointService; import org.maxkey.web.WebContext; @@ -56,9 +58,11 @@ public class UserAdjointController { @RequestMapping(value = { "/grid" }) @ResponseBody - public JpaPageResults queryDataGrid(@ModelAttribute("userInfoAdjoint") UserInfoAdjoint userInfoAdjoint) { + public JpaPageResults queryDataGrid( + @ModelAttribute("userInfoAdjoint") UserInfoAdjoint userInfoAdjoint, + @CurrentUser UserInfo currentUser){ _logger.debug(""+userInfoAdjoint); - userInfoAdjoint.setInstId(WebContext.getUserInfo().getInstId()); + userInfoAdjoint.setInstId(currentUser.getInstId()); return userInfoAdjointService.queryPageResults(userInfoAdjoint); } @@ -80,9 +84,11 @@ public class UserAdjointController { @ResponseBody @RequestMapping(value={"/add"}) - public Message insert(@ModelAttribute("userInfoAdjoint") UserInfoAdjoint userInfoAdjoint) { + public Message insert( + @ModelAttribute("userInfoAdjoint") UserInfoAdjoint userInfoAdjoint, + @CurrentUser UserInfo currentUser) { _logger.debug("-Add :" + userInfoAdjoint); - userInfoAdjoint.setInstId(WebContext.getUserInfo().getInstId()); + userInfoAdjoint.setInstId(currentUser.getInstId()); if (userInfoAdjointService.insert(userInfoAdjoint)) { return new Message(WebContext.getI18nValue(ConstsOperateMessage.INSERT_SUCCESS),MessageType.success); @@ -99,9 +105,11 @@ public class UserAdjointController { */ @ResponseBody @RequestMapping(value={"/query"}) - public Message query(@ModelAttribute("userInfoAdjoint") UserInfoAdjoint userInfoAdjoint) { + public Message query( + @ModelAttribute("userInfoAdjoint") UserInfoAdjoint userInfoAdjoint, + @CurrentUser UserInfo currentUser) { _logger.debug("-query :" + userInfoAdjoint); - userInfoAdjoint.setInstId(WebContext.getUserInfo().getInstId()); + userInfoAdjoint.setInstId(currentUser.getInstId()); if (userInfoAdjointService.load(userInfoAdjoint)!=null) { return new Message(WebContext.getI18nValue(ConstsOperateMessage.INSERT_SUCCESS),MessageType.success); @@ -118,9 +126,11 @@ public class UserAdjointController { */ @ResponseBody @RequestMapping(value={"/update"}) - public Message update(@ModelAttribute("userInfoAdjoint") UserInfoAdjoint userInfoAdjoint) { + public Message update( + @ModelAttribute("userInfoAdjoint") UserInfoAdjoint userInfoAdjoint, + @CurrentUser UserInfo currentUser) { _logger.debug("-update userInfoAdjoint :" + userInfoAdjoint); - userInfoAdjoint.setInstId(WebContext.getUserInfo().getInstId()); + userInfoAdjoint.setInstId(currentUser.getInstId()); if (userInfoAdjointService.update(userInfoAdjoint)) { return new Message(WebContext.getI18nValue(ConstsOperateMessage.UPDATE_SUCCESS),MessageType.success); diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/UserInfoController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/UserInfoController.java index bf3084635..c55d78518 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/UserInfoController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/UserInfoController.java @@ -1,5 +1,5 @@ /* - * Copyright [2020] [MaxKey of copyright http://www.maxkey.top] + * Copyright [2022] [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. @@ -35,6 +35,7 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.maxkey.authn.annotation.CurrentUser; import org.maxkey.constants.ConstsPasswordSetType; +import org.maxkey.entity.ChangePassword; import org.maxkey.entity.ExcelImport; import org.maxkey.entity.Message; import org.maxkey.entity.UserInfo; @@ -102,11 +103,7 @@ public class UserInfoController { @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity get(@PathVariable("id") String id) { UserInfo userInfo=userInfoService.get(id); - if(userInfo.getPicture()!=null){ - userInfo.transPictureBase64(); - } - userInfo.setPassword(""); - userInfo.setDecipherable(""); + userInfo.trans(); return new Message(userInfo).buildResponse(); } @@ -187,10 +184,12 @@ public class UserInfoController { @ResponseBody @RequestMapping(value="/changePassword", produces = {MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity changePassword( @ModelAttribute("userInfo")UserInfo userInfo) { - _logger.debug(userInfo.getId()); - userInfo.setPasswordSetType(ConstsPasswordSetType.PASSWORD_NORMAL); - if(userInfoService.changePassword(userInfo,true)) { + public ResponseEntity changePassword( + @ModelAttribute ChangePassword changePassword, + @CurrentUser UserInfo currentUser) { + _logger.debug("UserId {}",changePassword.getUserId()); + changePassword.setPasswordSetType(ConstsPasswordSetType.PASSWORD_NORMAL); + if(userInfoService.changePassword(changePassword,true)) { return new Message(Message.SUCCESS).buildResponse(); } else { @@ -199,7 +198,9 @@ public class UserInfoController { } @RequestMapping(value = "/import") - public ResponseEntity importingUsers(@ModelAttribute("excelImportFile")ExcelImport excelImportFile) { + public ResponseEntity importingUsers( + @ModelAttribute("excelImportFile")ExcelImport excelImportFile, + @CurrentUser UserInfo currentUser) { if (excelImportFile.isExcelNotEmpty() ) { try { List userInfoList = Lists.newArrayList(); @@ -214,7 +215,7 @@ public class UserInfoController { if (row == null || j <3 ) {//略过空行和前3行 continue; } else {//其他行是数据行 - UserInfo userInfo = buildUserFromSheetRow(row); + UserInfo userInfo = buildUserFromSheetRow(row,currentUser); userInfoList.add(userInfo); recordCount ++; _logger.debug("record {} user {} account {}",recordCount,userInfo.getDisplayName(),userInfo.getUsername()); @@ -258,7 +259,7 @@ public class UserInfoController { } - public UserInfo buildUserFromSheetRow(Row row) { + public UserInfo buildUserFromSheetRow(Row row,UserInfo currentUser) { UserInfo userInfo = new UserInfo(); userInfo.setCreatedDate(DateUtils.formatDateTime(new Date())); // 登录账号 @@ -358,7 +359,7 @@ public class UserInfoController { userInfo.setHomeEmail(ExcelUtils.getValue(row, 46)); userInfoService.passwordEncoder(userInfo); userInfo.setStatus(1); - userInfo.setInstId(WebContext.getUserInfo().getInstId()); + userInfo.setInstId(currentUser.getInstId()); return userInfo; } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/interceptor/HistoryLogsAdapter.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/interceptor/HistoryLogsAdapter.java index 399b93a7b..3fa242123 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/interceptor/HistoryLogsAdapter.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/interceptor/HistoryLogsAdapter.java @@ -19,6 +19,8 @@ package org.maxkey.web.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.entity.HistorySystemLogs; import org.maxkey.entity.UserInfo; import org.maxkey.persistence.service.HistorySystemLogsService; @@ -55,7 +57,7 @@ public class HistoryLogsAdapter implements AsyncHandlerInterceptor { if(message != null){ if(message.getMessageScope() == MessageScope.DB || message.getMessageScope() == MessageScope.DB_CLIENT) {//判断message类型 - UserInfo userInfo =WebContext.getUserInfo();//取得当前用户信息 + UserInfo userInfo = AuthorizationUtils.getUserInfo();//取得当前用户信息 //创建日志记录 HistorySystemLogs historySystemLog = new HistorySystemLogs(); historySystemLog.setTopic(message.getTopic()); diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/interceptor/RestApiPermissionAdapter.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/interceptor/RestApiPermissionAdapter.java index d8c2a266f..760c7936b 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/interceptor/RestApiPermissionAdapter.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/interceptor/RestApiPermissionAdapter.java @@ -22,12 +22,12 @@ import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.maxkey.authn.web.AuthorizationUtils; import org.maxkey.authz.oauth2.provider.OAuth2Authentication; import org.maxkey.authz.oauth2.provider.token.DefaultTokenServices; import org.maxkey.util.AuthorizationHeaderCredential; import org.maxkey.util.AuthorizationHeaderUtils; import org.maxkey.util.StringUtils; -import org.maxkey.web.WebContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -102,7 +102,7 @@ public class RestApiPermissionAdapter implements AsyncHandlerInterceptor { } if(authenticationToken !=null && authenticationToken.isAuthenticated()) { - WebContext.setAuthentication(authenticationToken); + AuthorizationUtils.setAuthentication(authenticationToken); return true; } }