MaxKey 3 лет назад
Родитель
Сommit
50bfb3087e
75 измененных файлов с 765 добавлено и 1637 удалено
  1. 0 7
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/AbstractAuthenticationProvider.java
  2. 2 20
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/RealmAuthenticationProvider.java
  3. 0 10
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/SavedRequestAwareAuthenticationSuccessHandler.java
  4. 22 10
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/jwt/AuthJwt.java
  5. 1 16
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/realm/AbstractAuthenticationRealm.java
  6. 4 10
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/realm/jdbc/JdbcAuthenticationRealm.java
  7. 2 2
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/jwt/HttpJwtEntryPoint.java
  8. 2 2
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/kerberos/HttpKerberosEntryPoint.java
  9. 0 166
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/AbstractRemeberMeService.java
  10. 0 149
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/HttpRemeberMeEntryPoint.java
  11. 0 54
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/InMemoryRemeberMeService.java
  12. 0 91
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/JdbcRemeberMeService.java
  13. 0 71
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/RedisRemeberMeService.java
  14. 0 74
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/RemeberMe.java
  15. 0 48
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/RemeberMeServiceFactory.java
  16. 2 2
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/wsfederation/HttpWsFederationEntryPoint.java
  17. 95 0
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/AuthorizationUtils.java
  18. 1 1
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/CurrentUserMethodArgumentResolver.java
  19. 2 2
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/SessionSecurityContextHolderStrategy.java
  20. 10 10
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/UnauthorizedEntryPoint.java
  21. 0 115
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/interceptor/PermissionAdapter.java
  22. 84 0
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/interceptor/PermissionInterceptor.java
  23. 0 16
      maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/autoconfigure/AuthenticationAutoConfiguration.java
  24. 5 26
      maxkey-authentications/maxkey-authentication-social/src/main/java/org/maxkey/authn/support/socialsignon/SocialSignOnEndpoint.java
  25. 48 17
      maxkey-core/src/main/java/org/maxkey/entity/ChangePassword.java
  26. 6 0
      maxkey-core/src/main/java/org/maxkey/entity/UserInfo.java
  27. 4 3
      maxkey-core/src/main/java/org/maxkey/persistence/repository/PasswordPolicyValidator.java
  28. 5 43
      maxkey-core/src/main/java/org/maxkey/web/WebContext.java
  29. 0 86
      maxkey-core/src/main/java/org/maxkey/web/tag/ThemeTagDirective.java
  30. 2 3
      maxkey-identitys/maxkey-identity-rest/src/main/java/org/maxkey/identity/rest/RestUserInfoController.java
  31. 2 1
      maxkey-persistence/src/main/java/org/maxkey/persistence/mapper/UserInfoMapper.java
  32. 47 68
      maxkey-persistence/src/main/java/org/maxkey/persistence/service/UserInfoService.java
  33. 2 2
      maxkey-persistence/src/main/resources/org/maxkey/persistence/mapper/xml/mysql/UserInfoMapper.xml
  34. 2 3
      maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/maxkey/authz/endpoint/AuthorizeBaseEndpoint.java
  35. 12 8
      maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/maxkey/authz/endpoint/AuthorizeCredentialEndpoint.java
  36. 5 3
      maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/maxkey/authz/endpoint/AuthorizeProtectedEndpoint.java
  37. 3 3
      maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/CasAuthorizeEndpoint.java
  38. 4 4
      maxkey-protocols/maxkey-protocol-cas/src/main/java/org/maxkey/authz/cas/endpoint/CasRestV1Endpoint.java
  39. 10 6
      maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/maxkey/authz/exapi/endpoint/ExtendApiAuthorizeEndpoint.java
  40. 8 6
      maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/maxkey/authz/formbased/endpoint/FormBasedAuthorizeEndpoint.java
  41. 7 4
      maxkey-protocols/maxkey-protocol-jwt/src/main/java/org/maxkey/authz/token/endpoint/JwtAuthorizeEndpoint.java
  42. 2 3
      maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/approval/endpoint/OAuth20AccessConfirmationEndpoint.java
  43. 4 2
      maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/endpoint/AuthorizationEndpoint.java
  44. 2 2
      maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/endpoint/TokenEndpoint.java
  45. 3 2
      maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/endpoint/TokenEndpointAuthenticationFilter.java
  46. 2 2
      maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oidc/idtoken/OIDCIdTokenEnhancer.java
  47. 10 5
      maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/endpoint/AssertionEndpoint.java
  48. 13 5
      maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/AssertionGenerator.java
  49. 12 7
      maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/AttributeStatementGenerator.java
  50. 5 2
      maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/AuthnResponseGenerator.java
  51. 2 2
      maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/maxkey/authz/saml20/provider/xml/SubjectGenerator.java
  52. 7 4
      maxkey-protocols/maxkey-protocol-tokenbased/src/main/java/org/maxkey/authz/token/endpoint/TokenBasedAuthorizeEndpoint.java
  53. 0 3
      maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/MaxKeyConfig.java
  54. 23 59
      maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/MaxKeyMvcConfig.java
  55. 1 1
      maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/AppListController.java
  56. 74 0
      maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/ChangePasswodController.java
  57. 2 1
      maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/ForgotPasswordContorller.java
  58. 23 38
      maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/ProfileController.java
  59. 13 111
      maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/contorller/SafeController.java
  60. 6 2
      maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/endpoint/LoginEntryPoint.java
  61. 3 3
      maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/endpoint/LogoutEndpoint.java
  62. 0 69
      maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/filter/SingleSignOnFilter.java
  63. 9 7
      maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/HistoryLogsInterceptor.java
  64. 25 17
      maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/HistorySignOnAppInterceptor.java
  65. 0 70
      maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/PreLoginAppAdapter.java
  66. 70 0
      maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/SingleSignOnInterceptor.java
  67. 0 3
      maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/MaxKeyMgtConfig.java
  68. 3 19
      maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/MaxKeyMgtMvcConfig.java
  69. 7 5
      maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/config/contorller/LocalizationController.java
  70. 1 1
      maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/LoginEntryPoint.java
  71. 6 5
      maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/OrganizationsController.java
  72. 18 8
      maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/UserAdjointController.java
  73. 15 14
      maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/contorller/UserInfoController.java
  74. 3 1
      maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/interceptor/HistoryLogsAdapter.java
  75. 2 2
      maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/interceptor/RestApiPermissionAdapter.java

+ 0 - 7
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<GrantedAuthority> grantedAdministratorsAuthoritys = new ArrayList<GrantedAuthority>();
@@ -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;
     }

+ 2 - 20
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;
     }

+ 0 - 10
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);
 

+ 22 - 10
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<String> 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<String> 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<String> 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();

+ 1 - 16
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<Groups> 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());
 
             

+ 4 - 10
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);
 	            }
 	        }
         }

+ 2 - 2
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 

+ 2 - 2
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);
 		 

+ 0 - 166
maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/AbstractRemeberMeService.java

@@ -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);
-    }
-}

+ 0 - 149
maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/HttpRemeberMeEntryPoint.java

@@ -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;
-	}
-	 
-	
-}

+ 0 - 54
maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/InMemoryRemeberMeService.java

@@ -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<String, RemeberMe> 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);
-    }
-
-}

+ 0 - 91
maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/JdbcRemeberMeService.java

@@ -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<RemeberMe> listRemeberMe = jdbcTemplate.query(DEFAULT_DEFAULT_SELECT_STATEMENT,
-                new RowMapper<RemeberMe>() {
-                    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);
-    }
-
-}

+ 0 - 71
maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/RedisRemeberMeService.java

@@ -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;
-    }
-
-    
-}

+ 0 - 74
maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/RemeberMe.java

@@ -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
-                + "]";
-    }
-}

+ 0 - 48
maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/support/rememberme/RemeberMeServiceFactory.java

@@ -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;
-	}
-}

+ 2 - 2
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);
 		 

+ 95 - 0
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;
+    }
+	
+}

+ 1 - 1
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) {

+ 2 - 2
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

+ 10 - 10
maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/AuthEntryPoint.java → 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<String, Object> body = new HashMap<>();
- 	    body.put("status", HttpServletResponse.SC_UNAUTHORIZED);
- 	    body.put("error", "Unauthorized");
- 	    body.put("message", "Unauthorized");
- 	    body.put("path", request.getServletPath());
+ 	    final Map<String, Object> 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);
  	}	
 }

+ 0 - 115
maxkey-authentications/maxkey-authentication-core/src/main/java/org/maxkey/authn/web/interceptor/PermissionAdapter.java

@@ -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;
-	}
-}

+ 84 - 0
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;
+	}
+}

+ 0 - 16
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(

+ 5 - 26
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);

+ 48 - 17
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("]");

+ 6 - 0
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() {

+ 4 - 3
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 ");

+ 5 - 43
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<String, Cookie> cookieMap = readCookieAll(request);
+    public static Cookie getCookie(HttpServletRequest request, String name) {
+        Map<String, Cookie> 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<String, Cookie> readCookieAll(HttpServletRequest request) {
+    private static Map<String, Cookie> getCookieAll(HttpServletRequest request) {
         Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
         Cookie[] cookies = request.getCookies();
         if (null != cookies) {

+ 0 - 86
maxkey-core/src/main/java/org/maxkey/web/tag/ThemeTagDirective.java

@@ -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);
-    }
-
-}

+ 2 - 3
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);

+ 2 - 1
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<UserInfo>{
 
 	public void updateBadPWDCount(UserInfo userInfo);
 	
-	public int 	updatePassword(UserInfo userInfo);
+	public int 	changePassword(ChangePassword changePassword);
 	
 	public int 	updateAppLoginPassword(UserInfo userInfo);
 	

+ 47 - 68
maxkey-persistence/src/main/java/org/maxkey/persistence/service/UserInfoService.java

@@ -77,7 +77,7 @@ public class UserInfoService extends JpaBaseService<UserInfo> {
 	}
 	
     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<UserInfo> {
     }
 	
     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<UserInfo> {
                         MqIdentityAction.UPDATE_ACTION);
             }
             
-            changePasswordProvisioning(userInfo);
+            changePasswordProvisioning(changePassword);
             return true;
         }
         return false;
@@ -151,11 +151,11 @@ public class UserInfoService extends JpaBaseService<UserInfo> {
 	    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<UserInfo> {
 	
 	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<UserInfo> {
 		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<UserInfo> {
 	 * @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<UserInfo> {
 	 * @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());
-            }
-
-            changeUserInfo = passwordEncoder(changeUserInfo);
+            changePassword = passwordEncoder(changePassword);
 
-            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<UserInfo> {
 	    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<UserInfo> {
 	
 	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) {

+ 2 - 2
maxkey-persistence/src/main/resources/org/maxkey/persistence/mapper/xml/mysql/UserInfoMapper.xml

@@ -84,7 +84,7 @@
 			id	=	#{id}
     </update>
     	
-	<update id="updatePassword" parameterType="UserInfo" >
+	<update id="changePassword" parameterType="ChangePassword" >
     	update mxk_userinfo set
     	<if test="password != null">
     		password			=	#{password},
@@ -93,7 +93,7 @@
 		</if>
 			passwordlastsettime		=	current_timestamp
 		where 
-			id	=	#{id}
+			id	=	#{userId}
     </update>
     
     <update id="updateSharedSecret" parameterType="UserInfo" >

+ 2 - 3
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());

+ 12 - 8
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)){
 				

+ 5 - 3
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);
 		}

+ 3 - 3
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);

+ 4 - 4
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;

+ 10 - 6
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);
 			

+ 8 - 6
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);
 			

+ 7 - 4
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

+ 2 - 3
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(),

+ 4 - 2
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<String, String> 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<String, ?> model,
 	                SessionStatus sessionStatus) {
 	    
-		Principal principal=(Principal)WebContext.getAuthentication();
+		Principal principal=(Principal)AuthorizationUtils.getAuthentication();
 		if (!(principal instanceof Authentication)) {
 			sessionStatus.setComplete();
 			throw new InsufficientAuthenticationException(

+ 2 - 2
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(

+ 3 - 2
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);
 	

+ 2 - 2
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);
 			}
 			

+ 10 - 5
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 <String,String>attributeMap=new HashMap<String,String>();
 		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());
 

+ 13 - 5
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,
-							HashMap<String,String>attributeMap
+							HashMap<String,String>attributeMap,
+							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<GrantedAuthority> grantedAuthoritys = new ArrayList<GrantedAuthority>();
 		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());

+ 12 - 7
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<GrantedAuthority> grantedAuthoritys) {
-		return generateAttributeStatement(saml20Details, grantedAuthoritys,null);
+	public AttributeStatement generateAttributeStatement(
+			AppsSAML20Details saml20Details,
+			ArrayList<GrantedAuthority> grantedAuthoritys,
+			UserInfo userInfo) {
+		return generateAttributeStatement(
+				saml20Details, grantedAuthoritys,null,userInfo);
 
 	}
 
 	public AttributeStatement generateAttributeStatement(
 					AppsSAML20Details saml20Details,
 					ArrayList<GrantedAuthority> grantedAuthoritys,
-					HashMap<String,String>attributeMap) {
+					HashMap<String,String>attributeMap,
+					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<Entry<String, String>> iterator = attributeMap.entrySet().iterator();
@@ -137,8 +141,9 @@ public class AttributeStatementGenerator {
 		return xsStringValue;
 	}
 	
-	public HashMap <String,String> putUserAttributes(HashMap <String,String> attributeMap){
-        UserInfo userInfo = WebContext.getUserInfo();
+	public HashMap <String,String> putUserAttributes(
+			HashMap <String,String> attributeMap,
+			UserInfo userInfo){
         attributeMap.put(ActiveDirectoryUser.USERNAME, userInfo.getUsername());
         attributeMap.put(ActiveDirectoryUser.UID, userInfo.getUsername());
         

+ 5 - 2
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,
 											HashMap<String,String>attributeMap, 
-											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())) {

+ 2 - 2
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")) {
 		    

+ 7 - 4
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();

+ 0 - 3
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

+ 23 - 59
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
@@ -60,27 +57,21 @@ public class MaxKeyMvcConfig implements WebMvcConfigurer {
     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;
     
     @Autowired
-    PreLoginAppAdapter preLoginAppAdapter;
+    SingleSignOnInterceptor singleSignOnInterceptor;
     
     @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");
         
 
     }

+ 1 - 1
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());

+ 74 - 0
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)+"<br>"
+				        +WebContext.getAttribute(PasswordPolicyValidator.PASSWORD_POLICY_VALIDATE_RESULT),
+				        MessageType.error);
+			}	
+	}
+
+}

+ 2 - 1
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);
             }

+ 23 - 38
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();
-
-        //  HashMap<String,Object>extraAttributeMap=new HashMap<String,Object>();
-        //  extraAttributeMap=(HashMap<String,Object>)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>(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<UserInfo>(Message.SUCCESS).buildResponse();
+        } 
+        
+        return new Message<UserInfo>(Message.FAIL).buildResponse();
+        
     }
 
 }

+ 13 - 111
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)+"<br>"
-				        +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);
 		
 	}
 	
+	
 }

+ 6 - 2
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<AuthJwt>(Message.FAIL).buildResponse();
+ 		}
  		String jwt = authJwtService.generateToken(authentication);
  		return new Message<AuthJwt>(new AuthJwt(jwt, authentication)).buildResponse();
  	}

+ 3 - 3
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<Entry<String, Apps>> entrySet = onlineTicket.getAuthorizedApps().entrySet();

+ 0 - 69
maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/filter/SingleSignOnFilter.java

@@ -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.");
-    }
-}

+ 9 - 7
maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/HistoryLogsAdapter.java → 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

+ 25 - 17
maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/HistoryLoginAppAdapter.java → 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);
+        }
+       
     }
 }

+ 0 - 70
maxkey-webs/maxkey-web-maxkey/src/main/java/org/maxkey/web/interceptor/PreLoginAppAdapter.java

@@ -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;
-    }
-}

+ 70 - 0
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;
+    }
+
+}

+ 0 - 3
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);
         

+ 3 - 19
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/**")

+ 7 - 5
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)) {

+ 1 - 1
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");

+ 6 - 5
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<Organizations> 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;
   }
 }

+ 18 - 8
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<UserInfoAdjoint> queryDataGrid(@ModelAttribute("userInfoAdjoint") UserInfoAdjoint userInfoAdjoint) {
+	public JpaPageResults<UserInfoAdjoint> 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);
 			

+ 15 - 14
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>(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<UserInfo>(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<UserInfo> 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;
 	}
 

+ 3 - 1
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());

+ 2 - 2
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;
 			}
 		}