diff --git a/integrations/jeesite/5.2.1/src/main/java/com/jeesite/modules/maxkey/base/AuthCustomSource.java b/integrations/jeesite/5.2.1/src/main/java/com/jeesite/modules/maxkey/base/AuthCustomSource.java index 625f9bdf4..c718973a9 100644 --- a/integrations/jeesite/5.2.1/src/main/java/com/jeesite/modules/maxkey/base/AuthCustomSource.java +++ b/integrations/jeesite/5.2.1/src/main/java/com/jeesite/modules/maxkey/base/AuthCustomSource.java @@ -17,44 +17,44 @@ public enum AuthCustomSource implements AuthSource { * 自己搭建的gitlab私服 */ MAXKEY { - /** - * 授权的api - * - * @return url - */ - @Override - public String authorize() { - return AuthMaxKeyJeeGitRequest.BASE_HOST + "/sign/authz/oauth/v20/authorize"; - } + /** + * 授权的api + * + * @return url + */ + @Override + public String authorize() { + return AuthMaxKeyJeeGitRequest.BASE_HOST + "/sign/authz/oauth/v20/authorize"; + } - /** - * 获取accessToken的api - * - * @return url - */ - @Override - public String accessToken() { - return AuthMaxKeyJeeGitRequest.BASE_HOST + "/sign/authz/oauth/v20/token"; - } + /** + * 获取accessToken的api + * + * @return url + */ + @Override + public String accessToken() { + return AuthMaxKeyJeeGitRequest.BASE_HOST + "/sign/authz/oauth/v20/token"; + } - /** - * 获取用户信息的api - * - * @return url - */ - @Override - public String userInfo() { - return AuthMaxKeyJeeGitRequest.BASE_HOST + "/sign/api/oauth/v20/me"; - } + /** + * 获取用户信息的api + * + * @return url + */ + @Override + public String userInfo() { + return AuthMaxKeyJeeGitRequest.BASE_HOST + "/sign/api/oauth/v20/me"; + } - /** - * 平台对应的 AuthRequest 实现类,必须继承自 {@link AuthDefaultRequest} - * - * @return class - */ - @Override - public Class getTargetClass() { - return AuthMaxKeyJeeGitRequest.class; - } + /** + * 平台对应的 AuthRequest 实现类,必须继承自 {@link AuthDefaultRequest} + * + * @return class + */ + @Override + public Class getTargetClass() { + return AuthMaxKeyJeeGitRequest.class; + } } } \ No newline at end of file diff --git a/integrations/jeesite/5.2.1/src/main/java/com/jeesite/modules/maxkey/oauth/realm/request/AuthMaxKeyJeeGitRequest.java b/integrations/jeesite/5.2.1/src/main/java/com/jeesite/modules/maxkey/oauth/realm/request/AuthMaxKeyJeeGitRequest.java index b6607e966..6ad091a2e 100644 --- a/integrations/jeesite/5.2.1/src/main/java/com/jeesite/modules/maxkey/oauth/realm/request/AuthMaxKeyJeeGitRequest.java +++ b/integrations/jeesite/5.2.1/src/main/java/com/jeesite/modules/maxkey/oauth/realm/request/AuthMaxKeyJeeGitRequest.java @@ -24,32 +24,32 @@ public class AuthMaxKeyJeeGitRequest extends AuthDefaultRequest { * @param config */ public AuthMaxKeyJeeGitRequest(AuthConfig config) { - super(config, AuthCustomSource.MAXKEY); + super(config, AuthCustomSource.MAXKEY); } public AuthMaxKeyJeeGitRequest(AuthConfig config, AuthSource source) { - super(config, source); + super(config, source); } public AuthMaxKeyJeeGitRequest(AuthConfig config, AuthStateCache authStateCache) { - super(config, AuthCustomSource.MAXKEY, authStateCache); + super(config, AuthCustomSource.MAXKEY, authStateCache); } @Override protected AuthToken getAccessToken(AuthCallback authCallback) { - String body = doPostAuthorizationCode(authCallback.getCode()); - JSONObject object = JSONObject.parseObject(body); - System.out.println("getAccessToken:"+JsonMapper.toJson(object)); - AuthCustomExceptionUtils.checkResponse(object); - return AuthToken.builder().accessToken(object.getString("access_token")).refreshToken(object.getString("refresh_token")).idToken(object.getString("id_token")).tokenType(object.getString("token_type")).scope(object.getString("scope")).build(); + String body = doPostAuthorizationCode(authCallback.getCode()); + JSONObject object = JSONObject.parseObject(body); + System.out.println("getAccessToken:"+JsonMapper.toJson(object)); + AuthCustomExceptionUtils.checkResponse(object); + return AuthToken.builder().accessToken(object.getString("access_token")).refreshToken(object.getString("refresh_token")).idToken(object.getString("id_token")).tokenType(object.getString("token_type")).scope(object.getString("scope")).build(); } @Override protected AuthUser getUserInfo(AuthToken authToken) { - String body = doGetUserInfo(authToken); - JSONObject object = JSONObject.parseObject(body); - AuthCustomExceptionUtils.checkResponse(object); - return AuthUser.builder().uuid(object.getString("id")).username(object.getString("username")).nickname(object.getString("name")).avatar(object.getString("avatar_url")).blog(object.getString("web_url")).company(object.getString("organization")).location(object.getString("location")).email(object.getString("email")).remark(object.getString("bio")).token(authToken).source(source.toString()).build(); + String body = doGetUserInfo(authToken); + JSONObject object = JSONObject.parseObject(body); + AuthCustomExceptionUtils.checkResponse(object); + return AuthUser.builder().uuid(object.getString("id")).username(object.getString("username")).nickname(object.getString("name")).avatar(object.getString("avatar_url")).blog(object.getString("web_url")).company(object.getString("organization")).location(object.getString("location")).email(object.getString("email")).remark(object.getString("bio")).token(authToken).source(source.toString()).build(); } } diff --git a/integrations/jeesite/5.2.1/src/main/java/com/jeesite/modules/maxkey/utils/Oauth2UserLoginUtils.java b/integrations/jeesite/5.2.1/src/main/java/com/jeesite/modules/maxkey/utils/Oauth2UserLoginUtils.java index 22d207a06..7d148dd3d 100644 --- a/integrations/jeesite/5.2.1/src/main/java/com/jeesite/modules/maxkey/utils/Oauth2UserLoginUtils.java +++ b/integrations/jeesite/5.2.1/src/main/java/com/jeesite/modules/maxkey/utils/Oauth2UserLoginUtils.java @@ -34,25 +34,25 @@ public class Oauth2UserLoginUtils{ private static final String DEFAULT_USER_CODE="system"; public static String getAuthUserToSysUserCode(String oauthUserId) { - //自行实现第三方用户到jeesite用户之间逻辑转换关系 - if(DEMO_MODE) { - return DEFAULT_USER_CODE; - } - return oauthUserId; + //自行实现第三方用户到jeesite用户之间逻辑转换关系 + if(DEMO_MODE) { + return DEFAULT_USER_CODE; + } + return oauthUserId; } public static void loginByOauthUserId(String oauthUserId) { - - HttpServletRequest request = ServletUtils.getRequest(); - HttpServletResponse response = ServletUtils.getResponse(); - try { - // FormToken 构造方法的三个参数:登录名、是否内部登录无条件、请求对象 - UserUtils.getSubject().login(new FormToken(getAuthUserToSysUserCode(oauthUserId), true, request)); - System.out.println("登录成功,__sid=" + UserUtils.getSession().getId()); - FormFilter.onLoginSuccess(request, response); - } catch (AuthenticationException e) { - FormFilter.onLoginFailure(e, request, response); - } + + HttpServletRequest request = ServletUtils.getRequest(); + HttpServletResponse response = ServletUtils.getResponse(); + try { + // FormToken 构造方法的三个参数:登录名、是否内部登录无条件、请求对象 + UserUtils.getSubject().login(new FormToken(getAuthUserToSysUserCode(oauthUserId), true, request)); + System.out.println("登录成功,__sid=" + UserUtils.getSession().getId()); + FormFilter.onLoginSuccess(request, response); + } catch (AuthenticationException e) { + FormFilter.onLoginFailure(e, request, response); + } } @@ -71,11 +71,11 @@ public class Oauth2UserLoginUtils{ // jeegit: -// clientId: 823874316692094976 -// clientSecret: t74BMTcwMjIwMjMwODIzNTA4NDQFLu -// serverUrl: http://sso.maxkey.top -// redirectUri: http://localhost:8980/js/oauth2/callback/jeegit -// className: com.jeesite.modules.oauth2.request.AuthMaxKeyRequest +// clientId: 823874316692094976 +// clientSecret: t74BMTcwMjIwMjMwODIzNTA4NDQFLu +// serverUrl: http://sso.maxkey.top +// redirectUri: http://localhost:8980/js/oauth2/callback/jeegit +// className: com.jeesite.modules.oauth2.request.AuthMaxKeyRequest authRequest = new AuthMaxKeyJeeGitRequest(AuthConfig.builder() .clientId(Global.getProperty("oauth2." + source + ".clientId")) .clientSecret(Global.getProperty("oauth2." + source + ".clientSecret")) diff --git a/integrations/jeesite/5.2.1/src/main/java/com/jeesite/modules/maxkey/web/JustOauth2Controller.java b/integrations/jeesite/5.2.1/src/main/java/com/jeesite/modules/maxkey/web/JustOauth2Controller.java index fe708a093..2b834c0e1 100644 --- a/integrations/jeesite/5.2.1/src/main/java/com/jeesite/modules/maxkey/web/JustOauth2Controller.java +++ b/integrations/jeesite/5.2.1/src/main/java/com/jeesite/modules/maxkey/web/JustOauth2Controller.java @@ -36,47 +36,47 @@ public class JustOauth2Controller extends BaseController implements IBaseJustOau @Override @RequestMapping({"/login/{source}"}) public String login(String source, HttpServletRequest request) { - // TODO Auto-generated method stub - logger.debug(source); - return "redirect:" + Oauth2UserLoginUtils.getAuthRequest(source).authorize((request.getParameter("state") == null ? AuthStateUtils.createState() : request.getParameter("state"))); + // TODO Auto-generated method stub + logger.debug(source); + return "redirect:" + Oauth2UserLoginUtils.getAuthRequest(source).authorize((request.getParameter("state") == null ? AuthStateUtils.createState() : request.getParameter("state"))); } @Override @RequestMapping({"/callback/{source}"}) public String callback(String source, AuthCallback callback, RedirectAttributes redirectAttributes, Model model, HttpServletRequest request, HttpServletResponse response) { - // TODO Auto-generated method stub - logger.debug(source); + // TODO Auto-generated method stub + logger.debug(source); - AuthRequest authRequest = Oauth2UserLoginUtils.getAuthRequest(source); - AuthResponse rauthResponse = authRequest.login(callback); - if(rauthResponse.getData() instanceof AuthUser) { - AuthUser authUser = (AuthUser) rauthResponse.getData(); - //处理相关的绑定业务,该处仅做简单集成与演示专用。 - logger.debug("authUser:"+JsonMapper.toJson(authUser)); - Oauth2UserLoginUtils.loginByOauthUserId(authUser.getUsername()); - return renderResult(Global.TRUE, text("回调信息获取成功!")); - } else { - return null; - } - + AuthRequest authRequest = Oauth2UserLoginUtils.getAuthRequest(source); + AuthResponse rauthResponse = authRequest.login(callback); + if(rauthResponse.getData() instanceof AuthUser) { + AuthUser authUser = (AuthUser) rauthResponse.getData(); + //处理相关的绑定业务,该处仅做简单集成与演示专用。 + logger.debug("authUser:"+JsonMapper.toJson(authUser)); + Oauth2UserLoginUtils.loginByOauthUserId(authUser.getUsername()); + return renderResult(Global.TRUE, text("回调信息获取成功!")); + } else { + return null; + } + } @Override @PostMapping({"/binder"}) @ResponseBody public String binder(String id, String username, String password, String validCode, HttpServletRequest request, HttpServletResponse response) { - // TODO Auto-generated method stub - logger.debug(id, username); - return null; + // TODO Auto-generated method stub + logger.debug(id, username); + return null; } @Override @RequestMapping({"/unbind"}) @ResponseBody public String unbind(String id, HttpServletRequest request, HttpServletResponse response) { - // TODO Auto-generated method stub - logger.debug(id); - return null; + // TODO Auto-generated method stub + logger.debug(id); + return null; } } diff --git a/integrations/spring-boot-security-oauth-client-sample/src/main/java/org/maxkey/springboot/oauthclient/SpringBootOauthClientApplication.java b/integrations/spring-boot-security-oauth-client-sample/src/main/java/org/maxkey/springboot/oauthclient/SpringBootOauthClientApplication.java index e57df5bc7..9301250fc 100644 --- a/integrations/spring-boot-security-oauth-client-sample/src/main/java/org/maxkey/springboot/oauthclient/SpringBootOauthClientApplication.java +++ b/integrations/spring-boot-security-oauth-client-sample/src/main/java/org/maxkey/springboot/oauthclient/SpringBootOauthClientApplication.java @@ -6,9 +6,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootOauthClientApplication { - public static void main(String[] args) { - SpringApplication.run(SpringBootOauthClientApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(SpringBootOauthClientApplication.class, args); + } } diff --git a/integrations/spring-boot-security-oauth-client-sample/src/main/java/org/maxkey/springboot/oauthclient/config/ResourceServerConfiguration.java b/integrations/spring-boot-security-oauth-client-sample/src/main/java/org/maxkey/springboot/oauthclient/config/ResourceServerConfiguration.java index 62b657a41..38d846e90 100644 --- a/integrations/spring-boot-security-oauth-client-sample/src/main/java/org/maxkey/springboot/oauthclient/config/ResourceServerConfiguration.java +++ b/integrations/spring-boot-security-oauth-client-sample/src/main/java/org/maxkey/springboot/oauthclient/config/ResourceServerConfiguration.java @@ -12,31 +12,31 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur @Configuration @EnableOAuth2Sso public class ResourceServerConfiguration extends WebSecurityConfigurerAdapter { - Logger log = LoggerFactory.getLogger(ResourceServerConfiguration.class); - - @Value("${maxkey-auth-url}") - String maxkeyAuthUrl; - - @Value("${security.oauth2.client.user-authorization-uri}") - String userAuthorizationUri; - - @Value("${security.oauth2.client.access-token-uri}") - String accessTokenUri; - - @Value("${security.oauth2.resource.user-info-uri}") - String userInfoUri; - + Logger log = LoggerFactory.getLogger(ResourceServerConfiguration.class); + + @Value("${maxkey-auth-url}") + String maxkeyAuthUrl; + + @Value("${security.oauth2.client.user-authorization-uri}") + String userAuthorizationUri; + + @Value("${security.oauth2.client.access-token-uri}") + String accessTokenUri; + + @Value("${security.oauth2.resource.user-info-uri}") + String userInfoUri; + @Override public void configure(HttpSecurity http) throws Exception { //http.antMatcher("/orgs/**").antMatcher("/userinfo").antMatcher("/login").authorizeRequests().anyRequest().authenticated(); - http.authorizeRequests().anyRequest().authenticated().and().csrf().disable(); - log.info("UserAuthorizationUri {}" ,userAuthorizationUri); - log.info("AccessTokenUri {}" ,accessTokenUri); - log.info("UserInfoUri {}" ,userInfoUri); - if(accessTokenUri.startsWith("https")) { - HttpsTrusts.beforeConnection(); - } - log.debug("ResourceServerConfiguration"); + http.authorizeRequests().anyRequest().authenticated().and().csrf().disable(); + log.info("UserAuthorizationUri {}" ,userAuthorizationUri); + log.info("AccessTokenUri {}" ,accessTokenUri); + log.info("UserInfoUri {}" ,userInfoUri); + if(accessTokenUri.startsWith("https")) { + HttpsTrusts.beforeConnection(); + } + log.debug("ResourceServerConfiguration"); } } diff --git a/integrations/spring-boot-security-oauth-client-sample/src/main/java/org/maxkey/springboot/oauthclient/controller/ResourceController.java b/integrations/spring-boot-security-oauth-client-sample/src/main/java/org/maxkey/springboot/oauthclient/controller/ResourceController.java index c717cc5bc..909f15110 100644 --- a/integrations/spring-boot-security-oauth-client-sample/src/main/java/org/maxkey/springboot/oauthclient/controller/ResourceController.java +++ b/integrations/spring-boot-security-oauth-client-sample/src/main/java/org/maxkey/springboot/oauthclient/controller/ResourceController.java @@ -10,11 +10,11 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class ResourceController { - Logger log = LoggerFactory.getLogger(ResourceController.class); - + Logger log = LoggerFactory.getLogger(ResourceController.class); + @GetMapping("/") public String index() { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return authentication.getPrincipal().toString(); } } diff --git a/integrations/spring-boot-security-oauth-client-sample/src/main/java/org/maxkey/springboot/oauthclient/http/HttpsTrusts.java b/integrations/spring-boot-security-oauth-client-sample/src/main/java/org/maxkey/springboot/oauthclient/http/HttpsTrusts.java index 00023810a..f683f082a 100644 --- a/integrations/spring-boot-security-oauth-client-sample/src/main/java/org/maxkey/springboot/oauthclient/http/HttpsTrusts.java +++ b/integrations/spring-boot-security-oauth-client-sample/src/main/java/org/maxkey/springboot/oauthclient/http/HttpsTrusts.java @@ -24,52 +24,52 @@ import javax.net.ssl.SSLSession; public class HttpsTrusts { private static void trustAllHttpsCertificates() throws Exception { - javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; - javax.net.ssl.TrustManager tm = new HttpsTrustsTM(); - trustAllCerts[0] = tm; - javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL"); - sc.init(null, trustAllCerts, null); - javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); - } + javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; + javax.net.ssl.TrustManager tm = new HttpsTrustsTM(); + trustAllCerts[0] = tm; + javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, null); + javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + } /* * https ssl auto trust */ - public static void beforeConnection() { - try { - trustAllHttpsCertificates(); - HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { - public boolean verify(String urlHostName, SSLSession session) { - System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost()); - return true; - } - }); - } catch(Exception e) { - e.printStackTrace(); - } - } - - static class HttpsTrustsTM implements javax.net.ssl.TrustManager,javax.net.ssl.X509TrustManager { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return null; - } + public static void beforeConnection() { + try { + trustAllHttpsCertificates(); + HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { + public boolean verify(String urlHostName, SSLSession session) { + System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost()); + return true; + } + }); + } catch(Exception e) { + e.printStackTrace(); + } + } + + static class HttpsTrustsTM implements javax.net.ssl.TrustManager,javax.net.ssl.X509TrustManager { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } - public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) { - return true; - } + public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) { + return true; + } - public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) { - return true; - } + public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) { + return true; + } - public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) - throws java.security.cert.CertificateException { - return; - } + public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) + throws java.security.cert.CertificateException { + return; + } - public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) - throws java.security.cert.CertificateException { - return; - } - } + public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) + throws java.security.cert.CertificateException { + return; + } + } } diff --git a/integrations/spring-security-oauth2-sso/spring-demo-client1/src/main/java/com/concretepage/client1/AppController.java b/integrations/spring-security-oauth2-sso/spring-demo-client1/src/main/java/com/concretepage/client1/AppController.java index 666bd6e13..b0c60a8d2 100644 --- a/integrations/spring-security-oauth2-sso/spring-demo-client1/src/main/java/com/concretepage/client1/AppController.java +++ b/integrations/spring-security-oauth2-sso/spring-demo-client1/src/main/java/com/concretepage/client1/AppController.java @@ -9,17 +9,17 @@ import java.util.Map; @Controller public class AppController { - @GetMapping("hello") - public ModelAndView welcome() { - ModelAndView mav = new ModelAndView(); - mav.setViewName("welcome"); - return mav; + @GetMapping("hello") + public ModelAndView welcome() { + ModelAndView mav = new ModelAndView(); + mav.setViewName("welcome"); + return mav; } - @GetMapping("error") - public ModelAndView error() { - Map model = new HashMap<>(); - ModelAndView mav = new ModelAndView(); - mav.setViewName("error"); - return mav; - } + @GetMapping("error") + public ModelAndView error() { + Map model = new HashMap<>(); + ModelAndView mav = new ModelAndView(); + mav.setViewName("error"); + return mav; + } } diff --git a/integrations/spring-security-oauth2-sso/spring-demo-client1/src/main/java/com/concretepage/client1/MainClient1.java b/integrations/spring-security-oauth2-sso/spring-demo-client1/src/main/java/com/concretepage/client1/MainClient1.java index f613470f5..35dcb17ef 100644 --- a/integrations/spring-security-oauth2-sso/spring-demo-client1/src/main/java/com/concretepage/client1/MainClient1.java +++ b/integrations/spring-security-oauth2-sso/spring-demo-client1/src/main/java/com/concretepage/client1/MainClient1.java @@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MainClient1 { - public static void main(String[] args) { - SpringApplication.run(MainClient1.class, args); - } + public static void main(String[] args) { + SpringApplication.run(MainClient1.class, args); + } } \ No newline at end of file diff --git a/integrations/spring-security-oauth2-sso/spring-demo-client1/src/main/java/com/concretepage/client1/SecurityConfiguration.java b/integrations/spring-security-oauth2-sso/spring-demo-client1/src/main/java/com/concretepage/client1/SecurityConfiguration.java index c6a44ee76..7e8993cd0 100644 --- a/integrations/spring-security-oauth2-sso/spring-demo-client1/src/main/java/com/concretepage/client1/SecurityConfiguration.java +++ b/integrations/spring-security-oauth2-sso/spring-demo-client1/src/main/java/com/concretepage/client1/SecurityConfiguration.java @@ -8,14 +8,14 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur @Configuration @EnableOAuth2Sso public class SecurityConfiguration extends WebSecurityConfigurerAdapter { - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .antMatchers("/", "/error**").permitAll() + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .antMatchers("/", "/error**").permitAll() .anyRequest().authenticated() .and().logout().logoutUrl("/logout") - .logoutSuccessUrl("http://sso.maxkey.top/sign/force/logout"); + .logoutSuccessUrl("http://sso.maxkey.top/sign/force/logout"); - } + } } \ No newline at end of file diff --git a/integrations/spring-security-oauth2-sso/spring-demo-client2/src/main/java/com/concretepage/client2/AppController.java b/integrations/spring-security-oauth2-sso/spring-demo-client2/src/main/java/com/concretepage/client2/AppController.java index a6b92114e..969d6b4df 100644 --- a/integrations/spring-security-oauth2-sso/spring-demo-client2/src/main/java/com/concretepage/client2/AppController.java +++ b/integrations/spring-security-oauth2-sso/spring-demo-client2/src/main/java/com/concretepage/client2/AppController.java @@ -9,17 +9,17 @@ import java.util.Map; @Controller public class AppController { - @GetMapping("hello") - public ModelAndView welcome() { - ModelAndView mav = new ModelAndView(); - mav.setViewName("welcome"); - return mav; + @GetMapping("hello") + public ModelAndView welcome() { + ModelAndView mav = new ModelAndView(); + mav.setViewName("welcome"); + return mav; } - @GetMapping("error") - public ModelAndView error() { - Map model = new HashMap<>(); - ModelAndView mav = new ModelAndView(); - mav.setViewName("error"); - return mav; - } + @GetMapping("error") + public ModelAndView error() { + Map model = new HashMap<>(); + ModelAndView mav = new ModelAndView(); + mav.setViewName("error"); + return mav; + } } diff --git a/integrations/spring-security-oauth2-sso/spring-demo-client2/src/main/java/com/concretepage/client2/MainClient2.java b/integrations/spring-security-oauth2-sso/spring-demo-client2/src/main/java/com/concretepage/client2/MainClient2.java index fc9e3162f..0b45b5347 100644 --- a/integrations/spring-security-oauth2-sso/spring-demo-client2/src/main/java/com/concretepage/client2/MainClient2.java +++ b/integrations/spring-security-oauth2-sso/spring-demo-client2/src/main/java/com/concretepage/client2/MainClient2.java @@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MainClient2 { - public static void main(String[] args) { - SpringApplication.run(MainClient2.class, args); - } + public static void main(String[] args) { + SpringApplication.run(MainClient2.class, args); + } } \ No newline at end of file diff --git a/integrations/spring-security-oauth2-sso/spring-demo-client2/src/main/java/com/concretepage/client2/SecurityConfiguration.java b/integrations/spring-security-oauth2-sso/spring-demo-client2/src/main/java/com/concretepage/client2/SecurityConfiguration.java index b19c9a848..2948ff185 100644 --- a/integrations/spring-security-oauth2-sso/spring-demo-client2/src/main/java/com/concretepage/client2/SecurityConfiguration.java +++ b/integrations/spring-security-oauth2-sso/spring-demo-client2/src/main/java/com/concretepage/client2/SecurityConfiguration.java @@ -8,14 +8,14 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur @Configuration @EnableOAuth2Sso public class SecurityConfiguration extends WebSecurityConfigurerAdapter { - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .antMatchers("/", "/error**").permitAll() + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .antMatchers("/", "/error**").permitAll() .anyRequest().authenticated() .and().logout().logoutUrl("/logout") - .logoutSuccessUrl("http://sso.maxkey.top/sign/force/logout"); + .logoutSuccessUrl("http://sso.maxkey.top/sign/force/logout"); - } + } } \ No newline at end of file diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/SignPrincipal.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/SignPrincipal.java index fff010f85..148d8c1c0 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/SignPrincipal.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/SignPrincipal.java @@ -37,7 +37,7 @@ public class SignPrincipal implements UserDetails { String sessionId; - int twoFactor; + int twoFactor; List grantedAuthority; @@ -47,13 +47,13 @@ public class SignPrincipal implements UserDetails { boolean roleAdministrators; - private boolean accountNonExpired; + private boolean accountNonExpired; - private boolean accountNonLocked; + private boolean accountNonLocked; - private boolean credentialsNonExpired; + private boolean credentialsNonExpired; - private boolean enabled; + private boolean enabled; /** * SigninPrincipal. @@ -160,22 +160,22 @@ public class SignPrincipal implements UserDetails { public String getSessionId() { - return sessionId; - } + return sessionId; + } - public void setSessionId(String sessionId) { - this.sessionId = sessionId; - } - - public String getInstId() { - return instId; - } + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + public String getInstId() { + return instId; + } - public String getUserId() { - return userId; - } + public String getUserId() { + return userId; + } - @Override + @Override public boolean isEnabled() { return this.enabled; } @@ -207,45 +207,45 @@ public class SignPrincipal implements UserDetails { } public int getTwoFactor() { - return twoFactor; - } + return twoFactor; + } - public void setTwoFactor(int twoFactor) { - this.twoFactor = twoFactor; - } - - public void clearTwoFactor() { - this.twoFactor = 0; - } + public void setTwoFactor(int twoFactor) { + this.twoFactor = twoFactor; + } + + public void clearTwoFactor() { + this.twoFactor = 0; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Principal [username="); - builder.append(getUsername()); - builder.append(", userInfo="); - builder.append(userInfo); - builder.append(", userDetails="); - builder.append(userDetails); - builder.append(", grantedAuthority="); - builder.append(grantedAuthority); - builder.append(", grantedAuthorityApps="); - builder.append(grantedAuthorityApps); - builder.append(", authenticated="); - builder.append(authenticated); - builder.append(", roleAdministrators="); - builder.append(roleAdministrators); - builder.append(", accountNonExpired="); - builder.append(accountNonExpired); - builder.append(", accountNonLocked="); - builder.append(accountNonLocked); - builder.append(", credentialsNonExpired="); - builder.append(credentialsNonExpired); - builder.append(", enabled="); - builder.append(enabled); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Principal [username="); + builder.append(getUsername()); + builder.append(", userInfo="); + builder.append(userInfo); + builder.append(", userDetails="); + builder.append(userDetails); + builder.append(", grantedAuthority="); + builder.append(grantedAuthority); + builder.append(", grantedAuthorityApps="); + builder.append(grantedAuthorityApps); + builder.append(", authenticated="); + builder.append(authenticated); + builder.append(", roleAdministrators="); + builder.append(roleAdministrators); + builder.append(", accountNonExpired="); + builder.append(accountNonExpired); + builder.append(", accountNonLocked="); + builder.append(accountNonLocked); + builder.append(", credentialsNonExpired="); + builder.append(credentialsNonExpired); + builder.append(", enabled="); + builder.append(enabled); + builder.append("]"); + return builder.toString(); + } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/AuthJwt.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/AuthJwt.java index a7bd1c522..79660909f 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/AuthJwt.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/AuthJwt.java @@ -31,218 +31,218 @@ import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.v3.oas.annotations.media.Schema; public class AuthJwt implements Serializable { - - private static final long serialVersionUID = -914373258878811144L; - - public static final String ACCESS_TOKEN = "access_token"; - - public static final String REFRESH_TOKEN = "refresh_token"; - - public static final String EXPIRES_IN = "expired"; - - private String ticket; - - private String type = "Bearer"; - - private String token; - - @JsonProperty(REFRESH_TOKEN) - private String refreshToken; - - @JsonProperty(EXPIRES_IN) - private int expiresIn; - - @JsonFormat(shape = JsonFormat.Shape.STRING) - @Schema(name = "twoFactor", description = "二次认证类型") - int twoFactor; + + private static final long serialVersionUID = -914373258878811144L; + + public static final String ACCESS_TOKEN = "access_token"; + + public static final String REFRESH_TOKEN = "refresh_token"; + + public static final String EXPIRES_IN = "expired"; + + private String ticket; + + private String type = "Bearer"; + + private String token; + + @JsonProperty(REFRESH_TOKEN) + private String refreshToken; + + @JsonProperty(EXPIRES_IN) + private int expiresIn; + + @JsonFormat(shape = JsonFormat.Shape.STRING) + @Schema(name = "twoFactor", description = "二次认证类型") + int twoFactor; - private String remeberMe; - private String id; - private String name; - private String username; - private String displayName; - private String email; - private String instId; - private String instName; - private int passwordSetType; - private List authorities; - - public AuthJwt(String ticket, String type, String token, String refreshToken, int expiresIn, String remeberMe, - String id, String name, String username, String displayName, String email, String instId, String instName, - int passwordSetType, List authorities) { - super(); - this.ticket = ticket; - this.type = type; - this.token = token; - this.refreshToken = refreshToken; - this.expiresIn = expiresIn; - this.remeberMe = remeberMe; - this.id = id; - this.name = name; - this.username = username; - this.displayName = displayName; - this.email = email; - this.instId = instId; - this.instName = instName; - this.passwordSetType = passwordSetType; - this.authorities = authorities; - } + private String remeberMe; + private String id; + private String name; + private String username; + private String displayName; + private String email; + private String instId; + private String instName; + private int passwordSetType; + private List authorities; + + public AuthJwt(String ticket, String type, String token, String refreshToken, int expiresIn, String remeberMe, + String id, String name, String username, String displayName, String email, String instId, String instName, + int passwordSetType, List authorities) { + super(); + this.ticket = ticket; + this.type = type; + this.token = token; + this.refreshToken = refreshToken; + this.expiresIn = expiresIn; + this.remeberMe = remeberMe; + this.id = id; + this.name = name; + this.username = username; + this.displayName = displayName; + this.email = email; + this.instId = instId; + this.instName = instName; + this.passwordSetType = passwordSetType; + this.authorities = authorities; + } - public AuthJwt(String token, Authentication authentication,int expiresIn,String refreshToken) { - SignPrincipal principal = ((SignPrincipal)authentication.getPrincipal()); - - this.token = token; - this.expiresIn = expiresIn; - this.refreshToken = refreshToken; - - this.ticket = principal.getSessionId(); - this.id = principal.getUserInfo().getId(); - this.username = principal.getUserInfo().getUsername(); - this.name = this.username; - this.displayName = principal.getUserInfo().getDisplayName(); - this.email = principal.getUserInfo().getEmail(); - this.instId = principal.getUserInfo().getInstId(); - this.instName = principal.getUserInfo().getInstName(); - this.twoFactor =principal.getTwoFactor(); - this.authorities = new ArrayList<>(); - for(GrantedAuthority grantedAuthority :authentication.getAuthorities()) { - this.authorities.add(grantedAuthority.getAuthority()); - } - } - - - public String getToken() { - return token; - } - public void setToken(String token) { - this.token = token; - } - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } + public AuthJwt(String token, Authentication authentication,int expiresIn,String refreshToken) { + SignPrincipal principal = ((SignPrincipal)authentication.getPrincipal()); + + this.token = token; + this.expiresIn = expiresIn; + this.refreshToken = refreshToken; + + this.ticket = principal.getSessionId(); + this.id = principal.getUserInfo().getId(); + this.username = principal.getUserInfo().getUsername(); + this.name = this.username; + this.displayName = principal.getUserInfo().getDisplayName(); + this.email = principal.getUserInfo().getEmail(); + this.instId = principal.getUserInfo().getInstId(); + this.instName = principal.getUserInfo().getInstName(); + this.twoFactor =principal.getTwoFactor(); + this.authorities = new ArrayList<>(); + for(GrantedAuthority grantedAuthority :authentication.getAuthorities()) { + this.authorities.add(grantedAuthority.getAuthority()); + } + } + + + public String getToken() { + return token; + } + public void setToken(String token) { + this.token = token; + } + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getUsername() { - return username; - } - public void setUsername(String username) { - this.username = username; - } - public String getDisplayName() { - return displayName; - } - public void setDisplayName(String displayName) { - this.displayName = displayName; - } - public String getEmail() { - return email; - } - public void setEmail(String email) { - this.email = email; - } - public String getInstId() { - return instId; - } - public void setInstId(String instId) { - this.instId = instId; - } - public String getInstName() { - return instName; - } - public void setInstName(String instName) { - this.instName = instName; - } - public List getAuthorities() { - return authorities; - } - public void setAuthorities(List authorities) { - this.authorities = authorities; - } - - public String getTicket() { - return ticket; - } + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + public String getDisplayName() { + return displayName; + } + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + public String getInstId() { + return instId; + } + public void setInstId(String instId) { + this.instId = instId; + } + public String getInstName() { + return instName; + } + public void setInstName(String instName) { + this.instName = instName; + } + public List getAuthorities() { + return authorities; + } + public void setAuthorities(List authorities) { + this.authorities = authorities; + } + + public String getTicket() { + return ticket; + } - public void setTicket(String ticket) { - this.ticket = ticket; - } - - public int getPasswordSetType() { - return passwordSetType; - } + public void setTicket(String ticket) { + this.ticket = ticket; + } + + public int getPasswordSetType() { + return passwordSetType; + } - public void setPasswordSetType(int passwordSetType) { - this.passwordSetType = passwordSetType; - } - - public String getRemeberMe() { - return remeberMe; - } + public void setPasswordSetType(int passwordSetType) { + this.passwordSetType = passwordSetType; + } + + public String getRemeberMe() { + return remeberMe; + } - public void setRemeberMe(String remeberMe) { - this.remeberMe = remeberMe; - } + public void setRemeberMe(String remeberMe) { + this.remeberMe = remeberMe; + } - public String getRefreshToken() { - return refreshToken; - } + public String getRefreshToken() { + return refreshToken; + } - public void setRefreshToken(String refreshToken) { - this.refreshToken = refreshToken; - } - - public int getExpiresIn() { - return expiresIn; - } + public void setRefreshToken(String refreshToken) { + this.refreshToken = refreshToken; + } + + public int getExpiresIn() { + return expiresIn; + } - public void setExpiresIn(int expiresIn) { - this.expiresIn = expiresIn; - } + public void setExpiresIn(int expiresIn) { + this.expiresIn = expiresIn; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("AuthJwt [token="); - builder.append(token); - builder.append(", type="); - builder.append(type); - builder.append(", id="); - builder.append(id); - builder.append(", username="); - builder.append(username); - builder.append(", displayName="); - builder.append(displayName); - builder.append(", email="); - builder.append(email); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append(", authorities="); - builder.append(authorities); - builder.append("]"); - return builder.toString(); - } - - - + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("AuthJwt [token="); + builder.append(token); + builder.append(", type="); + builder.append(type); + builder.append(", id="); + builder.append(id); + builder.append(", username="); + builder.append(username); + builder.append(", displayName="); + builder.append(displayName); + builder.append(", email="); + builder.append(email); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append(", authorities="); + builder.append(authorities); + builder.append("]"); + return builder.toString(); + } + + + } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/AuthJwtService.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/AuthJwtService.java index 98df61db3..2ed897820 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/AuthJwtService.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/AuthJwtService.java @@ -37,116 +37,116 @@ import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; public class AuthJwtService { - private static final Logger _logger = LoggerFactory.getLogger(AuthJwtService.class); - - Hmac512Service hmac512Service; - - /** - * JWT with Authentication - * @param authentication - * @return - */ - public String genJwt(Authentication authentication,String issuer,int expires) { - SignPrincipal principal = ((SignPrincipal)authentication.getPrincipal()); - UserInfo userInfo = principal.getUserInfo(); - DateTime currentDateTime = DateTime.now(); - String subject = principal.getUsername(); - Date expirationTime = currentDateTime.plusSeconds(expires).toDate(); - _logger.trace("jwt subject : {} , expiration Time : {}" , subject,expirationTime); - - JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder() - .issuer(issuer) - .subject(subject) - .jwtID(principal.getSessionId()) - .issueTime(currentDateTime.toDate()) - .expirationTime(expirationTime) - .claim("locale", userInfo.getLocale()) - .claim("kid", Hmac512Service.MXK_AUTH_JWK) - .claim(ConstsJwt.USER_ID, userInfo.getId()) - .claim(ConstsJwt.INST_ID, userInfo.getInstId()) - .build(); - - return signedJWT(jwtClaims); - } - - /** - * JWT with subject - * @param subject subject - * @return - */ - public String genJwt(String subject,String issuer,int expires) { - DateTime currentDateTime = DateTime.now(); - Date expirationTime = currentDateTime.plusSeconds(expires).toDate(); - _logger.trace("jwt subject : {} , expiration Time : {}" , subject,expirationTime); - - JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder() - .issuer(issuer) - .subject(subject) - .jwtID(WebContext.genId()) - .issueTime(currentDateTime.toDate()) - .expirationTime(expirationTime) - .build(); - - return signedJWT(jwtClaims); - } - - /** - * Random JWT - * @return - */ - public String genRandomJwt(int expires) { - Date expirationTime = DateTime.now().plusSeconds(expires).toDate(); - _logger.trace("expiration Time : {}" , expirationTime); - - JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder() - .jwtID(WebContext.genId()) - .expirationTime(expirationTime) - .build(); - - return signedJWT(jwtClaims); - } - - public String signedJWT(JWTClaimsSet jwtClaims) { - _logger.trace("jwt Claims : {}" , jwtClaims); - SignedJWT jwtToken = new SignedJWT( - new JWSHeader(JWSAlgorithm.HS512), - jwtClaims); - return hmac512Service.sign(jwtToken.getPayload()); - } - - /** - * Verify with HMAC512 and check ExpirationTime - * - * @param authToken - * @return true or false - */ - public boolean validateJwtToken(String authToken) { - if(StringUtils.isNotBlank(authToken) && authToken.length() > 20) { - try { - JWTClaimsSet claims = resolve(authToken); - boolean isExpiration = claims.getExpirationTime().after(DateTime.now().toDate()); - boolean isVerify = hmac512Service.verify(authToken); - boolean isValidate = isVerify && isExpiration; - _logger.trace("JWT Validate {} " , isValidate); - _logger.debug("HMAC Verify {} , now {} , ExpirationTime {} , is not Expiration : {}" , - isVerify,DateTime.now().toDate(),claims.getExpirationTime(),isExpiration); - return isValidate; - } catch (ParseException e) { - _logger.error("authToken {}",authToken); - _logger.error("ParseException ",e); - } - } - return false; - } - - public JWTClaimsSet resolve(String authToken) throws ParseException { - SignedJWT signedJWT = SignedJWT.parse(authToken); - _logger.trace("jwt Claims : {}" , signedJWT.getJWTClaimsSet()); - return signedJWT.getJWTClaimsSet(); - } - - public String resolveJWTID(String authToken) throws ParseException { - JWTClaimsSet claims = resolve(authToken); - return claims.getJWTID(); - } + private static final Logger _logger = LoggerFactory.getLogger(AuthJwtService.class); + + Hmac512Service hmac512Service; + + /** + * JWT with Authentication + * @param authentication + * @return + */ + public String genJwt(Authentication authentication,String issuer,int expires) { + SignPrincipal principal = ((SignPrincipal)authentication.getPrincipal()); + UserInfo userInfo = principal.getUserInfo(); + DateTime currentDateTime = DateTime.now(); + String subject = principal.getUsername(); + Date expirationTime = currentDateTime.plusSeconds(expires).toDate(); + _logger.trace("jwt subject : {} , expiration Time : {}" , subject,expirationTime); + + JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder() + .issuer(issuer) + .subject(subject) + .jwtID(principal.getSessionId()) + .issueTime(currentDateTime.toDate()) + .expirationTime(expirationTime) + .claim("locale", userInfo.getLocale()) + .claim("kid", Hmac512Service.MXK_AUTH_JWK) + .claim(ConstsJwt.USER_ID, userInfo.getId()) + .claim(ConstsJwt.INST_ID, userInfo.getInstId()) + .build(); + + return signedJWT(jwtClaims); + } + + /** + * JWT with subject + * @param subject subject + * @return + */ + public String genJwt(String subject,String issuer,int expires) { + DateTime currentDateTime = DateTime.now(); + Date expirationTime = currentDateTime.plusSeconds(expires).toDate(); + _logger.trace("jwt subject : {} , expiration Time : {}" , subject,expirationTime); + + JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder() + .issuer(issuer) + .subject(subject) + .jwtID(WebContext.genId()) + .issueTime(currentDateTime.toDate()) + .expirationTime(expirationTime) + .build(); + + return signedJWT(jwtClaims); + } + + /** + * Random JWT + * @return + */ + public String genRandomJwt(int expires) { + Date expirationTime = DateTime.now().plusSeconds(expires).toDate(); + _logger.trace("expiration Time : {}" , expirationTime); + + JWTClaimsSet jwtClaims =new JWTClaimsSet.Builder() + .jwtID(WebContext.genId()) + .expirationTime(expirationTime) + .build(); + + return signedJWT(jwtClaims); + } + + public String signedJWT(JWTClaimsSet jwtClaims) { + _logger.trace("jwt Claims : {}" , jwtClaims); + SignedJWT jwtToken = new SignedJWT( + new JWSHeader(JWSAlgorithm.HS512), + jwtClaims); + return hmac512Service.sign(jwtToken.getPayload()); + } + + /** + * Verify with HMAC512 and check ExpirationTime + * + * @param authToken + * @return true or false + */ + public boolean validateJwtToken(String authToken) { + if(StringUtils.isNotBlank(authToken) && authToken.length() > 20) { + try { + JWTClaimsSet claims = resolve(authToken); + boolean isExpiration = claims.getExpirationTime().after(DateTime.now().toDate()); + boolean isVerify = hmac512Service.verify(authToken); + boolean isValidate = isVerify && isExpiration; + _logger.trace("JWT Validate {} " , isValidate); + _logger.debug("HMAC Verify {} , now {} , ExpirationTime {} , is not Expiration : {}" , + isVerify,DateTime.now().toDate(),claims.getExpirationTime(),isExpiration); + return isValidate; + } catch (ParseException e) { + _logger.error("authToken {}",authToken); + _logger.error("ParseException ",e); + } + } + return false; + } + + public JWTClaimsSet resolve(String authToken) throws ParseException { + SignedJWT signedJWT = SignedJWT.parse(authToken); + _logger.trace("jwt Claims : {}" , signedJWT.getJWTClaimsSet()); + return signedJWT.getJWTClaimsSet(); + } + + public String resolveJWTID(String authToken) throws ParseException { + JWTClaimsSet claims = resolve(authToken); + return claims.getJWTID(); + } } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/AuthRefreshTokenService.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/AuthRefreshTokenService.java index 10ce0fb46..5eab9c60c 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/AuthRefreshTokenService.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/AuthRefreshTokenService.java @@ -26,26 +26,26 @@ import org.springframework.security.core.Authentication; import com.nimbusds.jose.JOSEException; public class AuthRefreshTokenService extends AuthJwtService{ - private static final Logger _logger = LoggerFactory.getLogger(AuthRefreshTokenService.class); - - AuthJwkConfig authJwkConfig; - - public AuthRefreshTokenService(AuthJwkConfig authJwkConfig) throws JOSEException { - this.authJwkConfig = authJwkConfig; - - this.hmac512Service = new Hmac512Service(authJwkConfig.getRefreshSecret()); - } - - /** - * JWT Refresh Token with Authentication - * @param authentication - * @return - */ - public String genRefreshToken(Authentication authentication) { - _logger.trace("generate Refresh JWT Token"); - return genJwt( - authentication, - authJwkConfig.getIssuer(), - authJwkConfig.getRefreshExpires()); - } + private static final Logger _logger = LoggerFactory.getLogger(AuthRefreshTokenService.class); + + AuthJwkConfig authJwkConfig; + + public AuthRefreshTokenService(AuthJwkConfig authJwkConfig) throws JOSEException { + this.authJwkConfig = authJwkConfig; + + this.hmac512Service = new Hmac512Service(authJwkConfig.getRefreshSecret()); + } + + /** + * JWT Refresh Token with Authentication + * @param authentication + * @return + */ + public String genRefreshToken(Authentication authentication) { + _logger.trace("generate Refresh JWT Token"); + return genJwt( + authentication, + authJwkConfig.getIssuer(), + authJwkConfig.getRefreshExpires()); + } } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/AuthTokenService.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/AuthTokenService.java index ad9912d9a..f21703023 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/AuthTokenService.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/AuthTokenService.java @@ -30,112 +30,112 @@ import org.springframework.security.core.Authentication; import com.nimbusds.jose.JOSEException; public class AuthTokenService extends AuthJwtService{ - private static final Logger _logger = LoggerFactory.getLogger(AuthTokenService.class); - - AuthJwkConfig authJwkConfig; - - CongressService congressService; - - MomentaryService momentaryService; - - AuthRefreshTokenService refreshTokenService; - - public AuthTokenService( - AuthJwkConfig authJwkConfig, - CongressService congressService, - MomentaryService momentaryService, - AuthRefreshTokenService refreshTokenService) throws JOSEException { - - this.authJwkConfig = authJwkConfig; - - this.congressService = congressService; - - this.momentaryService = momentaryService; - - this.refreshTokenService = refreshTokenService; - - this.hmac512Service = new Hmac512Service(authJwkConfig.getSecret()); - - } - - /** - * create AuthJwt use Authentication JWT - * @param authentication - * @return AuthJwt - */ - public AuthJwt genAuthJwt(Authentication authentication) { - if(authentication != null) { - String refreshToken = refreshTokenService.genRefreshToken(authentication); - _logger.trace("generate JWT Token"); - String accessToken = genJwt(authentication); - return new AuthJwt( - accessToken, - authentication, - authJwkConfig.getExpires(), - refreshToken); - } - return null; - } - - public String genJwt(Authentication authentication) { - return genJwt( - authentication, - authJwkConfig.getIssuer(), - authJwkConfig.getExpires()); - } - - - /** - * JWT with subject - * @param subject subject - * @return - */ - public String genJwt(String subject) { - return genJwt(subject,authJwkConfig.getIssuer(),authJwkConfig.getExpires()); - } - - /** - * Random JWT - * @return - */ - public String genRandomJwt() { - return genRandomJwt(authJwkConfig.getExpires()); - } - - public String createCongress(Authentication authentication) { - String congress = WebContext.genId(); - String refreshToken = refreshTokenService.genRefreshToken(authentication); - congressService.store( - congress, - new AuthJwt( - genJwt(authentication), - authentication, - authJwkConfig.getExpires(), - refreshToken) - ); - return congress; - } - - public AuthJwt consumeCongress(String congress) { - return congressService.consume(congress); - } - - public boolean validateCaptcha(String state,String captcha) { - try { - String jwtId = resolveJWTID(state); - if(StringUtils.isNotBlank(jwtId) &&StringUtils.isNotBlank(captcha)) { - Object momentaryCaptcha = momentaryService.get("", jwtId); - _logger.debug("captcha : {}, momentary Captcha : {}" ,captcha, momentaryCaptcha); - if (!StringUtils.isBlank(captcha) &&momentaryCaptcha != null && captcha.equals(momentaryCaptcha.toString())) { - momentaryService.remove("", jwtId); - return true; - } - } - } catch (ParseException e) { - _logger.debug("Exception ",e); - } - return false; + private static final Logger _logger = LoggerFactory.getLogger(AuthTokenService.class); + + AuthJwkConfig authJwkConfig; + + CongressService congressService; + + MomentaryService momentaryService; + + AuthRefreshTokenService refreshTokenService; + + public AuthTokenService( + AuthJwkConfig authJwkConfig, + CongressService congressService, + MomentaryService momentaryService, + AuthRefreshTokenService refreshTokenService) throws JOSEException { + + this.authJwkConfig = authJwkConfig; + + this.congressService = congressService; + + this.momentaryService = momentaryService; + + this.refreshTokenService = refreshTokenService; + + this.hmac512Service = new Hmac512Service(authJwkConfig.getSecret()); + } - - + + /** + * create AuthJwt use Authentication JWT + * @param authentication + * @return AuthJwt + */ + public AuthJwt genAuthJwt(Authentication authentication) { + if(authentication != null) { + String refreshToken = refreshTokenService.genRefreshToken(authentication); + _logger.trace("generate JWT Token"); + String accessToken = genJwt(authentication); + return new AuthJwt( + accessToken, + authentication, + authJwkConfig.getExpires(), + refreshToken); + } + return null; + } + + public String genJwt(Authentication authentication) { + return genJwt( + authentication, + authJwkConfig.getIssuer(), + authJwkConfig.getExpires()); + } + + + /** + * JWT with subject + * @param subject subject + * @return + */ + public String genJwt(String subject) { + return genJwt(subject,authJwkConfig.getIssuer(),authJwkConfig.getExpires()); + } + + /** + * Random JWT + * @return + */ + public String genRandomJwt() { + return genRandomJwt(authJwkConfig.getExpires()); + } + + public String createCongress(Authentication authentication) { + String congress = WebContext.genId(); + String refreshToken = refreshTokenService.genRefreshToken(authentication); + congressService.store( + congress, + new AuthJwt( + genJwt(authentication), + authentication, + authJwkConfig.getExpires(), + refreshToken) + ); + return congress; + } + + public AuthJwt consumeCongress(String congress) { + return congressService.consume(congress); + } + + public boolean validateCaptcha(String state,String captcha) { + try { + String jwtId = resolveJWTID(state); + if(StringUtils.isNotBlank(jwtId) &&StringUtils.isNotBlank(captcha)) { + Object momentaryCaptcha = momentaryService.get("", jwtId); + _logger.debug("captcha : {}, momentary Captcha : {}" ,captcha, momentaryCaptcha); + if (!StringUtils.isBlank(captcha) &&momentaryCaptcha != null && captcha.equals(momentaryCaptcha.toString())) { + momentaryService.remove("", jwtId); + return true; + } + } + } catch (ParseException e) { + _logger.debug("Exception ",e); + } + return false; + } + + } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/CongressService.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/CongressService.java index e0a62f50c..16ff74d49 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/CongressService.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/CongressService.java @@ -19,10 +19,10 @@ package org.dromara.maxkey.authn.jwt; public interface CongressService { - public void store(String congress, AuthJwt authJwt); + public void store(String congress, AuthJwt authJwt); - public AuthJwt consume(String congress); - + public AuthJwt consume(String congress); + public AuthJwt remove(String congress); public AuthJwt get(String congress); diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/InMemoryCongressService.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/InMemoryCongressService.java index 7b202da73..945483bec 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/InMemoryCongressService.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/InMemoryCongressService.java @@ -28,38 +28,38 @@ import com.github.benmanes.caffeine.cache.Caffeine; public class InMemoryCongressService implements CongressService{ private static final Logger logger = LoggerFactory.getLogger(InMemoryCongressService.class); - protected static Cache congressStore = - Caffeine.newBuilder() - .expireAfterWrite(3, TimeUnit.MINUTES) - .maximumSize(200000) - .build(); - - public InMemoryCongressService() { + protected static Cache congressStore = + Caffeine.newBuilder() + .expireAfterWrite(3, TimeUnit.MINUTES) + .maximumSize(200000) + .build(); + + public InMemoryCongressService() { super(); } @Override - public void store(String congress, AuthJwt authJwt) { - congressStore.put(congress, authJwt); - } + public void store(String congress, AuthJwt authJwt) { + congressStore.put(congress, authJwt); + } - @Override - public AuthJwt remove(String congress) { - AuthJwt authJwt = congressStore.getIfPresent(congress); - congressStore.invalidate(congress); - return authJwt; - } + @Override + public AuthJwt remove(String congress) { + AuthJwt authJwt = congressStore.getIfPresent(congress); + congressStore.invalidate(congress); + return authJwt; + } @Override public AuthJwt get(String congress) { - return congressStore.getIfPresent(congress); + return congressStore.getIfPresent(congress); } - @Override - public AuthJwt consume(String congress) { - AuthJwt authJwt = congressStore.getIfPresent(congress); - congressStore.invalidate(congress); - return authJwt; - } + @Override + public AuthJwt consume(String congress) { + AuthJwt authJwt = congressStore.getIfPresent(congress); + congressStore.invalidate(congress); + return authJwt; + } } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/RedisCongressService.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/RedisCongressService.java index ca95a67dc..65ba8057d 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/RedisCongressService.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/jwt/RedisCongressService.java @@ -25,47 +25,47 @@ import org.slf4j.LoggerFactory; public class RedisCongressService implements CongressService { private static final Logger logger = LoggerFactory.getLogger(RedisCongressService.class); - - protected int validitySeconds = 60 * 3; //default 3 minutes. - - RedisConnectionFactory connectionFactory; - - public static final String PREFIX = "REDIS:CONGRESS:"; - /** - * @param connectionFactory - */ - public RedisCongressService( - RedisConnectionFactory connectionFactory) { - super(); - this.connectionFactory = connectionFactory; - } - - /** - * - */ - public RedisCongressService() { - - } + + protected int validitySeconds = 60 * 3; //default 3 minutes. + + RedisConnectionFactory connectionFactory; + + public static final String PREFIX = "REDIS:CONGRESS:"; + /** + * @param connectionFactory + */ + public RedisCongressService( + RedisConnectionFactory connectionFactory) { + super(); + this.connectionFactory = connectionFactory; + } + + /** + * + */ + public RedisCongressService() { + + } - public void setConnectionFactory(RedisConnectionFactory connectionFactory) { - this.connectionFactory = connectionFactory; - } + public void setConnectionFactory(RedisConnectionFactory connectionFactory) { + this.connectionFactory = connectionFactory; + } - @Override - public void store(String congress, AuthJwt authJwt) { - RedisConnection conn = connectionFactory.getConnection(); - conn.setexObject(PREFIX + congress, validitySeconds, authJwt); - conn.close(); - } + @Override + public void store(String congress, AuthJwt authJwt) { + RedisConnection conn = connectionFactory.getConnection(); + conn.setexObject(PREFIX + congress, validitySeconds, authJwt); + conn.close(); + } - @Override - public AuthJwt remove(String congress) { - RedisConnection conn=connectionFactory.getConnection(); - AuthJwt authJwt = conn.getObject(PREFIX + congress); - conn.delete(PREFIX+congress); - conn.close(); - return authJwt; - } + @Override + public AuthJwt remove(String congress) { + RedisConnection conn=connectionFactory.getConnection(); + AuthJwt authJwt = conn.getObject(PREFIX + congress); + conn.delete(PREFIX+congress); + conn.close(); + return authJwt; + } @Override public AuthJwt get(String congress) { @@ -75,14 +75,14 @@ public class RedisCongressService implements CongressService { return authJwt; } - @Override - public AuthJwt consume(String congress) { - RedisConnection conn=connectionFactory.getConnection(); - AuthJwt authJwt = conn.getObject(PREFIX + congress); - conn.delete(PREFIX+congress); - conn.close(); - return authJwt; - } + @Override + public AuthJwt consume(String congress) { + RedisConnection conn=connectionFactory.getConnection(); + AuthJwt authJwt = conn.getObject(PREFIX + congress); + conn.delete(PREFIX+congress); + conn.close(); + return authJwt; + } - + } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/listener/SessionListenerAdapter.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/listener/SessionListenerAdapter.java index eee81f283..e2d43e9ad 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/listener/SessionListenerAdapter.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/listener/SessionListenerAdapter.java @@ -30,49 +30,49 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SessionListenerAdapter extends ScheduleAdapter implements Job , Serializable { - static final Logger logger = LoggerFactory.getLogger(SessionListenerAdapter.class); - - private static final long serialVersionUID = 4782358765969474833L; - - transient SessionManager sessionManager; + static final Logger logger = LoggerFactory.getLogger(SessionListenerAdapter.class); + + private static final long serialVersionUID = 4782358765969474833L; + + transient SessionManager sessionManager; - Integer category; - - @Override - public void execute(JobExecutionContext context) throws JobExecutionException { - if(jobStatus == JOBSTATUS.RUNNING) {return;} - init(context); - - logger.debug("running ... " ); + Integer category; + + @Override + public void execute(JobExecutionContext context) throws JobExecutionException { + if(jobStatus == JOBSTATUS.RUNNING) {return;} + init(context); + + logger.debug("running ... " ); jobStatus = JOBSTATUS.RUNNING; try { if(sessionManager != null) { - int sessionCount = 0; - for (HistoryLogin login : sessionManager.querySessions(category)) { - Session session = sessionManager.get(login.getSessionId()); - if(session == null) { - logger.debug("TimeOut user {} session {} Login at {} and at {} ." , - login.getUsername(), - login.getId(), - login.getLoginTime(), - DateUtils.formatDateTime(new Date()) - ); - sessionManager.terminate( - login.getSessionId(), - login.getUserId(), - login.getUsername()); - }else { - logger.debug("user {} session {} Login at {} , Last Access at {} will Expired at {}." , - login.getUsername(), - login.getId(), - session.getStartTimestamp(), - session.getLastAccessTime(), - session.getExpiredTime() - ); - sessionCount ++ ; - } - } - logger.debug("current session count {} ." ,sessionCount); + int sessionCount = 0; + for (HistoryLogin login : sessionManager.querySessions(category)) { + Session session = sessionManager.get(login.getSessionId()); + if(session == null) { + logger.debug("TimeOut user {} session {} Login at {} and at {} ." , + login.getUsername(), + login.getId(), + login.getLoginTime(), + DateUtils.formatDateTime(new Date()) + ); + sessionManager.terminate( + login.getSessionId(), + login.getUserId(), + login.getUsername()); + }else { + logger.debug("user {} session {} Login at {} , Last Access at {} will Expired at {}." , + login.getUsername(), + login.getId(), + session.getStartTimestamp(), + session.getLastAccessTime(), + session.getExpiredTime() + ); + sessionCount ++ ; + } + } + logger.debug("current session count {} ." ,sessionCount); } logger.debug("finished " ); jobStatus = JOBSTATUS.FINISHED; @@ -80,15 +80,15 @@ public class SessionListenerAdapter extends ScheduleAdapter implements Job , S jobStatus = JOBSTATUS.ERROR; logger.error("Exception " ,e); } - - } + + } - @Override - protected void init(JobExecutionContext context){ - super.init(context); - if(sessionManager == null) { - sessionManager = getParameter("sessionManager",SessionManager.class); - category = getParameter("category",Integer.class); + @Override + protected void init(JobExecutionContext context){ + super.init(context); + if(sessionManager == null) { + sessionManager = getParameter("sessionManager",SessionManager.class); + category = getParameter("category",Integer.class); } } } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/Session.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/Session.java index 725b42ac1..de7f0c47b 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/Session.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/Session.java @@ -26,7 +26,7 @@ import org.dromara.maxkey.web.WebContext; import org.springframework.security.core.Authentication; public class Session implements Serializable{ - private static final long serialVersionUID = 9008067569150338296L; + private static final long serialVersionUID = 9008067569150338296L; public static final int MAX_EXPIRY_DURATION = 60 * 5; //default 5 minutes. @@ -65,8 +65,8 @@ public class Session implements Serializable{ } public String getId() { - return id; - } + return id; + } public void setId(String sessionId) { this.id = sessionId; @@ -74,30 +74,30 @@ public class Session implements Serializable{ public LocalDateTime getStartTimestamp() { - return startTimestamp; - } + return startTimestamp; + } - public void setStartTimestamp(LocalDateTime startTimestamp) { - this.startTimestamp = startTimestamp; - } + public void setStartTimestamp(LocalDateTime startTimestamp) { + this.startTimestamp = startTimestamp; + } - public LocalDateTime getLastAccessTime() { - return lastAccessTime; - } + public LocalDateTime getLastAccessTime() { + return lastAccessTime; + } - public void setLastAccessTime(LocalDateTime lastAccessTime) { - this.lastAccessTime = lastAccessTime; - } + public void setLastAccessTime(LocalDateTime lastAccessTime) { + this.lastAccessTime = lastAccessTime; + } - public LocalDateTime getExpiredTime() { - return expiredTime; - } + public LocalDateTime getExpiredTime() { + return expiredTime; + } - public void setExpiredTime(LocalDateTime expiredTime) { - this.expiredTime = expiredTime; - } + public void setExpiredTime(LocalDateTime expiredTime) { + this.expiredTime = expiredTime; + } - public Authentication getAuthentication() { + public Authentication getAuthentication() { return authentication; } @@ -110,25 +110,25 @@ public class Session implements Serializable{ } public Map getVisited() { - return visited; - } + return visited; + } - public void setVisited(Map visited) { - this.visited = visited; - } + public void setVisited(Map visited) { + this.visited = visited; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Session [id="); - builder.append(id); - builder.append(", startTimestamp="); - builder.append(startTimestamp); - builder.append(", lastAccessTime="); - builder.append(lastAccessTime); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Session [id="); + builder.append(id); + builder.append(", startTimestamp="); + builder.append(startTimestamp); + builder.append(", lastAccessTime="); + builder.append(lastAccessTime); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/SessionCategory.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/SessionCategory.java index 0a07d601b..75f4758fa 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/SessionCategory.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/SessionCategory.java @@ -18,13 +18,13 @@ package org.dromara.maxkey.authn.session; public class SessionCategory { - /** - * 认证端 - */ - public static final int SIGN = 1; - - /** - * 管理端 - */ - public static final int MGMT = 5; + /** + * 认证端 + */ + public static final int SIGN = 1; + + /** + * 管理端 + */ + public static final int MGMT = 5; } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/SessionManager.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/SessionManager.java index 6b44aac02..31094a412 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/SessionManager.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/SessionManager.java @@ -24,7 +24,7 @@ import org.dromara.maxkey.entity.history.HistoryLogin; public interface SessionManager { - public void create(String sessionId, Session session); + public void create(String sessionId, Session session); public Session remove(String sessionId); diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/VisitedDto.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/VisitedDto.java index 890c58a2c..36b749ad9 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/VisitedDto.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/VisitedDto.java @@ -24,133 +24,133 @@ import org.dromara.maxkey.entity.apps.AppsCasDetails; public class VisitedDto implements Serializable{ - /** - * - */ - private static final long serialVersionUID = -6694914707659511202L; + /** + * + */ + private static final long serialVersionUID = -6694914707659511202L; - /** - * appId or client id - */ - String appId; - /** - * protocol - */ - String protocol; - /** - * ticket - */ - String ticket; - /** - * token - */ - String token; - - /** - * refreshToken - */ - String refreshToken; - /** - * logoutType - */ - int logoutType; - /** - * logoutUrl - */ - String logoutUrl; - - - public VisitedDto(AppsCasDetails app,String ticket ) { - this.appId = app.getId(); - this.protocol = app.getProtocol(); - this.logoutType = app.getLogoutType(); - this.logoutUrl = app.getLogoutUrl(); - this.ticket = ticket; - } - - public VisitedDto(Apps app,String ticket ) { - this.appId = app.getId(); - this.protocol = app.getProtocol(); - this.logoutType = app.getLogoutType(); - this.logoutUrl = app.getLogoutUrl(); - this.ticket = ticket; - } + /** + * appId or client id + */ + String appId; + /** + * protocol + */ + String protocol; + /** + * ticket + */ + String ticket; + /** + * token + */ + String token; + + /** + * refreshToken + */ + String refreshToken; + /** + * logoutType + */ + int logoutType; + /** + * logoutUrl + */ + String logoutUrl; + + + public VisitedDto(AppsCasDetails app,String ticket ) { + this.appId = app.getId(); + this.protocol = app.getProtocol(); + this.logoutType = app.getLogoutType(); + this.logoutUrl = app.getLogoutUrl(); + this.ticket = ticket; + } + + public VisitedDto(Apps app,String ticket ) { + this.appId = app.getId(); + this.protocol = app.getProtocol(); + this.logoutType = app.getLogoutType(); + this.logoutUrl = app.getLogoutUrl(); + this.ticket = ticket; + } - public String getAppId() { - return appId; - } + public String getAppId() { + return appId; + } - public void setAppId(String appId) { - this.appId = appId; - } + public void setAppId(String appId) { + this.appId = appId; + } - public String getProtocol() { - return protocol; - } + public String getProtocol() { + return protocol; + } - public void setProtocol(String protocol) { - this.protocol = protocol; - } + public void setProtocol(String protocol) { + this.protocol = protocol; + } - public String getTicket() { - return ticket; - } + public String getTicket() { + return ticket; + } - public void setTicket(String ticket) { - this.ticket = ticket; - } + public void setTicket(String ticket) { + this.ticket = ticket; + } - public String getToken() { - return token; - } + public String getToken() { + return token; + } - public void setToken(String token) { - this.token = token; - } + public void setToken(String token) { + this.token = token; + } - public String getRefreshToken() { - return refreshToken; - } + public String getRefreshToken() { + return refreshToken; + } - public void setRefreshToken(String refreshToken) { - this.refreshToken = refreshToken; - } + public void setRefreshToken(String refreshToken) { + this.refreshToken = refreshToken; + } - public int getLogoutType() { - return logoutType; - } + public int getLogoutType() { + return logoutType; + } - public void setLogoutType(int logoutType) { - this.logoutType = logoutType; - } + public void setLogoutType(int logoutType) { + this.logoutType = logoutType; + } - public String getLogoutUrl() { - return logoutUrl; - } + public String getLogoutUrl() { + return logoutUrl; + } - public void setLogoutUrl(String logoutUrl) { - this.logoutUrl = logoutUrl; - } + public void setLogoutUrl(String logoutUrl) { + this.logoutUrl = logoutUrl; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("VisitedDto [appId="); - builder.append(appId); - builder.append(", protocol="); - builder.append(protocol); - builder.append(", ticket="); - builder.append(ticket); - builder.append(", token="); - builder.append(token); - builder.append(", refreshToken="); - builder.append(refreshToken); - builder.append(", logoutType="); - builder.append(logoutType); - builder.append(", logoutUrl="); - builder.append(logoutUrl); - builder.append("]"); - return builder.toString(); - } - + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("VisitedDto [appId="); + builder.append(appId); + builder.append(", protocol="); + builder.append(protocol); + builder.append(", ticket="); + builder.append(ticket); + builder.append(", token="); + builder.append(token); + builder.append(", refreshToken="); + builder.append(refreshToken); + builder.append(", logoutType="); + builder.append(logoutType); + builder.append(", logoutUrl="); + builder.append(logoutUrl); + builder.append("]"); + return builder.toString(); + } + } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/impl/InMemorySessionManager.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/impl/InMemorySessionManager.java index 4179df6c0..5fdafc798 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/impl/InMemorySessionManager.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/impl/InMemorySessionManager.java @@ -35,14 +35,14 @@ import com.github.benmanes.caffeine.cache.Caffeine; public class InMemorySessionManager implements SessionManager{ private static final Logger _logger = LoggerFactory.getLogger(InMemorySessionManager.class); - static final long CACHE_MAXIMUM_SIZE = 2000000; - protected int validitySeconds = 60 * 30; //default 30 minutes. + static final long CACHE_MAXIMUM_SIZE = 2000000; + protected int validitySeconds = 60 * 30; //default 30 minutes. - Cache sessionStore; - - Cache sessionTwoFactorStore; - - public InMemorySessionManager(int validitySeconds) { + Cache sessionStore; + + Cache sessionTwoFactorStore; + + public InMemorySessionManager(int validitySeconds) { super(); this.validitySeconds = validitySeconds; if(validitySeconds > 0) { @@ -52,30 +52,30 @@ public class InMemorySessionManager implements SessionManager{ .maximumSize(CACHE_MAXIMUM_SIZE) .build(); }else { - sessionStore = Caffeine.newBuilder() - .expireAfterWrite(10, TimeUnit.MINUTES) - .maximumSize(CACHE_MAXIMUM_SIZE) - .build(); + sessionStore = Caffeine.newBuilder() + .expireAfterWrite(10, TimeUnit.MINUTES) + .maximumSize(CACHE_MAXIMUM_SIZE) + .build(); } sessionTwoFactorStore = Caffeine.newBuilder() - .expireAfterWrite(10, TimeUnit.MINUTES) - .maximumSize(CACHE_MAXIMUM_SIZE) - .build(); + .expireAfterWrite(10, TimeUnit.MINUTES) + .maximumSize(CACHE_MAXIMUM_SIZE) + .build(); } @Override - public void create(String sessionId, Session session) { - session.setExpiredTime(session.getLastAccessTime().plusSeconds(validitySeconds)); - sessionStore.put(sessionId, session); - } + public void create(String sessionId, Session session) { + session.setExpiredTime(session.getLastAccessTime().plusSeconds(validitySeconds)); + sessionStore.put(sessionId, session); + } - @Override - public Session remove(String sessionId) { - Session session = sessionStore.getIfPresent(sessionId); - sessionStore.invalidate(sessionId); - return session; - } + @Override + public Session remove(String sessionId) { + Session session = sessionStore.getIfPresent(sessionId); + sessionStore.invalidate(sessionId); + return session; + } @Override public Session get(String sessionId) { @@ -87,10 +87,10 @@ public class InMemorySessionManager implements SessionManager{ public Session refresh(String sessionId,LocalDateTime refreshTime) { Session session = get(sessionId); if(session != null) { - _logger.debug("refresh session Id {} at refreshTime {}",sessionId,refreshTime); - session.setLastAccessTime(refreshTime); - //put new session - create(sessionId , session); + _logger.debug("refresh session Id {} at refreshTime {}",sessionId,refreshTime); + session.setLastAccessTime(refreshTime); + //put new session + create(sessionId , session); } return session; } @@ -100,60 +100,60 @@ public class InMemorySessionManager implements SessionManager{ Session session = get(sessionId); if(session != null) { - LocalDateTime currentTime = LocalDateTime.now(); - _logger.debug("refresh session Id {} at time {}",sessionId,currentTime); - session.setLastAccessTime(currentTime); - //sessionId then renew one - create(sessionId , session); + LocalDateTime currentTime = LocalDateTime.now(); + _logger.debug("refresh session Id {} at time {}",sessionId,currentTime); + session.setLastAccessTime(currentTime); + //sessionId then renew one + create(sessionId , session); } return session; } @Override - public int getValiditySeconds() { - return validitySeconds; - } + public int getValiditySeconds() { + return validitySeconds; + } - @Override - public List querySessions(Integer category) { - // not need implement - return null; - } + @Override + public List querySessions(Integer category) { + // not need implement + return null; + } - @Override - public void terminate(String sessionId, String userId, String username) { - // not need implement - } + @Override + public void terminate(String sessionId, String userId, String username) { + // not need implement + } - @Override - public void visited(String sessionId, VisitedDto visited) { - Session session = this.get(sessionId); - if(session != null) { - //set token or ticket to Visited , bind user session - session.visited(visited); - //override the session - this.create(sessionId, session); - _logger.debug("session {} store visited {} ." , sessionId , visited); - } - } - - @Override - public void createTwoFactor(String sessionId, Session session) { - session.setExpiredTime(session.getLastAccessTime().plusSeconds(validitySeconds)); - sessionTwoFactorStore.put(sessionId, session); - } + @Override + public void visited(String sessionId, VisitedDto visited) { + Session session = this.get(sessionId); + if(session != null) { + //set token or ticket to Visited , bind user session + session.visited(visited); + //override the session + this.create(sessionId, session); + _logger.debug("session {} store visited {} ." , sessionId , visited); + } + } + + @Override + public void createTwoFactor(String sessionId, Session session) { + session.setExpiredTime(session.getLastAccessTime().plusSeconds(validitySeconds)); + sessionTwoFactorStore.put(sessionId, session); + } - @Override - public Session removeTwoFactor(String sessionId) { - Session session = sessionTwoFactorStore.getIfPresent(sessionId); - sessionTwoFactorStore.invalidate(sessionId); - return session; - } + @Override + public Session removeTwoFactor(String sessionId) { + Session session = sessionTwoFactorStore.getIfPresent(sessionId); + sessionTwoFactorStore.invalidate(sessionId); + return session; + } - @Override - public Session getTwoFactor(String sessionId) { - Session session = sessionTwoFactorStore.getIfPresent(sessionId); - return session; - } + @Override + public Session getTwoFactor(String sessionId) { + Session session = sessionTwoFactorStore.getIfPresent(sessionId); + return session; + } } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/impl/RedisSessionManager.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/impl/RedisSessionManager.java index 6245bcf28..c7eeec99b 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/impl/RedisSessionManager.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/impl/RedisSessionManager.java @@ -32,65 +32,65 @@ import org.slf4j.LoggerFactory; public class RedisSessionManager implements SessionManager { private static final Logger _logger = LoggerFactory.getLogger(RedisSessionManager.class); - + protected int validitySeconds = 60 * 30; //default 30 minutes. - int twoFactorValidity = 10 * 60; //default 10 minutes. + int twoFactorValidity = 10 * 60; //default 10 minutes. - RedisConnectionFactory connectionFactory; - - public static final String PREFIX = "MXK_SESSION_"; - - public static final String PREFIX_TWOFACTOR = "mxk:session:twofactor:%s"; - - - public String getKey(String sessionId) { - return PREFIX + sessionId; - } - - /** - * @param connectionFactory - */ - public RedisSessionManager( - RedisConnectionFactory connectionFactory, - int validitySeconds) { - super(); - this.connectionFactory = connectionFactory; - this.validitySeconds = validitySeconds; - } - - /** - * - */ - public RedisSessionManager() { - - } + RedisConnectionFactory connectionFactory; + + public static final String PREFIX = "MXK_SESSION_"; + + public static final String PREFIX_TWOFACTOR = "mxk:session:twofactor:%s"; + + + public String getKey(String sessionId) { + return PREFIX + sessionId; + } + + /** + * @param connectionFactory + */ + public RedisSessionManager( + RedisConnectionFactory connectionFactory, + int validitySeconds) { + super(); + this.connectionFactory = connectionFactory; + this.validitySeconds = validitySeconds; + } + + /** + * + */ + public RedisSessionManager() { + + } - public void setConnectionFactory(RedisConnectionFactory connectionFactory) { - this.connectionFactory = connectionFactory; - } + public void setConnectionFactory(RedisConnectionFactory connectionFactory) { + this.connectionFactory = connectionFactory; + } - @Override - public void create(String sessionId, Session session) { - _logger.debug("store session key {} .",sessionId); - session.setExpiredTime(session.getLastAccessTime().plusSeconds(validitySeconds)); - RedisConnection conn = connectionFactory.getConnection(); - _logger.trace("store session {} ...",sessionId); - conn.setexObject( getKey(sessionId), validitySeconds, session); - _logger.debug("store session {} successful .",sessionId); - _logger.trace("close conn ..."); - conn.close(); - _logger.trace("close conn successful ."); - } + @Override + public void create(String sessionId, Session session) { + _logger.debug("store session key {} .",sessionId); + session.setExpiredTime(session.getLastAccessTime().plusSeconds(validitySeconds)); + RedisConnection conn = connectionFactory.getConnection(); + _logger.trace("store session {} ...",sessionId); + conn.setexObject( getKey(sessionId), validitySeconds, session); + _logger.debug("store session {} successful .",sessionId); + _logger.trace("close conn ..."); + conn.close(); + _logger.trace("close conn successful ."); + } - @Override - public Session remove(String sessionId) { - RedisConnection conn=connectionFactory.getConnection(); - Session ticket = conn.getObject(getKey(sessionId)); - conn.delete(getKey(sessionId)); - conn.close(); - return ticket; - } + @Override + public Session remove(String sessionId) { + RedisConnection conn=connectionFactory.getConnection(); + Session ticket = conn.getObject(getKey(sessionId)); + conn.delete(getKey(sessionId)); + conn.close(); + return ticket; + } @Override public Session get(String sessionId) { @@ -102,20 +102,20 @@ public class RedisSessionManager implements SessionManager { @Override public int getValiditySeconds() { - return validitySeconds; - } + return validitySeconds; + } - public void setValiditySeconds(int validitySeconds) { - this.validitySeconds = validitySeconds; - } + public void setValiditySeconds(int validitySeconds) { + this.validitySeconds = validitySeconds; + } - @Override + @Override public Session refresh(String sessionId,LocalDateTime refreshTime) { Session session = get(sessionId); if(session != null) { - _logger.debug("refresh session Id {} at {}",sessionId,refreshTime); - session.setLastAccessTime(refreshTime); - create(sessionId , session); + _logger.debug("refresh session Id {} at {}",sessionId,refreshTime); + session.setLastAccessTime(refreshTime); + create(sessionId , session); } return session; } @@ -124,65 +124,65 @@ public class RedisSessionManager implements SessionManager { public Session refresh(String sessionId) { Session session = get(sessionId); if(session != null) { - LocalDateTime currentTime = LocalDateTime.now(); - _logger.debug("refresh session Id {} at time {}",sessionId,currentTime); - session.setLastAccessTime(currentTime); - create(sessionId , session); + LocalDateTime currentTime = LocalDateTime.now(); + _logger.debug("refresh session Id {} at time {}",sessionId,currentTime); + session.setLastAccessTime(currentTime); + create(sessionId , session); } return session; } - @Override - public List querySessions(Integer category) { - // not need implement - return null; - } + @Override + public List querySessions(Integer category) { + // not need implement + return null; + } - @Override - public void terminate(String sessionId, String userId, String username) { - // not need implement - } + @Override + public void terminate(String sessionId, String userId, String username) { + // not need implement + } - @Override - public void visited(String sessionId, VisitedDto visited) { - Session session = this.get(sessionId); - if(session != null) { - //set token or ticket to Visited , bind user session - session.visited(visited); - //override the session - this.create(sessionId, session); - _logger.debug("session {} store visited {} ." , sessionId , visited); - } - } - - public String formatTwoFactorKey(String sessionId) { - return PREFIX_TWOFACTOR.formatted(sessionId) ; - } - - @Override - public void createTwoFactor(String sessionId, Session session) { - session.setExpiredTime(session.getLastAccessTime().plusSeconds(validitySeconds)); - RedisConnection conn = connectionFactory.getConnection(); - conn.setexObject( formatTwoFactorKey(sessionId), twoFactorValidity, session); - conn.close(); - - } + @Override + public void visited(String sessionId, VisitedDto visited) { + Session session = this.get(sessionId); + if(session != null) { + //set token or ticket to Visited , bind user session + session.visited(visited); + //override the session + this.create(sessionId, session); + _logger.debug("session {} store visited {} ." , sessionId , visited); + } + } + + public String formatTwoFactorKey(String sessionId) { + return PREFIX_TWOFACTOR.formatted(sessionId) ; + } + + @Override + public void createTwoFactor(String sessionId, Session session) { + session.setExpiredTime(session.getLastAccessTime().plusSeconds(validitySeconds)); + RedisConnection conn = connectionFactory.getConnection(); + conn.setexObject( formatTwoFactorKey(sessionId), twoFactorValidity, session); + conn.close(); + + } - @Override - public Session removeTwoFactor(String sessionId) { - RedisConnection conn = connectionFactory.getConnection(); - Session ticket = conn.getObject(formatTwoFactorKey(sessionId)); - conn.delete(formatTwoFactorKey(sessionId)); - conn.close(); - return ticket; - } + @Override + public Session removeTwoFactor(String sessionId) { + RedisConnection conn = connectionFactory.getConnection(); + Session ticket = conn.getObject(formatTwoFactorKey(sessionId)); + conn.delete(formatTwoFactorKey(sessionId)); + conn.close(); + return ticket; + } - @Override - public Session getTwoFactor(String sessionId) { - RedisConnection conn = connectionFactory.getConnection(); + @Override + public Session getTwoFactor(String sessionId) { + RedisConnection conn = connectionFactory.getConnection(); Session session = conn.getObject(formatTwoFactorKey(sessionId)); conn.close(); return session; - } - + } + } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/impl/SessionManagerImpl.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/impl/SessionManagerImpl.java index cad5252de..7f46e3077 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/impl/SessionManagerImpl.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/session/impl/SessionManagerImpl.java @@ -46,122 +46,122 @@ import org.springframework.jdbc.core.RowMapper; * */ public class SessionManagerImpl implements SessionManager{ - private static final Logger _logger = LoggerFactory.getLogger(SessionManagerImpl.class); - - private static final String DEFAULT_DEFAULT_SELECT_STATEMENT = - "select id,sessionid,userId,username,displayname,logintime from mxk_history_login where sessionstatus = 1"; - + private static final Logger _logger = LoggerFactory.getLogger(SessionManagerImpl.class); + + private static final String DEFAULT_DEFAULT_SELECT_STATEMENT = + "select id,sessionid,userId,username,displayname,logintime from mxk_history_login where sessionstatus = 1"; + private static final String LOGOUT_USERINFO_UPDATE_STATEMENT = - "update mxk_userinfo set lastlogofftime = ? , online = " + UserInfo.ONLINE.OFFLINE + " where id = ?"; - + "update mxk_userinfo set lastlogofftime = ? , online = " + UserInfo.ONLINE.OFFLINE + " where id = ?"; + private static final String HISTORY_LOGOUT_UPDATE_STATEMENT = - "update mxk_history_login set logouttime = ? ,sessionstatus = 7 where sessionid = ?"; + "update mxk_history_login set logouttime = ? ,sessionstatus = 7 where sessionid = ?"; private static final String NO_SESSION_UPDATE_STATEMENT = - "update mxk_history_login set sessionstatus = 7 where sessionstatus = 1 and (sessionid is null or sessionid = '')"; + "update mxk_history_login set sessionstatus = 7 where sessionstatus = 1 and (sessionid is null or sessionid = '')"; private JdbcTemplate jdbcTemplate; - private InMemorySessionManager inMemorySessionManager; - - private RedisSessionManager redisSessionManager; - - private boolean isRedis = false; - - private int validitySeconds ; - - public SessionManagerImpl(int persistence, - JdbcTemplate jdbcTemplate, - RedisConnectionFactory redisConnFactory, - int validitySeconds) { - this.validitySeconds = validitySeconds; - this.jdbcTemplate = jdbcTemplate; - this.inMemorySessionManager = - new InMemorySessionManager(validitySeconds); - _logger.debug("InMemorySessionManager"); - if (persistence == ConstsPersistence.REDIS) { - isRedis = true; - this.redisSessionManager = - new RedisSessionManager(redisConnFactory,validitySeconds); - _logger.debug("RedisSessionManager"); - } - } + private InMemorySessionManager inMemorySessionManager; + + private RedisSessionManager redisSessionManager; + + private boolean isRedis = false; + + private int validitySeconds ; + + public SessionManagerImpl(int persistence, + JdbcTemplate jdbcTemplate, + RedisConnectionFactory redisConnFactory, + int validitySeconds) { + this.validitySeconds = validitySeconds; + this.jdbcTemplate = jdbcTemplate; + this.inMemorySessionManager = + new InMemorySessionManager(validitySeconds); + _logger.debug("InMemorySessionManager"); + if (persistence == ConstsPersistence.REDIS) { + isRedis = true; + this.redisSessionManager = + new RedisSessionManager(redisConnFactory,validitySeconds); + _logger.debug("RedisSessionManager"); + } + } - @Override - public void create(String sessionId, Session session) { - inMemorySessionManager.create(sessionId, session); - if(isRedis) { - redisSessionManager.create(sessionId, session); - } - } + @Override + public void create(String sessionId, Session session) { + inMemorySessionManager.create(sessionId, session); + if(isRedis) { + redisSessionManager.create(sessionId, session); + } + } - @Override - public Session remove(String sessionId) { - Session session = inMemorySessionManager.remove(sessionId); - if(isRedis) { - session = redisSessionManager.remove(sessionId); - } - return session; - } + @Override + public Session remove(String sessionId) { + Session session = inMemorySessionManager.remove(sessionId); + if(isRedis) { + session = redisSessionManager.remove(sessionId); + } + return session; + } - @Override - public Session get(String sessionId) { - Session session = inMemorySessionManager.get(sessionId); - if(session == null && isRedis) { - session = redisSessionManager.get(sessionId); - } - return session; - } + @Override + public Session get(String sessionId) { + Session session = inMemorySessionManager.get(sessionId); + if(session == null && isRedis) { + session = redisSessionManager.get(sessionId); + } + return session; + } - @Override - public Session refresh(String sessionId, LocalDateTime refreshTime) { - Session session = null; - if(isRedis) { - session = redisSessionManager.refresh(sessionId,refreshTime); - //renew one in Memory - inMemorySessionManager.create(sessionId, session); - }else { - session = inMemorySessionManager.refresh(sessionId,refreshTime); - } - return session; - } + @Override + public Session refresh(String sessionId, LocalDateTime refreshTime) { + Session session = null; + if(isRedis) { + session = redisSessionManager.refresh(sessionId,refreshTime); + //renew one in Memory + inMemorySessionManager.create(sessionId, session); + }else { + session = inMemorySessionManager.refresh(sessionId,refreshTime); + } + return session; + } - @Override - public Session refresh(String sessionId) { - Session session = null; - if(isRedis) { - session = redisSessionManager.refresh(sessionId); - //renew one - inMemorySessionManager.remove(sessionId); - inMemorySessionManager.create(sessionId, session); - }else { - session = inMemorySessionManager.refresh(sessionId); - } - - return session; - } + @Override + public Session refresh(String sessionId) { + Session session = null; + if(isRedis) { + session = redisSessionManager.refresh(sessionId); + //renew one + inMemorySessionManager.remove(sessionId); + inMemorySessionManager.create(sessionId, session); + }else { + session = inMemorySessionManager.refresh(sessionId); + } + + return session; + } - @Override - public List querySessions(Integer category) { - //clear session id is null - jdbcTemplate.execute(NO_SESSION_UPDATE_STATEMENT); - String sessionSql = DEFAULT_DEFAULT_SELECT_STATEMENT; - if(!isRedis) { - sessionSql = sessionSql + " and category = " + category; - } - _logger.trace("sessionSql {} " ,sessionSql); - //query on line session - List listSessions = jdbcTemplate.query( - sessionSql, - new OnlineTicketRowMapper()); - return listSessions; - } + @Override + public List querySessions(Integer category) { + //clear session id is null + jdbcTemplate.execute(NO_SESSION_UPDATE_STATEMENT); + String sessionSql = DEFAULT_DEFAULT_SELECT_STATEMENT; + if(!isRedis) { + sessionSql = sessionSql + " and category = " + category; + } + _logger.trace("sessionSql {} " ,sessionSql); + //query on line session + List listSessions = jdbcTemplate.query( + sessionSql, + new OnlineTicketRowMapper()); + return listSessions; + } private void profileLastLogoffTime(String userId,String lastLogoffTime) { _logger.trace("userId {} , lastlogofftime {}" ,userId, lastLogoffTime); - jdbcTemplate.update( LOGOUT_USERINFO_UPDATE_STATEMENT, - new Object[] { lastLogoffTime, userId }, - new int[] { Types.TIMESTAMP, Types.VARCHAR }); + jdbcTemplate.update( LOGOUT_USERINFO_UPDATE_STATEMENT, + new Object[] { lastLogoffTime, userId }, + new int[] { Types.TIMESTAMP, Types.VARCHAR }); } private void sessionLogoff(String sessionId,String lastLogoffTime) { @@ -172,70 +172,70 @@ public class SessionManagerImpl implements SessionManager{ } @Override - public void terminate(String sessionId, String userId, String username) { - String lastLogoffTime = DateUtils.formatDateTime(new Date()); - _logger.trace("{} user {} terminate session {} ." ,lastLogoffTime,username, sessionId); - this.profileLastLogoffTime(userId, lastLogoffTime); - this.sessionLogoff(sessionId, lastLogoffTime); - this.remove(sessionId); - } - + public void terminate(String sessionId, String userId, String username) { + String lastLogoffTime = DateUtils.formatDateTime(new Date()); + _logger.trace("{} user {} terminate session {} ." ,lastLogoffTime,username, sessionId); + this.profileLastLogoffTime(userId, lastLogoffTime); + this.sessionLogoff(sessionId, lastLogoffTime); + this.remove(sessionId); + } + @Override - public int getValiditySeconds() { - return validitySeconds; - } - - private final class OnlineTicketRowMapper implements RowMapper { - @Override - public HistoryLogin mapRow(ResultSet rs, int rowNum) - throws SQLException { - HistoryLogin history=new HistoryLogin(); - history.setId(rs.getString(1)); - history.setSessionId(rs.getString(2)); - history.setUserId(rs.getString(3)); - history.setUsername(rs.getString(4)); - history.setDisplayName(rs.getString(5)); - history.setLoginTime(rs.getTimestamp(6)); - return history; - } - } + public int getValiditySeconds() { + return validitySeconds; + } + + private final class OnlineTicketRowMapper implements RowMapper { + @Override + public HistoryLogin mapRow(ResultSet rs, int rowNum) + throws SQLException { + HistoryLogin history=new HistoryLogin(); + history.setId(rs.getString(1)); + history.setSessionId(rs.getString(2)); + history.setUserId(rs.getString(3)); + history.setUsername(rs.getString(4)); + history.setDisplayName(rs.getString(5)); + history.setLoginTime(rs.getTimestamp(6)); + return history; + } + } - @Override - public void visited(String sessionId, VisitedDto visited) { + @Override + public void visited(String sessionId, VisitedDto visited) { inMemorySessionManager.visited(sessionId,visited); - if(isRedis) { - redisSessionManager.visited(sessionId,visited); - } - } - - @Override - public void createTwoFactor(String sessionId, Session session) { - if(isRedis) { - redisSessionManager.createTwoFactor(sessionId, session); - }else { - inMemorySessionManager.createTwoFactor(sessionId, session); - } - } + if(isRedis) { + redisSessionManager.visited(sessionId,visited); + } + } + + @Override + public void createTwoFactor(String sessionId, Session session) { + if(isRedis) { + redisSessionManager.createTwoFactor(sessionId, session); + }else { + inMemorySessionManager.createTwoFactor(sessionId, session); + } + } - @Override - public Session removeTwoFactor(String sessionId) { - Session session = null; - if(isRedis) { - session = redisSessionManager.removeTwoFactor(sessionId); - }else { - session = inMemorySessionManager.removeTwoFactor(sessionId); - } - return session; - } + @Override + public Session removeTwoFactor(String sessionId) { + Session session = null; + if(isRedis) { + session = redisSessionManager.removeTwoFactor(sessionId); + }else { + session = inMemorySessionManager.removeTwoFactor(sessionId); + } + return session; + } - @Override - public Session getTwoFactor(String sessionId) { - Session session = null; - if(isRedis) { - session = redisSessionManager.getTwoFactor(sessionId); - }else { - session = inMemorySessionManager.getTwoFactor(sessionId); - } - return session; - } + @Override + public Session getTwoFactor(String sessionId) { + Session session = null; + if(isRedis) { + session = redisSessionManager.getTwoFactor(sessionId); + }else { + session = inMemorySessionManager.getTwoFactor(sessionId); + } + return session; + } } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/AuthTokenRefreshPoint.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/AuthTokenRefreshPoint.java index 0156102b5..405a3beb1 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/AuthTokenRefreshPoint.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/AuthTokenRefreshPoint.java @@ -40,47 +40,47 @@ import jakarta.servlet.http.HttpServletRequest; @RestController @RequestMapping(value = "/auth") public class AuthTokenRefreshPoint { - private static final Logger _logger = LoggerFactory.getLogger(AuthTokenRefreshPoint.class); - - @Autowired - AuthTokenService authTokenService; - - @Autowired - AuthRefreshTokenService refreshTokenService; - - @Autowired - SessionManager sessionManager; - - @GetMapping(value={"/token/refresh"}) - public ResponseEntity refreshGet(HttpServletRequest request, - @RequestParam(name = "refresh_token", required = false) String refreshToken) { - return refresh(request,refreshToken); - } - - @PostMapping(value={"/token/refresh"}) - public ResponseEntity refresh(HttpServletRequest request, - @RequestParam(name = "refresh_token", required = false) String refreshToken) { - _logger.debug("try to refresh token " ); - _logger.trace("refresh token {} " , refreshToken); - if(_logger.isTraceEnabled()) {WebContext.printRequest(request);} - try { - if(refreshTokenService.validateJwtToken(refreshToken)) { - String sessionId = refreshTokenService.resolveJWTID(refreshToken); - _logger.trace("Try to refresh sessionId [{}]" , sessionId); - Session session = sessionManager.refresh(sessionId); - if(session != null) { - AuthJwt authJwt = authTokenService.genAuthJwt(session.getAuthentication()); - _logger.trace("Grant new token {}" , authJwt); - return new Message(authJwt).buildResponse(); - }else { - _logger.debug("Session is timeout , sessionId [{}]" , sessionId); - } - }else { - _logger.debug("refresh token is not validate ."); - } - }catch(Exception e) { - _logger.error("Refresh Exception !",e); - } - return new ResponseEntity<>("Refresh Token Fail !", HttpStatus.UNAUTHORIZED); - } + private static final Logger _logger = LoggerFactory.getLogger(AuthTokenRefreshPoint.class); + + @Autowired + AuthTokenService authTokenService; + + @Autowired + AuthRefreshTokenService refreshTokenService; + + @Autowired + SessionManager sessionManager; + + @GetMapping(value={"/token/refresh"}) + public ResponseEntity refreshGet(HttpServletRequest request, + @RequestParam(name = "refresh_token", required = false) String refreshToken) { + return refresh(request,refreshToken); + } + + @PostMapping(value={"/token/refresh"}) + public ResponseEntity refresh(HttpServletRequest request, + @RequestParam(name = "refresh_token", required = false) String refreshToken) { + _logger.debug("try to refresh token " ); + _logger.trace("refresh token {} " , refreshToken); + if(_logger.isTraceEnabled()) {WebContext.printRequest(request);} + try { + if(refreshTokenService.validateJwtToken(refreshToken)) { + String sessionId = refreshTokenService.resolveJWTID(refreshToken); + _logger.trace("Try to refresh sessionId [{}]" , sessionId); + Session session = sessionManager.refresh(sessionId); + if(session != null) { + AuthJwt authJwt = authTokenService.genAuthJwt(session.getAuthentication()); + _logger.trace("Grant new token {}" , authJwt); + return new Message(authJwt).buildResponse(); + }else { + _logger.debug("Session is timeout , sessionId [{}]" , sessionId); + } + }else { + _logger.debug("refresh token is not validate ."); + } + }catch(Exception e) { + _logger.error("Refresh Exception !",e); + } + return new ResponseEntity<>("Refresh Token Fail !", HttpStatus.UNAUTHORIZED); + } } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/AuthorizationUtils.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/AuthorizationUtils.java index c622d2050..d97008f1b 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/AuthorizationUtils.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/AuthorizationUtils.java @@ -37,125 +37,125 @@ import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; public class AuthorizationUtils { - private static final Logger _logger = LoggerFactory.getLogger(AuthorizationUtils.class); + private static final Logger _logger = LoggerFactory.getLogger(AuthorizationUtils.class); - public static final class BEARERTYPE{ + public static final class BEARERTYPE{ - public static final String CONGRESS = "congress"; + public static final String CONGRESS = "congress"; - public static final String AUTHORIZATION = "Authorization"; - } + public static final String AUTHORIZATION = "Authorization"; + } - public static void authenticateWithCookie( - HttpServletRequest request, - AuthTokenService authTokenService, - SessionManager sessionManager - ) throws ParseException{ - Cookie authCookie = WebContext.getCookie(request, BEARERTYPE.CONGRESS); - if(authCookie != null ) { - String authorization = authCookie.getValue(); - _logger.trace("Try congress authenticate ."); - doJwtAuthenticate(BEARERTYPE.CONGRESS,authorization,authTokenService,sessionManager); - }else { - _logger.debug("cookie is null , clear authentication ."); - clearAuthentication(); - } - } + public static void authenticateWithCookie( + HttpServletRequest request, + AuthTokenService authTokenService, + SessionManager sessionManager + ) throws ParseException{ + Cookie authCookie = WebContext.getCookie(request, BEARERTYPE.CONGRESS); + if(authCookie != null ) { + String authorization = authCookie.getValue(); + _logger.trace("Try congress authenticate ."); + doJwtAuthenticate(BEARERTYPE.CONGRESS,authorization,authTokenService,sessionManager); + }else { + _logger.debug("cookie is null , clear authentication ."); + clearAuthentication(); + } + } - public static void authenticate( - HttpServletRequest request, - AuthTokenService authTokenService, - SessionManager sessionManager - ) throws ParseException{ - String authorization = AuthorizationHeaderUtils.resolveBearer(request); - if(authorization != null ) { - _logger.trace("Try Authorization authenticate ."); - doJwtAuthenticate(BEARERTYPE.AUTHORIZATION,authorization,authTokenService,sessionManager); - } + public static void authenticate( + HttpServletRequest request, + AuthTokenService authTokenService, + SessionManager sessionManager + ) throws ParseException{ + String authorization = AuthorizationHeaderUtils.resolveBearer(request); + if(authorization != null ) { + _logger.trace("Try Authorization authenticate ."); + doJwtAuthenticate(BEARERTYPE.AUTHORIZATION,authorization,authTokenService,sessionManager); + } - } + } - public static void doJwtAuthenticate( - String bearerType, - String authorization, - AuthTokenService authTokenService, - SessionManager sessionManager) throws ParseException { - if(authTokenService.validateJwtToken(authorization)) { - if(isNotAuthenticated()) { - String sessionId = authTokenService.resolveJWTID(authorization); - Session session = sessionManager.get(sessionId); - if(session != null) { - setAuthentication(session.getAuthentication()); - _logger.debug("{} Automatic authenticated .",bearerType); - }else { - //time out - _logger.debug("Session timeout ."); - clearAuthentication(); - } - } - }else { - //token invalidate - _logger.debug("Token invalidate ."); - clearAuthentication(); - } - } + public static void doJwtAuthenticate( + String bearerType, + String authorization, + AuthTokenService authTokenService, + SessionManager sessionManager) throws ParseException { + if(authTokenService.validateJwtToken(authorization)) { + if(isNotAuthenticated()) { + String sessionId = authTokenService.resolveJWTID(authorization); + Session session = sessionManager.get(sessionId); + if(session != null) { + setAuthentication(session.getAuthentication()); + _logger.debug("{} Automatic authenticated .",bearerType); + }else { + //time out + _logger.debug("Session timeout ."); + clearAuthentication(); + } + } + }else { + //token invalidate + _logger.debug("Token invalidate ."); + clearAuthentication(); + } + } - public static Session getSession(SessionManager sessionManager, String authorization) throws ParseException { - _logger.debug("get session by authorization {}", authorization); - SignedJWT signedJWT = SignedJWT.parse(authorization); - String sessionId = signedJWT.getJWTClaimsSet().getJWTID(); - _logger.debug("sessionId {}", sessionId); - return sessionManager.get(sessionId); - } + public static Session getSession(SessionManager sessionManager, String authorization) throws ParseException { + _logger.debug("get session by authorization {}", authorization); + SignedJWT signedJWT = SignedJWT.parse(authorization); + String sessionId = signedJWT.getJWTClaimsSet().getJWTID(); + _logger.debug("sessionId {}", sessionId); + return sessionManager.get(sessionId); + } public static Authentication getAuthentication() { - Authentication authentication = (Authentication) getAuthentication(WebContext.getRequest()); + Authentication authentication = (Authentication) getAuthentication(WebContext.getRequest()); return authentication; } public static Authentication getAuthentication(HttpServletRequest request) { - Authentication authentication = (Authentication) request.getSession().getAttribute(WebConstants.AUTHENTICATION); + Authentication authentication = (Authentication) request.getSession().getAttribute(WebConstants.AUTHENTICATION); return authentication; } //set Authentication to http session public static void setAuthentication(Authentication authentication) { - WebContext.setAttribute(WebConstants.AUTHENTICATION, authentication); + WebContext.setAttribute(WebConstants.AUTHENTICATION, authentication); } public static void clearAuthentication() { - WebContext.removeAttribute(WebConstants.AUTHENTICATION); + WebContext.removeAttribute(WebConstants.AUTHENTICATION); } public static boolean isAuthenticated() { - return getAuthentication() != null; + return getAuthentication() != null; } public static boolean isNotAuthenticated() { - return ! isAuthenticated(); + return ! isAuthenticated(); } public static SignPrincipal getPrincipal() { - Authentication authentication = getAuthentication(); - return getPrincipal(authentication); + Authentication authentication = getAuthentication(); + return getPrincipal(authentication); } public static SignPrincipal getPrincipal(Authentication authentication) { - return authentication == null ? null : (SignPrincipal) authentication.getPrincipal(); + return authentication == null ? null : (SignPrincipal) authentication.getPrincipal(); } public static UserInfo getUserInfo(Authentication authentication) { - UserInfo userInfo = null; - SignPrincipal principal = getPrincipal(authentication); - if(principal != null ) { - userInfo = principal.getUserInfo(); + UserInfo userInfo = null; + SignPrincipal principal = getPrincipal(authentication); + if(principal != null ) { + userInfo = principal.getUserInfo(); } - return userInfo; + return userInfo; } public static UserInfo getUserInfo() { - return getUserInfo(getAuthentication()); + return getUserInfo(getAuthentication()); } } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/CurrentUserMethodArgumentResolver.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/CurrentUserMethodArgumentResolver.java index f364ac09b..df22e70db 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/CurrentUserMethodArgumentResolver.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/CurrentUserMethodArgumentResolver.java @@ -30,14 +30,14 @@ import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.multipart.support.MissingServletRequestPartException; public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver { - + @Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { - Authentication authentication = - (Authentication ) webRequest.getAttribute( - WebConstants.AUTHENTICATION, RequestAttributes.SCOPE_SESSION); - UserInfo userInfo = AuthorizationUtils.getUserInfo(authentication); - if (userInfo != null) { + Authentication authentication = + (Authentication ) webRequest.getAttribute( + WebConstants.AUTHENTICATION, RequestAttributes.SCOPE_SESSION); + UserInfo userInfo = AuthorizationUtils.getUserInfo(authentication); + if (userInfo != null) { return userInfo; } throw new MissingServletRequestPartException("currentUser"); diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/FileUploadEndpoint.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/FileUploadEndpoint.java index 26c99861f..6526d2e0e 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/FileUploadEndpoint.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/FileUploadEndpoint.java @@ -37,37 +37,37 @@ import jakarta.servlet.http.HttpServletResponse; @Controller public class FileUploadEndpoint { - - private static Logger _logger = LoggerFactory.getLogger(FileUploadEndpoint.class); - - @Autowired - FileUploadService fileUploadService; - - @PostMapping({"/file/upload/"}) - @ResponseBody - public Message upload( HttpServletRequest request, - HttpServletResponse response, - @ModelAttribute FileUpload fileUpload, - @CurrentUser UserInfo currentUser){ - _logger.debug("FileUpload"); - fileUpload.setId(fileUpload.generateId()); - fileUpload.setContentType(fileUpload.getUploadFile().getContentType()); - fileUpload.setFileName(fileUpload.getUploadFile().getOriginalFilename()); - fileUpload.setContentSize(fileUpload.getUploadFile().getSize()); - fileUpload.setCreatedBy(currentUser.getUsername()); - /* - * upload UploadFile MultipartFile to Uploaded Bytes - */ - if(null!=fileUpload.getUploadFile()&&!fileUpload.getUploadFile().isEmpty()){ - try { - fileUpload.setUploaded(fileUpload.getUploadFile().getBytes()); - fileUploadService.insert(fileUpload); - _logger.trace("FileUpload SUCCESS"); - } catch (IOException e) { - _logger.error("FileUpload IOException",e); - } - } - return new Message(Message.SUCCESS,(Object)fileUpload.getId()); - } - + + private static Logger _logger = LoggerFactory.getLogger(FileUploadEndpoint.class); + + @Autowired + FileUploadService fileUploadService; + + @PostMapping({"/file/upload/"}) + @ResponseBody + public Message upload( HttpServletRequest request, + HttpServletResponse response, + @ModelAttribute FileUpload fileUpload, + @CurrentUser UserInfo currentUser){ + _logger.debug("FileUpload"); + fileUpload.setId(fileUpload.generateId()); + fileUpload.setContentType(fileUpload.getUploadFile().getContentType()); + fileUpload.setFileName(fileUpload.getUploadFile().getOriginalFilename()); + fileUpload.setContentSize(fileUpload.getUploadFile().getSize()); + fileUpload.setCreatedBy(currentUser.getUsername()); + /* + * upload UploadFile MultipartFile to Uploaded Bytes + */ + if(null!=fileUpload.getUploadFile()&&!fileUpload.getUploadFile().isEmpty()){ + try { + fileUpload.setUploaded(fileUpload.getUploadFile().getBytes()); + fileUploadService.insert(fileUpload); + _logger.trace("FileUpload SUCCESS"); + } catch (IOException e) { + _logger.error("FileUpload IOException",e); + } + } + return new Message(Message.SUCCESS,(Object)fileUpload.getId()); + } + } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/HttpSessionListenerAdapter.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/HttpSessionListenerAdapter.java index b59d60ae3..009b69c12 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/HttpSessionListenerAdapter.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/HttpSessionListenerAdapter.java @@ -58,31 +58,31 @@ public class HttpSessionListenerAdapter implements HttpSessionListener { Object principal = authentication == null ? null : authentication.getPrincipal(); _logger.trace("principal {}",principal); if(principal != null ) { - if(principal instanceof SignPrincipal && ((SignPrincipal)principal).getUserInfo()!=null) { - SignPrincipal signPrincipal = (SignPrincipal)principal; - _logger.trace("{} HttpSession Id {} for userId {} , username {} @Ticket {} Destroyed" , - DateUtils.formatDateTime(new Date()), - session.getId(), - signPrincipal.getUserInfo().getId(), - signPrincipal.getUserInfo().getUsername(), - signPrincipal.getSessionId()); - }else if(principal instanceof User) { - User user = (User)principal; - _logger.trace("{} HttpSession Id {} for username {} password {} Destroyed" , - DateUtils.formatDateTime(new Date()), - session.getId(), - user.getUsername(), - user.getPassword()); - }else{ - _logger.trace("{} HttpSession Id {} for principal {} Destroyed" , - DateUtils.formatDateTime(new Date()), - session.getId(), - principal); - } + if(principal instanceof SignPrincipal && ((SignPrincipal)principal).getUserInfo()!=null) { + SignPrincipal signPrincipal = (SignPrincipal)principal; + _logger.trace("{} HttpSession Id {} for userId {} , username {} @Ticket {} Destroyed" , + DateUtils.formatDateTime(new Date()), + session.getId(), + signPrincipal.getUserInfo().getId(), + signPrincipal.getUserInfo().getUsername(), + signPrincipal.getSessionId()); + }else if(principal instanceof User) { + User user = (User)principal; + _logger.trace("{} HttpSession Id {} for username {} password {} Destroyed" , + DateUtils.formatDateTime(new Date()), + session.getId(), + user.getUsername(), + user.getPassword()); + }else{ + _logger.trace("{} HttpSession Id {} for principal {} Destroyed" , + DateUtils.formatDateTime(new Date()), + session.getId(), + principal); + } }else { - _logger.trace("{} HttpSession Id {} Destroyed" , - DateUtils.formatDateTime(new Date()), - session.getId()); + _logger.trace("{} HttpSession Id {} Destroyed" , + DateUtils.formatDateTime(new Date()), + session.getId()); } } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/InstitutionEndpoint.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/InstitutionEndpoint.java index 144a9d4f1..d1a326be1 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/InstitutionEndpoint.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/InstitutionEndpoint.java @@ -35,45 +35,45 @@ import jakarta.servlet.http.HttpServletRequest; @RestController @RequestMapping(value = "/inst") public class InstitutionEndpoint { - private static final Logger _logger = LoggerFactory.getLogger(InstitutionEndpoint.class); - - public static final String HEADER_HOST = "host"; - - public static final String HEADER_HOSTNAME = "hostname"; - - @Autowired - InstitutionsService institutionsService; - - @Autowired - ApplicationConfig applicationConfig; - - @GetMapping(value={"/get"}) - public Message get( - HttpServletRequest request, - @RequestHeader(value = "Origin",required=false) String originURL, - @RequestHeader(value = HEADER_HOSTNAME,required=false) String headerHostName, - @RequestHeader(value = HEADER_HOST,required=false) String headerHost) { - _logger.debug("get Institution" ); - - String host = headerHostName; - _logger.trace("hostname {}",host); - if(StringUtils.isEmpty(host)) { - host = headerHost; - _logger.trace("host {}",host); - } - - if(StringUtils.isEmpty(host)) { - host = applicationConfig.getDomainName(); - _logger.trace("config domain {}",host); - } - - if(host.indexOf(":")> -1 ) { - host = host.split(":")[0]; - _logger.trace("domain split {}",host); - } - - Institutions inst = institutionsService.get(host); - _logger.debug("inst {}",inst); - return new Message<>(inst); - } + private static final Logger _logger = LoggerFactory.getLogger(InstitutionEndpoint.class); + + public static final String HEADER_HOST = "host"; + + public static final String HEADER_HOSTNAME = "hostname"; + + @Autowired + InstitutionsService institutionsService; + + @Autowired + ApplicationConfig applicationConfig; + + @GetMapping(value={"/get"}) + public Message get( + HttpServletRequest request, + @RequestHeader(value = "Origin",required=false) String originURL, + @RequestHeader(value = HEADER_HOSTNAME,required=false) String headerHostName, + @RequestHeader(value = HEADER_HOST,required=false) String headerHost) { + _logger.debug("get Institution" ); + + String host = headerHostName; + _logger.trace("hostname {}",host); + if(StringUtils.isEmpty(host)) { + host = headerHost; + _logger.trace("host {}",host); + } + + if(StringUtils.isEmpty(host)) { + host = applicationConfig.getDomainName(); + _logger.trace("config domain {}",host); + } + + if(host.indexOf(":")> -1 ) { + host = host.split(":")[0]; + _logger.trace("domain split {}",host); + } + + Institutions inst = institutionsService.get(host); + _logger.debug("inst {}",inst); + return new Message<>(inst); + } } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/PersistFieldAutoFillHandler.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/PersistFieldAutoFillHandler.java index 2b5a34f6f..596c4dcaa 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/PersistFieldAutoFillHandler.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/PersistFieldAutoFillHandler.java @@ -27,39 +27,39 @@ import org.springframework.stereotype.Component; @Component public class PersistFieldAutoFillHandler extends FieldAutoFillHandler{ - @Override - public void insertFill(MetaObject metaObject) { - - SignPrincipal principal = getPrincipal(); - if(principal != null) { - this.setFieldValue(metaObject , "instId", principal.getInstId()); - this.setFieldValue(metaObject , "createdBy", principal.getUserId()); - } - this.setFieldValue(metaObject , "createdDate", new Date()); - - } + @Override + public void insertFill(MetaObject metaObject) { + + SignPrincipal principal = getPrincipal(); + if(principal != null) { + this.setFieldValue(metaObject , "instId", principal.getInstId()); + this.setFieldValue(metaObject , "createdBy", principal.getUserId()); + } + this.setFieldValue(metaObject , "createdDate", new Date()); + + } - @Override - public void updateFill(MetaObject metaObject) { - SignPrincipal principal = getPrincipal(); - if(principal != null) { - this.setFieldValue(metaObject , "modifiedBy", principal.getUserId()); - } - this.setFieldValue(metaObject , "modifiedDate", new Date()); - } - - /** - * 获取principal , 忽略异常情况 - * @return - */ - SignPrincipal getPrincipal() { - SignPrincipal principal = null; - try { - principal = AuthorizationUtils.getPrincipal(); - }catch(Exception e) { - // - } - return principal; - } + @Override + public void updateFill(MetaObject metaObject) { + SignPrincipal principal = getPrincipal(); + if(principal != null) { + this.setFieldValue(metaObject , "modifiedBy", principal.getUserId()); + } + this.setFieldValue(metaObject , "modifiedDate", new Date()); + } + + /** + * 获取principal , 忽略异常情况 + * @return + */ + SignPrincipal getPrincipal() { + SignPrincipal principal = null; + try { + principal = AuthorizationUtils.getPrincipal(); + }catch(Exception e) { + // + } + return principal; + } } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/SessionSecurityContextHolderStrategy.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/SessionSecurityContextHolderStrategy.java index 3a1dd667d..26ff4a912 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/SessionSecurityContextHolderStrategy.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/SessionSecurityContextHolderStrategy.java @@ -59,7 +59,7 @@ public class SessionSecurityContextHolderStrategy implements SecurityContextHold @Override public void setContext(SecurityContext context) { - AuthorizationUtils.setAuthentication(context.getAuthentication()); + AuthorizationUtils.setAuthentication(context.getAuthentication()); } @Override diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/UnauthorizedEntryPoint.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/UnauthorizedEntryPoint.java index bac263776..b7e2690fb 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/UnauthorizedEntryPoint.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/UnauthorizedEntryPoint.java @@ -38,23 +38,23 @@ import jakarta.servlet.http.HttpServletResponse; @Controller @RequestMapping(value = "/auth") public class UnauthorizedEntryPoint { - private static final Logger _logger = LoggerFactory.getLogger(UnauthorizedEntryPoint.class); - - @RequestMapping(value={"/entrypoint"}) - public void entryPoint( - HttpServletRequest request, HttpServletResponse response) - throws StreamWriteException, DatabindException, IOException { - _logger.trace("UnauthorizedEntryPoint /entrypoint."); - response.setContentType(MediaType.APPLICATION_JSON_VALUE); - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + private static final Logger _logger = LoggerFactory.getLogger(UnauthorizedEntryPoint.class); + + @RequestMapping(value={"/entrypoint"}) + public void entryPoint( + HttpServletRequest request, HttpServletResponse response) + throws StreamWriteException, DatabindException, IOException { + _logger.trace("UnauthorizedEntryPoint /entrypoint."); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - final Map responseBody = new HashMap<>(); - responseBody.put("status", HttpServletResponse.SC_UNAUTHORIZED); - responseBody.put("error", "Unauthorized"); - responseBody.put("message", "Unauthorized"); - responseBody.put("path", request.getServletPath()); + final Map responseBody = new HashMap<>(); + responseBody.put("status", HttpServletResponse.SC_UNAUTHORIZED); + responseBody.put("error", "Unauthorized"); + responseBody.put("message", "Unauthorized"); + responseBody.put("path", request.getServletPath()); - final ObjectMapper mapper = new ObjectMapper(); - mapper.writeValue(response.getOutputStream(), responseBody); - } + final ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(response.getOutputStream(), responseBody); + } } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/interceptor/PermissionInterceptor.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/interceptor/PermissionInterceptor.java index 1ca630137..124bef658 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/interceptor/PermissionInterceptor.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/authn/web/interceptor/PermissionInterceptor.java @@ -39,51 +39,51 @@ import jakarta.servlet.http.HttpServletResponse; */ @Component public class PermissionInterceptor implements AsyncHandlerInterceptor { - private static final Logger _logger = LoggerFactory.getLogger(PermissionInterceptor.class); - //无需Interceptor url - @Autowired - ApplicationConfig applicationConfig; - - @Autowired - SessionManager sessionManager; - - @Autowired - AuthTokenService authTokenService ; - - boolean mgmt = false; - - /* - * 请求前处理 - * (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("Permission Interceptor ."); - AuthorizationUtils.authenticate(request, authTokenService, sessionManager); - SignPrincipal principal = AuthorizationUtils.getPrincipal(); - //判断用户是否登录,判断用户是否登录用户 - if(principal == null){ - _logger.debug("No Authentication ... forward to /auth/entrypoint , request URI {}" , request.getRequestURI()); - RequestDispatcher dispatcher = request.getRequestDispatcher("/auth/entrypoint"); - dispatcher.forward(request, response); - return false; - } - - //管理端必须使用管理员登录,非管理员用户直接注销 - if (this.mgmt && !principal.isRoleAdministrators()) { - _logger.debug("Not ADMINISTRATORS Authentication ."); - RequestDispatcher dispatcher = request.getRequestDispatcher("/auth/entrypoint"); - dispatcher.forward(request, response); - return false; - } - - return true; - } + private static final Logger _logger = LoggerFactory.getLogger(PermissionInterceptor.class); + //无需Interceptor url + @Autowired + ApplicationConfig applicationConfig; + + @Autowired + SessionManager sessionManager; + + @Autowired + AuthTokenService authTokenService ; + + boolean mgmt = false; + + /* + * 请求前处理 + * (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("Permission Interceptor ."); + AuthorizationUtils.authenticate(request, authTokenService, sessionManager); + SignPrincipal principal = AuthorizationUtils.getPrincipal(); + //判断用户是否登录,判断用户是否登录用户 + if(principal == null){ + _logger.debug("No Authentication ... forward to /auth/entrypoint , request URI {}" , request.getRequestURI()); + RequestDispatcher dispatcher = request.getRequestDispatcher("/auth/entrypoint"); + dispatcher.forward(request, response); + return false; + } + + //管理端必须使用管理员登录,非管理员用户直接注销 + if (this.mgmt && !principal.isRoleAdministrators()) { + _logger.debug("Not ADMINISTRATORS Authentication ."); + RequestDispatcher dispatcher = request.getRequestDispatcher("/auth/entrypoint"); + dispatcher.forward(request, response); + return false; + } + + return true; + } - public void setMgmt(boolean mgmt) { - this.mgmt = mgmt; - _logger.debug("Permission for ADMINISTRATORS {}", this.mgmt); - } - + public void setMgmt(boolean mgmt) { + this.mgmt = mgmt; + _logger.debug("Permission for ADMINISTRATORS {}", this.mgmt); + } + } diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/autoconfigure/SessionAutoConfiguration.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/autoconfigure/SessionAutoConfiguration.java index c9c230a7d..2ae93aea3 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/autoconfigure/SessionAutoConfiguration.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/autoconfigure/SessionAutoConfiguration.java @@ -49,9 +49,9 @@ public class SessionAutoConfiguration { RedisConnectionFactory redisConnFactory, @Value("${maxkey.auth.session.timeout:1800}") int timeout ) { - _logger.debug("session timeout {}" , timeout); + _logger.debug("session timeout {}" , timeout); return new SessionManagerImpl( - persistence, jdbcTemplate, redisConnFactory,timeout); + persistence, jdbcTemplate, redisConnFactory,timeout); } @Bean diff --git a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/autoconfigure/TokenAutoConfiguration.java b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/autoconfigure/TokenAutoConfiguration.java index ee3aa9b9a..d8dc7731e 100644 --- a/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/autoconfigure/TokenAutoConfiguration.java +++ b/maxkey-authentications/maxkey-authentication-core/src/main/java/org/dromara/maxkey/autoconfigure/TokenAutoConfiguration.java @@ -41,30 +41,30 @@ public class TokenAutoConfiguration{ @Bean AuthTokenService authTokenService( - AuthJwkConfig authJwkConfig, - RedisConnectionFactory redisConnFactory, - MomentaryService momentaryService, - AuthRefreshTokenService refreshTokenService, - @Value("${maxkey.server.persistence}") int persistence) throws JOSEException { - CongressService congressService; - _logger.debug("cache persistence {}" , persistence); - if (persistence == ConstsPersistence.REDIS) { - congressService = new RedisCongressService(redisConnFactory); - }else { - congressService = new InMemoryCongressService(); - } - - return new AuthTokenService( - authJwkConfig, - congressService, - momentaryService, - refreshTokenService - ); + AuthJwkConfig authJwkConfig, + RedisConnectionFactory redisConnFactory, + MomentaryService momentaryService, + AuthRefreshTokenService refreshTokenService, + @Value("${maxkey.server.persistence}") int persistence) throws JOSEException { + CongressService congressService; + _logger.debug("cache persistence {}" , persistence); + if (persistence == ConstsPersistence.REDIS) { + congressService = new RedisCongressService(redisConnFactory); + }else { + congressService = new InMemoryCongressService(); + } + + return new AuthTokenService( + authJwkConfig, + congressService, + momentaryService, + refreshTokenService + ); } @Bean AuthRefreshTokenService refreshTokenService(AuthJwkConfig authJwkConfig) throws JOSEException { - return new AuthRefreshTokenService(authJwkConfig); + return new AuthRefreshTokenService(authJwkConfig); } } diff --git a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/provider/AbstractAuthenticationProvider.java b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/provider/AbstractAuthenticationProvider.java index 1d8298da5..f1415fbf7 100644 --- a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/provider/AbstractAuthenticationProvider.java +++ b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/provider/AbstractAuthenticationProvider.java @@ -56,19 +56,19 @@ public abstract class AbstractAuthenticationProvider { public static String PROVIDER_SUFFIX = "AuthenticationProvider"; public class AuthType{ - public static final String NORMAL = "normal"; - public static final String TFA = "tfa"; - public static final String MOBILE = "mobile"; - public static final String TRUSTED = "trusted"; + public static final String NORMAL = "normal"; + public static final String TFA = "tfa"; + public static final String MOBILE = "mobile"; + public static final String TRUSTED = "trusted"; /** * 扫描认证 */ - public static final String SCAN_CODE = "scancode"; + public static final String SCAN_CODE = "scancode"; /** * 手机端APP */ - public static final String APP = "app"; + public static final String APP = "app"; } protected ApplicationConfig applicationConfig; @@ -99,11 +99,11 @@ public abstract class AbstractAuthenticationProvider { } public Authentication authenticate(LoginCredential authentication){ - return null; + return null; } public Authentication authenticate(LoginCredential authentication,boolean trusted) { - return null; + return null; } /** @@ -124,7 +124,7 @@ public abstract class AbstractAuthenticationProvider { for(GrantedAuthority administratorsAuthority : grantedAdministratorsAuthoritys) { if(grantedAuthoritys.contains(administratorsAuthority)) { - principal.setRoleAdministrators(true); + principal.setRoleAdministrators(true); _logger.trace("ROLE ADMINISTRATORS Authentication ."); } } @@ -134,7 +134,7 @@ public abstract class AbstractAuthenticationProvider { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( - principal, + principal, "PASSWORD", grantedAuthoritys ); @@ -228,34 +228,34 @@ public abstract class AbstractAuthenticationProvider { loginUser.setDisplayName("not exist"); loginUser.setLoginCount(0); authenticationRealm.insertLoginHistory( - loginUser, - ConstsLoginType.LOCAL, - "", - i18nMessage, - WebConstants.LOGIN_RESULT.USER_NOT_EXIST); + loginUser, + ConstsLoginType.LOCAL, + "", + i18nMessage, + WebConstants.LOGIN_RESULT.USER_NOT_EXIST); throw new BadCredentialsException(i18nMessage); } return true; } protected boolean statusValid(LoginCredential loginCredential , UserInfo userInfo) { - if(userInfo.getIsLocked()==ConstsStatus.LOCK) { - authenticationRealm.insertLoginHistory( - userInfo, + if(userInfo.getIsLocked()==ConstsStatus.LOCK) { + authenticationRealm.insertLoginHistory( + userInfo, loginCredential.getAuthType(), loginCredential.getProvider(), loginCredential.getCode(), WebConstants.LOGIN_RESULT.USER_LOCKED ); - }else if(userInfo.getStatus()!=ConstsStatus.ACTIVE) { - authenticationRealm.insertLoginHistory( - userInfo, + }else if(userInfo.getStatus()!=ConstsStatus.ACTIVE) { + authenticationRealm.insertLoginHistory( + userInfo, loginCredential.getAuthType(), loginCredential.getProvider(), loginCredential.getCode(), WebConstants.LOGIN_RESULT.USER_INACTIVE ); - } + } return true; } diff --git a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/provider/AuthenticationProviderFactory.java b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/provider/AuthenticationProviderFactory.java index a06312720..a8a3ad76a 100644 --- a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/provider/AuthenticationProviderFactory.java +++ b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/provider/AuthenticationProviderFactory.java @@ -26,33 +26,33 @@ public class AuthenticationProviderFactory extends AbstractAuthenticationProvide @Override public Authentication authenticate(LoginCredential authentication){ - if(authentication.getAuthType().equalsIgnoreCase("trusted")) { - //risk remove - return null; - } - AbstractAuthenticationProvider provider = providers.get(authentication.getAuthType() + PROVIDER_SUFFIX); - - return provider == null ? null : provider.doAuthenticate(authentication); + if(authentication.getAuthType().equalsIgnoreCase("trusted")) { + //risk remove + return null; + } + AbstractAuthenticationProvider provider = providers.get(authentication.getAuthType() + PROVIDER_SUFFIX); + + return provider == null ? null : provider.doAuthenticate(authentication); } @Override public Authentication authenticate(LoginCredential authentication,boolean trusted){ - AbstractAuthenticationProvider provider = providers.get(AuthType.TRUSTED + PROVIDER_SUFFIX); - return provider.doAuthenticate(authentication); + AbstractAuthenticationProvider provider = providers.get(AuthType.TRUSTED + PROVIDER_SUFFIX); + return provider.doAuthenticate(authentication); } public void addAuthenticationProvider(AbstractAuthenticationProvider provider) { - providers.put(provider.getProviderName(), provider); + providers.put(provider.getProviderName(), provider); } - @Override - public String getProviderName() { - return "AuthenticationProviderFactory"; - } + @Override + public String getProviderName() { + return "AuthenticationProviderFactory"; + } - @Override - public Authentication doAuthenticate(LoginCredential authentication) { - //AuthenticationProvider Factory do nothing - return null; - } + @Override + public Authentication doAuthenticate(LoginCredential authentication) { + //AuthenticationProvider Factory do nothing + return null; + } } diff --git a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/provider/impl/NormalAuthenticationProvider.java b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/provider/impl/NormalAuthenticationProvider.java index 310df9427..2fd8a9269 100644 --- a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/provider/impl/NormalAuthenticationProvider.java +++ b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/provider/impl/NormalAuthenticationProvider.java @@ -51,65 +51,65 @@ public class NormalAuthenticationProvider extends AbstractAuthenticationProvider public NormalAuthenticationProvider() { - super(); - } + super(); + } public NormalAuthenticationProvider( - AbstractAuthenticationRealm authenticationRealm, - ApplicationConfig applicationConfig, - SessionManager sessionManager, - AuthTokenService authTokenService) { - this.authenticationRealm = authenticationRealm; - this.applicationConfig = applicationConfig; - this.sessionManager = sessionManager; - this.authTokenService = authTokenService; - } + AbstractAuthenticationRealm authenticationRealm, + ApplicationConfig applicationConfig, + SessionManager sessionManager, + AuthTokenService authTokenService) { + this.authenticationRealm = authenticationRealm; + this.applicationConfig = applicationConfig; + this.sessionManager = sessionManager; + this.authTokenService = authTokenService; + } @Override - public Authentication doAuthenticate(LoginCredential loginCredential) { - UsernamePasswordAuthenticationToken authenticationToken = null; - _logger.debug("Trying to authenticate user '{}' via {}", + public Authentication doAuthenticate(LoginCredential loginCredential) { + UsernamePasswordAuthenticationToken authenticationToken = null; + _logger.debug("Trying to authenticate user '{}' via {}", loginCredential.getPrincipal(), getProviderName()); try { - - _logger.debug("authentication {}" , loginCredential); - - if(this.applicationConfig.getLoginConfig().isCaptcha()) { - captchaValid(loginCredential.getState(),loginCredential.getCaptcha()); - } - - emptyPasswordValid(loginCredential.getPassword()); - - emptyUsernameValid(loginCredential.getUsername()); - - UserInfo userInfo = loadUserInfo(loginCredential.getUsername(),loginCredential.getPassword()); - - isUserExist(loginCredential , userInfo); - - //Validate PasswordPolicy - authenticationRealm.getLoginService().passwordPolicyValid(userInfo); - - statusValid(loginCredential , userInfo); - - //Match password - authenticationRealm.passwordMatches(userInfo, loginCredential.getPassword()); + + _logger.debug("authentication {}" , loginCredential); + + if(this.applicationConfig.getLoginConfig().isCaptcha()) { + captchaValid(loginCredential.getState(),loginCredential.getCaptcha()); + } + + emptyPasswordValid(loginCredential.getPassword()); + + emptyUsernameValid(loginCredential.getUsername()); + + UserInfo userInfo = loadUserInfo(loginCredential.getUsername(),loginCredential.getPassword()); + + isUserExist(loginCredential , userInfo); + + //Validate PasswordPolicy + authenticationRealm.getLoginService().passwordPolicyValid(userInfo); + + statusValid(loginCredential , userInfo); + + //Match password + authenticationRealm.passwordMatches(userInfo, loginCredential.getPassword()); - //apply PasswordSetType and resetBadPasswordCount - authenticationRealm.getLoginService().applyPasswordPolicy(userInfo); - - authenticationToken = createOnlineTicket(loginCredential,userInfo); - // user authenticated - _logger.debug("'{}' authenticated successfully by {}.", - loginCredential.getPrincipal(), getProviderName()); - - authenticationRealm.insertLoginHistory(userInfo, - ConstsLoginType.LOCAL, - "", - "xe00000004", - WebConstants.LOGIN_RESULT.SUCCESS); + //apply PasswordSetType and resetBadPasswordCount + authenticationRealm.getLoginService().applyPasswordPolicy(userInfo); + + authenticationToken = createOnlineTicket(loginCredential,userInfo); + // user authenticated + _logger.debug("'{}' authenticated successfully by {}.", + loginCredential.getPrincipal(), getProviderName()); + + authenticationRealm.insertLoginHistory(userInfo, + ConstsLoginType.LOCAL, + "", + "xe00000004", + WebConstants.LOGIN_RESULT.SUCCESS); } catch (AuthenticationException e) { _logger.error("Failed to authenticate user {} via {}: {}", - loginCredential.getPrincipal(), + loginCredential.getPrincipal(), getProviderName(), e.getMessage() ); WebContext.setAttribute( @@ -131,8 +131,8 @@ public class NormalAuthenticationProvider extends AbstractAuthenticationProvider */ protected void captchaValid(String state ,String captcha) { // for basic - if(!authTokenService.validateCaptcha(state,captcha)) { - throw new BadCredentialsException(WebContext.getI18nValue("login.error.captcha")); - } + if(!authTokenService.validateCaptcha(state,captcha)) { + throw new BadCredentialsException(WebContext.getI18nValue("login.error.captcha")); + } } } diff --git a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/provider/impl/TrustedAuthenticationProvider.java b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/provider/impl/TrustedAuthenticationProvider.java index 69bc61a52..bdb0c5b01 100644 --- a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/provider/impl/TrustedAuthenticationProvider.java +++ b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/provider/impl/TrustedAuthenticationProvider.java @@ -43,20 +43,20 @@ public class TrustedAuthenticationProvider extends AbstractAuthenticationProvide } public TrustedAuthenticationProvider() { - super(); - } + super(); + } public TrustedAuthenticationProvider( - AbstractAuthenticationRealm authenticationRealm, - ApplicationConfig applicationConfig, - SessionManager sessionManager) { - this.authenticationRealm = authenticationRealm; - this.applicationConfig = applicationConfig; - this.sessionManager = sessionManager; - } + AbstractAuthenticationRealm authenticationRealm, + ApplicationConfig applicationConfig, + SessionManager sessionManager) { + this.authenticationRealm = authenticationRealm; + this.applicationConfig = applicationConfig; + this.sessionManager = sessionManager; + } @Override - public Authentication doAuthenticate(LoginCredential loginCredential) { + public Authentication doAuthenticate(LoginCredential loginCredential) { UserInfo loadeduserInfo = loadUserInfo(loginCredential.getUsername(), ""); statusValid(loginCredential , loadeduserInfo); if (loadeduserInfo != null) { diff --git a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/AbstractAuthenticationRealm.java b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/AbstractAuthenticationRealm.java index e56c325ae..f9b531ae5 100644 --- a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/AbstractAuthenticationRealm.java +++ b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/AbstractAuthenticationRealm.java @@ -127,8 +127,8 @@ public abstract class AbstractAuthenticationRealm { historyLogin.setSessionStatus(7); Authentication authentication = (Authentication ) WebContext.getAttribute(WebConstants.AUTHENTICATION); if(authentication != null - && authentication.getPrincipal() instanceof SignPrincipal) { - historyLogin.setSessionStatus(1); + && authentication.getPrincipal() instanceof SignPrincipal) { + historyLogin.setSessionStatus(1); historyLogin.setSessionId(userInfo.getSessionId()); } @@ -153,10 +153,10 @@ public abstract class AbstractAuthenticationRealm { Region ipRegion =ipLocationParser.region(userInfo.getLastLoginIp()); if(ipRegion != null) { - historyLogin.setCountry(ipRegion.getCountry()); - historyLogin.setProvince(ipRegion.getProvince()); - historyLogin.setCity(ipRegion.getCity()); - historyLogin.setLocation(ipRegion.getAddr()); + historyLogin.setCountry(ipRegion.getCountry()); + historyLogin.setProvince(ipRegion.getProvince()); + historyLogin.setCity(ipRegion.getCity()); + historyLogin.setLocation(ipRegion.getAddr()); } historyLoginService.login(historyLogin); diff --git a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/jdbc/JdbcAuthenticationRealm.java b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/jdbc/JdbcAuthenticationRealm.java index 40683172b..0fb601a04 100644 --- a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/jdbc/JdbcAuthenticationRealm.java +++ b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/jdbc/JdbcAuthenticationRealm.java @@ -57,40 +57,40 @@ public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm { } public JdbcAuthenticationRealm( - PasswordEncoder passwordEncoder, - PasswordPolicyValidatorService passwordPolicyValidatorService, - LoginService loginService, - HistoryLoginService historyLoginService, - UserInfoService userInfoService, - IpLocationParser ipLocationParser, - JdbcTemplate jdbcTemplate) { - - this.passwordEncoder =passwordEncoder; - this.passwordPolicyValidatorService=passwordPolicyValidatorService; - this.loginService = loginService; - this.historyLoginService = historyLoginService; - this.userInfoService = userInfoService; - this.ipLocationParser = ipLocationParser; + PasswordEncoder passwordEncoder, + PasswordPolicyValidatorService passwordPolicyValidatorService, + LoginService loginService, + HistoryLoginService historyLoginService, + UserInfoService userInfoService, + IpLocationParser ipLocationParser, + JdbcTemplate jdbcTemplate) { + + this.passwordEncoder =passwordEncoder; + this.passwordPolicyValidatorService=passwordPolicyValidatorService; + this.loginService = loginService; + this.historyLoginService = historyLoginService; + this.userInfoService = userInfoService; + this.ipLocationParser = ipLocationParser; this.jdbcTemplate = jdbcTemplate; } public JdbcAuthenticationRealm( - PasswordEncoder passwordEncoder, - PasswordPolicyValidatorService passwordPolicyValidatorService, - LoginService loginService, - HistoryLoginService historyLoginService, - UserInfoService userInfoService, - IpLocationParser ipLocationParser, - JdbcTemplate jdbcTemplate, - LdapAuthenticationRealmService ldapAuthenticationRealmService) { - this.passwordEncoder = passwordEncoder; - this.passwordPolicyValidatorService = passwordPolicyValidatorService; - this.loginService = loginService; - this.historyLoginService = historyLoginService; - this.userInfoService = userInfoService; - this.ipLocationParser = ipLocationParser; - this.jdbcTemplate = jdbcTemplate; - this.ldapAuthenticationRealmService = ldapAuthenticationRealmService; + PasswordEncoder passwordEncoder, + PasswordPolicyValidatorService passwordPolicyValidatorService, + LoginService loginService, + HistoryLoginService historyLoginService, + UserInfoService userInfoService, + IpLocationParser ipLocationParser, + JdbcTemplate jdbcTemplate, + LdapAuthenticationRealmService ldapAuthenticationRealmService) { + this.passwordEncoder = passwordEncoder; + this.passwordPolicyValidatorService = passwordPolicyValidatorService; + this.loginService = loginService; + this.historyLoginService = historyLoginService; + this.userInfoService = userInfoService; + this.ipLocationParser = ipLocationParser; + this.jdbcTemplate = jdbcTemplate; + this.ldapAuthenticationRealmService = ldapAuthenticationRealmService; } /** @@ -105,28 +105,28 @@ public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm { passwordMatches = passwordEncoder.matches(password,userInfo.getPassword()); if(ldapAuthenticationRealmService != null) { - //passwordMatches == false and ldapSupport ==true - //validate password with LDAP - try { - LdapAuthenticationRealm ldapRealm = ldapAuthenticationRealmService.getByInstId(userInfo.getInstId()); - if(!passwordMatches && ldapRealm != null - && ldapRealm.isLdapSupport() - && userInfo.getIsLocked() == ConstsStatus.ACTIVE) { - passwordMatches = ldapRealm.passwordMatches(userInfo, password); - if(passwordMatches) { - //write password to database Realm - ChangePassword changePassword = new ChangePassword(userInfo); - changePassword.setPassword(password); - userInfoService.changePassword(changePassword, false); - } - } - }catch(Exception e) { - _logger.debug("passwordvalid Exception : {}" , e); - } + //passwordMatches == false and ldapSupport ==true + //validate password with LDAP + try { + LdapAuthenticationRealm ldapRealm = ldapAuthenticationRealmService.getByInstId(userInfo.getInstId()); + if(!passwordMatches && ldapRealm != null + && ldapRealm.isLdapSupport() + && userInfo.getIsLocked() == ConstsStatus.ACTIVE) { + passwordMatches = ldapRealm.passwordMatches(userInfo, password); + if(passwordMatches) { + //write password to database Realm + ChangePassword changePassword = new ChangePassword(userInfo); + changePassword.setPassword(password); + userInfoService.changePassword(changePassword, false); + } + } + }catch(Exception e) { + _logger.debug("passwordvalid Exception : {}" , e); + } } _logger.debug("passwordvalid : {}" , passwordMatches); if (!passwordMatches) { - loginService.plusBadPasswordCount(userInfo); + loginService.plusBadPasswordCount(userInfo); insertLoginHistory(userInfo, ConstsLoginType.LOCAL, "", "xe00000004", WebConstants.LOGIN_RESULT.PASSWORD_ERROE); CnfPasswordPolicy passwordPolicy = passwordPolicyValidatorService.getPasswordPolicy(); if(userInfo.getBadPasswordCount()>=(passwordPolicy.getAttempts()/2)) { diff --git a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/ldap/ActiveDirectoryServer.java b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/ldap/ActiveDirectoryServer.java index 55dde105f..f31b9f72e 100644 --- a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/ldap/ActiveDirectoryServer.java +++ b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/ldap/ActiveDirectoryServer.java @@ -30,59 +30,59 @@ import org.slf4j.LoggerFactory; * */ public final class ActiveDirectoryServer implements IAuthenticationServer { - private static final Logger _logger = LoggerFactory.getLogger(ActiveDirectoryServer.class); + private static final Logger _logger = LoggerFactory.getLogger(ActiveDirectoryServer.class); - ActiveDirectoryUtils activeDirectoryUtils; + ActiveDirectoryUtils activeDirectoryUtils; - String filter; - - boolean mapping; - - /* (non-Javadoc) - * @see com.connsec.web.authentication.realm.IAuthenticationServer#authenticate(java.lang.String, java.lang.String) - */ - @Override - public boolean authenticate(String username, String password) { - ActiveDirectoryUtils ldapPassWordValid = - new ActiveDirectoryUtils( - activeDirectoryUtils.getProviderUrl(), - username, - password, - activeDirectoryUtils.getDomain() - ); - ldapPassWordValid.openConnection(); - if(ldapPassWordValid.getCtx()!=null){ - _logger.debug("Active Directory user " + username + " is validate ."); - ldapPassWordValid.close(); - return true; - } - - ldapPassWordValid.close(); - return false; - } + String filter; + + boolean mapping; + + /* (non-Javadoc) + * @see com.connsec.web.authentication.realm.IAuthenticationServer#authenticate(java.lang.String, java.lang.String) + */ + @Override + public boolean authenticate(String username, String password) { + ActiveDirectoryUtils ldapPassWordValid = + new ActiveDirectoryUtils( + activeDirectoryUtils.getProviderUrl(), + username, + password, + activeDirectoryUtils.getDomain() + ); + ldapPassWordValid.openConnection(); + if(ldapPassWordValid.getCtx()!=null){ + _logger.debug("Active Directory user " + username + " is validate ."); + ldapPassWordValid.close(); + return true; + } + + ldapPassWordValid.close(); + return false; + } - public ActiveDirectoryUtils getActiveDirectoryUtils() { - return activeDirectoryUtils; - } + public ActiveDirectoryUtils getActiveDirectoryUtils() { + return activeDirectoryUtils; + } - public void setActiveDirectoryUtils(ActiveDirectoryUtils activeDirectoryUtils) { - this.activeDirectoryUtils = activeDirectoryUtils; - } + public void setActiveDirectoryUtils(ActiveDirectoryUtils activeDirectoryUtils) { + this.activeDirectoryUtils = activeDirectoryUtils; + } - public String getFilter() { - return filter; - } + public String getFilter() { + return filter; + } - public void setFilter(String filter) { - this.filter = filter; - } + public void setFilter(String filter) { + this.filter = filter; + } - @Override - public boolean isMapping() { - return mapping; - } + @Override + public boolean isMapping() { + return mapping; + } - public void setMapping(boolean mapping) { - this.mapping = mapping; - } + public void setMapping(boolean mapping) { + this.mapping = mapping; + } } diff --git a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/ldap/LdapAuthenticationRealm.java b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/ldap/LdapAuthenticationRealm.java index c6d5c860b..7d89a0349 100644 --- a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/ldap/LdapAuthenticationRealm.java +++ b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/ldap/LdapAuthenticationRealm.java @@ -30,65 +30,65 @@ import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; public class LdapAuthenticationRealm extends AbstractAuthenticationRealm{ - private static final Logger _logger = LoggerFactory.getLogger(LdapAuthenticationRealm.class); - - @NotNull + private static final Logger _logger = LoggerFactory.getLogger(LdapAuthenticationRealm.class); + + @NotNull @Size(min=1) private List ldapServers; - - private boolean ldapSupport; - - /** - * - */ - public LdapAuthenticationRealm() { - - } + + private boolean ldapSupport; + + /** + * + */ + public LdapAuthenticationRealm() { + + } - public LdapAuthenticationRealm(boolean ldapSupport) { - this.ldapSupport = ldapSupport; - } - - /** - * @param jdbcTemplate - */ - public LdapAuthenticationRealm(JdbcTemplate jdbcTemplate) { - super(jdbcTemplate); - } - - - @Override - public boolean passwordMatches(UserInfo userInfo, String password) { - boolean isAuthenticated=false; - for (final IAuthenticationServer ldapServer : this.ldapServers) { - String username = userInfo.getUsername(); - if(ldapServer.isMapping()) {//if ldap Context accountMapping equals YES - username = userInfo.getWindowsAccount(); - } + public LdapAuthenticationRealm(boolean ldapSupport) { + this.ldapSupport = ldapSupport; + } + + /** + * @param jdbcTemplate + */ + public LdapAuthenticationRealm(JdbcTemplate jdbcTemplate) { + super(jdbcTemplate); + } + + + @Override + public boolean passwordMatches(UserInfo userInfo, String password) { + boolean isAuthenticated=false; + for (final IAuthenticationServer ldapServer : this.ldapServers) { + String username = userInfo.getUsername(); + if(ldapServer.isMapping()) {//if ldap Context accountMapping equals YES + username = userInfo.getWindowsAccount(); + } _logger.debug("Attempting to authenticate {} at {}", username, ldapServer); try { - isAuthenticated = ldapServer.authenticate(username, password); + isAuthenticated = ldapServer.authenticate(username, password); }catch(Exception e) { - _logger.debug("Attempting Authenticated fail ."); + _logger.debug("Attempting Authenticated fail ."); } if (isAuthenticated ) { - return true; + return true; } - } - return false; - } + } + return false; + } - public void setLdapServers(List ldapServers) { - this.ldapServers = ldapServers; - } + public void setLdapServers(List ldapServers) { + this.ldapServers = ldapServers; + } - public boolean isLdapSupport() { - return ldapSupport; - } + public boolean isLdapSupport() { + return ldapSupport; + } - public void setLdapSupport(boolean ldapSupport) { - this.ldapSupport = ldapSupport; - } + public void setLdapSupport(boolean ldapSupport) { + this.ldapSupport = ldapSupport; + } } diff --git a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/ldap/LdapAuthenticationRealmService.java b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/ldap/LdapAuthenticationRealmService.java index 26d749c29..9acf840f2 100644 --- a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/ldap/LdapAuthenticationRealmService.java +++ b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/ldap/LdapAuthenticationRealmService.java @@ -40,54 +40,54 @@ public class LdapAuthenticationRealmService { public LdapAuthenticationRealmService(CnfLdapContextService ldapContextService) { - this.ldapContextService = ldapContextService; - } + this.ldapContextService = ldapContextService; + } - public LdapAuthenticationRealm getByInstId(String instId) { - LdapAuthenticationRealm authenticationRealm = ldapRealmStore.getIfPresent(instId); - if(authenticationRealm == null) { - List ldapContexts = - ldapContextService.find("where instid = ? and status = 1 ", new Object[]{instId}, new int[]{Types.VARCHAR}); - authenticationRealm = new LdapAuthenticationRealm(false); - if(ldapContexts != null && ldapContexts.size()>0) { - authenticationRealm.setLdapSupport(true); - List ldapAuthenticationServers = new ArrayList(); - for(CnfLdapContext ldapContext : ldapContexts) { - if(ldapContext.getProduct().equalsIgnoreCase("ActiveDirectory")) { - ActiveDirectoryServer ldapServer = new ActiveDirectoryServer(); - ActiveDirectoryUtils ldapUtils = new ActiveDirectoryUtils( - ldapContext.getProviderUrl(), - ldapContext.getPrincipal(), - PasswordReciprocal.getInstance().decoder( - ldapContext.getCredentials()), - ldapContext.getMsadDomain()); - ldapServer.setActiveDirectoryUtils(ldapUtils); - if(ldapContext.getAccountMapping().equalsIgnoreCase("YES")) { - ldapServer.setMapping(true); - } - ldapAuthenticationServers.add(ldapServer); - - }else { - StandardLdapServer standardLdapServer=new StandardLdapServer(); - LdapUtils ldapUtils = new LdapUtils( - ldapContext.getProviderUrl(), - ldapContext.getPrincipal(), - PasswordReciprocal.getInstance().decoder( - ldapContext.getCredentials()), - ldapContext.getBasedn()); - standardLdapServer.setLdapUtils(ldapUtils); - standardLdapServer.setFilterAttribute(ldapContext.getFilters()); - if(ldapContext.getAccountMapping().equalsIgnoreCase("YES")) { - standardLdapServer.setMapping(true); - } - ldapAuthenticationServers.add(standardLdapServer); - } - } - authenticationRealm.setLdapServers(ldapAuthenticationServers); - } - ldapRealmStore.put(instId, authenticationRealm); - } - return authenticationRealm; - + public LdapAuthenticationRealm getByInstId(String instId) { + LdapAuthenticationRealm authenticationRealm = ldapRealmStore.getIfPresent(instId); + if(authenticationRealm == null) { + List ldapContexts = + ldapContextService.find("where instid = ? and status = 1 ", new Object[]{instId}, new int[]{Types.VARCHAR}); + authenticationRealm = new LdapAuthenticationRealm(false); + if(ldapContexts != null && ldapContexts.size()>0) { + authenticationRealm.setLdapSupport(true); + List ldapAuthenticationServers = new ArrayList(); + for(CnfLdapContext ldapContext : ldapContexts) { + if(ldapContext.getProduct().equalsIgnoreCase("ActiveDirectory")) { + ActiveDirectoryServer ldapServer = new ActiveDirectoryServer(); + ActiveDirectoryUtils ldapUtils = new ActiveDirectoryUtils( + ldapContext.getProviderUrl(), + ldapContext.getPrincipal(), + PasswordReciprocal.getInstance().decoder( + ldapContext.getCredentials()), + ldapContext.getMsadDomain()); + ldapServer.setActiveDirectoryUtils(ldapUtils); + if(ldapContext.getAccountMapping().equalsIgnoreCase("YES")) { + ldapServer.setMapping(true); + } + ldapAuthenticationServers.add(ldapServer); + + }else { + StandardLdapServer standardLdapServer=new StandardLdapServer(); + LdapUtils ldapUtils = new LdapUtils( + ldapContext.getProviderUrl(), + ldapContext.getPrincipal(), + PasswordReciprocal.getInstance().decoder( + ldapContext.getCredentials()), + ldapContext.getBasedn()); + standardLdapServer.setLdapUtils(ldapUtils); + standardLdapServer.setFilterAttribute(ldapContext.getFilters()); + if(ldapContext.getAccountMapping().equalsIgnoreCase("YES")) { + standardLdapServer.setMapping(true); + } + ldapAuthenticationServers.add(standardLdapServer); + } + } + authenticationRealm.setLdapServers(ldapAuthenticationServers); + } + ldapRealmStore.put(instId, authenticationRealm); + } + return authenticationRealm; + } } diff --git a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/ldap/StandardLdapServer.java b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/ldap/StandardLdapServer.java index 32c1f5854..0d442f665 100644 --- a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/ldap/StandardLdapServer.java +++ b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/realm/ldap/StandardLdapServer.java @@ -35,75 +35,75 @@ import org.slf4j.LoggerFactory; * */ public final class StandardLdapServer implements IAuthenticationServer { - private static final Logger _logger = LoggerFactory.getLogger(StandardLdapServer.class); - - LdapUtils ldapUtils; - - String filterAttribute; - - boolean mapping; - - /* (non-Javadoc) - * @see com.connsec.web.authentication.realm.IAuthenticationServer#authenticate(java.lang.String, java.lang.String) - */ - @Override - public boolean authenticate(String username, String password) { - String queryFilter = String.format(filterAttribute, username); - _logger.info(" filter : " + queryFilter); - String dn=""; - SearchControls constraints = new SearchControls(); - constraints.setSearchScope(ldapUtils.getSearchScope()); - try { - NamingEnumeration results = ldapUtils.getConnection() - .search(ldapUtils.getBaseDN(), queryFilter, constraints); - - if (results == null || !results.hasMore()) { - _logger.error("Ldap user "+username +" not found . "); - return false; - }else{ - while (results != null && results.hasMore()) { - SearchResult sr = (SearchResult) results.next(); - //String rdn = sr.getName(); - dn = sr.getNameInNamespace(); - _logger.debug("Directory user dn is "+dn+" ."); - } - } - } catch (NamingException e) { - _logger.error("query throw NamingException:" + e.getMessage()); - } finally { - //ldapUtils.close(); - } - - LdapUtils ldapPassWordValid=new LdapUtils(ldapUtils.getProviderUrl(),dn,password); - ldapPassWordValid.openConnection(); - if(ldapPassWordValid.getCtx()!=null){ - _logger.debug("Directory user " + username + " is validate ."); - ldapPassWordValid.close(); - return true; - } - return false; - } - - public LdapUtils getLdapUtils() { - return ldapUtils; - } - public void setLdapUtils(LdapUtils ldapUtils) { - this.ldapUtils = ldapUtils; - } - public String getFilterAttribute() { - return filterAttribute; - } - public void setFilterAttribute(String filterAttribute) { - this.filterAttribute = filterAttribute; - } + private static final Logger _logger = LoggerFactory.getLogger(StandardLdapServer.class); + + LdapUtils ldapUtils; + + String filterAttribute; + + boolean mapping; + + /* (non-Javadoc) + * @see com.connsec.web.authentication.realm.IAuthenticationServer#authenticate(java.lang.String, java.lang.String) + */ + @Override + public boolean authenticate(String username, String password) { + String queryFilter = String.format(filterAttribute, username); + _logger.info(" filter : " + queryFilter); + String dn=""; + SearchControls constraints = new SearchControls(); + constraints.setSearchScope(ldapUtils.getSearchScope()); + try { + NamingEnumeration results = ldapUtils.getConnection() + .search(ldapUtils.getBaseDN(), queryFilter, constraints); + + if (results == null || !results.hasMore()) { + _logger.error("Ldap user "+username +" not found . "); + return false; + }else{ + while (results != null && results.hasMore()) { + SearchResult sr = (SearchResult) results.next(); + //String rdn = sr.getName(); + dn = sr.getNameInNamespace(); + _logger.debug("Directory user dn is "+dn+" ."); + } + } + } catch (NamingException e) { + _logger.error("query throw NamingException:" + e.getMessage()); + } finally { + //ldapUtils.close(); + } + + LdapUtils ldapPassWordValid=new LdapUtils(ldapUtils.getProviderUrl(),dn,password); + ldapPassWordValid.openConnection(); + if(ldapPassWordValid.getCtx()!=null){ + _logger.debug("Directory user " + username + " is validate ."); + ldapPassWordValid.close(); + return true; + } + return false; + } + + public LdapUtils getLdapUtils() { + return ldapUtils; + } + public void setLdapUtils(LdapUtils ldapUtils) { + this.ldapUtils = ldapUtils; + } + public String getFilterAttribute() { + return filterAttribute; + } + public void setFilterAttribute(String filterAttribute) { + this.filterAttribute = filterAttribute; + } - @Override - public boolean isMapping() { - return mapping; - } + @Override + public boolean isMapping() { + return mapping; + } - public void setMapping(boolean mapping) { - this.mapping = mapping; - } + public void setMapping(boolean mapping) { + this.mapping = mapping; + } } diff --git a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/support/cas/CasTrustLoginService.java b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/support/cas/CasTrustLoginService.java index 3982d0ef2..acb8afd0f 100644 --- a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/support/cas/CasTrustLoginService.java +++ b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/support/cas/CasTrustLoginService.java @@ -33,25 +33,25 @@ public class CasTrustLoginService { Cas20ServiceTicketValidator cas20ServiceTicketValidator; public CasTrustLoginService(String casServerUrlPrefix,String service) { - this.service = service; + this.service = service; this.cas20ServiceTicketValidator = new Cas20ServiceTicketValidator(casServerUrlPrefix); } public String buildLoginUser(String ticket) { - _logger.debug("build Login User ."); + _logger.debug("build Login User ."); String user = null; Assertion assertion; - try { - assertion = cas20ServiceTicketValidator.validate(ticket, service); - if(assertion != null) { - user = assertion.getPrincipal().getName(); - } - } catch (TicketValidationException e) { - _logger.error("cas TicketValidationException" , e); - e.printStackTrace(); - } + try { + assertion = cas20ServiceTicketValidator.validate(ticket, service); + if(assertion != null) { + user = assertion.getPrincipal().getName(); + } + } catch (TicketValidationException e) { + _logger.error("cas TicketValidationException" , e); + e.printStackTrace(); + } - _logger.debug("cas user : {}" , user); + _logger.debug("cas user : {}" , user); return user; } diff --git a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/support/cas/HttpTrustEntryPoint.java b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/support/cas/HttpTrustEntryPoint.java index 496f113d8..9fd908080 100644 --- a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/support/cas/HttpTrustEntryPoint.java +++ b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/authn/support/cas/HttpTrustEntryPoint.java @@ -38,49 +38,49 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value = "/login") public class HttpTrustEntryPoint { - private static final Logger _logger = LoggerFactory.getLogger(HttpTrustEntryPoint.class); + private static final Logger _logger = LoggerFactory.getLogger(HttpTrustEntryPoint.class); - @Autowired - ApplicationConfig applicationConfig; + @Autowired + ApplicationConfig applicationConfig; - @Autowired + @Autowired AbstractAuthenticationProvider authenticationProvider ; - - @Autowired - AuthTokenService authTokenService; - - @Autowired - CasTrustLoginService casTrustLoginService; - - @GetMapping(value={"/trust"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message trust(@RequestParam(value = WebConstants.CAS_TICKET_PARAMETER, required = true) String ticket) { - try { - //for ticket Login - _logger.debug("ticket : {}" , ticket); - - String username = casTrustLoginService.buildLoginUser(ticket); - - if(username != null) { - LoginCredential loginCredential =new LoginCredential(username,"",ConstsLoginType.CAS); - Authentication authentication = authenticationProvider.authenticate(loginCredential,true); - _logger.debug("CAS Logined in , username {}" , username); - AuthJwt authJwt = authTokenService.genAuthJwt(authentication); - return new Message<>(authJwt); - } - }catch(Exception e) { - _logger.error("Exception ",e); - } - - return new Message<>(Message.FAIL); - } + + @Autowired + AuthTokenService authTokenService; + + @Autowired + CasTrustLoginService casTrustLoginService; + + @GetMapping(value={"/trust"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message trust(@RequestParam(value = WebConstants.CAS_TICKET_PARAMETER, required = true) String ticket) { + try { + //for ticket Login + _logger.debug("ticket : {}" , ticket); + + String username = casTrustLoginService.buildLoginUser(ticket); + + if(username != null) { + LoginCredential loginCredential =new LoginCredential(username,"",ConstsLoginType.CAS); + Authentication authentication = authenticationProvider.authenticate(loginCredential,true); + _logger.debug("CAS Logined in , username {}" , username); + AuthJwt authJwt = authTokenService.genAuthJwt(authentication); + return new Message<>(authJwt); + } + }catch(Exception e) { + _logger.error("Exception ",e); + } + + return new Message<>(Message.FAIL); + } - public void setApplicationConfig(ApplicationConfig applicationConfig) { - this.applicationConfig = applicationConfig; - } + public void setApplicationConfig(ApplicationConfig applicationConfig) { + this.applicationConfig = applicationConfig; + } - public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) { - this.authenticationProvider = authenticationProvider; - } - + public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) { + this.authenticationProvider = authenticationProvider; + } + } diff --git a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/autoconfigure/AuthnProviderAutoConfiguration.java b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/autoconfigure/AuthnProviderAutoConfiguration.java index 35624dcb6..92337c578 100644 --- a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/autoconfigure/AuthnProviderAutoConfiguration.java +++ b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/autoconfigure/AuthnProviderAutoConfiguration.java @@ -41,67 +41,67 @@ public class AuthnProviderAutoConfiguration { @Bean AbstractAuthenticationProvider authenticationProvider( - NormalAuthenticationProvider normalAuthenticationProvider, - MobileAuthenticationProvider mobileAuthenticationProvider, - TrustedAuthenticationProvider trustedAuthenticationProvider - ) { - AuthenticationProviderFactory authenticationProvider = new AuthenticationProviderFactory(); - authenticationProvider.addAuthenticationProvider(normalAuthenticationProvider); - authenticationProvider.addAuthenticationProvider(mobileAuthenticationProvider); - authenticationProvider.addAuthenticationProvider(trustedAuthenticationProvider); - return authenticationProvider; + NormalAuthenticationProvider normalAuthenticationProvider, + MobileAuthenticationProvider mobileAuthenticationProvider, + TrustedAuthenticationProvider trustedAuthenticationProvider + ) { + AuthenticationProviderFactory authenticationProvider = new AuthenticationProviderFactory(); + authenticationProvider.addAuthenticationProvider(normalAuthenticationProvider); + authenticationProvider.addAuthenticationProvider(mobileAuthenticationProvider); + authenticationProvider.addAuthenticationProvider(trustedAuthenticationProvider); + return authenticationProvider; } @Bean NormalAuthenticationProvider normalAuthenticationProvider( - AbstractAuthenticationRealm authenticationRealm, - ApplicationConfig applicationConfig, - SessionManager sessionManager, - AuthTokenService authTokenService - ) { - _logger.debug("init authentication Provider ."); - return new NormalAuthenticationProvider( - authenticationRealm, - applicationConfig, - sessionManager, - authTokenService - ); + AbstractAuthenticationRealm authenticationRealm, + ApplicationConfig applicationConfig, + SessionManager sessionManager, + AuthTokenService authTokenService + ) { + _logger.debug("init authentication Provider ."); + return new NormalAuthenticationProvider( + authenticationRealm, + applicationConfig, + sessionManager, + authTokenService + ); } @Bean MobileAuthenticationProvider mobileAuthenticationProvider( - AbstractAuthenticationRealm authenticationRealm, - ApplicationConfig applicationConfig, - SmsOtpAuthnService smsAuthnService, - SessionManager sessionManager - ) { - _logger.debug("init Mobile authentication Provider ."); - return new MobileAuthenticationProvider( - authenticationRealm, - applicationConfig, - smsAuthnService, - sessionManager - ); + AbstractAuthenticationRealm authenticationRealm, + ApplicationConfig applicationConfig, + SmsOtpAuthnService smsAuthnService, + SessionManager sessionManager + ) { + _logger.debug("init Mobile authentication Provider ."); + return new MobileAuthenticationProvider( + authenticationRealm, + applicationConfig, + smsAuthnService, + sessionManager + ); } @Bean TrustedAuthenticationProvider trustedAuthenticationProvider( - AbstractAuthenticationRealm authenticationRealm, - ApplicationConfig applicationConfig, - SessionManager sessionManager - ) { - _logger.debug("init Mobile authentication Provider ."); - return new TrustedAuthenticationProvider( - authenticationRealm, - applicationConfig, - sessionManager - ); + AbstractAuthenticationRealm authenticationRealm, + ApplicationConfig applicationConfig, + SessionManager sessionManager + ) { + _logger.debug("init Mobile authentication Provider ."); + return new TrustedAuthenticationProvider( + authenticationRealm, + applicationConfig, + sessionManager + ); } @Bean PasswordPolicyValidatorService passwordPolicyValidatorService( - CnfPasswordPolicyService cnfPasswordPolicyService, - MessageSource messageSource) { + CnfPasswordPolicyService cnfPasswordPolicyService, + MessageSource messageSource) { return new PasswordPolicyValidatorServiceImpl(cnfPasswordPolicyService,messageSource); } diff --git a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/autoconfigure/CasAuthnAutoConfiguration.java b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/autoconfigure/CasAuthnAutoConfiguration.java index 4643b0612..9cb94c60f 100644 --- a/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/autoconfigure/CasAuthnAutoConfiguration.java +++ b/maxkey-authentications/maxkey-authentication-provider-mgt/src/main/java/org/dromara/maxkey/autoconfigure/CasAuthnAutoConfiguration.java @@ -36,8 +36,8 @@ public class CasAuthnAutoConfiguration { @Bean CasTrustLoginService casTrustLoginService(LoginConfig loginConfig) { CasTrustLoginService casTrustLoginService = new CasTrustLoginService( - loginConfig.getCasServerUrlPrefix() , - loginConfig.getCasService()); + loginConfig.getCasServerUrlPrefix() , + loginConfig.getCasService()); _logger.debug("CAS Login Service init."); return casTrustLoginService; } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/AbstractAuthenticationProvider.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/AbstractAuthenticationProvider.java index 01a349200..b50894c6a 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/AbstractAuthenticationProvider.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/AbstractAuthenticationProvider.java @@ -58,19 +58,19 @@ public abstract class AbstractAuthenticationProvider { public static String PROVIDER_SUFFIX = "AuthenticationProvider"; public class AuthType{ - public static final String NORMAL = "normal"; - public static final String TFA = "tfa"; - public static final String MOBILE = "mobile"; - public static final String TRUSTED = "trusted"; + public static final String NORMAL = "normal"; + public static final String TFA = "tfa"; + public static final String MOBILE = "mobile"; + public static final String TRUSTED = "trusted"; /** * 扫描认证 */ - public static final String SCAN_CODE = "scancode"; + public static final String SCAN_CODE = "scancode"; /** * 手机端APP */ - public static final String APP = "app"; + public static final String APP = "app"; } protected ApplicationConfig applicationConfig; @@ -96,7 +96,7 @@ public abstract class AbstractAuthenticationProvider { public abstract Authentication doAuthenticate(LoginCredential authentication); public Authentication doTwoFactorAuthenticate(LoginCredential credential , UserInfo user) { - return null; + return null; } @SuppressWarnings("rawtypes") @@ -105,11 +105,11 @@ public abstract class AbstractAuthenticationProvider { } public Authentication authenticate(LoginCredential authentication){ - return null; + return null; } public Authentication authenticate(LoginCredential authentication,boolean trusted) { - return null; + return null; } /** @@ -130,7 +130,7 @@ public abstract class AbstractAuthenticationProvider { for(GrantedAuthority administratorsAuthority : grantedAdministratorsAuthoritys) { if(grantedAuthoritys.contains(administratorsAuthority)) { - principal.setRoleAdministrators(true); + principal.setRoleAdministrators(true); _logger.trace("ROLE ADMINISTRATORS Authentication ."); } } @@ -140,7 +140,7 @@ public abstract class AbstractAuthenticationProvider { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( - principal, + principal, "PASSWORD", grantedAuthoritys ); @@ -154,10 +154,10 @@ public abstract class AbstractAuthenticationProvider { session.setAuthentication(authenticationToken); if(credential.getAuthType().equalsIgnoreCase(AuthType.NORMAL) - && userInfo.getAuthnType() > ConstsTwoFactor.NONE ) { - //用户配置二次认证 - principal.setTwoFactor(userInfo.getAuthnType()); - this.sessionManager.createTwoFactor(session.getId(), session); + && userInfo.getAuthnType() > ConstsTwoFactor.NONE ) { + //用户配置二次认证 + principal.setTwoFactor(userInfo.getAuthnType()); + this.sessionManager.createTwoFactor(session.getId(), session); } //create session @@ -241,34 +241,34 @@ public abstract class AbstractAuthenticationProvider { loginUser.setDisplayName("not exist"); loginUser.setLoginCount(0); authenticationRealm.insertLoginHistory( - loginUser, - ConstsLoginType.LOCAL, - "", - i18nMessage, - WebConstants.LOGIN_RESULT.USER_NOT_EXIST); + loginUser, + ConstsLoginType.LOCAL, + "", + i18nMessage, + WebConstants.LOGIN_RESULT.USER_NOT_EXIST); throw new BadCredentialsException(i18nMessage); } return true; } protected boolean statusValid(LoginCredential loginCredential , UserInfo userInfo) { - if(userInfo.getIsLocked()==ConstsStatus.LOCK) { - authenticationRealm.insertLoginHistory( - userInfo, + if(userInfo.getIsLocked()==ConstsStatus.LOCK) { + authenticationRealm.insertLoginHistory( + userInfo, loginCredential.getAuthType(), loginCredential.getProvider(), loginCredential.getCode(), WebConstants.LOGIN_RESULT.USER_LOCKED ); - }else if(userInfo.getStatus()!=ConstsStatus.ACTIVE) { - authenticationRealm.insertLoginHistory( - userInfo, + }else if(userInfo.getStatus()!=ConstsStatus.ACTIVE) { + authenticationRealm.insertLoginHistory( + userInfo, loginCredential.getAuthType(), loginCredential.getProvider(), loginCredential.getCode(), WebConstants.LOGIN_RESULT.USER_INACTIVE ); - } + } return true; } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/AuthenticationProviderFactory.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/AuthenticationProviderFactory.java index a06312720..a8a3ad76a 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/AuthenticationProviderFactory.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/AuthenticationProviderFactory.java @@ -26,33 +26,33 @@ public class AuthenticationProviderFactory extends AbstractAuthenticationProvide @Override public Authentication authenticate(LoginCredential authentication){ - if(authentication.getAuthType().equalsIgnoreCase("trusted")) { - //risk remove - return null; - } - AbstractAuthenticationProvider provider = providers.get(authentication.getAuthType() + PROVIDER_SUFFIX); - - return provider == null ? null : provider.doAuthenticate(authentication); + if(authentication.getAuthType().equalsIgnoreCase("trusted")) { + //risk remove + return null; + } + AbstractAuthenticationProvider provider = providers.get(authentication.getAuthType() + PROVIDER_SUFFIX); + + return provider == null ? null : provider.doAuthenticate(authentication); } @Override public Authentication authenticate(LoginCredential authentication,boolean trusted){ - AbstractAuthenticationProvider provider = providers.get(AuthType.TRUSTED + PROVIDER_SUFFIX); - return provider.doAuthenticate(authentication); + AbstractAuthenticationProvider provider = providers.get(AuthType.TRUSTED + PROVIDER_SUFFIX); + return provider.doAuthenticate(authentication); } public void addAuthenticationProvider(AbstractAuthenticationProvider provider) { - providers.put(provider.getProviderName(), provider); + providers.put(provider.getProviderName(), provider); } - @Override - public String getProviderName() { - return "AuthenticationProviderFactory"; - } + @Override + public String getProviderName() { + return "AuthenticationProviderFactory"; + } - @Override - public Authentication doAuthenticate(LoginCredential authentication) { - //AuthenticationProvider Factory do nothing - return null; - } + @Override + public Authentication doAuthenticate(LoginCredential authentication) { + //AuthenticationProvider Factory do nothing + return null; + } } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/impl/MfaAuthenticationProvider.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/impl/MfaAuthenticationProvider.java index 54064f9d9..e7af884e2 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/impl/MfaAuthenticationProvider.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/impl/MfaAuthenticationProvider.java @@ -50,62 +50,62 @@ public class MfaAuthenticationProvider extends AbstractAuthenticationProvider { public MfaAuthenticationProvider() { - super(); - } + super(); + } public MfaAuthenticationProvider( - AbstractAuthenticationRealm authenticationRealm, - ApplicationConfig applicationConfig, - SessionManager sessionManager, - AuthTokenService authTokenService) { - this.authenticationRealm = authenticationRealm; - this.applicationConfig = applicationConfig; - this.sessionManager = sessionManager; - this.authTokenService = authTokenService; - } + AbstractAuthenticationRealm authenticationRealm, + ApplicationConfig applicationConfig, + SessionManager sessionManager, + AuthTokenService authTokenService) { + this.authenticationRealm = authenticationRealm; + this.applicationConfig = applicationConfig; + this.sessionManager = sessionManager; + this.authTokenService = authTokenService; + } @Override - public Authentication doAuthenticate(LoginCredential loginCredential) { - UsernamePasswordAuthenticationToken authenticationToken = null; - _logger.debug("Trying to authenticate user '{}' via {}", + public Authentication doAuthenticate(LoginCredential loginCredential) { + UsernamePasswordAuthenticationToken authenticationToken = null; + _logger.debug("Trying to authenticate user '{}' via {}", loginCredential.getPrincipal(), getProviderName()); try { - - _logger.debug("authentication {}" , loginCredential); - - emptyPasswordValid(loginCredential.getPassword()); - - UserInfo userInfo = null; - - emptyUsernameValid(loginCredential.getUsername()); - - userInfo = loadUserInfo(loginCredential.getUsername(),loginCredential.getPassword()); - - isUserExist(loginCredential , userInfo); - - statusValid(loginCredential , userInfo); - //mfa - mfacaptchaValid(loginCredential.getOtpCaptcha(),userInfo); - - //Validate PasswordPolicy - authenticationRealm.getLoginService().passwordPolicyValid(userInfo); - - //Match password - authenticationRealm.passwordMatches(userInfo, loginCredential.getPassword()); + + _logger.debug("authentication {}" , loginCredential); + + emptyPasswordValid(loginCredential.getPassword()); + + UserInfo userInfo = null; + + emptyUsernameValid(loginCredential.getUsername()); + + userInfo = loadUserInfo(loginCredential.getUsername(),loginCredential.getPassword()); + + isUserExist(loginCredential , userInfo); + + statusValid(loginCredential , userInfo); + //mfa + mfacaptchaValid(loginCredential.getOtpCaptcha(),userInfo); + + //Validate PasswordPolicy + authenticationRealm.getLoginService().passwordPolicyValid(userInfo); + + //Match password + authenticationRealm.passwordMatches(userInfo, loginCredential.getPassword()); - //apply PasswordSetType and resetBadPasswordCount - authenticationRealm.getLoginService().applyPasswordPolicy(userInfo); - - authenticationToken = createOnlineTicket(loginCredential,userInfo); - // user authenticated - _logger.debug("'{}' authenticated successfully by {}.", - loginCredential.getPrincipal(), getProviderName()); - - authenticationRealm.insertLoginHistory(userInfo, - ConstsLoginType.LOCAL, - "", - "xe00000004", - WebConstants.LOGIN_RESULT.SUCCESS); + //apply PasswordSetType and resetBadPasswordCount + authenticationRealm.getLoginService().applyPasswordPolicy(userInfo); + + authenticationToken = createOnlineTicket(loginCredential,userInfo); + // user authenticated + _logger.debug("'{}' authenticated successfully by {}.", + loginCredential.getPrincipal(), getProviderName()); + + authenticationRealm.insertLoginHistory(userInfo, + ConstsLoginType.LOCAL, + "", + "xe00000004", + WebConstants.LOGIN_RESULT.SUCCESS); } catch (AuthenticationException e) { _logger.error("Failed to authenticate user {} via {}: {}", new Object[] { loginCredential.getPrincipal(), diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/impl/NormalAuthenticationProvider.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/impl/NormalAuthenticationProvider.java index 310df9427..2fd8a9269 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/impl/NormalAuthenticationProvider.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/impl/NormalAuthenticationProvider.java @@ -51,65 +51,65 @@ public class NormalAuthenticationProvider extends AbstractAuthenticationProvider public NormalAuthenticationProvider() { - super(); - } + super(); + } public NormalAuthenticationProvider( - AbstractAuthenticationRealm authenticationRealm, - ApplicationConfig applicationConfig, - SessionManager sessionManager, - AuthTokenService authTokenService) { - this.authenticationRealm = authenticationRealm; - this.applicationConfig = applicationConfig; - this.sessionManager = sessionManager; - this.authTokenService = authTokenService; - } + AbstractAuthenticationRealm authenticationRealm, + ApplicationConfig applicationConfig, + SessionManager sessionManager, + AuthTokenService authTokenService) { + this.authenticationRealm = authenticationRealm; + this.applicationConfig = applicationConfig; + this.sessionManager = sessionManager; + this.authTokenService = authTokenService; + } @Override - public Authentication doAuthenticate(LoginCredential loginCredential) { - UsernamePasswordAuthenticationToken authenticationToken = null; - _logger.debug("Trying to authenticate user '{}' via {}", + public Authentication doAuthenticate(LoginCredential loginCredential) { + UsernamePasswordAuthenticationToken authenticationToken = null; + _logger.debug("Trying to authenticate user '{}' via {}", loginCredential.getPrincipal(), getProviderName()); try { - - _logger.debug("authentication {}" , loginCredential); - - if(this.applicationConfig.getLoginConfig().isCaptcha()) { - captchaValid(loginCredential.getState(),loginCredential.getCaptcha()); - } - - emptyPasswordValid(loginCredential.getPassword()); - - emptyUsernameValid(loginCredential.getUsername()); - - UserInfo userInfo = loadUserInfo(loginCredential.getUsername(),loginCredential.getPassword()); - - isUserExist(loginCredential , userInfo); - - //Validate PasswordPolicy - authenticationRealm.getLoginService().passwordPolicyValid(userInfo); - - statusValid(loginCredential , userInfo); - - //Match password - authenticationRealm.passwordMatches(userInfo, loginCredential.getPassword()); + + _logger.debug("authentication {}" , loginCredential); + + if(this.applicationConfig.getLoginConfig().isCaptcha()) { + captchaValid(loginCredential.getState(),loginCredential.getCaptcha()); + } + + emptyPasswordValid(loginCredential.getPassword()); + + emptyUsernameValid(loginCredential.getUsername()); + + UserInfo userInfo = loadUserInfo(loginCredential.getUsername(),loginCredential.getPassword()); + + isUserExist(loginCredential , userInfo); + + //Validate PasswordPolicy + authenticationRealm.getLoginService().passwordPolicyValid(userInfo); + + statusValid(loginCredential , userInfo); + + //Match password + authenticationRealm.passwordMatches(userInfo, loginCredential.getPassword()); - //apply PasswordSetType and resetBadPasswordCount - authenticationRealm.getLoginService().applyPasswordPolicy(userInfo); - - authenticationToken = createOnlineTicket(loginCredential,userInfo); - // user authenticated - _logger.debug("'{}' authenticated successfully by {}.", - loginCredential.getPrincipal(), getProviderName()); - - authenticationRealm.insertLoginHistory(userInfo, - ConstsLoginType.LOCAL, - "", - "xe00000004", - WebConstants.LOGIN_RESULT.SUCCESS); + //apply PasswordSetType and resetBadPasswordCount + authenticationRealm.getLoginService().applyPasswordPolicy(userInfo); + + authenticationToken = createOnlineTicket(loginCredential,userInfo); + // user authenticated + _logger.debug("'{}' authenticated successfully by {}.", + loginCredential.getPrincipal(), getProviderName()); + + authenticationRealm.insertLoginHistory(userInfo, + ConstsLoginType.LOCAL, + "", + "xe00000004", + WebConstants.LOGIN_RESULT.SUCCESS); } catch (AuthenticationException e) { _logger.error("Failed to authenticate user {} via {}: {}", - loginCredential.getPrincipal(), + loginCredential.getPrincipal(), getProviderName(), e.getMessage() ); WebContext.setAttribute( @@ -131,8 +131,8 @@ public class NormalAuthenticationProvider extends AbstractAuthenticationProvider */ protected void captchaValid(String state ,String captcha) { // for basic - if(!authTokenService.validateCaptcha(state,captcha)) { - throw new BadCredentialsException(WebContext.getI18nValue("login.error.captcha")); - } + if(!authTokenService.validateCaptcha(state,captcha)) { + throw new BadCredentialsException(WebContext.getI18nValue("login.error.captcha")); + } } } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/impl/TrustedAuthenticationProvider.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/impl/TrustedAuthenticationProvider.java index 9b03c1e57..653aed16d 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/impl/TrustedAuthenticationProvider.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/impl/TrustedAuthenticationProvider.java @@ -43,26 +43,26 @@ public class TrustedAuthenticationProvider extends AbstractAuthenticationProvide } public TrustedAuthenticationProvider() { - super(); - } + super(); + } public TrustedAuthenticationProvider( - AbstractAuthenticationRealm authenticationRealm, - ApplicationConfig applicationConfig, - SessionManager sessionManager) { - this.authenticationRealm = authenticationRealm; - this.applicationConfig = applicationConfig; - this.sessionManager = sessionManager; - } + AbstractAuthenticationRealm authenticationRealm, + ApplicationConfig applicationConfig, + SessionManager sessionManager) { + this.authenticationRealm = authenticationRealm; + this.applicationConfig = applicationConfig; + this.sessionManager = sessionManager; + } @Override - public Authentication doAuthenticate(LoginCredential loginCredential) { + public Authentication doAuthenticate(LoginCredential loginCredential) { UserInfo loadeduserInfo = loadUserInfo(loginCredential.getUsername(), ""); statusValid(loginCredential , loadeduserInfo); if (loadeduserInfo != null) { //Validate PasswordPolicy //authenticationRealm.getLoginService().passwordPolicyValid(loadeduserInfo); - + //apply PasswordSetType and resetBadPasswordCount //authenticationRealm.getLoginService().applyPasswordPolicy(loadeduserInfo); diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/twofactor/TwoFactorAuthenticationProvider.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/twofactor/TwoFactorAuthenticationProvider.java index f97fddf45..c8ea63c4f 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/twofactor/TwoFactorAuthenticationProvider.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/twofactor/TwoFactorAuthenticationProvider.java @@ -42,84 +42,84 @@ public class TwoFactorAuthenticationProvider extends AbstractAuthenticationProvi } public TwoFactorAuthenticationProvider( - AbstractAuthenticationRealm authenticationRealm, - SessionManager sessionManager, - LoginService loginService, - AuthTokenService authTokenService) { - this.authenticationRealm = authenticationRealm; - this.sessionManager = sessionManager; - this.authTokenService = authTokenService; - } + AbstractAuthenticationRealm authenticationRealm, + SessionManager sessionManager, + LoginService loginService, + AuthTokenService authTokenService) { + this.authenticationRealm = authenticationRealm; + this.sessionManager = sessionManager; + this.authTokenService = authTokenService; + } public void addProvider(int twoFactor,AbstractAuthenticationProvider provider) { - twoFactorProvider.put(twoFactor+"", provider); + twoFactorProvider.put(twoFactor+"", provider); } @Override - public Authentication doAuthenticate(LoginCredential credential) { - logger.debug("Credential {}" , credential); - emptyOtpCaptchaValid(credential.getOtpCaptcha()); + public Authentication doAuthenticate(LoginCredential credential) { + logger.debug("Credential {}" , credential); + emptyOtpCaptchaValid(credential.getOtpCaptcha()); try { - if(authTokenService.validateJwtToken(credential.getJwtToken())) { - //解析refreshToken,转换会话id - JWTClaimsSet claim = authTokenService.resolve(credential.getJwtToken()); - String sessionId = claim.getJWTID(); - String userId = claim.getClaim(ConstsJwt.USER_ID).toString(); - //String style = claim.getClaim(AuthorizationUtils.STYLE).toString(); - //尝试刷新会话 - logger.trace("Try to get user {} , sessionId [{}]" , userId, sessionId); - Session session = sessionManager.getTwoFactor(sessionId); - if(session != null) {//有会话 - Authentication twoFactorAuth = null; - SignPrincipal principal =(SignPrincipal) session.getAuthentication().getPrincipal(); - String loginType; - switch(principal.getTwoFactor()) { - case ConstsTwoFactor.TOTP -> { - loginType = ConstsLoginType.TwoFactor.TWO_FACTOR_TOTP; - } - case ConstsTwoFactor.EMAIL -> { - loginType = ConstsLoginType.TwoFactor.TWO_FACTOR_EMAIL; - } - case ConstsTwoFactor.SMS -> { - loginType = ConstsLoginType.TwoFactor.TWO_FACTOR_MOBILE; - } - default ->{ - loginType = ConstsLoginType.TwoFactor.TWO_FACTOR_TOTP; - } - } - logger.debug("loginType {}",loginType); - AbstractAuthenticationProvider authenticationProvider = twoFactorProvider.get(principal.getTwoFactor()+""); - logger.debug("Provider {}",authenticationProvider.getProviderName()); - UserInfo user = authenticationRealm.loadUserInfoById(userId); - //进行二次认证校验 - twoFactorAuth = authenticationProvider.doTwoFactorAuthenticate(credential , user); + if(authTokenService.validateJwtToken(credential.getJwtToken())) { + //解析refreshToken,转换会话id + JWTClaimsSet claim = authTokenService.resolve(credential.getJwtToken()); + String sessionId = claim.getJWTID(); + String userId = claim.getClaim(ConstsJwt.USER_ID).toString(); + //String style = claim.getClaim(AuthorizationUtils.STYLE).toString(); + //尝试刷新会话 + logger.trace("Try to get user {} , sessionId [{}]" , userId, sessionId); + Session session = sessionManager.getTwoFactor(sessionId); + if(session != null) {//有会话 + Authentication twoFactorAuth = null; + SignPrincipal principal =(SignPrincipal) session.getAuthentication().getPrincipal(); + String loginType; + switch(principal.getTwoFactor()) { + case ConstsTwoFactor.TOTP -> { + loginType = ConstsLoginType.TwoFactor.TWO_FACTOR_TOTP; + } + case ConstsTwoFactor.EMAIL -> { + loginType = ConstsLoginType.TwoFactor.TWO_FACTOR_EMAIL; + } + case ConstsTwoFactor.SMS -> { + loginType = ConstsLoginType.TwoFactor.TWO_FACTOR_MOBILE; + } + default ->{ + loginType = ConstsLoginType.TwoFactor.TWO_FACTOR_TOTP; + } + } + logger.debug("loginType {}",loginType); + AbstractAuthenticationProvider authenticationProvider = twoFactorProvider.get(principal.getTwoFactor()+""); + logger.debug("Provider {}",authenticationProvider.getProviderName()); + UserInfo user = authenticationRealm.loadUserInfoById(userId); + //进行二次认证校验 + twoFactorAuth = authenticationProvider.doTwoFactorAuthenticate(credential , user); - if(twoFactorAuth != null) { - logger.debug("twoFactorAuth success ."); - //设置正常状态 - principal.clearTwoFactor(); - //重新设置令牌参数 - sessionManager.create(sessionId, session); - sessionManager.removeTwoFactor(sessionId); - AuthorizationUtils.setAuthentication(session.getAuthentication()); - authenticationRealm.insertLoginHistory(user, - loginType, - "", - "xe00000004", - WebConstants.LOGIN_RESULT.SUCCESS); - return session.getAuthentication(); - }else { - logger.debug("twoFactorAuth fail ."); - } - }else {//无会话 - logger.debug("Session is timeout , sessionId [{}]" , sessionId); - } - }else {//验证失效 - logger.debug("jwt token is not validate ."); - } + if(twoFactorAuth != null) { + logger.debug("twoFactorAuth success ."); + //设置正常状态 + principal.clearTwoFactor(); + //重新设置令牌参数 + sessionManager.create(sessionId, session); + sessionManager.removeTwoFactor(sessionId); + AuthorizationUtils.setAuthentication(session.getAuthentication()); + authenticationRealm.insertLoginHistory(user, + loginType, + "", + "xe00000004", + WebConstants.LOGIN_RESULT.SUCCESS); + return session.getAuthentication(); + }else { + logger.debug("twoFactorAuth fail ."); + } + }else {//无会话 + logger.debug("Session is timeout , sessionId [{}]" , sessionId); + } + }else {//验证失效 + logger.debug("jwt token is not validate ."); + } }catch(Exception e) { - logger.error("Exception !",e); - } + logger.error("Exception !",e); + } return null; } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/twofactor/impl/TwoFactorEmailAuthenticationProvider.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/twofactor/impl/TwoFactorEmailAuthenticationProvider.java index 193578e35..feba1d984 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/twofactor/impl/TwoFactorEmailAuthenticationProvider.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/twofactor/impl/TwoFactorEmailAuthenticationProvider.java @@ -34,24 +34,24 @@ public class TwoFactorEmailAuthenticationProvider extends AbstractAuthentication } public TwoFactorEmailAuthenticationProvider(MailOtpAuthnService mailOtpAuthnService) { - this.mailOtpAuthnService = mailOtpAuthnService; - } + this.mailOtpAuthnService = mailOtpAuthnService; + } @Override - public Authentication doAuthenticate(LoginCredential credential) { - return null; + public Authentication doAuthenticate(LoginCredential credential) { + return null; } @Override - public Authentication doTwoFactorAuthenticate(LoginCredential credential,UserInfo user) { - UsernamePasswordAuthenticationToken authenticationToken = null; - logger.debug("loginCredential {}" , credential); + public Authentication doTwoFactorAuthenticate(LoginCredential credential,UserInfo user) { + UsernamePasswordAuthenticationToken authenticationToken = null; + logger.debug("loginCredential {}" , credential); try { - //短信验证码校验 - matches(credential.getOtpCaptcha(),user); - - authenticationToken = new UsernamePasswordAuthenticationToken(credential.getUsername(),"email"); - + //短信验证码校验 + matches(credential.getOtpCaptcha(),user); + + authenticationToken = new UsernamePasswordAuthenticationToken(credential.getUsername(),"email"); + } catch (AuthenticationException e) { logger.error("Failed to authenticate user {} via {}: {}",credential.getPrincipal(), getProviderName(), @@ -75,7 +75,7 @@ public class TwoFactorEmailAuthenticationProvider extends AbstractAuthentication * @param userInfo UserInfo */ protected void matches(String captcha, UserInfo userInfo) { - // for mobile password + // for mobile password UserInfo validUserInfo = new UserInfo(); validUserInfo.setUsername(userInfo.getUsername()); validUserInfo.setId(userInfo.getId()); diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/twofactor/impl/TwoFactorMobileAuthenticationProvider.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/twofactor/impl/TwoFactorMobileAuthenticationProvider.java index da34183a3..840b7eeb0 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/twofactor/impl/TwoFactorMobileAuthenticationProvider.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/twofactor/impl/TwoFactorMobileAuthenticationProvider.java @@ -34,24 +34,24 @@ public class TwoFactorMobileAuthenticationProvider extends AbstractAuthenticatio } public TwoFactorMobileAuthenticationProvider(SmsOtpAuthnService smsOtpAuthnService) { - this.smsOtpAuthnService = smsOtpAuthnService; - } + this.smsOtpAuthnService = smsOtpAuthnService; + } @Override - public Authentication doAuthenticate(LoginCredential credential) { - return null; + public Authentication doAuthenticate(LoginCredential credential) { + return null; } @Override - public Authentication doTwoFactorAuthenticate(LoginCredential credential,UserInfo user) { - UsernamePasswordAuthenticationToken authenticationToken = null; - logger.debug("loginCredential {}" , credential); + public Authentication doTwoFactorAuthenticate(LoginCredential credential,UserInfo user) { + UsernamePasswordAuthenticationToken authenticationToken = null; + logger.debug("loginCredential {}" , credential); try { - //短信验证码校验 - matches(credential.getOtpCaptcha(),user); - - authenticationToken = new UsernamePasswordAuthenticationToken(credential.getUsername(),"mobile"); - + //短信验证码校验 + matches(credential.getOtpCaptcha(),user); + + authenticationToken = new UsernamePasswordAuthenticationToken(credential.getUsername(),"mobile"); + } catch (AuthenticationException e) { logger.error("Failed to authenticate user {} via {}: {}",credential.getPrincipal(), getProviderName(), @@ -73,7 +73,7 @@ public class TwoFactorMobileAuthenticationProvider extends AbstractAuthenticatio * @param userInfo UserInfo */ protected void matches(String captcha, UserInfo userInfo) { - // for mobile password + // for mobile password UserInfo validUserInfo = new UserInfo(); validUserInfo.setUsername(userInfo.getUsername()); validUserInfo.setId(userInfo.getId()); diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/twofactor/impl/TwoFactorTotpAuthenticationProvider.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/twofactor/impl/TwoFactorTotpAuthenticationProvider.java index 2c0007af2..3d834a517 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/twofactor/impl/TwoFactorTotpAuthenticationProvider.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/provider/twofactor/impl/TwoFactorTotpAuthenticationProvider.java @@ -31,27 +31,27 @@ public class TwoFactorTotpAuthenticationProvider extends AbstractAuthenticationP } public TwoFactorTotpAuthenticationProvider(AbstractAuthenticationRealm authenticationRealm,AbstractOtpAuthn tfaOtpAuthn) { - this.authenticationRealm = authenticationRealm; - this.tfaOtpAuthn = tfaOtpAuthn; - } + this.authenticationRealm = authenticationRealm; + this.tfaOtpAuthn = tfaOtpAuthn; + } @Override - public Authentication doAuthenticate(LoginCredential credential) { - return null; + public Authentication doAuthenticate(LoginCredential credential) { + return null; } @Override - public Authentication doTwoFactorAuthenticate(LoginCredential credential,UserInfo user) { - UsernamePasswordAuthenticationToken authenticationToken = null; - logger.debug("loginCredential {}" , credential); + public Authentication doTwoFactorAuthenticate(LoginCredential credential,UserInfo user) { + UsernamePasswordAuthenticationToken authenticationToken = null; + logger.debug("loginCredential {}" , credential); try { - //验证码校验 - UserInfo userTotp = authenticationRealm.loadUserInfoById(user.getId()); - - matches(credential.getOtpCaptcha(),userTotp.getSharedSecret()); - - authenticationToken = new UsernamePasswordAuthenticationToken(credential.getUsername(),"TOTP"); - + //验证码校验 + UserInfo userTotp = authenticationRealm.loadUserInfoById(user.getId()); + + matches(credential.getOtpCaptcha(),userTotp.getSharedSecret()); + + authenticationToken = new UsernamePasswordAuthenticationToken(credential.getUsername(),"TOTP"); + } catch (AuthenticationException e) { logger.error("Failed to authenticate user {} via {}: {}",credential.getPrincipal(), getProviderName(), diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/AbstractAuthenticationRealm.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/AbstractAuthenticationRealm.java index b13c6699c..282d637f6 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/AbstractAuthenticationRealm.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/AbstractAuthenticationRealm.java @@ -131,8 +131,8 @@ public abstract class AbstractAuthenticationRealm { historyLogin.setSessionStatus(7); Authentication authentication = (Authentication ) WebContext.getAttribute(WebConstants.AUTHENTICATION); if(authentication != null - && authentication.getPrincipal() instanceof SignPrincipal) { - historyLogin.setSessionStatus(1); + && authentication.getPrincipal() instanceof SignPrincipal) { + historyLogin.setSessionStatus(1); historyLogin.setSessionId(userInfo.getSessionId()); } @@ -157,15 +157,15 @@ public abstract class AbstractAuthenticationRealm { Region ipRegion =ipLocationParser.region(userInfo.getLastLoginIp()); if(ipRegion != null) { - historyLogin.setCountry(ipRegion.getCountry()); - historyLogin.setProvince(ipRegion.getProvince()); - historyLogin.setCity(ipRegion.getCity()); - historyLogin.setLocation(ipRegion.getAddr()); + historyLogin.setCountry(ipRegion.getCountry()); + historyLogin.setProvince(ipRegion.getProvince()); + historyLogin.setCity(ipRegion.getCity()); + historyLogin.setLocation(ipRegion.getAddr()); } historyLoginService.login(historyLogin); if(WebConstants.LOGIN_RESULT.SUCCESS.equalsIgnoreCase(message)) { - loginService.updateLastLogin(userInfo); + loginService.updateLastLogin(userInfo); } return true; diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/jdbc/JdbcAuthenticationRealm.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/jdbc/JdbcAuthenticationRealm.java index 40683172b..0fb601a04 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/jdbc/JdbcAuthenticationRealm.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/jdbc/JdbcAuthenticationRealm.java @@ -57,40 +57,40 @@ public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm { } public JdbcAuthenticationRealm( - PasswordEncoder passwordEncoder, - PasswordPolicyValidatorService passwordPolicyValidatorService, - LoginService loginService, - HistoryLoginService historyLoginService, - UserInfoService userInfoService, - IpLocationParser ipLocationParser, - JdbcTemplate jdbcTemplate) { - - this.passwordEncoder =passwordEncoder; - this.passwordPolicyValidatorService=passwordPolicyValidatorService; - this.loginService = loginService; - this.historyLoginService = historyLoginService; - this.userInfoService = userInfoService; - this.ipLocationParser = ipLocationParser; + PasswordEncoder passwordEncoder, + PasswordPolicyValidatorService passwordPolicyValidatorService, + LoginService loginService, + HistoryLoginService historyLoginService, + UserInfoService userInfoService, + IpLocationParser ipLocationParser, + JdbcTemplate jdbcTemplate) { + + this.passwordEncoder =passwordEncoder; + this.passwordPolicyValidatorService=passwordPolicyValidatorService; + this.loginService = loginService; + this.historyLoginService = historyLoginService; + this.userInfoService = userInfoService; + this.ipLocationParser = ipLocationParser; this.jdbcTemplate = jdbcTemplate; } public JdbcAuthenticationRealm( - PasswordEncoder passwordEncoder, - PasswordPolicyValidatorService passwordPolicyValidatorService, - LoginService loginService, - HistoryLoginService historyLoginService, - UserInfoService userInfoService, - IpLocationParser ipLocationParser, - JdbcTemplate jdbcTemplate, - LdapAuthenticationRealmService ldapAuthenticationRealmService) { - this.passwordEncoder = passwordEncoder; - this.passwordPolicyValidatorService = passwordPolicyValidatorService; - this.loginService = loginService; - this.historyLoginService = historyLoginService; - this.userInfoService = userInfoService; - this.ipLocationParser = ipLocationParser; - this.jdbcTemplate = jdbcTemplate; - this.ldapAuthenticationRealmService = ldapAuthenticationRealmService; + PasswordEncoder passwordEncoder, + PasswordPolicyValidatorService passwordPolicyValidatorService, + LoginService loginService, + HistoryLoginService historyLoginService, + UserInfoService userInfoService, + IpLocationParser ipLocationParser, + JdbcTemplate jdbcTemplate, + LdapAuthenticationRealmService ldapAuthenticationRealmService) { + this.passwordEncoder = passwordEncoder; + this.passwordPolicyValidatorService = passwordPolicyValidatorService; + this.loginService = loginService; + this.historyLoginService = historyLoginService; + this.userInfoService = userInfoService; + this.ipLocationParser = ipLocationParser; + this.jdbcTemplate = jdbcTemplate; + this.ldapAuthenticationRealmService = ldapAuthenticationRealmService; } /** @@ -105,28 +105,28 @@ public class JdbcAuthenticationRealm extends AbstractAuthenticationRealm { passwordMatches = passwordEncoder.matches(password,userInfo.getPassword()); if(ldapAuthenticationRealmService != null) { - //passwordMatches == false and ldapSupport ==true - //validate password with LDAP - try { - LdapAuthenticationRealm ldapRealm = ldapAuthenticationRealmService.getByInstId(userInfo.getInstId()); - if(!passwordMatches && ldapRealm != null - && ldapRealm.isLdapSupport() - && userInfo.getIsLocked() == ConstsStatus.ACTIVE) { - passwordMatches = ldapRealm.passwordMatches(userInfo, password); - if(passwordMatches) { - //write password to database Realm - ChangePassword changePassword = new ChangePassword(userInfo); - changePassword.setPassword(password); - userInfoService.changePassword(changePassword, false); - } - } - }catch(Exception e) { - _logger.debug("passwordvalid Exception : {}" , e); - } + //passwordMatches == false and ldapSupport ==true + //validate password with LDAP + try { + LdapAuthenticationRealm ldapRealm = ldapAuthenticationRealmService.getByInstId(userInfo.getInstId()); + if(!passwordMatches && ldapRealm != null + && ldapRealm.isLdapSupport() + && userInfo.getIsLocked() == ConstsStatus.ACTIVE) { + passwordMatches = ldapRealm.passwordMatches(userInfo, password); + if(passwordMatches) { + //write password to database Realm + ChangePassword changePassword = new ChangePassword(userInfo); + changePassword.setPassword(password); + userInfoService.changePassword(changePassword, false); + } + } + }catch(Exception e) { + _logger.debug("passwordvalid Exception : {}" , e); + } } _logger.debug("passwordvalid : {}" , passwordMatches); if (!passwordMatches) { - loginService.plusBadPasswordCount(userInfo); + loginService.plusBadPasswordCount(userInfo); insertLoginHistory(userInfo, ConstsLoginType.LOCAL, "", "xe00000004", WebConstants.LOGIN_RESULT.PASSWORD_ERROE); CnfPasswordPolicy passwordPolicy = passwordPolicyValidatorService.getPasswordPolicy(); if(userInfo.getBadPasswordCount()>=(passwordPolicy.getAttempts()/2)) { diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/ldap/ActiveDirectoryServer.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/ldap/ActiveDirectoryServer.java index 55dde105f..f31b9f72e 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/ldap/ActiveDirectoryServer.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/ldap/ActiveDirectoryServer.java @@ -30,59 +30,59 @@ import org.slf4j.LoggerFactory; * */ public final class ActiveDirectoryServer implements IAuthenticationServer { - private static final Logger _logger = LoggerFactory.getLogger(ActiveDirectoryServer.class); + private static final Logger _logger = LoggerFactory.getLogger(ActiveDirectoryServer.class); - ActiveDirectoryUtils activeDirectoryUtils; + ActiveDirectoryUtils activeDirectoryUtils; - String filter; - - boolean mapping; - - /* (non-Javadoc) - * @see com.connsec.web.authentication.realm.IAuthenticationServer#authenticate(java.lang.String, java.lang.String) - */ - @Override - public boolean authenticate(String username, String password) { - ActiveDirectoryUtils ldapPassWordValid = - new ActiveDirectoryUtils( - activeDirectoryUtils.getProviderUrl(), - username, - password, - activeDirectoryUtils.getDomain() - ); - ldapPassWordValid.openConnection(); - if(ldapPassWordValid.getCtx()!=null){ - _logger.debug("Active Directory user " + username + " is validate ."); - ldapPassWordValid.close(); - return true; - } - - ldapPassWordValid.close(); - return false; - } + String filter; + + boolean mapping; + + /* (non-Javadoc) + * @see com.connsec.web.authentication.realm.IAuthenticationServer#authenticate(java.lang.String, java.lang.String) + */ + @Override + public boolean authenticate(String username, String password) { + ActiveDirectoryUtils ldapPassWordValid = + new ActiveDirectoryUtils( + activeDirectoryUtils.getProviderUrl(), + username, + password, + activeDirectoryUtils.getDomain() + ); + ldapPassWordValid.openConnection(); + if(ldapPassWordValid.getCtx()!=null){ + _logger.debug("Active Directory user " + username + " is validate ."); + ldapPassWordValid.close(); + return true; + } + + ldapPassWordValid.close(); + return false; + } - public ActiveDirectoryUtils getActiveDirectoryUtils() { - return activeDirectoryUtils; - } + public ActiveDirectoryUtils getActiveDirectoryUtils() { + return activeDirectoryUtils; + } - public void setActiveDirectoryUtils(ActiveDirectoryUtils activeDirectoryUtils) { - this.activeDirectoryUtils = activeDirectoryUtils; - } + public void setActiveDirectoryUtils(ActiveDirectoryUtils activeDirectoryUtils) { + this.activeDirectoryUtils = activeDirectoryUtils; + } - public String getFilter() { - return filter; - } + public String getFilter() { + return filter; + } - public void setFilter(String filter) { - this.filter = filter; - } + public void setFilter(String filter) { + this.filter = filter; + } - @Override - public boolean isMapping() { - return mapping; - } + @Override + public boolean isMapping() { + return mapping; + } - public void setMapping(boolean mapping) { - this.mapping = mapping; - } + public void setMapping(boolean mapping) { + this.mapping = mapping; + } } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/ldap/LdapAuthenticationRealm.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/ldap/LdapAuthenticationRealm.java index c6d5c860b..7d89a0349 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/ldap/LdapAuthenticationRealm.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/ldap/LdapAuthenticationRealm.java @@ -30,65 +30,65 @@ import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; public class LdapAuthenticationRealm extends AbstractAuthenticationRealm{ - private static final Logger _logger = LoggerFactory.getLogger(LdapAuthenticationRealm.class); - - @NotNull + private static final Logger _logger = LoggerFactory.getLogger(LdapAuthenticationRealm.class); + + @NotNull @Size(min=1) private List ldapServers; - - private boolean ldapSupport; - - /** - * - */ - public LdapAuthenticationRealm() { - - } + + private boolean ldapSupport; + + /** + * + */ + public LdapAuthenticationRealm() { + + } - public LdapAuthenticationRealm(boolean ldapSupport) { - this.ldapSupport = ldapSupport; - } - - /** - * @param jdbcTemplate - */ - public LdapAuthenticationRealm(JdbcTemplate jdbcTemplate) { - super(jdbcTemplate); - } - - - @Override - public boolean passwordMatches(UserInfo userInfo, String password) { - boolean isAuthenticated=false; - for (final IAuthenticationServer ldapServer : this.ldapServers) { - String username = userInfo.getUsername(); - if(ldapServer.isMapping()) {//if ldap Context accountMapping equals YES - username = userInfo.getWindowsAccount(); - } + public LdapAuthenticationRealm(boolean ldapSupport) { + this.ldapSupport = ldapSupport; + } + + /** + * @param jdbcTemplate + */ + public LdapAuthenticationRealm(JdbcTemplate jdbcTemplate) { + super(jdbcTemplate); + } + + + @Override + public boolean passwordMatches(UserInfo userInfo, String password) { + boolean isAuthenticated=false; + for (final IAuthenticationServer ldapServer : this.ldapServers) { + String username = userInfo.getUsername(); + if(ldapServer.isMapping()) {//if ldap Context accountMapping equals YES + username = userInfo.getWindowsAccount(); + } _logger.debug("Attempting to authenticate {} at {}", username, ldapServer); try { - isAuthenticated = ldapServer.authenticate(username, password); + isAuthenticated = ldapServer.authenticate(username, password); }catch(Exception e) { - _logger.debug("Attempting Authenticated fail ."); + _logger.debug("Attempting Authenticated fail ."); } if (isAuthenticated ) { - return true; + return true; } - } - return false; - } + } + return false; + } - public void setLdapServers(List ldapServers) { - this.ldapServers = ldapServers; - } + public void setLdapServers(List ldapServers) { + this.ldapServers = ldapServers; + } - public boolean isLdapSupport() { - return ldapSupport; - } + public boolean isLdapSupport() { + return ldapSupport; + } - public void setLdapSupport(boolean ldapSupport) { - this.ldapSupport = ldapSupport; - } + public void setLdapSupport(boolean ldapSupport) { + this.ldapSupport = ldapSupport; + } } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/ldap/LdapAuthenticationRealmService.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/ldap/LdapAuthenticationRealmService.java index 26d749c29..9acf840f2 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/ldap/LdapAuthenticationRealmService.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/ldap/LdapAuthenticationRealmService.java @@ -40,54 +40,54 @@ public class LdapAuthenticationRealmService { public LdapAuthenticationRealmService(CnfLdapContextService ldapContextService) { - this.ldapContextService = ldapContextService; - } + this.ldapContextService = ldapContextService; + } - public LdapAuthenticationRealm getByInstId(String instId) { - LdapAuthenticationRealm authenticationRealm = ldapRealmStore.getIfPresent(instId); - if(authenticationRealm == null) { - List ldapContexts = - ldapContextService.find("where instid = ? and status = 1 ", new Object[]{instId}, new int[]{Types.VARCHAR}); - authenticationRealm = new LdapAuthenticationRealm(false); - if(ldapContexts != null && ldapContexts.size()>0) { - authenticationRealm.setLdapSupport(true); - List ldapAuthenticationServers = new ArrayList(); - for(CnfLdapContext ldapContext : ldapContexts) { - if(ldapContext.getProduct().equalsIgnoreCase("ActiveDirectory")) { - ActiveDirectoryServer ldapServer = new ActiveDirectoryServer(); - ActiveDirectoryUtils ldapUtils = new ActiveDirectoryUtils( - ldapContext.getProviderUrl(), - ldapContext.getPrincipal(), - PasswordReciprocal.getInstance().decoder( - ldapContext.getCredentials()), - ldapContext.getMsadDomain()); - ldapServer.setActiveDirectoryUtils(ldapUtils); - if(ldapContext.getAccountMapping().equalsIgnoreCase("YES")) { - ldapServer.setMapping(true); - } - ldapAuthenticationServers.add(ldapServer); - - }else { - StandardLdapServer standardLdapServer=new StandardLdapServer(); - LdapUtils ldapUtils = new LdapUtils( - ldapContext.getProviderUrl(), - ldapContext.getPrincipal(), - PasswordReciprocal.getInstance().decoder( - ldapContext.getCredentials()), - ldapContext.getBasedn()); - standardLdapServer.setLdapUtils(ldapUtils); - standardLdapServer.setFilterAttribute(ldapContext.getFilters()); - if(ldapContext.getAccountMapping().equalsIgnoreCase("YES")) { - standardLdapServer.setMapping(true); - } - ldapAuthenticationServers.add(standardLdapServer); - } - } - authenticationRealm.setLdapServers(ldapAuthenticationServers); - } - ldapRealmStore.put(instId, authenticationRealm); - } - return authenticationRealm; - + public LdapAuthenticationRealm getByInstId(String instId) { + LdapAuthenticationRealm authenticationRealm = ldapRealmStore.getIfPresent(instId); + if(authenticationRealm == null) { + List ldapContexts = + ldapContextService.find("where instid = ? and status = 1 ", new Object[]{instId}, new int[]{Types.VARCHAR}); + authenticationRealm = new LdapAuthenticationRealm(false); + if(ldapContexts != null && ldapContexts.size()>0) { + authenticationRealm.setLdapSupport(true); + List ldapAuthenticationServers = new ArrayList(); + for(CnfLdapContext ldapContext : ldapContexts) { + if(ldapContext.getProduct().equalsIgnoreCase("ActiveDirectory")) { + ActiveDirectoryServer ldapServer = new ActiveDirectoryServer(); + ActiveDirectoryUtils ldapUtils = new ActiveDirectoryUtils( + ldapContext.getProviderUrl(), + ldapContext.getPrincipal(), + PasswordReciprocal.getInstance().decoder( + ldapContext.getCredentials()), + ldapContext.getMsadDomain()); + ldapServer.setActiveDirectoryUtils(ldapUtils); + if(ldapContext.getAccountMapping().equalsIgnoreCase("YES")) { + ldapServer.setMapping(true); + } + ldapAuthenticationServers.add(ldapServer); + + }else { + StandardLdapServer standardLdapServer=new StandardLdapServer(); + LdapUtils ldapUtils = new LdapUtils( + ldapContext.getProviderUrl(), + ldapContext.getPrincipal(), + PasswordReciprocal.getInstance().decoder( + ldapContext.getCredentials()), + ldapContext.getBasedn()); + standardLdapServer.setLdapUtils(ldapUtils); + standardLdapServer.setFilterAttribute(ldapContext.getFilters()); + if(ldapContext.getAccountMapping().equalsIgnoreCase("YES")) { + standardLdapServer.setMapping(true); + } + ldapAuthenticationServers.add(standardLdapServer); + } + } + authenticationRealm.setLdapServers(ldapAuthenticationServers); + } + ldapRealmStore.put(instId, authenticationRealm); + } + return authenticationRealm; + } } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/ldap/StandardLdapServer.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/ldap/StandardLdapServer.java index 32c1f5854..0d442f665 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/ldap/StandardLdapServer.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/realm/ldap/StandardLdapServer.java @@ -35,75 +35,75 @@ import org.slf4j.LoggerFactory; * */ public final class StandardLdapServer implements IAuthenticationServer { - private static final Logger _logger = LoggerFactory.getLogger(StandardLdapServer.class); - - LdapUtils ldapUtils; - - String filterAttribute; - - boolean mapping; - - /* (non-Javadoc) - * @see com.connsec.web.authentication.realm.IAuthenticationServer#authenticate(java.lang.String, java.lang.String) - */ - @Override - public boolean authenticate(String username, String password) { - String queryFilter = String.format(filterAttribute, username); - _logger.info(" filter : " + queryFilter); - String dn=""; - SearchControls constraints = new SearchControls(); - constraints.setSearchScope(ldapUtils.getSearchScope()); - try { - NamingEnumeration results = ldapUtils.getConnection() - .search(ldapUtils.getBaseDN(), queryFilter, constraints); - - if (results == null || !results.hasMore()) { - _logger.error("Ldap user "+username +" not found . "); - return false; - }else{ - while (results != null && results.hasMore()) { - SearchResult sr = (SearchResult) results.next(); - //String rdn = sr.getName(); - dn = sr.getNameInNamespace(); - _logger.debug("Directory user dn is "+dn+" ."); - } - } - } catch (NamingException e) { - _logger.error("query throw NamingException:" + e.getMessage()); - } finally { - //ldapUtils.close(); - } - - LdapUtils ldapPassWordValid=new LdapUtils(ldapUtils.getProviderUrl(),dn,password); - ldapPassWordValid.openConnection(); - if(ldapPassWordValid.getCtx()!=null){ - _logger.debug("Directory user " + username + " is validate ."); - ldapPassWordValid.close(); - return true; - } - return false; - } - - public LdapUtils getLdapUtils() { - return ldapUtils; - } - public void setLdapUtils(LdapUtils ldapUtils) { - this.ldapUtils = ldapUtils; - } - public String getFilterAttribute() { - return filterAttribute; - } - public void setFilterAttribute(String filterAttribute) { - this.filterAttribute = filterAttribute; - } + private static final Logger _logger = LoggerFactory.getLogger(StandardLdapServer.class); + + LdapUtils ldapUtils; + + String filterAttribute; + + boolean mapping; + + /* (non-Javadoc) + * @see com.connsec.web.authentication.realm.IAuthenticationServer#authenticate(java.lang.String, java.lang.String) + */ + @Override + public boolean authenticate(String username, String password) { + String queryFilter = String.format(filterAttribute, username); + _logger.info(" filter : " + queryFilter); + String dn=""; + SearchControls constraints = new SearchControls(); + constraints.setSearchScope(ldapUtils.getSearchScope()); + try { + NamingEnumeration results = ldapUtils.getConnection() + .search(ldapUtils.getBaseDN(), queryFilter, constraints); + + if (results == null || !results.hasMore()) { + _logger.error("Ldap user "+username +" not found . "); + return false; + }else{ + while (results != null && results.hasMore()) { + SearchResult sr = (SearchResult) results.next(); + //String rdn = sr.getName(); + dn = sr.getNameInNamespace(); + _logger.debug("Directory user dn is "+dn+" ."); + } + } + } catch (NamingException e) { + _logger.error("query throw NamingException:" + e.getMessage()); + } finally { + //ldapUtils.close(); + } + + LdapUtils ldapPassWordValid=new LdapUtils(ldapUtils.getProviderUrl(),dn,password); + ldapPassWordValid.openConnection(); + if(ldapPassWordValid.getCtx()!=null){ + _logger.debug("Directory user " + username + " is validate ."); + ldapPassWordValid.close(); + return true; + } + return false; + } + + public LdapUtils getLdapUtils() { + return ldapUtils; + } + public void setLdapUtils(LdapUtils ldapUtils) { + this.ldapUtils = ldapUtils; + } + public String getFilterAttribute() { + return filterAttribute; + } + public void setFilterAttribute(String filterAttribute) { + this.filterAttribute = filterAttribute; + } - @Override - public boolean isMapping() { - return mapping; - } + @Override + public boolean isMapping() { + return mapping; + } - public void setMapping(boolean mapping) { - this.mapping = mapping; - } + public void setMapping(boolean mapping) { + this.mapping = mapping; + } } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/basic/BasicEntryPoint.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/basic/BasicEntryPoint.java index 8dda15e9a..d3d5ea04a 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/basic/BasicEntryPoint.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/basic/BasicEntryPoint.java @@ -35,116 +35,116 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; public class BasicEntryPoint implements AsyncHandlerInterceptor { - private static final Logger _logger = LoggerFactory.getLogger(BasicEntryPoint.class); - - boolean enable; - - @Autowired + private static final Logger _logger = LoggerFactory.getLogger(BasicEntryPoint.class); + + boolean enable; + + @Autowired @Qualifier("authenticationProvider") - AbstractAuthenticationProvider authenticationProvider ; - - public BasicEntryPoint() { - + AbstractAuthenticationProvider authenticationProvider ; + + public BasicEntryPoint() { + } - - public BasicEntryPoint(boolean enable) { + + public BasicEntryPoint(boolean enable) { super(); this.enable = enable; } String []skipRequestURI={ - "/oauth/v20/token", - "/oauth/v10a/request_token", - "/oauth/v10a/access_token" - }; - - @Override - public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { - - if(!enable){ - return true; - } - String requestPath=request.getServletPath(); - _logger.debug("HttpHeader Login Start ..."); - _logger.info("Request url : "+ request.getRequestURL()); - _logger.info("Request URI : "+ request.getRequestURI()); - _logger.info("Request ContextPath : "+ request.getContextPath()); - _logger.info("Request ServletPath : "+ request.getServletPath()); - _logger.debug("RequestSessionId : "+ request.getRequestedSessionId()); - _logger.debug("isRequestedSessionIdValid : "+ request.isRequestedSessionIdValid()); - _logger.debug("getSession : "+ request.getSession(false)); - - for(int i=0;i-1){ - _logger.info("skip uri : "+ requestPath); - return true; - } - } - - // session not exists,session timeout,recreate new session - if(request.getSession(false) == null) { - _logger.info("recreate new session ."); - request.getSession(true); - } - String basicCredential =request.getHeader(AuthorizationHeaderUtils.HEADER_Authorization); - _logger.info("getSession.getId : "+ request.getSession().getId()); - - _logger.info("Authorization : " + basicCredential); - - - if(basicCredential==null||basicCredential.equals("")){ - _logger.info("Authentication fail header Authorization is null . "); - return false; - } - - AuthorizationHeader headerCredential = null; - - if(AuthorizationHeaderUtils.isBasic(basicCredential)){ - headerCredential=AuthorizationHeaderUtils.resolve(basicCredential); - }else{ - return false; - } - if(headerCredential.getUsername()==null||headerCredential.getUsername().equals("")){ - _logger.info("Authentication fail username is null . "); - return false; - } - if(headerCredential.getCredential()==null||headerCredential.getCredential().equals("")){ - _logger.info("Authentication fail password is null . "); - return false; - } - - boolean isAuthenticated=false; - - if(SecurityContextHolder.getContext().getAuthentication() == null) { - _logger.info("Security Authentication is null ."); - isAuthenticated=false; - }else { - _logger.info("Security Authentication not null . "); - UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); - String lastSessionUserName = authenticationToken.getPrincipal().toString(); - _logger.info("Authentication Principal : " + lastSessionUserName); - if (lastSessionUserName != null && !lastSessionUserName.equals(headerCredential.getUsername())) { - isAuthenticated=false; - }else{ - isAuthenticated=true; - } - } - - if(!isAuthenticated){ - LoginCredential loginCredential =new LoginCredential(headerCredential.getUsername(),"",ConstsLoginType.BASIC); - authenticationProvider.authenticate(loginCredential,true); - _logger.info("Authentication "+headerCredential.getUsername()+" successful ."); - } - - return true; - } + "/oauth/v20/token", + "/oauth/v10a/request_token", + "/oauth/v10a/access_token" + }; + + @Override + public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { + + if(!enable){ + return true; + } + String requestPath=request.getServletPath(); + _logger.debug("HttpHeader Login Start ..."); + _logger.info("Request url : "+ request.getRequestURL()); + _logger.info("Request URI : "+ request.getRequestURI()); + _logger.info("Request ContextPath : "+ request.getContextPath()); + _logger.info("Request ServletPath : "+ request.getServletPath()); + _logger.debug("RequestSessionId : "+ request.getRequestedSessionId()); + _logger.debug("isRequestedSessionIdValid : "+ request.isRequestedSessionIdValid()); + _logger.debug("getSession : "+ request.getSession(false)); + + for(int i=0;i-1){ + _logger.info("skip uri : "+ requestPath); + return true; + } + } + + // session not exists,session timeout,recreate new session + if(request.getSession(false) == null) { + _logger.info("recreate new session ."); + request.getSession(true); + } + String basicCredential =request.getHeader(AuthorizationHeaderUtils.HEADER_Authorization); + _logger.info("getSession.getId : "+ request.getSession().getId()); + + _logger.info("Authorization : " + basicCredential); + + + if(basicCredential==null||basicCredential.equals("")){ + _logger.info("Authentication fail header Authorization is null . "); + return false; + } + + AuthorizationHeader headerCredential = null; + + if(AuthorizationHeaderUtils.isBasic(basicCredential)){ + headerCredential=AuthorizationHeaderUtils.resolve(basicCredential); + }else{ + return false; + } + if(headerCredential.getUsername()==null||headerCredential.getUsername().equals("")){ + _logger.info("Authentication fail username is null . "); + return false; + } + if(headerCredential.getCredential()==null||headerCredential.getCredential().equals("")){ + _logger.info("Authentication fail password is null . "); + return false; + } + + boolean isAuthenticated=false; + + if(SecurityContextHolder.getContext().getAuthentication() == null) { + _logger.info("Security Authentication is null ."); + isAuthenticated=false; + }else { + _logger.info("Security Authentication not null . "); + UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); + String lastSessionUserName = authenticationToken.getPrincipal().toString(); + _logger.info("Authentication Principal : " + lastSessionUserName); + if (lastSessionUserName != null && !lastSessionUserName.equals(headerCredential.getUsername())) { + isAuthenticated=false; + }else{ + isAuthenticated=true; + } + } + + if(!isAuthenticated){ + LoginCredential loginCredential =new LoginCredential(headerCredential.getUsername(),"",ConstsLoginType.BASIC); + authenticationProvider.authenticate(loginCredential,true); + _logger.info("Authentication "+headerCredential.getUsername()+" successful ."); + } + + return true; + } - /** - * @param enable the enable to set - */ - public void setEnable(boolean enable) { - this.enable = enable; - } + /** + * @param enable the enable to set + */ + public void setEnable(boolean enable) { + this.enable = enable; + } - + } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/certs/HttpCertsEntryPoint.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/certs/HttpCertsEntryPoint.java index c94c476f9..0ef1e804a 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/certs/HttpCertsEntryPoint.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/certs/HttpCertsEntryPoint.java @@ -31,11 +31,11 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; public class HttpCertsEntryPoint implements AsyncHandlerInterceptor { - private static final Logger _logger = LoggerFactory.getLogger(HttpHeaderEntryPoint.class); - - static String CERTIFICATE_ATTRIBUTE = "javax.servlet.request.X509Certificate"; - static String PEER_CERTIFICATES_ATTRIBUTE = "javax.net.ssl.peer_certificates"; - + private static final Logger _logger = LoggerFactory.getLogger(HttpHeaderEntryPoint.class); + + static String CERTIFICATE_ATTRIBUTE = "javax.servlet.request.X509Certificate"; + static String PEER_CERTIFICATES_ATTRIBUTE = "javax.net.ssl.peer_certificates"; + boolean enable; @Autowired @@ -43,56 +43,56 @@ public class HttpCertsEntryPoint implements AsyncHandlerInterceptor { AbstractAuthenticationProvider authenticationProvider ; @Override - public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { - - if(!enable){ - return true; - } + public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { + + if(!enable){ + return true; + } - _logger.debug("Certificate Login Start ..."); - _logger.debug("Request url : "+ request.getRequestURL()); - _logger.debug("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)); - - X509Certificate[] certificates= (X509Certificate[])request.getAttribute(CERTIFICATE_ATTRIBUTE); // 2.2 spec - if (certificates == null) { - certificates = (X509Certificate[]) request.getAttribute(PEER_CERTIFICATES_ATTRIBUTE); // 2.1 spec + _logger.debug("Certificate Login Start ..."); + _logger.debug("Request url : "+ request.getRequestURL()); + _logger.debug("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)); + + X509Certificate[] certificates= (X509Certificate[])request.getAttribute(CERTIFICATE_ATTRIBUTE); // 2.2 spec + if (certificates == null) { + certificates = (X509Certificate[]) request.getAttribute(PEER_CERTIFICATES_ATTRIBUTE); // 2.1 spec } - - for (X509Certificate cert : certificates) { - cert.checkValidity(); - _logger.debug("cert validated"); - _logger.debug("cert infos {}" , cert.toString()); - _logger.debug("Version {}" , cert.getVersion()); - _logger.debug("SerialNumber {}" , cert.getSerialNumber().toString(16)); - _logger.debug("SubjectDN {}" , cert.getSubjectDN()); - _logger.debug("IssuerDN {}" , cert.getIssuerDN()); - _logger.debug("NotBefore {}" , cert.getNotBefore()); - _logger.debug("SigAlgName {}" , cert.getSigAlgName()); - byte[] sign = cert.getSignature(); - _logger.debug("Signature "); - for (int j = 0; j < sign.length; j++){ - _logger.debug("{} , ",sign[j] ); - } - java.security.PublicKey pk = cert.getPublicKey(); - byte[] pkenc = pk.getEncoded(); - _logger.debug("PublicKey "); - for (int j = 0; j < pkenc.length; j++){ - _logger.debug("{} ,",pkenc[j]); - } - } - return true; + + for (X509Certificate cert : certificates) { + cert.checkValidity(); + _logger.debug("cert validated"); + _logger.debug("cert infos {}" , cert.toString()); + _logger.debug("Version {}" , cert.getVersion()); + _logger.debug("SerialNumber {}" , cert.getSerialNumber().toString(16)); + _logger.debug("SubjectDN {}" , cert.getSubjectDN()); + _logger.debug("IssuerDN {}" , cert.getIssuerDN()); + _logger.debug("NotBefore {}" , cert.getNotBefore()); + _logger.debug("SigAlgName {}" , cert.getSigAlgName()); + byte[] sign = cert.getSignature(); + _logger.debug("Signature "); + for (int j = 0; j < sign.length; j++){ + _logger.debug("{} , ",sign[j] ); + } + java.security.PublicKey pk = cert.getPublicKey(); + byte[] pkenc = pk.getEncoded(); + _logger.debug("PublicKey "); + for (int j = 0; j < pkenc.length; j++){ + _logger.debug("{} ,",pkenc[j]); + } + } + return true; } - public HttpCertsEntryPoint(boolean enable, AbstractAuthenticationProvider authenticationProvider) { - super(); - this.enable = enable; - this.authenticationProvider = authenticationProvider; - } + public HttpCertsEntryPoint(boolean enable, AbstractAuthenticationProvider authenticationProvider) { + super(); + this.enable = enable; + this.authenticationProvider = authenticationProvider; + } } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/httpheader/HttpHeaderEntryPoint.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/httpheader/HttpHeaderEntryPoint.java index 854d593fd..834da4af5 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/httpheader/HttpHeaderEntryPoint.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/httpheader/HttpHeaderEntryPoint.java @@ -33,93 +33,93 @@ import jakarta.servlet.http.HttpServletResponse; public class HttpHeaderEntryPoint implements AsyncHandlerInterceptor { - private static final Logger _logger = LoggerFactory.getLogger(HttpHeaderEntryPoint.class); - - String headerName; + private static final Logger _logger = LoggerFactory.getLogger(HttpHeaderEntryPoint.class); + + String headerName; boolean enable; @Autowired @Qualifier("authenticationProvider") AbstractAuthenticationProvider authenticationProvider ; - - String []skipRequestURI={ - "/oauth/v20/token", - "/oauth/v10a/request_token", - "/oauth/v10a/access_token" - }; - - @Override - public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { - - if(!enable){ - return true; - } - String requestPath=request.getServletPath(); - _logger.trace("HttpHeader 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)); - - for(int i=0;i-1){ - _logger.trace("skip uri : "+ requestPath); - return true; - } - } - - - - // session not exists,session timeout,recreate new session - if(request.getSession(false) == null) { - _logger.trace("recreate new session ."); - request.getSession(true); - } - - _logger.trace("getSession.getId : "+ request.getSession().getId()); - String httpHeaderUsername = request.getHeader(headerName); + + String []skipRequestURI={ + "/oauth/v20/token", + "/oauth/v10a/request_token", + "/oauth/v10a/access_token" + }; + + @Override + public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { + + if(!enable){ + return true; + } + String requestPath=request.getServletPath(); + _logger.trace("HttpHeader 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)); + + for(int i=0;i-1){ + _logger.trace("skip uri : "+ requestPath); + return true; + } + } + + + + // session not exists,session timeout,recreate new session + if(request.getSession(false) == null) { + _logger.trace("recreate new session ."); + request.getSession(true); + } + + _logger.trace("getSession.getId : "+ request.getSession().getId()); + String httpHeaderUsername = request.getHeader(headerName); - _logger.trace("HttpHeader username : " + httpHeaderUsername); - - - if(httpHeaderUsername==null||httpHeaderUsername.equals("")){ - _logger.info("Authentication fail HttpHeader is null . "); - return false; - } - - boolean isAuthenticated=false; - - if(SecurityContextHolder.getContext().getAuthentication() == null) { - _logger.info("Security Authentication is null ."); - isAuthenticated=false; - }else { - _logger.info("Security Authentication not null . "); - UsernamePasswordAuthenticationToken authenticationToken = - (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); - String lastSessionUserName = authenticationToken.getPrincipal().toString(); - _logger.info("Authentication Principal : " + lastSessionUserName); - if (lastSessionUserName != null && !lastSessionUserName.equals(httpHeaderUsername)) { - isAuthenticated=false; - }else{ - isAuthenticated=true; - } - } - - if(!isAuthenticated){ - LoginCredential loginCredential =new LoginCredential(httpHeaderUsername,"",ConstsLoginType.HTTPHEADER); + _logger.trace("HttpHeader username : " + httpHeaderUsername); + + + if(httpHeaderUsername==null||httpHeaderUsername.equals("")){ + _logger.info("Authentication fail HttpHeader is null . "); + return false; + } + + boolean isAuthenticated=false; + + if(SecurityContextHolder.getContext().getAuthentication() == null) { + _logger.info("Security Authentication is null ."); + isAuthenticated=false; + }else { + _logger.info("Security Authentication not null . "); + UsernamePasswordAuthenticationToken authenticationToken = + (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); + String lastSessionUserName = authenticationToken.getPrincipal().toString(); + _logger.info("Authentication Principal : " + lastSessionUserName); + if (lastSessionUserName != null && !lastSessionUserName.equals(httpHeaderUsername)) { + isAuthenticated=false; + }else{ + isAuthenticated=true; + } + } + + if(!isAuthenticated){ + LoginCredential loginCredential =new LoginCredential(httpHeaderUsername,"",ConstsLoginType.HTTPHEADER); authenticationProvider.authenticate(loginCredential,true); - _logger.info("Authentication "+httpHeaderUsername+" successful ."); - } - - return true; - } + _logger.info("Authentication "+httpHeaderUsername+" successful ."); + } + + return true; + } - public HttpHeaderEntryPoint() { - super(); - } + public HttpHeaderEntryPoint() { + super(); + } public HttpHeaderEntryPoint(String headerName, boolean enable) { super(); @@ -142,6 +142,6 @@ public class HttpHeaderEntryPoint implements AsyncHandlerInterceptor { public void setEnable(boolean enable) { this.enable = enable; } - - + + } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/jwt/HttpJwtEntryPoint.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/jwt/HttpJwtEntryPoint.java index 3a504e0fc..0132e049b 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/jwt/HttpJwtEntryPoint.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/jwt/HttpJwtEntryPoint.java @@ -40,80 +40,80 @@ import com.nimbusds.jwt.SignedJWT; @RestController @RequestMapping(value = "/login") public class HttpJwtEntryPoint { - private static final Logger _logger = LoggerFactory.getLogger(HttpJwtEntryPoint.class); + private static final Logger _logger = LoggerFactory.getLogger(HttpJwtEntryPoint.class); - @Autowired - ApplicationConfig applicationConfig; - - @Autowired - AbstractAuthenticationProvider authenticationProvider ; - - @Autowired - AuthTokenService authTokenService; - @Autowired - JwtLoginService jwtLoginService; - - @RequestMapping(value={"/jwt"}, produces = {MediaType.APPLICATION_JSON_VALUE},method={RequestMethod.GET,RequestMethod.POST}) - public Message jwt(@RequestParam(value = WebConstants.JWT_TOKEN_PARAMETER, required = true) String jwt) { - try { - //for jwt Login - _logger.debug("jwt : {}" , jwt); - - SignedJWT signedJWT = jwtLoginService.jwtTokenValidation(jwt); - - if(signedJWT != null) { - String username =signedJWT.getJWTClaimsSet().getSubject(); - LoginCredential loginCredential =new LoginCredential(username,"",ConstsLoginType.JWT); - Authentication authentication = authenticationProvider.authenticate(loginCredential,true); - _logger.debug("JWT Logined in , username {}" , username); - AuthJwt authJwt = authTokenService.genAuthJwt(authentication); - return new Message<>(authJwt); - } - }catch(Exception e) { - _logger.error("Exception ",e); - } - - return new Message<>(Message.FAIL); - } - - /** - * trust same HS512 - * @param jwt - * @return - */ - @RequestMapping(value={"/jwt/trust"}, produces = {MediaType.APPLICATION_JSON_VALUE},method={RequestMethod.GET,RequestMethod.POST}) - public Message jwtTrust(@RequestParam(value = WebConstants.JWT_TOKEN_PARAMETER, required = true) String jwt) { - try { - //for jwt Login - _logger.debug("jwt : {}" , jwt); + ApplicationConfig applicationConfig; + + @Autowired + AbstractAuthenticationProvider authenticationProvider ; + + @Autowired + AuthTokenService authTokenService; + + @Autowired + JwtLoginService jwtLoginService; + + @RequestMapping(value={"/jwt"}, produces = {MediaType.APPLICATION_JSON_VALUE},method={RequestMethod.GET,RequestMethod.POST}) + public Message jwt(@RequestParam(value = WebConstants.JWT_TOKEN_PARAMETER, required = true) String jwt) { + try { + //for jwt Login + _logger.debug("jwt : {}" , jwt); + + SignedJWT signedJWT = jwtLoginService.jwtTokenValidation(jwt); + + if(signedJWT != null) { + String username =signedJWT.getJWTClaimsSet().getSubject(); + LoginCredential loginCredential =new LoginCredential(username,"",ConstsLoginType.JWT); + Authentication authentication = authenticationProvider.authenticate(loginCredential,true); + _logger.debug("JWT Logined in , username {}" , username); + AuthJwt authJwt = authTokenService.genAuthJwt(authentication); + return new Message<>(authJwt); + } + }catch(Exception e) { + _logger.error("Exception ",e); + } + + return new Message<>(Message.FAIL); + } + + /** + * trust same HS512 + * @param jwt + * @return + */ + @RequestMapping(value={"/jwt/trust"}, produces = {MediaType.APPLICATION_JSON_VALUE},method={RequestMethod.GET,RequestMethod.POST}) + public Message jwtTrust(@RequestParam(value = WebConstants.JWT_TOKEN_PARAMETER, required = true) String jwt) { + try { + //for jwt Login + _logger.debug("jwt : {}" , jwt); - if(authTokenService.validateJwtToken(jwt)) { - String username =authTokenService.resolve(jwt).getSubject(); - LoginCredential loginCredential =new LoginCredential(username,"",ConstsLoginType.JWT); - Authentication authentication = authenticationProvider.authenticate(loginCredential,true); - _logger.debug("JWT Logined in , username {}" , username); - AuthJwt authJwt = authTokenService.genAuthJwt(authentication); - return new Message<>(authJwt); - } - }catch(Exception e) { - _logger.error("Exception ",e); - } - - return new Message<>(Message.FAIL); - } + if(authTokenService.validateJwtToken(jwt)) { + String username =authTokenService.resolve(jwt).getSubject(); + LoginCredential loginCredential =new LoginCredential(username,"",ConstsLoginType.JWT); + Authentication authentication = authenticationProvider.authenticate(loginCredential,true); + _logger.debug("JWT Logined in , username {}" , username); + AuthJwt authJwt = authTokenService.genAuthJwt(authentication); + return new Message<>(authJwt); + } + }catch(Exception e) { + _logger.error("Exception ",e); + } + + return new Message<>(Message.FAIL); + } - public void setApplicationConfig(ApplicationConfig applicationConfig) { - this.applicationConfig = applicationConfig; - } + public void setApplicationConfig(ApplicationConfig applicationConfig) { + this.applicationConfig = applicationConfig; + } - public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) { - this.authenticationProvider = authenticationProvider; - } + public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) { + this.authenticationProvider = authenticationProvider; + } - public void setJwtLoginService(JwtLoginService jwtLoginService) { - this.jwtLoginService = jwtLoginService; - } - + public void setJwtLoginService(JwtLoginService jwtLoginService) { + this.jwtLoginService = jwtLoginService; + } + } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/jwt/JwtLoginService.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/jwt/JwtLoginService.java index f1c4a2da2..b890fdf45 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/jwt/JwtLoginService.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/jwt/JwtLoginService.java @@ -87,11 +87,11 @@ public class JwtLoginService { signedJWT = SignedJWT.parse(jwt); if (signedJWT.verify(rsaSSAVerifier)) { - jwtClaimsSet = signedJWT.getJWTClaimsSet(); - boolean isIssuerMatches = jwtClaimsSet.getIssuer().equals(getIssuer()); - boolean isExpiration = (new DateTime()).isBefore( - jwtClaimsSet.getExpirationTime().getTime()); - + jwtClaimsSet = signedJWT.getJWTClaimsSet(); + boolean isIssuerMatches = jwtClaimsSet.getIssuer().equals(getIssuer()); + boolean isExpiration = (new DateTime()).isBefore( + jwtClaimsSet.getExpirationTime().getTime()); + _logger.debug("Signed JWT {}" , signedJWT.getPayload()); _logger.debug("Subject is {}" , jwtClaimsSet.getSubject()); _logger.debug("ExpirationTime Validation {}" ,isExpiration); @@ -118,9 +118,9 @@ public class JwtLoginService { this.jwtSignerValidationService = jwtSignerValidationService; } - public DefaultJwtSigningAndValidationService getJwtSignerValidationService() { - return jwtSignerValidationService; - } + public DefaultJwtSigningAndValidationService getJwtSignerValidationService() { + return jwtSignerValidationService; + } public String getIssuer() { return issuer; diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/HttpKerberosEntryPoint.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/HttpKerberosEntryPoint.java index eed6fcfd5..4d6b517ef 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/HttpKerberosEntryPoint.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/HttpKerberosEntryPoint.java @@ -36,78 +36,78 @@ import jakarta.servlet.http.HttpServletResponse; public class HttpKerberosEntryPoint implements AsyncHandlerInterceptor { - private static final Logger _logger = LoggerFactory.getLogger(HttpKerberosEntryPoint.class); - + private static final Logger _logger = LoggerFactory.getLogger(HttpKerberosEntryPoint.class); + boolean enable; - ApplicationConfig applicationConfig; + ApplicationConfig applicationConfig; AbstractAuthenticationProvider authenticationProvider ; - KerberosService kerberosService; - - @Override - public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { - boolean isAuthenticated= AuthorizationUtils.isAuthenticated(); - String kerberosTokenString = request.getParameter(WebConstants.KERBEROS_TOKEN_PARAMETER); - String kerberosUserDomain = request.getParameter(WebConstants.KERBEROS_USERDOMAIN_PARAMETER); - - if(!enable - || isAuthenticated - || kerberosTokenString == null){ - return true; - } - - _logger.trace("Kerberos 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.trace("recreate new session ."); - request.getSession(true); - } - - _logger.trace("getSession.getId : "+ request.getSession().getId()); + KerberosService kerberosService; + + @Override + public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { + boolean isAuthenticated= AuthorizationUtils.isAuthenticated(); + String kerberosTokenString = request.getParameter(WebConstants.KERBEROS_TOKEN_PARAMETER); + String kerberosUserDomain = request.getParameter(WebConstants.KERBEROS_USERDOMAIN_PARAMETER); + + if(!enable + || isAuthenticated + || kerberosTokenString == null){ + return true; + } + + _logger.trace("Kerberos 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.trace("recreate new session ."); + request.getSession(true); + } + + _logger.trace("getSession.getId : "+ request.getSession().getId()); - //for Kerberos Login - _logger.debug("Try Kerberos login "); - _logger.debug("encoder Kerberos Token "+kerberosTokenString); - _logger.debug("kerberos UserDomain "+kerberosUserDomain); - - String decoderKerberosToken=null; - for(KerberosProxy kerberosProxy : kerberosService.getKerberosProxys()){ - if(kerberosProxy.getUserdomain().equalsIgnoreCase(kerberosUserDomain)){ - decoderKerberosToken=ReciprocalUtils.aesDecoder(kerberosTokenString, kerberosProxy.getCrypto()); - break; - } - } - _logger.debug("decoder Kerberos Token "+decoderKerberosToken); - KerberosToken kerberosToken=new KerberosToken(); - kerberosToken=(KerberosToken)JsonUtils.stringToObject(decoderKerberosToken, kerberosToken); - _logger.debug("Kerberos Token "+kerberosToken); - - DateTime notOnOrAfter=DateUtils.toUtcDate(kerberosToken.getNotOnOrAfter()); - _logger.debug("Kerberos Token is After Now "+notOnOrAfter.isAfterNow()); - - if(notOnOrAfter.isAfterNow()){ - LoginCredential loginCredential =new LoginCredential(kerberosToken.getPrincipal(),"",ConstsLoginType.KERBEROS); - loginCredential.setProvider(kerberosUserDomain); + //for Kerberos Login + _logger.debug("Try Kerberos login "); + _logger.debug("encoder Kerberos Token "+kerberosTokenString); + _logger.debug("kerberos UserDomain "+kerberosUserDomain); + + String decoderKerberosToken=null; + for(KerberosProxy kerberosProxy : kerberosService.getKerberosProxys()){ + if(kerberosProxy.getUserdomain().equalsIgnoreCase(kerberosUserDomain)){ + decoderKerberosToken=ReciprocalUtils.aesDecoder(kerberosTokenString, kerberosProxy.getCrypto()); + break; + } + } + _logger.debug("decoder Kerberos Token "+decoderKerberosToken); + KerberosToken kerberosToken=new KerberosToken(); + kerberosToken=(KerberosToken)JsonUtils.stringToObject(decoderKerberosToken, kerberosToken); + _logger.debug("Kerberos Token "+kerberosToken); + + DateTime notOnOrAfter=DateUtils.toUtcDate(kerberosToken.getNotOnOrAfter()); + _logger.debug("Kerberos Token is After Now "+notOnOrAfter.isAfterNow()); + + if(notOnOrAfter.isAfterNow()){ + LoginCredential loginCredential =new LoginCredential(kerberosToken.getPrincipal(),"",ConstsLoginType.KERBEROS); + loginCredential.setProvider(kerberosUserDomain); authenticationProvider.authenticate(loginCredential,true); - _logger.debug("Kerberos Logined in , username " + kerberosToken.getPrincipal()); - } - - return true; - } + _logger.debug("Kerberos Logined in , username " + kerberosToken.getPrincipal()); + } + + return true; + } - public HttpKerberosEntryPoint() { - super(); - } + public HttpKerberosEntryPoint() { + super(); + } public HttpKerberosEntryPoint (boolean enable) { super(); @@ -115,15 +115,15 @@ public class HttpKerberosEntryPoint implements AsyncHandlerInterceptor { } public HttpKerberosEntryPoint(AbstractAuthenticationProvider authenticationProvider, KerberosService kerberosService, - ApplicationConfig applicationConfig, boolean enable) { - super(); - this.authenticationProvider = authenticationProvider; - this.kerberosService = kerberosService; - this.applicationConfig = applicationConfig; - this.enable = enable; - } + ApplicationConfig applicationConfig, boolean enable) { + super(); + this.authenticationProvider = authenticationProvider; + this.kerberosService = kerberosService; + this.applicationConfig = applicationConfig; + this.enable = enable; + } - public boolean isEnable() { + public boolean isEnable() { return enable; } @@ -131,14 +131,14 @@ public class HttpKerberosEntryPoint implements AsyncHandlerInterceptor { this.enable = enable; } - public void setApplicationConfig(ApplicationConfig applicationConfig) { - this.applicationConfig = applicationConfig; - } + public void setApplicationConfig(ApplicationConfig applicationConfig) { + this.applicationConfig = applicationConfig; + } - public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) { - this.authenticationProvider = authenticationProvider; - } + public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) { + this.authenticationProvider = authenticationProvider; + } - + } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/KerberosProxy.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/KerberosProxy.java index ea0ceca8e..493af0a91 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/KerberosProxy.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/KerberosProxy.java @@ -18,63 +18,63 @@ package org.dromara.maxkey.authn.support.kerberos; public class KerberosProxy { - - String userdomain; - - String fullUserdomain; - - String crypto; - - String redirectUri; + + String userdomain; + + String fullUserdomain; + + String crypto; + + String redirectUri; - - /** - * - */ - public KerberosProxy() { - super(); - } + + /** + * + */ + public KerberosProxy() { + super(); + } - public String getUserdomain() { - return userdomain; - } + public String getUserdomain() { + return userdomain; + } - public void setUserdomain(String userdomain) { - this.userdomain = userdomain.toUpperCase(); - } + public void setUserdomain(String userdomain) { + this.userdomain = userdomain.toUpperCase(); + } - public String getFullUserdomain() { - return fullUserdomain; - } + public String getFullUserdomain() { + return fullUserdomain; + } - public void setFullUserdomain(String fullUserdomain) { - this.fullUserdomain = fullUserdomain.toUpperCase(); - } + public void setFullUserdomain(String fullUserdomain) { + this.fullUserdomain = fullUserdomain.toUpperCase(); + } - public String getCrypto() { - return crypto; - } + public String getCrypto() { + return crypto; + } - public void setCrypto(String crypto) { - this.crypto = crypto; - } + public void setCrypto(String crypto) { + this.crypto = crypto; + } - public String getRedirectUri() { - return redirectUri; - } + public String getRedirectUri() { + return redirectUri; + } - public void setRedirectUri(String redirectUri) { - this.redirectUri = redirectUri; - } + public void setRedirectUri(String redirectUri) { + this.redirectUri = redirectUri; + } - @Override - public String toString() { - return "KerberosProxy [userdomain=" + userdomain + ", fullUserdomain=" - + fullUserdomain + ", crypto=" + crypto - + ", redirectUri=" + redirectUri + "]"; - } - - + @Override + public String toString() { + return "KerberosProxy [userdomain=" + userdomain + ", fullUserdomain=" + + fullUserdomain + ", crypto=" + crypto + + ", redirectUri=" + redirectUri + "]"; + } + + } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/KerberosService.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/KerberosService.java index 665a84aca..6035da159 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/KerberosService.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/KerberosService.java @@ -20,9 +20,9 @@ package org.dromara.maxkey.authn.support.kerberos; import java.util.List; public interface KerberosService { - - public List getKerberosProxys(); - - public String buildKerberosProxys( ); - + + public List getKerberosProxys(); + + public String buildKerberosProxys( ); + } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/KerberosToken.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/KerberosToken.java index 803b15d6e..3cfbed054 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/KerberosToken.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/KerberosToken.java @@ -20,58 +20,58 @@ package org.dromara.maxkey.authn.support.kerberos; public class KerberosToken { - private String principal; - - private String fullPrincipal; - - private String notOnOrAfter; - - private String userDomain; + private String principal; + + private String fullPrincipal; + + private String notOnOrAfter; + + private String userDomain; - /** - * - */ - public KerberosToken() { - super(); - } + /** + * + */ + public KerberosToken() { + super(); + } - public String getPrincipal() { - return principal; - } + public String getPrincipal() { + return principal; + } - public void setPrincipal(String principal) { - this.principal = principal; - } + public void setPrincipal(String principal) { + this.principal = principal; + } - public String getFullPrincipal() { - return fullPrincipal; - } + public String getFullPrincipal() { + return fullPrincipal; + } - public void setFullPrincipal(String fullPrincipal) { - this.fullPrincipal = fullPrincipal; - } - - public String getNotOnOrAfter() { - return notOnOrAfter; - } + public void setFullPrincipal(String fullPrincipal) { + this.fullPrincipal = fullPrincipal; + } + + public String getNotOnOrAfter() { + return notOnOrAfter; + } - public void setNotOnOrAfter(String notOnOrAfter) { - this.notOnOrAfter = notOnOrAfter; - } + public void setNotOnOrAfter(String notOnOrAfter) { + this.notOnOrAfter = notOnOrAfter; + } - public String getUserDomain() { - return userDomain; - } + public String getUserDomain() { + return userDomain; + } - public void setUserDomain(String userDomain) { - this.userDomain = userDomain; - } + public void setUserDomain(String userDomain) { + this.userDomain = userDomain; + } - @Override - public String toString() { - return "KerberosToken [principal=" + principal + ", fullPrincipal=" - + fullPrincipal + ", notOnOrAfter=" + notOnOrAfter - + ", userDomain=" + userDomain + "]"; - } + @Override + public String toString() { + return "KerberosToken [principal=" + principal + ", fullPrincipal=" + + fullPrincipal + ", notOnOrAfter=" + notOnOrAfter + + ", userDomain=" + userDomain + "]"; + } } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/RemoteKerberosService.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/RemoteKerberosService.java index 5f462a6d7..ab916da8d 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/RemoteKerberosService.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/kerberos/RemoteKerberosService.java @@ -27,30 +27,30 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RemoteKerberosService implements KerberosService{ - private static Logger _logger = LoggerFactory.getLogger(RemoteKerberosService.class); - List kerberosProxys; + private static Logger _logger = LoggerFactory.getLogger(RemoteKerberosService.class); + List kerberosProxys; - @Override - public List getKerberosProxys() { - return kerberosProxys; - } + @Override + public List getKerberosProxys() { + return kerberosProxys; + } - public void setKerberosProxys(List kerberosProxys) { - this.kerberosProxys = kerberosProxys; - } - - @Override - public String buildKerberosProxys(){ - List>userDomainUrlList=new ArrayList>(); - for (KerberosProxy kerberosProxy :kerberosProxys){ - Map userDomainUrl =new HashMap(); - userDomainUrl.put("userDomain", kerberosProxy.getUserdomain()); - userDomainUrl.put("redirectUri", kerberosProxy.getRedirectUri()); - userDomainUrlList.add(userDomainUrl); - } - _logger.debug(""+userDomainUrlList); - String userDomainUrlJson=JsonUtils.toString(userDomainUrlList); - _logger.debug("userDomain Url Json "+userDomainUrlJson); - return userDomainUrlJson; - } + public void setKerberosProxys(List kerberosProxys) { + this.kerberosProxys = kerberosProxys; + } + + @Override + public String buildKerberosProxys(){ + List>userDomainUrlList=new ArrayList>(); + for (KerberosProxy kerberosProxy :kerberosProxys){ + Map userDomainUrl =new HashMap(); + userDomainUrl.put("userDomain", kerberosProxy.getUserdomain()); + userDomainUrl.put("redirectUri", kerberosProxy.getRedirectUri()); + userDomainUrlList.add(userDomainUrl); + } + _logger.debug(""+userDomainUrlList); + String userDomainUrlJson=JsonUtils.toString(userDomainUrlList); + _logger.debug("userDomain Url Json "+userDomainUrlJson); + return userDomainUrlJson; + } } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/rememberme/AbstractRemeberMeManager.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/rememberme/AbstractRemeberMeManager.java index 14c994eec..d9976a8e1 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/rememberme/AbstractRemeberMeManager.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/rememberme/AbstractRemeberMeManager.java @@ -57,10 +57,10 @@ public abstract class AbstractRemeberMeManager { // end persist public String createRemeberMe(Authentication authentication, - HttpServletRequest request, HttpServletResponse response) { + HttpServletRequest request, HttpServletResponse response) { if (applicationConfig.getLoginConfig().isRemeberMe()) { - SignPrincipal principal = ((SignPrincipal)authentication.getPrincipal()); - UserInfo userInfo = principal.getUserInfo(); + SignPrincipal principal = ((SignPrincipal)authentication.getPrincipal()); + UserInfo userInfo = principal.getUserInfo(); _logger.debug("Remeber Me ..."); RemeberMe remeberMe = new RemeberMe(); remeberMe.setId(WebContext.genId()); @@ -91,37 +91,37 @@ public abstract class AbstractRemeberMeManager { } public RemeberMe resolve(String rememberMeJwt) throws ParseException { - JWTClaimsSet claims = authTokenService.resolve(rememberMeJwt); - RemeberMe remeberMe = new RemeberMe(); - remeberMe.setId(claims.getJWTID()); - remeberMe.setUsername(claims.getSubject()); - return read(remeberMe); + JWTClaimsSet claims = authTokenService.resolve(rememberMeJwt); + RemeberMe remeberMe = new RemeberMe(); + remeberMe.setId(claims.getJWTID()); + remeberMe.setUsername(claims.getSubject()); + return read(remeberMe); } public String genRemeberMe(RemeberMe remeberMe ) { - _logger.debug("expiration Time : {}" , remeberMe.getExpirationTime()); - - JWTClaimsSet remeberMeJwtClaims =new JWTClaimsSet.Builder() - .issuer("") - .subject(remeberMe.getUsername()) - .jwtID(remeberMe.getId()) - .issueTime(remeberMe.getLastLoginTime()) - .expirationTime(remeberMe.getExpirationTime()) - .claim("kid", Hmac512Service.MXK_AUTH_JWK) - .build(); - - return authTokenService.signedJWT(remeberMeJwtClaims); - } + _logger.debug("expiration Time : {}" , remeberMe.getExpirationTime()); + + JWTClaimsSet remeberMeJwtClaims =new JWTClaimsSet.Builder() + .issuer("") + .subject(remeberMe.getUsername()) + .jwtID(remeberMe.getId()) + .issueTime(remeberMe.getLastLoginTime()) + .expirationTime(remeberMe.getExpirationTime()) + .claim("kid", Hmac512Service.MXK_AUTH_JWK) + .build(); + + return authTokenService.signedJWT(remeberMeJwtClaims); + } - public Integer getValidity() { - return validity; - } + public Integer getValidity() { + return validity; + } - public void setValidity(Integer validity) { - if(validity != 0 ) { - this.validity = validity; - } - } + public void setValidity(Integer validity) { + if(validity != 0 ) { + this.validity = validity; + } + } } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/rememberme/JdbcRemeberMeManager.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/rememberme/JdbcRemeberMeManager.java index 0e52ba756..0141d5b94 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/rememberme/JdbcRemeberMeManager.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/rememberme/JdbcRemeberMeManager.java @@ -48,15 +48,15 @@ public class JdbcRemeberMeManager extends AbstractRemeberMeManager { private final JdbcTemplate jdbcTemplate; public JdbcRemeberMeManager( - JdbcTemplate jdbcTemplate, - ApplicationConfig applicationConfig, - AuthTokenService authTokenService, - int validity) { + JdbcTemplate jdbcTemplate, + ApplicationConfig applicationConfig, + AuthTokenService authTokenService, + int validity) { this.jdbcTemplate = jdbcTemplate; this.applicationConfig = applicationConfig; this.authTokenService = authTokenService; if(validity != 0) { - this.validity = validity; + this.validity = validity; } } @@ -64,18 +64,18 @@ public class JdbcRemeberMeManager extends AbstractRemeberMeManager { public void save(RemeberMe remeberMe) { jdbcTemplate.update(DEFAULT_DEFAULT_INSERT_STATEMENT, new Object[] { - remeberMe.getId(), - remeberMe.getUserId(), - remeberMe.getUsername(), - remeberMe.getLastLoginTime(), - remeberMe.getExpirationTime()}, + remeberMe.getId(), + remeberMe.getUserId(), + remeberMe.getUsername(), + remeberMe.getLastLoginTime(), + remeberMe.getExpirationTime()}, new int[] { - Types.VARCHAR, - Types.VARCHAR, - Types.VARCHAR, - Types.TIMESTAMP, - Types.TIMESTAMP - }); + Types.VARCHAR, + Types.VARCHAR, + Types.VARCHAR, + Types.TIMESTAMP, + Types.TIMESTAMP + }); } @Override @@ -92,7 +92,7 @@ public class JdbcRemeberMeManager extends AbstractRemeberMeManager { public RemeberMe read(RemeberMe remeberMe) { List listRemeberMe = jdbcTemplate.query(DEFAULT_DEFAULT_SELECT_STATEMENT, new RowMapper() { - @Override + @Override public RemeberMe mapRow(ResultSet rs, int rowNum) throws SQLException { RemeberMe remeberMe = new RemeberMe(); remeberMe.setId(rs.getString(1)); diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/rememberme/RemeberMe.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/rememberme/RemeberMe.java index 3f9b64b7f..ac32fabd4 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/rememberme/RemeberMe.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/rememberme/RemeberMe.java @@ -35,10 +35,10 @@ public class RemeberMe implements Serializable { Date expirationTime; public RemeberMe() { - super(); - } + super(); + } - public String getId() { + public String getId() { return id; } @@ -47,14 +47,14 @@ public class RemeberMe implements Serializable { } public String getUserId() { - return userId; - } + return userId; + } - public void setUserId(String userId) { - this.userId = userId; - } + public void setUserId(String userId) { + this.userId = userId; + } - public String getUsername() { + public String getUsername() { return username; } @@ -63,35 +63,35 @@ public class RemeberMe implements Serializable { } public Date getLastLoginTime() { - return lastLoginTime; - } + return lastLoginTime; + } - public void setLastLoginTime(Date lastLoginTime) { - this.lastLoginTime = lastLoginTime; - } + public void setLastLoginTime(Date lastLoginTime) { + this.lastLoginTime = lastLoginTime; + } - public Date getExpirationTime() { - return expirationTime; - } + public Date getExpirationTime() { + return expirationTime; + } - public void setExpirationTime(Date expirationTime) { - this.expirationTime = expirationTime; - } + public void setExpirationTime(Date expirationTime) { + this.expirationTime = expirationTime; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("RemeberMe [id="); - builder.append(id); - builder.append(", userId="); - builder.append(userId); - builder.append(", username="); - builder.append(username); - builder.append(", lastLoginTime="); - builder.append(lastLoginTime); - builder.append(", expirationTime="); - builder.append(expirationTime); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("RemeberMe [id="); + builder.append(id); + builder.append(", userId="); + builder.append(userId); + builder.append(", username="); + builder.append(username); + builder.append(", lastLoginTime="); + builder.append(lastLoginTime); + builder.append(", expirationTime="); + builder.append(expirationTime); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/rememberme/RemeberMeManagerFactory.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/rememberme/RemeberMeManagerFactory.java index 9c0f20577..bfdd5ced6 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/rememberme/RemeberMeManagerFactory.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/rememberme/RemeberMeManagerFactory.java @@ -24,24 +24,24 @@ import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; public class RemeberMeManagerFactory { - private static final Logger _logger = + private static final Logger _logger = LoggerFactory.getLogger(RemeberMeManagerFactory.class); - - public AbstractRemeberMeManager getService( - int persistence, - JdbcTemplate jdbcTemplate, - RedisConnectionFactory redisConnFactory){ - - AbstractRemeberMeManager remeberMeService = null; - if (persistence == ConstsPersistence.INMEMORY) { - remeberMeService = new InMemoryRemeberMeManager(); - _logger.debug("InMemoryRemeberMeService"); - } else if (persistence == ConstsPersistence.JDBC) { - //remeberMeService = new JdbcRemeberMeService(jdbcTemplate); - _logger.debug("JdbcRemeberMeService not support "); - } else if (persistence == ConstsPersistence.REDIS) { - _logger.debug("RedisRemeberMeService not support "); - } - return remeberMeService; - } + + public AbstractRemeberMeManager getService( + int persistence, + JdbcTemplate jdbcTemplate, + RedisConnectionFactory redisConnFactory){ + + AbstractRemeberMeManager remeberMeService = null; + if (persistence == ConstsPersistence.INMEMORY) { + remeberMeService = new InMemoryRemeberMeManager(); + _logger.debug("InMemoryRemeberMeService"); + } else if (persistence == ConstsPersistence.JDBC) { + //remeberMeService = new JdbcRemeberMeService(jdbcTemplate); + _logger.debug("JdbcRemeberMeService not support "); + } else if (persistence == ConstsPersistence.REDIS) { + _logger.debug("RedisRemeberMeService not support "); + } + return remeberMeService; + } } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/HttpWsFederationEntryPoint.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/HttpWsFederationEntryPoint.java index 441814770..a9c216088 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/HttpWsFederationEntryPoint.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/HttpWsFederationEntryPoint.java @@ -34,55 +34,55 @@ import jakarta.servlet.http.HttpServletResponse; public class HttpWsFederationEntryPoint implements AsyncHandlerInterceptor { - private static final Logger _logger = LoggerFactory.getLogger(HttpWsFederationEntryPoint.class); - + private static final Logger _logger = LoggerFactory.getLogger(HttpWsFederationEntryPoint.class); + boolean enable; - ApplicationConfig applicationConfig; + ApplicationConfig applicationConfig; AbstractAuthenticationProvider authenticationProvider ; - WsFederationService wsFederationService; - - @Override - public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { - boolean isAuthenticated= AuthorizationUtils.isAuthenticated(); - String wsFederationWA = request.getParameter(WsFederationConstants.WA); - String wsFederationWResult = request.getParameter(WsFederationConstants.WRESULT); - - if(!enable - || isAuthenticated - || !applicationConfig.getLoginConfig().isWsFederation() - || wsFederationWA == null){ - return true; - } - - _logger.trace("WsFederation 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.trace("recreate new session ."); - request.getSession(true); - } - - _logger.trace("getSession.getId : "+ request.getSession().getId()); + WsFederationService wsFederationService; + + @Override + public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { + boolean isAuthenticated= AuthorizationUtils.isAuthenticated(); + String wsFederationWA = request.getParameter(WsFederationConstants.WA); + String wsFederationWResult = request.getParameter(WsFederationConstants.WRESULT); + + if(!enable + || isAuthenticated + || !applicationConfig.getLoginConfig().isWsFederation() + || wsFederationWA == null){ + return true; + } + + _logger.trace("WsFederation 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.trace("recreate new session ."); + request.getSession(true); + } + + _logger.trace("getSession.getId : "+ request.getSession().getId()); - //for WsFederation Login - _logger.debug("WsFederation : " + wsFederationWA +" , wsFederationWResult : " + wsFederationWResult); - if(applicationConfig.getLoginConfig().isWsFederation() - && StringUtils.isNotEmpty(wsFederationWA) - && wsFederationWA.equalsIgnoreCase(WsFederationConstants.WSIGNIN)){ - _logger.debug("wresult : {}"+wsFederationWResult); + //for WsFederation Login + _logger.debug("WsFederation : " + wsFederationWA +" , wsFederationWResult : " + wsFederationWResult); + if(applicationConfig.getLoginConfig().isWsFederation() + && StringUtils.isNotEmpty(wsFederationWA) + && wsFederationWA.equalsIgnoreCase(WsFederationConstants.WSIGNIN)){ + _logger.debug("wresult : {}"+wsFederationWResult); - final String wctx = request.getParameter(WsFederationConstants.WCTX); - _logger.debug("wctx : {}"+ wctx); + final String wctx = request.getParameter(WsFederationConstants.WCTX); + _logger.debug("wctx : {}"+ wctx); // create credentials final AssertionImpl assertion = WsFederationUtils.parseTokenFromString(wsFederationWResult); @@ -91,14 +91,14 @@ public class HttpWsFederationEntryPoint implements AsyncHandlerInterceptor { final WsFederationCredential wsFederationCredential = WsFederationUtils.createCredentialFromToken(assertion); if (wsFederationCredential != null && wsFederationCredential.isValid(wsFederationService.getWsFederationConfiguration().getRelyingParty(), - wsFederationService.getWsFederationConfiguration().getIdentifier(), - wsFederationService.getWsFederationConfiguration().getTolerance())) { + wsFederationService.getWsFederationConfiguration().getIdentifier(), + wsFederationService.getWsFederationConfiguration().getTolerance())) { //Give the library user a chance to change the attributes as necessary if (wsFederationService.getWsFederationConfiguration().getAttributeMutator() != null) { - wsFederationService.getWsFederationConfiguration().getAttributeMutator().modifyAttributes( - wsFederationCredential.getAttributes(), - wsFederationService.getWsFederationConfiguration().getUpnSuffix()); + wsFederationService.getWsFederationConfiguration().getAttributeMutator().modifyAttributes( + wsFederationCredential.getAttributes(), + wsFederationService.getWsFederationConfiguration().getUpnSuffix()); } LoginCredential loginCredential =new LoginCredential( wsFederationCredential.getAttributes().get("").toString(),"",ConstsLoginType.WSFEDERATION); @@ -110,14 +110,14 @@ public class HttpWsFederationEntryPoint implements AsyncHandlerInterceptor { } else { _logger.error("WS Requested Security Token is blank or the signature is not valid."); } - } - - return true; - } + } + + return true; + } - public HttpWsFederationEntryPoint() { - super(); - } + public HttpWsFederationEntryPoint() { + super(); + } public HttpWsFederationEntryPoint (boolean enable) { super(); @@ -125,15 +125,15 @@ public class HttpWsFederationEntryPoint implements AsyncHandlerInterceptor { } public HttpWsFederationEntryPoint(AbstractAuthenticationProvider authenticationProvider, WsFederationService wsFederationService, - ApplicationConfig applicationConfig, boolean enable) { - super(); - this.authenticationProvider = authenticationProvider; - this.wsFederationService = wsFederationService; - this.applicationConfig = applicationConfig; - this.enable = enable; - } + ApplicationConfig applicationConfig, boolean enable) { + super(); + this.authenticationProvider = authenticationProvider; + this.wsFederationService = wsFederationService; + this.applicationConfig = applicationConfig; + this.enable = enable; + } - public boolean isEnable() { + public boolean isEnable() { return enable; } @@ -141,18 +141,18 @@ public class HttpWsFederationEntryPoint implements AsyncHandlerInterceptor { this.enable = enable; } - public void setApplicationConfig(ApplicationConfig applicationConfig) { - this.applicationConfig = applicationConfig; - } + public void setApplicationConfig(ApplicationConfig applicationConfig) { + this.applicationConfig = applicationConfig; + } - public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) { - this.authenticationProvider = authenticationProvider; - } + public void setAuthenticationProvider(AbstractAuthenticationProvider authenticationProvider) { + this.authenticationProvider = authenticationProvider; + } - public void setWsFederationService(WsFederationService wsFederationService) { - this.wsFederationService = wsFederationService; - } + public void setWsFederationService(WsFederationService wsFederationService) { + this.wsFederationService = wsFederationService; + } - + } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/WsFederationConfiguration.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/WsFederationConfiguration.java index c2f81e508..8b0d01801 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/WsFederationConfiguration.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/WsFederationConfiguration.java @@ -31,7 +31,7 @@ import java.util.List; * */ public final class WsFederationConfiguration { - + @NotNull private String identifier; @@ -57,44 +57,44 @@ public final class WsFederationConfiguration { private String logoutUrl; public String getIdentifier() { - return identifier; - } + return identifier; + } - public void setIdentifier(String identifier) { - this.identifier = identifier; - } + public void setIdentifier(String identifier) { + this.identifier = identifier; + } - public String getUrl() { - return url; - } + public String getUrl() { + return url; + } - public void setUrl(String url) { - this.url = url; - } + public void setUrl(String url) { + this.url = url; + } - public String getPrincipal() { - return principal; - } + public String getPrincipal() { + return principal; + } - public void setPrincipal(String principal) { - this.principal = principal; - } + public void setPrincipal(String principal) { + this.principal = principal; + } - public String getRelyingParty() { - return relyingParty; - } + public String getRelyingParty() { + return relyingParty; + } - public void setRelyingParty(String relyingParty) { - this.relyingParty = relyingParty; - } + public void setRelyingParty(String relyingParty) { + this.relyingParty = relyingParty; + } - public List getSigningWallet() { - return signingWallet; - } + public List getSigningWallet() { + return signingWallet; + } - public void setSigningWallet(List signingWallet) { - this.signingWallet = signingWallet; - } + public void setSigningWallet(List signingWallet) { + this.signingWallet = signingWallet; + } /** * gets the signing certificates. @@ -105,7 +105,7 @@ public final class WsFederationConfiguration { return this.signingWallet; } - /** + /** * sets the signing certs. * * @param signingCertificateFiles a list of certificate files to read in. @@ -158,20 +158,20 @@ public final class WsFederationConfiguration { this.attributeMutator = attributeMutator; } - public String getUpnSuffix() { - return upnSuffix; - } + public String getUpnSuffix() { + return upnSuffix; + } - public void setUpnSuffix(String upnSuffix) { - this.upnSuffix = upnSuffix; - } + public void setUpnSuffix(String upnSuffix) { + this.upnSuffix = upnSuffix; + } - public String getLogoutUrl() { - return logoutUrl; - } + public String getLogoutUrl() { + return logoutUrl; + } - public void setLogoutUrl(String logoutUrl) { - this.logoutUrl = logoutUrl; - } + public void setLogoutUrl(String logoutUrl) { + this.logoutUrl = logoutUrl; + } } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/WsFederationConstants.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/WsFederationConstants.java index ddb7d158d..4c73d1ee3 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/WsFederationConstants.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/WsFederationConstants.java @@ -18,14 +18,14 @@ package org.dromara.maxkey.authn.support.wsfederation; public class WsFederationConstants { - public static final String LOCALE = "locale"; - public static final String METHOD = "method"; - public static final String PROVIDERURL = "WsFederationIdentityProviderUrl"; - public static final String QUERYSTRING = "?wa=wsignin1.0&wtrealm="; - public static final String SERVICE = "service"; - public static final String THEME = "theme"; - public static final String WA = "wa"; - public static final String WCTX = "wctx"; - public static final String WRESULT = "wresult"; - public static final String WSIGNIN = "wsignin1.0"; + public static final String LOCALE = "locale"; + public static final String METHOD = "method"; + public static final String PROVIDERURL = "WsFederationIdentityProviderUrl"; + public static final String QUERYSTRING = "?wa=wsignin1.0&wtrealm="; + public static final String SERVICE = "service"; + public static final String THEME = "theme"; + public static final String WA = "wa"; + public static final String WCTX = "wctx"; + public static final String WRESULT = "wresult"; + public static final String WSIGNIN = "wsignin1.0"; } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/WsFederationService.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/WsFederationService.java index 598458b44..7f9f05c59 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/WsFederationService.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/WsFederationService.java @@ -18,6 +18,6 @@ package org.dromara.maxkey.authn.support.wsfederation; public interface WsFederationService { - public WsFederationConfiguration getWsFederationConfiguration(); - + public WsFederationConfiguration getWsFederationConfiguration(); + } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/WsFederationServiceImpl.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/WsFederationServiceImpl.java index 6200000df..84501f834 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/WsFederationServiceImpl.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/authn/support/wsfederation/WsFederationServiceImpl.java @@ -22,20 +22,20 @@ import org.slf4j.LoggerFactory; public class WsFederationServiceImpl implements WsFederationService{ - static final Logger _logger = LoggerFactory.getLogger(WsFederationServiceImpl.class); - - private WsFederationConfiguration wsFederationConfiguration; + static final Logger _logger = LoggerFactory.getLogger(WsFederationServiceImpl.class); + + private WsFederationConfiguration wsFederationConfiguration; - public void setWsFederationConfiguration( - WsFederationConfiguration wsFederationConfiguration) { - this.wsFederationConfiguration = wsFederationConfiguration; - } + public void setWsFederationConfiguration( + WsFederationConfiguration wsFederationConfiguration) { + this.wsFederationConfiguration = wsFederationConfiguration; + } - @Override - public WsFederationConfiguration getWsFederationConfiguration() { - return wsFederationConfiguration; - } - - - + @Override + public WsFederationConfiguration getWsFederationConfiguration() { + return wsFederationConfiguration; + } + + + } diff --git a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/autoconfigure/AuthnProviderAutoConfiguration.java b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/autoconfigure/AuthnProviderAutoConfiguration.java index 7c688640e..ad56a8fc4 100644 --- a/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/autoconfigure/AuthnProviderAutoConfiguration.java +++ b/maxkey-authentications/maxkey-authentication-provider/src/main/java/org/dromara/maxkey/autoconfigure/AuthnProviderAutoConfiguration.java @@ -55,102 +55,102 @@ public class AuthnProviderAutoConfiguration { @Bean AbstractAuthenticationProvider authenticationProvider( - NormalAuthenticationProvider normalAuthenticationProvider, - MobileAuthenticationProvider mobileAuthenticationProvider, - TrustedAuthenticationProvider trustedAuthenticationProvider, - ScanCodeAuthenticationProvider scanCodeAuthenticationProvider, - AppAuthenticationProvider appAuthenticationProvider, - TwoFactorAuthenticationProvider twoFactorAuthenticationProvider - ) { - AuthenticationProviderFactory authenticationProvider = new AuthenticationProviderFactory(); - authenticationProvider.addAuthenticationProvider(normalAuthenticationProvider); - authenticationProvider.addAuthenticationProvider(mobileAuthenticationProvider); - authenticationProvider.addAuthenticationProvider(trustedAuthenticationProvider); - authenticationProvider.addAuthenticationProvider(scanCodeAuthenticationProvider); - authenticationProvider.addAuthenticationProvider(appAuthenticationProvider); + NormalAuthenticationProvider normalAuthenticationProvider, + MobileAuthenticationProvider mobileAuthenticationProvider, + TrustedAuthenticationProvider trustedAuthenticationProvider, + ScanCodeAuthenticationProvider scanCodeAuthenticationProvider, + AppAuthenticationProvider appAuthenticationProvider, + TwoFactorAuthenticationProvider twoFactorAuthenticationProvider + ) { + AuthenticationProviderFactory authenticationProvider = new AuthenticationProviderFactory(); + authenticationProvider.addAuthenticationProvider(normalAuthenticationProvider); + authenticationProvider.addAuthenticationProvider(mobileAuthenticationProvider); + authenticationProvider.addAuthenticationProvider(trustedAuthenticationProvider); + authenticationProvider.addAuthenticationProvider(scanCodeAuthenticationProvider); + authenticationProvider.addAuthenticationProvider(appAuthenticationProvider); - //二次认证 - authenticationProvider.addAuthenticationProvider(twoFactorAuthenticationProvider); - - return authenticationProvider; + //二次认证 + authenticationProvider.addAuthenticationProvider(twoFactorAuthenticationProvider); + + return authenticationProvider; } @Bean NormalAuthenticationProvider normalAuthenticationProvider( - AbstractAuthenticationRealm authenticationRealm, - ApplicationConfig applicationConfig, - SessionManager sessionManager, - AuthTokenService authTokenService - ) { - _logger.debug("init authentication Provider ."); - return new NormalAuthenticationProvider( - authenticationRealm, - applicationConfig, - sessionManager, - authTokenService - ); + AbstractAuthenticationRealm authenticationRealm, + ApplicationConfig applicationConfig, + SessionManager sessionManager, + AuthTokenService authTokenService + ) { + _logger.debug("init authentication Provider ."); + return new NormalAuthenticationProvider( + authenticationRealm, + applicationConfig, + sessionManager, + authTokenService + ); } - @Bean - ScanCodeAuthenticationProvider scanCodeAuthenticationProvider( - AbstractAuthenticationRealm authenticationRealm, - SessionManager sessionManager - ) { - return new ScanCodeAuthenticationProvider( - authenticationRealm, - sessionManager - ); - } + @Bean + ScanCodeAuthenticationProvider scanCodeAuthenticationProvider( + AbstractAuthenticationRealm authenticationRealm, + SessionManager sessionManager + ) { + return new ScanCodeAuthenticationProvider( + authenticationRealm, + sessionManager + ); + } - @Bean - AppAuthenticationProvider appAuthenticationProvider( - AbstractAuthenticationRealm authenticationRealm, - ApplicationConfig applicationConfig, - SessionManager sessionManager, - AuthTokenService authTokenService - ) { - return new AppAuthenticationProvider( - authenticationRealm, - applicationConfig, - sessionManager, - authTokenService - ); - } + @Bean + AppAuthenticationProvider appAuthenticationProvider( + AbstractAuthenticationRealm authenticationRealm, + ApplicationConfig applicationConfig, + SessionManager sessionManager, + AuthTokenService authTokenService + ) { + return new AppAuthenticationProvider( + authenticationRealm, + applicationConfig, + sessionManager, + authTokenService + ); + } @Bean MobileAuthenticationProvider mobileAuthenticationProvider( - AbstractAuthenticationRealm authenticationRealm, - ApplicationConfig applicationConfig, - SmsOtpAuthnService smsAuthnService, - SessionManager sessionManager - ) { - _logger.debug("init Mobile authentication Provider ."); - return new MobileAuthenticationProvider( - authenticationRealm, - applicationConfig, - smsAuthnService, - sessionManager - ); + AbstractAuthenticationRealm authenticationRealm, + ApplicationConfig applicationConfig, + SmsOtpAuthnService smsAuthnService, + SessionManager sessionManager + ) { + _logger.debug("init Mobile authentication Provider ."); + return new MobileAuthenticationProvider( + authenticationRealm, + applicationConfig, + smsAuthnService, + sessionManager + ); } @Bean TrustedAuthenticationProvider trustedAuthenticationProvider( - AbstractAuthenticationRealm authenticationRealm, - ApplicationConfig applicationConfig, - SessionManager sessionManager - ) { - _logger.debug("init Mobile authentication Provider ."); - return new TrustedAuthenticationProvider( - authenticationRealm, - applicationConfig, - sessionManager - ); + AbstractAuthenticationRealm authenticationRealm, + ApplicationConfig applicationConfig, + SessionManager sessionManager + ) { + _logger.debug("init Mobile authentication Provider ."); + return new TrustedAuthenticationProvider( + authenticationRealm, + applicationConfig, + sessionManager + ); } @Bean PasswordPolicyValidatorService passwordPolicyValidatorService( - CnfPasswordPolicyService cnfPasswordPolicyService, - MessageSource messageSource) { + CnfPasswordPolicyService cnfPasswordPolicyService, + MessageSource messageSource) { return new PasswordPolicyValidatorServiceImpl(cnfPasswordPolicyService,messageSource); } @@ -165,14 +165,14 @@ public class AuthnProviderAutoConfiguration { ApplicationConfig applicationConfig, AuthTokenService authTokenService, JdbcTemplate jdbcTemplate) { - _logger.trace("init RemeberMeManager , validity {}." , validity); + _logger.trace("init RemeberMeManager , validity {}." , validity); return new JdbcRemeberMeManager( - jdbcTemplate,applicationConfig,authTokenService,validity); + jdbcTemplate,applicationConfig,authTokenService,validity); } @Bean TwoFactorAuthenticationProvider twoFactorAuthenticationProvider( - AbstractAuthenticationRealm authenticationRealm, + AbstractAuthenticationRealm authenticationRealm, SessionManager sessionManager, LoginService loginService, AuthTokenService authTokenService, @@ -180,37 +180,37 @@ public class AuthnProviderAutoConfiguration { TwoFactorTotpAuthenticationProvider twoFactorTotpAuthenticationProvider, TwoFactorMobileAuthenticationProvider twoFactorMobileAuthenticationProvider, TwoFactorEmailAuthenticationProvider twoFactorEmailAuthenticationProvider) { - _logger.debug("init TwoFactor authentication Provider ."); - TwoFactorAuthenticationProvider twoFactorProvider =new TwoFactorAuthenticationProvider( - authenticationRealm, - sessionManager, - loginService, - authTokenService - ); - - twoFactorProvider.addProvider(ConstsTwoFactor.TOTP, twoFactorTotpAuthenticationProvider); - twoFactorProvider.addProvider(ConstsTwoFactor.EMAIL, twoFactorEmailAuthenticationProvider); - twoFactorProvider.addProvider(ConstsTwoFactor.SMS, twoFactorMobileAuthenticationProvider); - return twoFactorProvider; + _logger.debug("init TwoFactor authentication Provider ."); + TwoFactorAuthenticationProvider twoFactorProvider =new TwoFactorAuthenticationProvider( + authenticationRealm, + sessionManager, + loginService, + authTokenService + ); + + twoFactorProvider.addProvider(ConstsTwoFactor.TOTP, twoFactorTotpAuthenticationProvider); + twoFactorProvider.addProvider(ConstsTwoFactor.EMAIL, twoFactorEmailAuthenticationProvider); + twoFactorProvider.addProvider(ConstsTwoFactor.SMS, twoFactorMobileAuthenticationProvider); + return twoFactorProvider; } @Bean TwoFactorTotpAuthenticationProvider twoFactorTotpAuthenticationProvider(@Qualifier("tfaOtpAuthn") AbstractOtpAuthn tfaOtpAuthn, - AbstractAuthenticationRealm authenticationRealm) { - _logger.debug("init TwoFactor authentication Provider ."); - return new TwoFactorTotpAuthenticationProvider(authenticationRealm,tfaOtpAuthn); + AbstractAuthenticationRealm authenticationRealm) { + _logger.debug("init TwoFactor authentication Provider ."); + return new TwoFactorTotpAuthenticationProvider(authenticationRealm,tfaOtpAuthn); } @Bean TwoFactorMobileAuthenticationProvider twoFactorMobileAuthenticationProvider(SmsOtpAuthnService smsOtpAuthnService) { - _logger.debug("init TwoFactor Mobile authentication Provider ."); - return new TwoFactorMobileAuthenticationProvider(smsOtpAuthnService); + _logger.debug("init TwoFactor Mobile authentication Provider ."); + return new TwoFactorMobileAuthenticationProvider(smsOtpAuthnService); } @Bean TwoFactorEmailAuthenticationProvider twoFactorEmailAuthenticationProvider(MailOtpAuthnService mailOtpAuthnService) { - _logger.debug("init TwoFactor Email authentication Provider ."); - return new TwoFactorEmailAuthenticationProvider(mailOtpAuthnService); + _logger.debug("init TwoFactor Email authentication Provider ."); + return new TwoFactorEmailAuthenticationProvider(mailOtpAuthnService); } } diff --git a/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/cache/InMemoryMomentaryService.java b/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/cache/InMemoryMomentaryService.java index 104bde9d0..4b6ef26af 100644 --- a/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/cache/InMemoryMomentaryService.java +++ b/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/cache/InMemoryMomentaryService.java @@ -28,41 +28,41 @@ import com.github.benmanes.caffeine.cache.Caffeine; public class InMemoryMomentaryService implements MomentaryService{ private static final Logger _logger = LoggerFactory.getLogger(InMemoryMomentaryService.class); - protected static Cache momentaryStore = - Caffeine.newBuilder() - .expireAfterWrite(5, TimeUnit.MINUTES) - .maximumSize(200000) - .build(); - - public InMemoryMomentaryService() { + protected static Cache momentaryStore = + Caffeine.newBuilder() + .expireAfterWrite(5, TimeUnit.MINUTES) + .maximumSize(200000) + .build(); + + public InMemoryMomentaryService() { super(); } @Override public void put(String sessionId , String name, Object value){ - String sessionKey = getSessionKey(sessionId , name); - _logger.trace("key {}, value {}",sessionKey,value); - momentaryStore.put(sessionKey, value); - } + String sessionKey = getSessionKey(sessionId , name); + _logger.trace("key {}, value {}",sessionKey,value); + momentaryStore.put(sessionKey, value); + } - @Override - public Object remove(String sessionId , String name) { - String sessionKey = getSessionKey(sessionId , name); - Object value = momentaryStore.getIfPresent(sessionKey); - momentaryStore.invalidate(sessionKey); - _logger.trace("key {}, value {}",sessionKey,value); - return value; - } + @Override + public Object remove(String sessionId , String name) { + String sessionKey = getSessionKey(sessionId , name); + Object value = momentaryStore.getIfPresent(sessionKey); + momentaryStore.invalidate(sessionKey); + _logger.trace("key {}, value {}",sessionKey,value); + return value; + } @Override public Object get(String sessionId , String name) { - String sessionKey = getSessionKey(sessionId , name); - _logger.trace("key {}",sessionKey); - return momentaryStore.getIfPresent(sessionKey); + String sessionKey = getSessionKey(sessionId , name); + _logger.trace("key {}",sessionKey); + return momentaryStore.getIfPresent(sessionKey); } private String getSessionKey(String sessionId , String name) { - return sessionId + "_" + name; + return sessionId + "_" + name; } } diff --git a/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/cache/MomentaryService.java b/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/cache/MomentaryService.java index a0dff8298..18ac69b22 100644 --- a/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/cache/MomentaryService.java +++ b/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/cache/MomentaryService.java @@ -19,7 +19,7 @@ package org.dromara.maxkey.persistence.cache; public interface MomentaryService { - public void put(String sessionId , String name, Object value); + public void put(String sessionId , String name, Object value); public Object get(String sessionId , String name); diff --git a/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/cache/RedisMomentaryService.java b/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/cache/RedisMomentaryService.java index a98f5c673..cb57ce5c8 100644 --- a/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/cache/RedisMomentaryService.java +++ b/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/cache/RedisMomentaryService.java @@ -25,41 +25,41 @@ import org.slf4j.LoggerFactory; public class RedisMomentaryService implements MomentaryService { private static final Logger _logger = LoggerFactory.getLogger(RedisMomentaryService.class); - - protected int validitySeconds = 60 * 5; //default 5 minutes. - - RedisConnectionFactory connectionFactory; - - public static final String PREFIX = "mxk:momentary:"; - - /** - * @param connectionFactory - */ - public RedisMomentaryService( - RedisConnectionFactory connectionFactory) { - super(); - this.connectionFactory = connectionFactory; - } - - /** - * - */ - public RedisMomentaryService() { - - } + + protected int validitySeconds = 60 * 5; //default 5 minutes. + + RedisConnectionFactory connectionFactory; + + public static final String PREFIX = "mxk:momentary:"; + + /** + * @param connectionFactory + */ + public RedisMomentaryService( + RedisConnectionFactory connectionFactory) { + super(); + this.connectionFactory = connectionFactory; + } + + /** + * + */ + public RedisMomentaryService() { + + } - public void setConnectionFactory(RedisConnectionFactory connectionFactory) { - this.connectionFactory = connectionFactory; - } + public void setConnectionFactory(RedisConnectionFactory connectionFactory) { + this.connectionFactory = connectionFactory; + } - @Override - public void put(String sessionId , String name, Object value){ - RedisConnection conn = connectionFactory.getConnection(); - String sessionKey = getSessionKey(sessionId , name); - conn.setexObject(sessionKey, validitySeconds, value); - _logger.trace("key {}, validitySeconds {}, value {}",sessionKey,validitySeconds,value); - conn.close(); - } + @Override + public void put(String sessionId , String name, Object value){ + RedisConnection conn = connectionFactory.getConnection(); + String sessionKey = getSessionKey(sessionId , name); + conn.setexObject(sessionKey, validitySeconds, value); + _logger.trace("key {}, validitySeconds {}, value {}",sessionKey,validitySeconds,value); + conn.close(); + } @Override public Object get(String sessionId , String name) { @@ -71,19 +71,19 @@ public class RedisMomentaryService implements MomentaryService { return value; } - @Override - public Object remove(String sessionId, String name) { - RedisConnection conn = connectionFactory.getConnection(); - String sessionKey = getSessionKey(sessionId , name); + @Override + public Object remove(String sessionId, String name) { + RedisConnection conn = connectionFactory.getConnection(); + String sessionKey = getSessionKey(sessionId , name); Object value = conn.getObject(sessionKey); conn.delete(getSessionKey(sessionId , name)); conn.close(); _logger.trace("key {}, value {}",sessionKey,value); return value; - } - + } + private String getSessionKey(String sessionId , String name) { - return PREFIX + sessionId + name; + return PREFIX + sessionId + name; } } diff --git a/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/redis/RedisConnection.java b/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/redis/RedisConnection.java index 9cccf77b5..a0813cf16 100644 --- a/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/redis/RedisConnection.java +++ b/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/redis/RedisConnection.java @@ -28,146 +28,146 @@ import redis.clients.jedis.Jedis; import redis.clients.jedis.Pipeline; public class RedisConnection { - private static final Logger _logger = LoggerFactory.getLogger(RedisConnection.class); - - Jedis conn ; - RedisConnectionFactory connectionFactory; - - Pipeline pipeline ; - - public RedisConnection() { - - } - - public RedisConnection(RedisConnectionFactory connectionFactory) { - this.conn=connectionFactory.open(); - this.connectionFactory=connectionFactory; - } + private static final Logger _logger = LoggerFactory.getLogger(RedisConnection.class); + + Jedis conn ; + RedisConnectionFactory connectionFactory; + + Pipeline pipeline ; + + public RedisConnection() { + + } + + public RedisConnection(RedisConnectionFactory connectionFactory) { + this.conn=connectionFactory.open(); + this.connectionFactory=connectionFactory; + } - /** - * @param key - * @param value - */ - public void set(String key, String value){ - conn.set(key, value); - } - + /** + * @param key + * @param value + */ + public void set(String key, String value){ + conn.set(key, value); + } + - /** - * @param key - * @param value - */ - public void setObject(String key, Object value){ - if(value instanceof Serializable) { - set(key, ObjectTransformer.serialize((Serializable)value)); - }else { - _logger.error("value must implements of Serializable ."); - } - } - - public void setexObject(String key,int seconds, Object value){ - if(value instanceof Serializable) { - setex(key, seconds, ObjectTransformer.serialize((Serializable)value)); - }else { - _logger.error("value must implements of Serializable ."); - } - } - - /** - * @param key - * @param seconds - * @param value - */ - public void setex(String key,long seconds, String value){ - _logger.trace("setex key {} ..." , key); - if(seconds==0){ - conn.setex(key, RedisDefaultConfig.DEFAULT_LIFETIME, value); - }else{ - conn.setex(key, seconds, value); - } - _logger.trace("setex successful ."); - } - - - /** - * @param key - * @return String - */ - public String get(String key){ - _logger.trace("get key {} ..." , key); - String value = null; - if(key != null){ - value = conn.get(key); - } - return value; - } - - /** - * @param key - * @return String - */ - public T getObject(String key){ - String value = null; - if(key != null){ - value = get(key); - if(value!=null){ - return ObjectTransformer.deserialize(value); - } - } - return null; - } - - public void expire(String key,long seconds){ - _logger.trace("expire key {} , {}" , key , seconds); - conn.expire(key, seconds); - } - - public void delete(String key){ - _logger.trace("del key {}" , key); - conn.del(key); - } - - public void rPush(String key, Serializable object){ - conn.rpush(key, ObjectTransformer.serialize(object)); - } - - public long lRem(String key,int count,String value){ - return conn.lrem(key, count, value); - } - - - public List lRange(String key,int start,int end){ - return conn.lrange(key, start, end); - } - - public void openPipeline(){ - this.pipeline=conn.pipelined(); - } - - public List closePipeline(){ - return pipeline.syncAndReturnAll(); - } - /** + /** + * @param key + * @param value + */ + public void setObject(String key, Object value){ + if(value instanceof Serializable) { + set(key, ObjectTransformer.serialize((Serializable)value)); + }else { + _logger.error("value must implements of Serializable ."); + } + } + + public void setexObject(String key,int seconds, Object value){ + if(value instanceof Serializable) { + setex(key, seconds, ObjectTransformer.serialize((Serializable)value)); + }else { + _logger.error("value must implements of Serializable ."); + } + } + + /** + * @param key + * @param seconds + * @param value + */ + public void setex(String key,long seconds, String value){ + _logger.trace("setex key {} ..." , key); + if(seconds==0){ + conn.setex(key, RedisDefaultConfig.DEFAULT_LIFETIME, value); + }else{ + conn.setex(key, seconds, value); + } + _logger.trace("setex successful ."); + } + + + /** + * @param key + * @return String + */ + public String get(String key){ + _logger.trace("get key {} ..." , key); + String value = null; + if(key != null){ + value = conn.get(key); + } + return value; + } + + /** + * @param key + * @return String + */ + public T getObject(String key){ + String value = null; + if(key != null){ + value = get(key); + if(value!=null){ + return ObjectTransformer.deserialize(value); + } + } + return null; + } + + public void expire(String key,long seconds){ + _logger.trace("expire key {} , {}" , key , seconds); + conn.expire(key, seconds); + } + + public void delete(String key){ + _logger.trace("del key {}" , key); + conn.del(key); + } + + public void rPush(String key, Serializable object){ + conn.rpush(key, ObjectTransformer.serialize(object)); + } + + public long lRem(String key,int count,String value){ + return conn.lrem(key, count, value); + } + + + public List lRange(String key,int start,int end){ + return conn.lrange(key, start, end); + } + + public void openPipeline(){ + this.pipeline=conn.pipelined(); + } + + public List closePipeline(){ + return pipeline.syncAndReturnAll(); + } + /** * 释放jedis资源 * @param jedis */ - public void close() { + public void close() { if (conn != null) { - connectionFactory.close(conn); + connectionFactory.close(conn); } } - public Jedis getConn() { - return conn; - } + public Jedis getConn() { + return conn; + } - public void setConn(Jedis conn) { - this.conn = conn; - } + public void setConn(Jedis conn) { + this.conn = conn; + } - public Pipeline getPipeline() { - return pipeline; - } - - + public Pipeline getPipeline() { + return pipeline; + } + + } diff --git a/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/redis/RedisConnectionFactory.java b/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/redis/RedisConnectionFactory.java index d882d3499..c1a581993 100644 --- a/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/redis/RedisConnectionFactory.java +++ b/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/redis/RedisConnectionFactory.java @@ -25,7 +25,7 @@ import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class RedisConnectionFactory { - private static final Logger _logger = LoggerFactory.getLogger(RedisConnectionFactory.class); + private static final Logger _logger = LoggerFactory.getLogger(RedisConnectionFactory.class); JedisPoolConfig poolConfig; @@ -42,7 +42,7 @@ public class RedisConnectionFactory { public void initConnectionFactory() { if (jedisPool == null) { - _logger.debug("init Jedis Pool ."); + _logger.debug("init Jedis Pool ."); try { if (this.hostName == null || hostName.equals("")) { hostName = RedisDefaultConfig.DEFAULT_ADDRESS; @@ -75,16 +75,16 @@ public class RedisConnectionFactory { } public Jedis open() { - _logger.trace("get jedisPool Resource ..."); - Jedis jedis = jedisPool.getResource(); - _logger.trace("return jedisPool Resource ."); + _logger.trace("get jedisPool Resource ..."); + Jedis jedis = jedisPool.getResource(); + _logger.trace("return jedisPool Resource ."); return jedis; } public void close(Jedis conn) { // jedisPool.returnResource(conn); - _logger.trace("close conn ."); + _logger.trace("close conn ."); conn.close(); _logger.trace("closed conn ."); } diff --git a/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/redis/RedisDefaultConfig.java b/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/redis/RedisDefaultConfig.java index 6d54e8937..7cef3bd1c 100644 --- a/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/redis/RedisDefaultConfig.java +++ b/maxkey-commons/maxkey-cache/src/main/java/org/dromara/maxkey/persistence/redis/RedisDefaultConfig.java @@ -1,7 +1,7 @@ package org.dromara.maxkey.persistence.redis; public class RedisDefaultConfig { - /** + /** * Redis默认服务器IP */ public static final String DEFAULT_ADDRESS = "127.0.0.1"; diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsAct.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsAct.java index b5ba3b5e7..d97826597 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsAct.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsAct.java @@ -22,42 +22,42 @@ import java.util.concurrent.ConcurrentMap; public final class ConstsAct { - public static final String CREATE = "create"; + public static final String CREATE = "create"; - public static final String DELETE = "delete"; + public static final String DELETE = "delete"; - public static final String UPDATE = "update"; + public static final String UPDATE = "update"; - public static final String CHANGE_PASSWORD = "change_password"; + public static final String CHANGE_PASSWORD = "change_password"; - public static final String FORGOT_PASSWORD = "forgot_password"; + public static final String FORGOT_PASSWORD = "forgot_password"; - public static final String ADD_MEMBER = "add_member"; + public static final String ADD_MEMBER = "add_member"; - public static final String DELETE_MEMBER = "delete_member"; + public static final String DELETE_MEMBER = "delete_member"; - public static final String ENABLE = "enable"; + public static final String ENABLE = "enable"; - public static final String DISABLE = "disable"; + public static final String DISABLE = "disable"; - public static final String INACTIVE = "inactive"; + public static final String INACTIVE = "inactive"; - public static final String LOCK = "lock"; + public static final String LOCK = "lock"; - public static final String UNLOCK = "unlock"; + public static final String UNLOCK = "unlock"; - public static final String VIEW = "view"; + public static final String VIEW = "view"; public static final ConcurrentMap statusActon ; static { - statusActon = new ConcurrentHashMap<>(); - statusActon.put(ConstsStatus.ACTIVE, ENABLE); - statusActon.put(ConstsStatus.INACTIVE, INACTIVE); - statusActon.put(ConstsStatus.DISABLED, DISABLE); - statusActon.put(ConstsStatus.LOCK, LOCK); - statusActon.put(ConstsStatus.UNLOCK, UNLOCK); - statusActon.put(ConstsStatus.DELETE, DELETE); + statusActon = new ConcurrentHashMap<>(); + statusActon.put(ConstsStatus.ACTIVE, ENABLE); + statusActon.put(ConstsStatus.INACTIVE, INACTIVE); + statusActon.put(ConstsStatus.DISABLED, DISABLE); + statusActon.put(ConstsStatus.LOCK, LOCK); + statusActon.put(ConstsStatus.UNLOCK, UNLOCK); + statusActon.put(ConstsStatus.DELETE, DELETE); } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsActResult.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsActResult.java index 25e0bdce8..db58ed9dd 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsActResult.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsActResult.java @@ -18,8 +18,8 @@ package org.dromara.maxkey.constants; public final class ConstsActResult { - public static final String SUCCESS = "success"; - public static final String ERROR = "error"; - public static final String FAIL = "fail"; + public static final String SUCCESS = "success"; + public static final String ERROR = "error"; + public static final String FAIL = "fail"; } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsBoolean.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsBoolean.java index 738987fa0..f96f1dcae 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsBoolean.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsBoolean.java @@ -25,11 +25,11 @@ package org.dromara.maxkey.constants; */ public class ConstsBoolean { - public static final int FALSE = 0; + public static final int FALSE = 0; - public static final int TRUE = 1; + public static final int TRUE = 1; - private int value = FALSE; + private int value = FALSE; public ConstsBoolean() { diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsDatabase.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsDatabase.java index db9e37cbc..3950521da 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsDatabase.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsDatabase.java @@ -19,15 +19,15 @@ package org.dromara.maxkey.constants; public class ConstsDatabase { - public static final String MYSQL = "MySQL"; + public static final String MYSQL = "MySQL"; - public static final String POSTGRESQL = "PostgreSQL"; + public static final String POSTGRESQL = "PostgreSQL"; - public static final String ORACLE = "Oracle"; + public static final String ORACLE = "Oracle"; - public static final String MSSQLSERVER = "SQL Server"; + public static final String MSSQLSERVER = "SQL Server"; - public static final String DB2 = "db2"; + public static final String DB2 = "db2"; } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsEntryType.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsEntryType.java index d2efe2ebe..984f5b0f4 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsEntryType.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsEntryType.java @@ -19,21 +19,21 @@ package org.dromara.maxkey.constants; public class ConstsEntryType { - public static String USERINFO = "user"; + public static String USERINFO = "user"; - public static String ORGANIZATION = "organization"; + public static String ORGANIZATION = "organization"; - public static String APPLICATION = "application"; + public static String APPLICATION = "application"; - public static String ACCOUNT = "account"; + public static String ACCOUNT = "account"; - public static String ROLE = "role"; + public static String ROLE = "role"; - public static String PASSWORD = "password"; + public static String PASSWORD = "password"; - public static String RESOURCE = "resource"; + public static String RESOURCE = "resource"; - public static String PERMISSION = "permission"; + public static String PERMISSION = "permission"; diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsLoginType.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsLoginType.java index 0145a1466..5e3927ab7 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsLoginType.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsLoginType.java @@ -19,43 +19,43 @@ package org.dromara.maxkey.constants; public class ConstsLoginType { - public static final String LOCAL = "Local Login"; + public static final String LOCAL = "Local Login"; - public static final String BASIC = "Basic"; + public static final String BASIC = "Basic"; - public static final String SOCIALSIGNON = "Social Sign On"; + public static final String SOCIALSIGNON = "Social Sign On"; - public static final String REMEBER_ME = "RemeberMe"; + public static final String REMEBER_ME = "RemeberMe"; - public static final String DESKTOP = "Desktop"; + public static final String DESKTOP = "Desktop"; - public static final String KERBEROS = "Kerberos"; + public static final String KERBEROS = "Kerberos"; - public static final String SAMLTRUST = "SAML v2.0 Trust"; + public static final String SAMLTRUST = "SAML v2.0 Trust"; - public static final String MSADTRUST = "MS AD Trust"; + public static final String MSADTRUST = "MS AD Trust"; - public static final String CAS = "CAS"; + public static final String CAS = "CAS"; - public static final String WSFEDERATION = "WsFederation"; + public static final String WSFEDERATION = "WsFederation"; - public static final String JWT = "Jwt"; + public static final String JWT = "Jwt"; - public static final String HTTPHEADER = "HttpHeader"; + public static final String HTTPHEADER = "HttpHeader"; public static final class TwoFactor{ - /** - * 1=TOTP(动态验证码) - */ - public static final String TWO_FACTOR_TOTP = "TwoFactorTotp"; - /** - * 2=邮箱验证码 - */ - public static final String TWO_FACTOR_EMAIL = "TwoFactorEmail"; - /** - * 3=手机短信 - */ - public static final String TWO_FACTOR_MOBILE = "TwoFactorMobile"; + /** + * 1=TOTP(动态验证码) + */ + public static final String TWO_FACTOR_TOTP = "TwoFactorTotp"; + /** + * 2=邮箱验证码 + */ + public static final String TWO_FACTOR_EMAIL = "TwoFactorEmail"; + /** + * 3=手机短信 + */ + public static final String TWO_FACTOR_MOBILE = "TwoFactorMobile"; } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsPasswordSetType.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsPasswordSetType.java index 58f537f6c..9307b3d7c 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsPasswordSetType.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsPasswordSetType.java @@ -24,12 +24,12 @@ package org.dromara.maxkey.constants; */ public final class ConstsPasswordSetType { - public static final int PASSWORD_NORMAL = 0; + public static final int PASSWORD_NORMAL = 0; - public static final int INITIAL_PASSWORD = 1; + public static final int INITIAL_PASSWORD = 1; - public static final int PASSWORD_EXPIRED = 3; + public static final int PASSWORD_EXPIRED = 3; - public static final int MANAGER_CHANGED_PASSWORD = 2; + public static final int MANAGER_CHANGED_PASSWORD = 2; } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsPersistence.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsPersistence.java index efedd2383..e40f64f06 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsPersistence.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsPersistence.java @@ -24,10 +24,10 @@ package org.dromara.maxkey.constants; */ public final class ConstsPersistence { - public static final int INMEMORY = 0; + public static final int INMEMORY = 0; - public static final int JDBC = 1; + public static final int JDBC = 1; - public static final int REDIS = 2; + public static final int REDIS = 2; } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsPlatformRole.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsPlatformRole.java index 95f3b8efc..c52ba09f9 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsPlatformRole.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsPlatformRole.java @@ -19,9 +19,9 @@ package org.dromara.maxkey.constants; public final class ConstsPlatformRole { - public static final String PLATFORM_ADMIN = "PLATFORM_ADMIN"; + public static final String PLATFORM_ADMIN = "PLATFORM_ADMIN"; - public static final String TANANT_ADMIN = "TANANT_ADMIN"; + public static final String TANANT_ADMIN = "TANANT_ADMIN"; - public static final String ORDINARY_USER = "ORDINARY_USER"; + public static final String ORDINARY_USER = "ORDINARY_USER"; } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsProperties.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsProperties.java index ad948b00c..82097225e 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsProperties.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsProperties.java @@ -24,9 +24,9 @@ public class ConstsProperties { } public static String classPathResource(String propertySource,String active) { - if(active == null || active.equals("")) { - return propertySource.replaceAll("classpath:",""); - } + if(active == null || active.equals("")) { + return propertySource.replaceAll("classpath:",""); + } return propertySource.replace(".", "-"+active+".").replaceAll("classpath:",""); } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsProtocols.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsProtocols.java index 3d90ab637..62fa68203 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsProtocols.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsProtocols.java @@ -24,26 +24,26 @@ package org.dromara.maxkey.constants; */ public final class ConstsProtocols { - public static final String BASIC = "Basic"; + public static final String BASIC = "Basic"; - public static final String EXTEND_API = "Extend_API"; + public static final String EXTEND_API = "Extend_API"; - public static final String FORMBASED = "Form_Based"; + public static final String FORMBASED = "Form_Based"; - public static final String TOKENBASED = "Token_Based"; + public static final String TOKENBASED = "Token_Based"; // SAML - public static final String SAML20 = "SAML_v2.0"; + public static final String SAML20 = "SAML_v2.0"; - public static final String CAS = "CAS"; + public static final String CAS = "CAS"; - public static final String JWT = "JWT"; + public static final String JWT = "JWT"; // OAuth - public static final String OAUTH20 = "OAuth_v2.0"; + public static final String OAUTH20 = "OAuth_v2.0"; - public static final String OAUTH21 = "OAuth_v2.1"; + public static final String OAUTH21 = "OAuth_v2.1"; - public static final String OPEN_ID_CONNECT10 = "OpenID_Connect_v1.0"; + public static final String OPEN_ID_CONNECT10 = "OpenID_Connect_v1.0"; } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsRegex.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsRegex.java index 2d4373b6d..2a259754c 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsRegex.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsRegex.java @@ -23,14 +23,14 @@ import java.util.regex.Pattern; * Regex for email , mobile and etc. */ public class ConstsRegex { - - public static final Pattern EMAIL_PATTERN = Pattern.compile("^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$"); + + public static final Pattern EMAIL_PATTERN = Pattern.compile("^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$"); - public static final Pattern MOBILE_PATTERN = Pattern.compile("^[1][3,4,5,6,7,8,9][0-9]{9}$"); - - public static final Pattern IPADDRESS_REGEX = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); - - public static final Pattern WHITESPACE_REGEX = Pattern.compile("\\s"); - - public static final Pattern CHINESE_REGEX = Pattern.compile("[\\u4e00-\\u9fa5]"); + public static final Pattern MOBILE_PATTERN = Pattern.compile("^[1][3,4,5,6,7,8,9][0-9]{9}$"); + + public static final Pattern IPADDRESS_REGEX = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); + + public static final Pattern WHITESPACE_REGEX = Pattern.compile("\\s"); + + public static final Pattern CHINESE_REGEX = Pattern.compile("[\\u4e00-\\u9fa5]"); } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsRoles.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsRoles.java index c86463744..5be64f421 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsRoles.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsRoles.java @@ -26,14 +26,14 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; */ public final class ConstsRoles { - public static final SimpleGrantedAuthority ROLE_ADMINISTRATORS = new SimpleGrantedAuthority("ROLE_ADMINISTRATORS"); + public static final SimpleGrantedAuthority ROLE_ADMINISTRATORS = new SimpleGrantedAuthority("ROLE_ADMINISTRATORS"); - public static final SimpleGrantedAuthority ROLE_MANAGERS = new SimpleGrantedAuthority("ROLE_MANAGERS"); + public static final SimpleGrantedAuthority ROLE_MANAGERS = new SimpleGrantedAuthority("ROLE_MANAGERS"); - public static final SimpleGrantedAuthority ROLE_USER = new SimpleGrantedAuthority("ROLE_USER"); + public static final SimpleGrantedAuthority ROLE_USER = new SimpleGrantedAuthority("ROLE_USER"); - public static final SimpleGrantedAuthority ROLE_ALL_USER = new SimpleGrantedAuthority("ROLE_ALL_USER"); + public static final SimpleGrantedAuthority ROLE_ALL_USER = new SimpleGrantedAuthority("ROLE_ALL_USER"); - public static final SimpleGrantedAuthority ROLE_ORDINARY_USER = new SimpleGrantedAuthority("ROLE_ORDINARY_USER"); + public static final SimpleGrantedAuthority ROLE_ORDINARY_USER = new SimpleGrantedAuthority("ROLE_ORDINARY_USER"); } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsStatus.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsStatus.java index 766c2a0bb..9584cc506 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsStatus.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsStatus.java @@ -18,41 +18,41 @@ package org.dromara.maxkey.constants; public final class ConstsStatus { - - public static final int ACTIVE = 1; - - public static final int INACTIVE = 2; - - public static final int ENABLED = 3; - - public static final int DISABLED = 4; - - public static final int LOCK = 5; - - public static final int UNLOCK = 6; - - public static final int INVALID = 7; - - public static final int EXPIRED = 8; - - public static final int DELETE = 9; - - public static final int VALIDATED = 10; - - public static final int START = 11; - - public static final int STOP = 12; - - public static final int APPLY = 13; - public static final int APPROVED = 14; + public static final int ACTIVE = 1; + + public static final int INACTIVE = 2; + + public static final int ENABLED = 3; + + public static final int DISABLED = 4; + + public static final int LOCK = 5; + + public static final int UNLOCK = 6; + + public static final int INVALID = 7; + + public static final int EXPIRED = 8; + + public static final int DELETE = 9; + + public static final int VALIDATED = 10; + + public static final int START = 11; + + public static final int STOP = 12; + + public static final int APPLY = 13; - public static final int QUITED = 15; + public static final int APPROVED = 14; - public static final String NONE = "NONE"; + public static final int QUITED = 15; - public static final String YES = "YES"; + public static final String NONE = "NONE"; - public static final String NO = "NO"; + public static final String YES = "YES"; + + public static final String NO = "NO"; } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsTimeInterval.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsTimeInterval.java index ecb0302af..93f2b2e3f 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsTimeInterval.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsTimeInterval.java @@ -19,22 +19,22 @@ package org.dromara.maxkey.constants; public final class ConstsTimeInterval { - public static final Integer ONE_MINUTE = 60; // 1 minutes + public static final Integer ONE_MINUTE = 60; // 1 minutes - public static final Integer ONE_HOUR = 60 * 60; // 1 hour + public static final Integer ONE_HOUR = 60 * 60; // 1 hour - public static final Integer ONE_DAY = 60 * 60 * 24; // 1 day + public static final Integer ONE_DAY = 60 * 60 * 24; // 1 day - public static final Integer ONE_WEEK = ONE_DAY * 7; // 1 week + public static final Integer ONE_WEEK = ONE_DAY * 7; // 1 week - public static final Integer TWO_WEEK = ONE_DAY * 14; // 2 week + public static final Integer TWO_WEEK = ONE_DAY * 14; // 2 week - public static final Integer ONE_MONTH = ONE_DAY * 30; // 1 month + public static final Integer ONE_MONTH = ONE_DAY * 30; // 1 month - public static final Integer TWO_MONTH = ONE_DAY * 60; // 2 month + public static final Integer TWO_MONTH = ONE_DAY * 60; // 2 month /** * The number of seconds in one year (= 60 * 60 * 24 * 365). */ - public static final Integer ONE_YEAR = 60 * 60 * 24 * 365; + public static final Integer ONE_YEAR = 60 * 60 * 24 * 365; } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsTwoFactor.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsTwoFactor.java index ef0acc4e6..21dc4b2ba 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsTwoFactor.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ConstsTwoFactor.java @@ -7,21 +7,21 @@ package org.dromara.maxkey.constants; */ public class ConstsTwoFactor { - /** - * 无 - */ - public static final int NONE = 0; + /** + * 无 + */ + public static final int NONE = 0; /** * 动态令牌TOTP */ - public static final int TOTP = 1; + public static final int TOTP = 1; /** * 邮件验证码 */ - public static final int EMAIL = 2; + public static final int EMAIL = 2; /** * 短信验证码 */ - public static final int SMS = 3; + public static final int SMS = 3; } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ContentType.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ContentType.java index d602f0e36..e05297eea 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ContentType.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/constants/ContentType.java @@ -19,36 +19,36 @@ package org.dromara.maxkey.constants; public class ContentType { - public static final String TEXT_PLAIN = "text/plain"; + public static final String TEXT_PLAIN = "text/plain"; - public static final String TEXT_PLAIN_UTF8 = "text/plain;charset=UTF-8"; + public static final String TEXT_PLAIN_UTF8 = "text/plain;charset=UTF-8"; - public static final String TEXT_XML = "text/xml"; + public static final String TEXT_XML = "text/xml"; - public static final String TEXT_XML_UTF8 = "text/xml;charset=UTF-8"; + public static final String TEXT_XML_UTF8 = "text/xml;charset=UTF-8"; - public static final String APPLICATION_JSON = "application/json"; + public static final String APPLICATION_JSON = "application/json"; - public static final String APPLICATION_JSON_UTF8 = "application/json;charset=UTF-8"; + public static final String APPLICATION_JSON_UTF8 = "application/json;charset=UTF-8"; - public static final String APPLICATION_JWT = "application/jwt"; + public static final String APPLICATION_JWT = "application/jwt"; - public static final String APPLICATION_JWT_UTF8 = "application/jwt;charset=UTF-8"; + public static final String APPLICATION_JWT_UTF8 = "application/jwt;charset=UTF-8"; - public static final String APPLICATION_XML = "application/xml"; + public static final String APPLICATION_XML = "application/xml"; - public static final String APPLICATION_XML_UTF8 = "application/xml;charset=UTF-8"; + public static final String APPLICATION_XML_UTF8 = "application/xml;charset=UTF-8"; - public static final String APPLICATION_FORM = "application/x-www-form-urlencoded"; + public static final String APPLICATION_FORM = "application/x-www-form-urlencoded"; - public static final String IMAGE_GIF = "image/gif"; + public static final String IMAGE_GIF = "image/gif"; - public static final String IMAGE_JPEG = "image/jpeg"; + public static final String IMAGE_JPEG = "image/jpeg"; - public static final String IMAGE_PNG = "image/png"; + public static final String IMAGE_PNG = "image/png"; - public static final String JSON = "json"; + public static final String JSON = "json"; - public static final String XML = "xml"; + public static final String XML = "xml"; } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/DbTableColumn.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/DbTableColumn.java index de3185809..212da6b56 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/DbTableColumn.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/DbTableColumn.java @@ -27,49 +27,49 @@ package org.dromara.maxkey.entity; public class DbTableColumn { - String column; - String type; - int precision; - int scale; + String column; + String type; + int precision; + int scale; - public DbTableColumn(String column, String type, int precision, int scale) { - super(); - this.column = column; - this.type = type; - this.precision = precision; - this.scale = scale; - } + public DbTableColumn(String column, String type, int precision, int scale) { + super(); + this.column = column; + this.type = type; + this.precision = precision; + this.scale = scale; + } - public String getColumn() { - return column; - } + public String getColumn() { + return column; + } - public void setColumn(String column) { - this.column = column; - } + public void setColumn(String column) { + this.column = column; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public int getPrecision() { - return precision; - } + public int getPrecision() { + return precision; + } - public void setPrecision(int precision) { - this.precision = precision; - } + public void setPrecision(int precision) { + this.precision = precision; + } - public int getScale() { - return scale; - } + public int getScale() { + return scale; + } - public void setScale(int scale) { - this.scale = scale; - } + public void setScale(int scale) { + this.scale = scale; + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/DbTableMetaData.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/DbTableMetaData.java index 38d89a840..32624741f 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/DbTableMetaData.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/DbTableMetaData.java @@ -30,40 +30,40 @@ import java.util.ArrayList; import java.util.HashMap; public class DbTableMetaData { - String tableName; - - ArrayList columns = new ArrayList(); - - HashMap columnsMap = new HashMap(); + String tableName; + + ArrayList columns = new ArrayList(); + + HashMap columnsMap = new HashMap(); - public DbTableMetaData(String tableName) { - super(); - this.tableName = tableName; - } + public DbTableMetaData(String tableName) { + super(); + this.tableName = tableName; + } - public String getTableName() { - return tableName; - } + public String getTableName() { + return tableName; + } - public void setTableName(String tableName) { - this.tableName = tableName; - } + public void setTableName(String tableName) { + this.tableName = tableName; + } - public ArrayList getColumns() { - return columns; - } + public ArrayList getColumns() { + return columns; + } - public void setColumns(ArrayList columns) { - this.columns = columns; - } + public void setColumns(ArrayList columns) { + this.columns = columns; + } - public HashMap getColumnsMap() { - return columnsMap; - } + public HashMap getColumnsMap() { + return columnsMap; + } - public void setColumnsMap(HashMap columnsMap) { - this.columnsMap = columnsMap; - } - - + public void setColumnsMap(HashMap columnsMap) { + this.columnsMap = columnsMap; + } + + } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/Message.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/Message.java index c85803671..acf525945 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/Message.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/Message.java @@ -20,91 +20,91 @@ package org.dromara.maxkey.entity; import org.springframework.http.ResponseEntity; public class Message { - - public static final int SUCCESS = 0; //成功 - public static final int ERROR = 1; //错误 - public static final int FAIL = 2; //失败 - public static final int INFO = 101; //信息 - public static final int PROMPT = 102; //提示 - public static final int WARNING = 103; //警告 - - int code; - - String message; - - T data; + + public static final int SUCCESS = 0; //成功 + public static final int ERROR = 1; //错误 + public static final int FAIL = 2; //失败 + public static final int INFO = 101; //信息 + public static final int PROMPT = 102; //提示 + public static final int WARNING = 103; //警告 + + int code; + + String message; + + T data; - public Message() { - this.code = SUCCESS; - } + public Message() { + this.code = SUCCESS; + } - public Message(int code) { - this.code = code; - } - public Message(T data) { - this.data = data; - } - - public Message(int code, String message) { - this.code = code; - this.message = message; - } - - public Message(int code, String message, T data) { - this.code = code; - this.message = message; - this.data = data; - } - - public Message(int code, T data) { - this.code = code; - this.data = data; - } - - public int getCode() { - return code; - } + public Message(int code) { + this.code = code; + } + public Message(T data) { + this.data = data; + } + + public Message(int code, String message) { + this.code = code; + this.message = message; + } + + public Message(int code, String message, T data) { + this.code = code; + this.message = message; + this.data = data; + } + + public Message(int code, T data) { + this.code = code; + this.data = data; + } + + public int getCode() { + return code; + } - public void setCode(int code) { - this.code = code; - } + public void setCode(int code) { + this.code = code; + } - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } - public void setMessage(String message) { - this.message = message; - } - - public void setMessage(int code,String message) { - this.code = code; - this.message = message; - } + public void setMessage(String message) { + this.message = message; + } + + public void setMessage(int code,String message) { + this.code = code; + this.message = message; + } - public T getData() { - return data; - } + public T getData() { + return data; + } - public void setData(T data) { - this.data = data; - } - - public ResponseEntity buildResponse() { - return ResponseEntity.ok(this); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Message [code="); - builder.append(code); - builder.append(", message="); - builder.append(message); - builder.append(", data="); - builder.append(data); - builder.append("]"); - return builder.toString(); - } + public void setData(T data) { + this.data = data; + } + + public ResponseEntity buildResponse() { + return ResponseEntity.ok(this); + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Message [code="); + builder.append(code); + builder.append(", message="); + builder.append(message); + builder.append(", data="); + builder.append(data); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/TreeAttributes.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/TreeAttributes.java index cd4a1bc48..a968f5c79 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/TreeAttributes.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/TreeAttributes.java @@ -26,43 +26,43 @@ import java.util.ArrayList; */ public class TreeAttributes { - TreeNode rootNode; + TreeNode rootNode; - int nodeCount; + int nodeCount; - ArrayList nodes = new ArrayList(); + ArrayList nodes = new ArrayList(); - public ArrayList getNodes() { - return nodes; - } + public ArrayList getNodes() { + return nodes; + } - public void setNodes(ArrayList nodes) { - this.nodes = nodes; - } + public void setNodes(ArrayList nodes) { + this.nodes = nodes; + } - public TreeNode getRootNode() { - return rootNode; - } + public TreeNode getRootNode() { + return rootNode; + } - public void setRootNode(TreeNode rootNode) { - this.rootNode = rootNode; - } + public void setRootNode(TreeNode rootNode) { + this.rootNode = rootNode; + } - public int getNodeCount() { - return nodeCount; - } + public int getNodeCount() { + return nodeCount; + } - public void setNodeCount(int nodeCount) { - this.nodeCount = nodeCount; - } + public void setNodeCount(int nodeCount) { + this.nodeCount = nodeCount; + } - /** - * 新增节点到列表 - * - * @param treeNode - */ - public void addNode(TreeNode treeNode) { - this.nodes.add(treeNode); - } + /** + * 新增节点到列表 + * + * @param treeNode + */ + public void addNode(TreeNode treeNode) { + this.nodes.add(treeNode); + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/TreeNode.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/TreeNode.java index 90463ea01..3ce89ba72 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/TreeNode.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/entity/TreeNode.java @@ -24,21 +24,21 @@ package org.dromara.maxkey.entity; * */ public class TreeNode { - String key; - String code; - String title; - - String codePath; - String namePath; - - String parentKey; - String parentCode; - String parentTitle; - - - boolean expanded; - boolean isLeaf; - + String key; + String code; + String title; + + String codePath; + String namePath; + + String parentKey; + String parentCode; + String parentTitle; + + + boolean expanded; + boolean isLeaf; + // TreeNode Object attrs; @@ -51,92 +51,92 @@ public class TreeNode { this.title = title; } - public String getKey() { - return key; - } + public String getKey() { + return key; + } - public void setKey(String key) { - this.key = key; - } + public void setKey(String key) { + this.key = key; + } - public String getCode() { - return code; - } + public String getCode() { + return code; + } - public void setCode(String code) { - this.code = code; - } + public void setCode(String code) { + this.code = code; + } - public String getTitle() { - return title; - } + public String getTitle() { + return title; + } - public void setTitle(String title) { - this.title = title; - } + public void setTitle(String title) { + this.title = title; + } - public String getCodePath() { - return codePath; - } + public String getCodePath() { + return codePath; + } - public void setCodePath(String codePath) { - this.codePath = codePath; - } + public void setCodePath(String codePath) { + this.codePath = codePath; + } - public String getNamePath() { - return namePath; - } + public String getNamePath() { + return namePath; + } - public void setNamePath(String namePath) { - this.namePath = namePath; - } + public void setNamePath(String namePath) { + this.namePath = namePath; + } - public String getParentKey() { - return parentKey; - } + public String getParentKey() { + return parentKey; + } - public void setParentKey(String parentKey) { - this.parentKey = parentKey; - } + public void setParentKey(String parentKey) { + this.parentKey = parentKey; + } - public String getParentCode() { - return parentCode; - } + public String getParentCode() { + return parentCode; + } - public void setParentCode(String parentCode) { - this.parentCode = parentCode; - } + public void setParentCode(String parentCode) { + this.parentCode = parentCode; + } - public String getParentTitle() { - return parentTitle; - } + public String getParentTitle() { + return parentTitle; + } - public void setParentTitle(String parentTitle) { - this.parentTitle = parentTitle; - } + public void setParentTitle(String parentTitle) { + this.parentTitle = parentTitle; + } - public boolean isExpanded() { - return expanded; - } + public boolean isExpanded() { + return expanded; + } - public void setExpanded(boolean expanded) { - this.expanded = expanded; - } + public void setExpanded(boolean expanded) { + this.expanded = expanded; + } - public boolean getIsLeaf() { - return isLeaf; - } + public boolean getIsLeaf() { + return isLeaf; + } - public void setLeaf(boolean isLeaf) { - this.isLeaf = isLeaf; - } + public void setLeaf(boolean isLeaf) { + this.isLeaf = isLeaf; + } - public Object getAttrs() { - return attrs; - } + public Object getAttrs() { + return attrs; + } - public void setAttrs(Object attrs) { - this.attrs = attrs; - } + public void setAttrs(Object attrs) { + this.attrs = attrs; + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/Pretty.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/Pretty.java index d1a7dac41..1c00f795f 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/Pretty.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/Pretty.java @@ -18,9 +18,9 @@ package org.dromara.maxkey.pretty; public interface Pretty { - public static final String LINE_BREAK = "\n"; - - public String format(String source); + public static final String LINE_BREAK = "\n"; + + public String format(String source); - public String formatln(String source); + public String formatln(String source); } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/PrettyFactory.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/PrettyFactory.java index e8665dae3..9bcd64d19 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/PrettyFactory.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/PrettyFactory.java @@ -21,7 +21,7 @@ import org.dromara.maxkey.pretty.impl.JsonPretty; import org.dromara.maxkey.pretty.impl.XmlPretty; public class PrettyFactory { - + public static Pretty getJsonPretty() { return JsonPretty.getInstance(); } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/impl/JsonPretty.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/impl/JsonPretty.java index 76748bbdb..3d8d0f91e 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/impl/JsonPretty.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/impl/JsonPretty.java @@ -30,97 +30,97 @@ import com.google.gson.JsonParser; public class JsonPretty implements Pretty{ - static JsonPretty instance ; - - public JsonPretty() { + static JsonPretty instance ; + + public JsonPretty() { - } + } - public static JsonPretty getInstance() { - if (null == instance) { - synchronized (JsonPretty.class) { - if (instance == null) { - instance = new JsonPretty(); - } - } - } - return instance; - } - - /** - * prettyJson use jackson - * @param bean - * @return String - */ - public String jacksonFormat(Object bean){ - String prettyJson = ""; - try { - prettyJson = (new ObjectMapper()) - .writerWithDefaultPrettyPrinter() - .writeValueAsString(bean); - } catch (JsonGenerationException e) { - e.printStackTrace(); - } catch (JsonMappingException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - return prettyJson; - } - - /** - * prettyJson use Gson - * @param bean - * @return String - */ - public String format(Object bean){ - Gson gson = new GsonBuilder() - .setPrettyPrinting() - .create(); - String json = gson.toJson(bean); - return json; - } - - /** - * prettyJson use Gson , htmlEscaping - * @param bean - * @return String - */ - public String format(Object bean,boolean htmlEscaping){ - if(!htmlEscaping) { - return format(bean); - } - - Gson gson = new GsonBuilder() - .setPrettyPrinting() - .disableHtmlEscaping() - .create(); - String json = gson.toJson(bean); - return json; - } - - /** - * prettyJson use Gson - * @param bean - * @return String - */ - public String formatln(Object bean){ - return LINE_BREAK + format(bean); - } - - /** - * prettyJson use Gson - * @param JSON String - * @return String - */ - @Override - public String format(String jsonString){ - return format(JsonParser.parseString(jsonString)); - } + public static JsonPretty getInstance() { + if (null == instance) { + synchronized (JsonPretty.class) { + if (instance == null) { + instance = new JsonPretty(); + } + } + } + return instance; + } + + /** + * prettyJson use jackson + * @param bean + * @return String + */ + public String jacksonFormat(Object bean){ + String prettyJson = ""; + try { + prettyJson = (new ObjectMapper()) + .writerWithDefaultPrettyPrinter() + .writeValueAsString(bean); + } catch (JsonGenerationException e) { + e.printStackTrace(); + } catch (JsonMappingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return prettyJson; + } + + /** + * prettyJson use Gson + * @param bean + * @return String + */ + public String format(Object bean){ + Gson gson = new GsonBuilder() + .setPrettyPrinting() + .create(); + String json = gson.toJson(bean); + return json; + } + + /** + * prettyJson use Gson , htmlEscaping + * @param bean + * @return String + */ + public String format(Object bean,boolean htmlEscaping){ + if(!htmlEscaping) { + return format(bean); + } + + Gson gson = new GsonBuilder() + .setPrettyPrinting() + .disableHtmlEscaping() + .create(); + String json = gson.toJson(bean); + return json; + } + + /** + * prettyJson use Gson + * @param bean + * @return String + */ + public String formatln(Object bean){ + return LINE_BREAK + format(bean); + } + + /** + * prettyJson use Gson + * @param JSON String + * @return String + */ + @Override + public String format(String jsonString){ + return format(JsonParser.parseString(jsonString)); + } - @Override - public String formatln(String source) { - return LINE_BREAK + format(source); - } - + @Override + public String formatln(String source) { + return LINE_BREAK + format(source); + } + } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/impl/SqlPretty.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/impl/SqlPretty.java index bf6f0c2c5..612cf1aac 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/impl/SqlPretty.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/impl/SqlPretty.java @@ -26,398 +26,398 @@ import java.util.StringTokenizer; import org.dromara.maxkey.pretty.Pretty; public class SqlPretty implements Pretty{ - - static SqlPretty instance ; - - public static final String WHITESPACE = " \n\r\f\t"; - private static final Set BEGIN_CLAUSES = new HashSet(); - private static final Set END_CLAUSES = new HashSet(); - private static final Set LOGICAL = new HashSet(); - private static final Set QUANTIFIERS = new HashSet(); - private static final Set DML = new HashSet(); - private static final Set MISC = new HashSet(); - private static final String INDENT_STRING = " "; - //mhshi modify - private static final String INITIAL = "";//System.lineSeparator() + INDENT_STRING; - - static { - BEGIN_CLAUSES.add( "left" ); - BEGIN_CLAUSES.add( "right" ); - BEGIN_CLAUSES.add( "inner" ); - BEGIN_CLAUSES.add( "outer" ); - BEGIN_CLAUSES.add( "group" ); - BEGIN_CLAUSES.add( "order" ); + + static SqlPretty instance ; + + public static final String WHITESPACE = " \n\r\f\t"; + private static final Set BEGIN_CLAUSES = new HashSet(); + private static final Set END_CLAUSES = new HashSet(); + private static final Set LOGICAL = new HashSet(); + private static final Set QUANTIFIERS = new HashSet(); + private static final Set DML = new HashSet(); + private static final Set MISC = new HashSet(); + private static final String INDENT_STRING = " "; + //mhshi modify + private static final String INITIAL = "";//System.lineSeparator() + INDENT_STRING; + + static { + BEGIN_CLAUSES.add( "left" ); + BEGIN_CLAUSES.add( "right" ); + BEGIN_CLAUSES.add( "inner" ); + BEGIN_CLAUSES.add( "outer" ); + BEGIN_CLAUSES.add( "group" ); + BEGIN_CLAUSES.add( "order" ); - END_CLAUSES.add( "where" ); - END_CLAUSES.add( "set" ); - END_CLAUSES.add( "having" ); - END_CLAUSES.add( "join" ); - END_CLAUSES.add( "from" ); - END_CLAUSES.add( "by" ); - END_CLAUSES.add( "join" ); - END_CLAUSES.add( "into" ); - END_CLAUSES.add( "union" ); + END_CLAUSES.add( "where" ); + END_CLAUSES.add( "set" ); + END_CLAUSES.add( "having" ); + END_CLAUSES.add( "join" ); + END_CLAUSES.add( "from" ); + END_CLAUSES.add( "by" ); + END_CLAUSES.add( "join" ); + END_CLAUSES.add( "into" ); + END_CLAUSES.add( "union" ); - LOGICAL.add( "and" ); - LOGICAL.add( "or" ); - LOGICAL.add( "when" ); - LOGICAL.add( "else" ); - LOGICAL.add( "end" ); + LOGICAL.add( "and" ); + LOGICAL.add( "or" ); + LOGICAL.add( "when" ); + LOGICAL.add( "else" ); + LOGICAL.add( "end" ); - QUANTIFIERS.add( "in" ); - QUANTIFIERS.add( "all" ); - QUANTIFIERS.add( "exists" ); - QUANTIFIERS.add( "some" ); - QUANTIFIERS.add( "any" ); + QUANTIFIERS.add( "in" ); + QUANTIFIERS.add( "all" ); + QUANTIFIERS.add( "exists" ); + QUANTIFIERS.add( "some" ); + QUANTIFIERS.add( "any" ); - DML.add( "insert" ); - DML.add( "update" ); - DML.add( "delete" ); + DML.add( "insert" ); + DML.add( "update" ); + DML.add( "delete" ); - MISC.add( "select" ); - MISC.add( "on" ); - } + MISC.add( "select" ); + MISC.add( "on" ); + } - public SqlPretty() { - - } - - public static SqlPretty getInstance() { - if (null == instance) { - synchronized (JsonPretty.class) { - if (instance == null) { - instance = new SqlPretty(); - } - } - } - return instance; - } - - @Override - public String format(String source) { - return new FormatProcess( source ).perform(); - } - - @Override - public String formatln(String source) { - return LINE_BREAK + format(source); - } + public SqlPretty() { + + } + + public static SqlPretty getInstance() { + if (null == instance) { + synchronized (JsonPretty.class) { + if (instance == null) { + instance = new SqlPretty(); + } + } + } + return instance; + } + + @Override + public String format(String source) { + return new FormatProcess( source ).perform(); + } + + @Override + public String formatln(String source) { + return LINE_BREAK + format(source); + } - private static class FormatProcess { - boolean beginLine = true; - boolean afterBeginBeforeEnd; - boolean afterByOrSetOrFromOrSelect; - boolean afterValues; - boolean afterOn; - boolean afterBetween; - boolean afterInsert; - int inFunction; - int parensSinceSelect; - private LinkedList parenCounts = new LinkedList(); - private LinkedList afterByOrFromOrSelects = new LinkedList(); - //mhshi modify - int indent = 0;//1; + private static class FormatProcess { + boolean beginLine = true; + boolean afterBeginBeforeEnd; + boolean afterByOrSetOrFromOrSelect; + boolean afterValues; + boolean afterOn; + boolean afterBetween; + boolean afterInsert; + int inFunction; + int parensSinceSelect; + private LinkedList parenCounts = new LinkedList(); + private LinkedList afterByOrFromOrSelects = new LinkedList(); + //mhshi modify + int indent = 0;//1; - StringBuilder result = new StringBuilder(); - StringTokenizer tokens; - String lastToken; - String token; - String lcToken; + StringBuilder result = new StringBuilder(); + StringTokenizer tokens; + String lastToken; + String token; + String lcToken; - public FormatProcess(String sql) { - tokens = new StringTokenizer( - sql, - "()+*/-=<>'`\"[]," + WHITESPACE, - true - ); - } + public FormatProcess(String sql) { + tokens = new StringTokenizer( + sql, + "()+*/-=<>'`\"[]," + WHITESPACE, + true + ); + } - public String perform() { + public String perform() { - result.append( INITIAL ); + result.append( INITIAL ); - while ( tokens.hasMoreTokens() ) { - token = tokens.nextToken(); - lcToken = token.toLowerCase(Locale.ROOT); + while ( tokens.hasMoreTokens() ) { + token = tokens.nextToken(); + lcToken = token.toLowerCase(Locale.ROOT); - if ( "'".equals( token ) ) { - String t; - do { - t = tokens.nextToken(); - token += t; - } - // cannot handle single quotes - while ( !"'".equals( t ) && tokens.hasMoreTokens() ); - } - else if ( "\"".equals( token ) ) { - String t; - do { - t = tokens.nextToken(); - token += t; - } - while ( !"\"".equals( t ) && tokens.hasMoreTokens() ); - } - // SQL Server uses "[" and "]" to escape reserved words - // see SQLServerDialect.openQuote and SQLServerDialect.closeQuote - else if ( "[".equals( token ) ) { - String t; - do { - t = tokens.nextToken(); - token += t; - } - while ( !"]".equals( t ) && tokens.hasMoreTokens()); - } + if ( "'".equals( token ) ) { + String t; + do { + t = tokens.nextToken(); + token += t; + } + // cannot handle single quotes + while ( !"'".equals( t ) && tokens.hasMoreTokens() ); + } + else if ( "\"".equals( token ) ) { + String t; + do { + t = tokens.nextToken(); + token += t; + } + while ( !"\"".equals( t ) && tokens.hasMoreTokens() ); + } + // SQL Server uses "[" and "]" to escape reserved words + // see SQLServerDialect.openQuote and SQLServerDialect.closeQuote + else if ( "[".equals( token ) ) { + String t; + do { + t = tokens.nextToken(); + token += t; + } + while ( !"]".equals( t ) && tokens.hasMoreTokens()); + } - if ( afterByOrSetOrFromOrSelect && ",".equals( token ) ) { - commaAfterByOrFromOrSelect(); - } - else if ( afterOn && ",".equals( token ) ) { - commaAfterOn(); - } + if ( afterByOrSetOrFromOrSelect && ",".equals( token ) ) { + commaAfterByOrFromOrSelect(); + } + else if ( afterOn && ",".equals( token ) ) { + commaAfterOn(); + } - else if ( "(".equals( token ) ) { - openParen(); - } - else if ( ")".equals( token ) ) { - closeParen(); - } + else if ( "(".equals( token ) ) { + openParen(); + } + else if ( ")".equals( token ) ) { + closeParen(); + } - else if ( BEGIN_CLAUSES.contains( lcToken ) ) { - beginNewClause(); - } + else if ( BEGIN_CLAUSES.contains( lcToken ) ) { + beginNewClause(); + } - else if ( END_CLAUSES.contains( lcToken ) ) { - endNewClause(); - } + else if ( END_CLAUSES.contains( lcToken ) ) { + endNewClause(); + } - else if ( "select".equals( lcToken ) ) { - select(); - } + else if ( "select".equals( lcToken ) ) { + select(); + } - else if ( DML.contains( lcToken ) ) { - updateOrInsertOrDelete(); - } + else if ( DML.contains( lcToken ) ) { + updateOrInsertOrDelete(); + } - else if ( "values".equals( lcToken ) ) { - values(); - } + else if ( "values".equals( lcToken ) ) { + values(); + } - else if ( "on".equals( lcToken ) ) { - on(); - } + else if ( "on".equals( lcToken ) ) { + on(); + } - else if ( afterBetween && lcToken.equals( "and" ) ) { - misc(); - afterBetween = false; - } + else if ( afterBetween && lcToken.equals( "and" ) ) { + misc(); + afterBetween = false; + } - else if ( LOGICAL.contains( lcToken ) ) { - logical(); - } + else if ( LOGICAL.contains( lcToken ) ) { + logical(); + } - else if ( isWhitespace( token ) ) { - white(); - } + else if ( isWhitespace( token ) ) { + white(); + } - else { - misc(); - } + else { + misc(); + } - if ( !isWhitespace( token ) ) { - lastToken = lcToken; - } + if ( !isWhitespace( token ) ) { + lastToken = lcToken; + } - } - return result.toString(); - } + } + return result.toString(); + } - private void commaAfterOn() { - out(); - indent--; - newline(); - afterOn = false; - afterByOrSetOrFromOrSelect = true; - } + private void commaAfterOn() { + out(); + indent--; + newline(); + afterOn = false; + afterByOrSetOrFromOrSelect = true; + } - private void commaAfterByOrFromOrSelect() { - out(); - newline(); - } + private void commaAfterByOrFromOrSelect() { + out(); + newline(); + } - private void logical() { - if ( "end".equals( lcToken ) ) { - indent--; - } - newline(); - out(); - beginLine = false; - } + private void logical() { + if ( "end".equals( lcToken ) ) { + indent--; + } + newline(); + out(); + beginLine = false; + } - private void on() { - indent++; - afterOn = true; - newline(); - out(); - beginLine = false; - } + private void on() { + indent++; + afterOn = true; + newline(); + out(); + beginLine = false; + } - private void misc() { - out(); - if ( "between".equals( lcToken ) ) { - afterBetween = true; - } - if ( afterInsert ) { - newline(); - afterInsert = false; - } - else { - beginLine = false; - if ( "case".equals( lcToken ) ) { - indent++; - } - } - } + private void misc() { + out(); + if ( "between".equals( lcToken ) ) { + afterBetween = true; + } + if ( afterInsert ) { + newline(); + afterInsert = false; + } + else { + beginLine = false; + if ( "case".equals( lcToken ) ) { + indent++; + } + } + } - private void white() { - if ( !beginLine ) { - result.append( " " ); - } - } + private void white() { + if ( !beginLine ) { + result.append( " " ); + } + } - private void updateOrInsertOrDelete() { - out(); - indent++; - beginLine = false; - if ( "update".equals( lcToken ) ) { - newline(); - } - if ( "insert".equals( lcToken ) ) { - afterInsert = true; - } - } + private void updateOrInsertOrDelete() { + out(); + indent++; + beginLine = false; + if ( "update".equals( lcToken ) ) { + newline(); + } + if ( "insert".equals( lcToken ) ) { + afterInsert = true; + } + } - private void select() { - out(); - indent++; - newline(); - parenCounts.addLast( parensSinceSelect ); - afterByOrFromOrSelects.addLast( afterByOrSetOrFromOrSelect ); - parensSinceSelect = 0; - afterByOrSetOrFromOrSelect = true; - } + private void select() { + out(); + indent++; + newline(); + parenCounts.addLast( parensSinceSelect ); + afterByOrFromOrSelects.addLast( afterByOrSetOrFromOrSelect ); + parensSinceSelect = 0; + afterByOrSetOrFromOrSelect = true; + } - private void out() { - result.append( token ); - } + private void out() { + result.append( token ); + } - private void endNewClause() { - if ( !afterBeginBeforeEnd ) { - indent--; - if ( afterOn ) { - indent--; - afterOn = false; - } - newline(); - } - out(); - if ( !"union".equals( lcToken ) ) { - indent++; - } - newline(); - afterBeginBeforeEnd = false; - afterByOrSetOrFromOrSelect = "by".equals( lcToken ) - || "set".equals( lcToken ) - || "from".equals( lcToken ); - } + private void endNewClause() { + if ( !afterBeginBeforeEnd ) { + indent--; + if ( afterOn ) { + indent--; + afterOn = false; + } + newline(); + } + out(); + if ( !"union".equals( lcToken ) ) { + indent++; + } + newline(); + afterBeginBeforeEnd = false; + afterByOrSetOrFromOrSelect = "by".equals( lcToken ) + || "set".equals( lcToken ) + || "from".equals( lcToken ); + } - private void beginNewClause() { - if ( !afterBeginBeforeEnd ) { - if ( afterOn ) { - indent--; - afterOn = false; - } - indent--; - newline(); - } - out(); - beginLine = false; - afterBeginBeforeEnd = true; - } + private void beginNewClause() { + if ( !afterBeginBeforeEnd ) { + if ( afterOn ) { + indent--; + afterOn = false; + } + indent--; + newline(); + } + out(); + beginLine = false; + afterBeginBeforeEnd = true; + } - private void values() { - indent--; - newline(); - out(); - indent++; - newline(); - afterValues = true; - } + private void values() { + indent--; + newline(); + out(); + indent++; + newline(); + afterValues = true; + } - private void closeParen() { - parensSinceSelect--; - if ( parensSinceSelect < 0 ) { - indent--; - parensSinceSelect = parenCounts.removeLast(); - afterByOrSetOrFromOrSelect = afterByOrFromOrSelects.removeLast(); - } - if ( inFunction > 0 ) { - inFunction--; - out(); - } - else { - if ( !afterByOrSetOrFromOrSelect ) { - indent--; - newline(); - } - out(); - } - beginLine = false; - } + private void closeParen() { + parensSinceSelect--; + if ( parensSinceSelect < 0 ) { + indent--; + parensSinceSelect = parenCounts.removeLast(); + afterByOrSetOrFromOrSelect = afterByOrFromOrSelects.removeLast(); + } + if ( inFunction > 0 ) { + inFunction--; + out(); + } + else { + if ( !afterByOrSetOrFromOrSelect ) { + indent--; + newline(); + } + out(); + } + beginLine = false; + } - private void openParen() { - if ( isFunctionName( lastToken ) || inFunction > 0 ) { - inFunction++; - } - beginLine = false; - if ( inFunction > 0 ) { - out(); - } - else { - out(); - if ( !afterByOrSetOrFromOrSelect ) { - indent++; - newline(); - beginLine = true; - } - } - parensSinceSelect++; - } + private void openParen() { + if ( isFunctionName( lastToken ) || inFunction > 0 ) { + inFunction++; + } + beginLine = false; + if ( inFunction > 0 ) { + out(); + } + else { + out(); + if ( !afterByOrSetOrFromOrSelect ) { + indent++; + newline(); + beginLine = true; + } + } + parensSinceSelect++; + } - private static boolean isFunctionName(String tok) { - if ( tok == null || tok.length() == 0 ) { - return false; - } + private static boolean isFunctionName(String tok) { + if ( tok == null || tok.length() == 0 ) { + return false; + } - final char begin = tok.charAt( 0 ); - final boolean isIdentifier = Character.isJavaIdentifierStart( begin ) || '"' == begin; - return isIdentifier && - !LOGICAL.contains( tok ) && - !END_CLAUSES.contains( tok ) && - !QUANTIFIERS.contains( tok ) && - !DML.contains( tok ) && - !MISC.contains( tok ); - } + final char begin = tok.charAt( 0 ); + final boolean isIdentifier = Character.isJavaIdentifierStart( begin ) || '"' == begin; + return isIdentifier && + !LOGICAL.contains( tok ) && + !END_CLAUSES.contains( tok ) && + !QUANTIFIERS.contains( tok ) && + !DML.contains( tok ) && + !MISC.contains( tok ); + } - private static boolean isWhitespace(String token) { - return WHITESPACE.contains( token ); - } + private static boolean isWhitespace(String token) { + return WHITESPACE.contains( token ); + } - private void newline() { - result.append( System.lineSeparator() ); - for ( int i = 0; i < indent; i++ ) { - result.append( INDENT_STRING ); - } - beginLine = true; - } - } + private void newline() { + result.append( System.lineSeparator() ); + for ( int i = 0; i < indent; i++ ) { + result.append( INDENT_STRING ); + } + beginLine = true; + } + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/impl/XMLHelper.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/impl/XMLHelper.java index fd7d04836..7b9ca4d2f 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/impl/XMLHelper.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/impl/XMLHelper.java @@ -84,17 +84,17 @@ public class XMLHelper { return writer.toString(); } - public static String prettyPrintXML(String xmlString){ - try{ - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document document = documentBuilder.parse(new InputSource(new StringReader(xmlString))); - return prettyPrintXML(document); - }catch(Exception e){ - e.printStackTrace(); - return null; - } - } + public static String prettyPrintXML(String xmlString){ + try{ + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document document = documentBuilder.parse(new InputSource(new StringReader(xmlString))); + return prettyPrintXML(document); + }catch(Exception e){ + e.printStackTrace(); + return null; + } + } /** * Create the parameters set used in pretty print formatting of an LSSerializer. @@ -193,12 +193,12 @@ public class XMLHelper { serializer.setFilter(new LSSerializerFilter() { - @Override + @Override public short acceptNode(Node arg0) { return FILTER_ACCEPT; } - @Override + @Override public int getWhatToShow() { return SHOW_ALL; } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/impl/XmlPretty.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/impl/XmlPretty.java index 6058fe7de..ecd7056ba 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/impl/XmlPretty.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/pretty/impl/XmlPretty.java @@ -29,47 +29,47 @@ import org.xml.sax.InputSource; public class XmlPretty implements Pretty{ - static XmlPretty instance ; - - public XmlPretty() { + static XmlPretty instance ; + + public XmlPretty() { - } - - public static XmlPretty getInstance() { - if (null == instance) { - synchronized (JsonPretty.class) { - if (instance == null) { - instance = new XmlPretty(); - } - } - } - return instance; - } - - @Override - public String format(String xmlString){ - try{ - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document document = documentBuilder.parse(new InputSource(new StringReader(xmlString))); - return format(document); - }catch(Exception e){ - e.printStackTrace(); - return null; - } - } - - public String format(Node node){ - try{ - return XMLHelper.prettyPrintXML(node); - }catch(Exception e){ - e.printStackTrace(); - return null; - } - } + } + + public static XmlPretty getInstance() { + if (null == instance) { + synchronized (JsonPretty.class) { + if (instance == null) { + instance = new XmlPretty(); + } + } + } + return instance; + } + + @Override + public String format(String xmlString){ + try{ + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document document = documentBuilder.parse(new InputSource(new StringReader(xmlString))); + return format(document); + }catch(Exception e){ + e.printStackTrace(); + return null; + } + } + + public String format(Node node){ + try{ + return XMLHelper.prettyPrintXML(node); + }catch(Exception e){ + e.printStackTrace(); + return null; + } + } - @Override - public String formatln(String source) { - return LINE_BREAK + format(source); - } + @Override + public String formatln(String source) { + return LINE_BREAK + format(source); + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/AuthorizationHeader.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/AuthorizationHeader.java index 7592a0176..912e4e7da 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/AuthorizationHeader.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/AuthorizationHeader.java @@ -18,70 +18,70 @@ package org.dromara.maxkey.util; public class AuthorizationHeader { - public static class Credential { + public static class Credential { - public static final String BASIC = "Basic "; + public static final String BASIC = "Basic "; - public static final String BEARER = "Bearer "; - } + public static final String BEARER = "Bearer "; + } - String credentialType = Credential.BASIC; - String username; - String credential; - String authorization; + String credentialType = Credential.BASIC; + String username; + String credential; + String authorization; - public AuthorizationHeader(String bearer) { - super(); - this.credential = bearer; - this.credentialType = Credential.BEARER; - } + public AuthorizationHeader(String bearer) { + super(); + this.credential = bearer; + this.credentialType = Credential.BEARER; + } - public AuthorizationHeader(String username, String credential) { - super(); - this.username = username; - this.credential = credential; - } + public AuthorizationHeader(String username, String credential) { + super(); + this.username = username; + this.credential = credential; + } - public String getCredentialType() { - return credentialType; - } + public String getCredentialType() { + return credentialType; + } - public void setCredentialType(String credentialType) { - this.credentialType = credentialType; - } + public void setCredentialType(String credentialType) { + this.credentialType = credentialType; + } - public String getUsername() { - return username; - } + public String getUsername() { + return username; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } - public String getCredential() { - return credential; - } + public String getCredential() { + return credential; + } - public void setCredential(String credential) { - this.credential = credential; - } + public void setCredential(String credential) { + this.credential = credential; + } - public String transform() { - if (credentialType.equalsIgnoreCase(Credential.BASIC)) { - return AuthorizationHeaderUtils.createBasic(username, credential); - } else { - return AuthorizationHeaderUtils.createBearer(credential); - } - } + public String transform() { + if (credentialType.equalsIgnoreCase(Credential.BASIC)) { + return AuthorizationHeaderUtils.createBasic(username, credential); + } else { + return AuthorizationHeaderUtils.createBearer(credential); + } + } - public boolean isBasic() { - return credentialType.equals(Credential.BASIC) ? true : false; - } + public boolean isBasic() { + return credentialType.equals(Credential.BASIC) ? true : false; + } - @Override - public String toString() { - return "AuthorizationHeaderCredential [credentialType=" + credentialType + ", username=" + username - + ", credential=" + credential + "]"; - } + @Override + public String toString() { + return "AuthorizationHeaderCredential [credentialType=" + credentialType + ", username=" + username + + ", credential=" + credential + "]"; + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/AuthorizationHeaderUtils.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/AuthorizationHeaderUtils.java index 5b806ed0b..c90ebda48 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/AuthorizationHeaderUtils.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/AuthorizationHeaderUtils.java @@ -28,9 +28,9 @@ import jakarta.servlet.http.HttpServletRequest; */ public class AuthorizationHeaderUtils { - /** - * first UpperCase - */ + /** + * first UpperCase + */ public static final String HEADER_Authorization = "Authorization"; /** * first LowerCase @@ -48,8 +48,8 @@ public class AuthorizationHeaderUtils { } public static AuthorizationHeader resolve(HttpServletRequest request) { - String authorization = resolveBearer(request); - return resolve(authorization); + String authorization = resolveBearer(request); + return resolve(authorization); } public static AuthorizationHeader resolve(String authorization) { @@ -63,13 +63,13 @@ public class AuthorizationHeaderUtils { } public static String resolveBearer(HttpServletRequest request) { - String authorization = - StringUtils.isNotBlank(request.getHeader(HEADER_Authorization)) ? - request.getHeader(HEADER_Authorization) : request.getHeader(HEADER_authorization); - if(StringUtils.isNotBlank(authorization)) { - return resolveBearer(authorization); - } - return null; + String authorization = + StringUtils.isNotBlank(request.getHeader(HEADER_Authorization)) ? + request.getHeader(HEADER_Authorization) : request.getHeader(HEADER_authorization); + if(StringUtils.isNotBlank(authorization)) { + return resolveBearer(authorization); + } + return null; } public static boolean isBasic(String basic) { diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/BeanConvert.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/BeanConvert.java index e772bc0ad..1973c4cb9 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/BeanConvert.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/BeanConvert.java @@ -35,45 +35,45 @@ import org.apache.commons.logging.LogFactory; */ public class BeanConvert { - /** - * - */ - public BeanConvert() { - - } - - public static Map bean2Map( T bean){ - Map mapBean=new HashMap(); - Field[] flds = bean.getClass().getDeclaredFields(); - LogFactory.getLog(BeanConvert.class).debug("bean2Map() *******************************************"); - LogFactory.getLog(BeanConvert.class).debug("bean2Map() "+bean.getClass().getName()); - for (int i = 0; i < flds.length; i++) { - String fieldName = flds[i].getName(); - if(BeanUtil.isGetProperty(bean.getClass(),fieldName)){ - Object value=BeanUtil.get(bean, fieldName); - mapBean.put(fieldName,value ); - LogFactory.getLog(BeanConvert.class).debug("bean2Map() field "+(i+1)+" : "+fieldName+" = "+value+" type : "+flds[i].getType()); - } - } - LogFactory.getLog(BeanConvert.class).debug("bean2Map() *******************************************"); - return mapBean; - } - - - public static Object map2Bean(T bean,HashMap valueMap){ - Map beanFiledMap=null; - try { - beanFiledMap = BeanUtil.getFields(bean); - } catch (Exception e) { - e.printStackTrace(); - } - if(beanFiledMap==null) { - return bean; - } - Iterator fieldit = beanFiledMap.entrySet().iterator(); - LogFactory.getLog(BeanConvert.class).debug("map2Bean() *******************************************"); - LogFactory.getLog(BeanConvert.class).debug("map2Bean() "+bean.getClass().getName()); - int i=1; + /** + * + */ + public BeanConvert() { + + } + + public static Map bean2Map( T bean){ + Map mapBean=new HashMap(); + Field[] flds = bean.getClass().getDeclaredFields(); + LogFactory.getLog(BeanConvert.class).debug("bean2Map() *******************************************"); + LogFactory.getLog(BeanConvert.class).debug("bean2Map() "+bean.getClass().getName()); + for (int i = 0; i < flds.length; i++) { + String fieldName = flds[i].getName(); + if(BeanUtil.isGetProperty(bean.getClass(),fieldName)){ + Object value=BeanUtil.get(bean, fieldName); + mapBean.put(fieldName,value ); + LogFactory.getLog(BeanConvert.class).debug("bean2Map() field "+(i+1)+" : "+fieldName+" = "+value+" type : "+flds[i].getType()); + } + } + LogFactory.getLog(BeanConvert.class).debug("bean2Map() *******************************************"); + return mapBean; + } + + + public static Object map2Bean(T bean,HashMap valueMap){ + Map beanFiledMap=null; + try { + beanFiledMap = BeanUtil.getFields(bean); + } catch (Exception e) { + e.printStackTrace(); + } + if(beanFiledMap==null) { + return bean; + } + Iterator fieldit = beanFiledMap.entrySet().iterator(); + LogFactory.getLog(BeanConvert.class).debug("map2Bean() *******************************************"); + LogFactory.getLog(BeanConvert.class).debug("map2Bean() "+bean.getClass().getName()); + int i=1; while (fieldit.hasNext()) { @SuppressWarnings("rawtypes") Map.Entry entry = (Map.Entry) fieldit.next(); @@ -81,54 +81,54 @@ public class BeanConvert { Object value = null; String fieldType=(String)beanFiledMap.get(fieldName); if(valueMap.get(fieldName)==null) { - continue; + continue; } String fillValue=valueMap.get(fieldName).toString(); LogFactory.getLog(BeanConvert.class).debug("map2Bean() field "+(i++)+" : "+fieldName+" = "+fillValue+" type : "+fieldType); if(fieldType.equals("java.lang.String")){ - value=String.valueOf(fillValue); + value=String.valueOf(fillValue); }else if(fieldType.equals("int")){ - value=Integer.parseInt(fillValue); + value=Integer.parseInt(fillValue); }else if(fieldType.equals("java.lang.Integer")){ - value=Integer.parseInt(fillValue); + value=Integer.parseInt(fillValue); }else if(fieldType.equals("long")){ - value=Long.parseLong(fillValue); + value=Long.parseLong(fillValue); }else if(fieldType.equals("java.lang.Long")){ - value= Long.parseLong(fillValue); + value= Long.parseLong(fillValue); }else if(fieldType.equals("double")){ - value=(double)Double.valueOf(fillValue); + value=(double)Double.valueOf(fillValue); }else if(fieldType.equals("java.lang.Double")){ - value=Double.valueOf(fillValue); + value=Double.valueOf(fillValue); }else if(fieldType.equals("float")){ - value=Float.parseFloat(fillValue); + value=Float.parseFloat(fillValue); }else if(fieldType.equals("java.lang.Float")){ - value=Float.parseFloat(fillValue); + value=Float.parseFloat(fillValue); }else if(fieldType.equals("java.util.Date")){ - try { - if(fillValue.length()==10){ - fillValue+=" 00:00:00"; - value=(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).parse(fillValue); - }else{ - continue; - } - } catch (ParseException e) { - e.printStackTrace(); - } + try { + if(fillValue.length()==10){ + fillValue+=" 00:00:00"; + value=(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).parse(fillValue); + }else{ + continue; + } + } catch (ParseException e) { + e.printStackTrace(); + } }else if(fieldType.equals("java.lang.Object")){ - value=valueMap.get(fieldName); + value=valueMap.get(fieldName); }else if(fieldType.equals("char")){ - value=Character.valueOf(fillValue.charAt(0)); + value=Character.valueOf(fillValue.charAt(0)); }else if(fieldType.equals("boolean")){ - value=Boolean.parseBoolean(fillValue); + value=Boolean.parseBoolean(fillValue); }else if(fieldType.equals("short")){ - value=Short.parseShort(fillValue); + value=Short.parseShort(fillValue); }else if(fieldType.equals("byte")){ - value=Byte.parseByte(fillValue); + value=Byte.parseByte(fillValue); } BeanUtil.set(bean, fieldName, value); } - LogFactory.getLog(BeanConvert.class).debug("map2Bean() *******************************************"); - return bean; - } + LogFactory.getLog(BeanConvert.class).debug("map2Bean() *******************************************"); + return bean; + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/BeanUtil.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/BeanUtil.java index 7e462f78d..92ac7a85c 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/BeanUtil.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/BeanUtil.java @@ -28,338 +28,338 @@ import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.logging.LogFactory; public class BeanUtil { - - public static void copyBean(Object origin,Object target) { - if( origin == null || target == null) { - return; - } - try { - BeanUtils.copyProperties( origin, target); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static Object cloneSupper(Object origin) { - Object target = null; - if(origin == null) { - return target; - } - try { - target = origin.getClass().getSuperclass().newInstance(); - BeanUtils.copyProperties(target,origin); - } catch (Exception e) { - e.printStackTrace(); - } - return target; - } - - public static String getValue(Object bean,String field ) { - if(bean == null) { - return null; - } - String retVal = ""; - try { - retVal = BeanUtils.getProperty(bean, field); - } catch(Exception e) { - e.printStackTrace(); - } - return retVal; - } - - @SuppressWarnings("rawtypes") - public static boolean isNotNull(Collection collection) { - if(collection != null && collection.size() > 0) { - return true; - } - return false; - } - - @SuppressWarnings("rawtypes") - public static boolean isNotNull(Map map) { - if(map != null && map.size() > 0) { - return true; - } - return false; - } - - public static Object get(Object bean, String fieldName) { - try { - return invokeMethod(bean,getMethodByProperty("get",fieldName)); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object set(Object bean, String fieldName,Object value) { - try { - return invokeMethod(bean,getMethodByProperty("set",fieldName),new Object[]{value}); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object getPublicProperty(Object bean, String fieldName) { - try { - Field field = bean.getClass().getField(fieldName); - return field.get(bean); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static boolean setPublicProperty(Object bean, String fieldName,Object value) { - try { - Field field = bean.getClass().getField(fieldName); - field.set(bean,value); - return true; - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - public static Boolean isPublicProperty(Class cls, String fieldName) { - if (isSetProperty(cls, fieldName)&& isGetProperty(cls, fieldName)) { - return true; - } else { - return false; - } - } - - public static Boolean isPublicProperty(Object bean, String fieldName) { - if (isSetProperty(bean.getClass(), fieldName) - && isGetProperty(bean.getClass(), fieldName)) { - return true; - } else { - return false; - } - } - - public static Boolean isSetProperty(Class cls, String fieldName) { - Method[] method = cls.getDeclaredMethods(); - for (int i = 0; i < method.length; i++) { - if (method[i].getModifiers() == Modifier.PUBLIC - && method[i].getName().equals(getMethodByProperty("set",fieldName))) { - return true; - } - } - return false; - } - - public static Boolean isGetProperty(Class cls, String fieldName) { - Method[] method = cls.getDeclaredMethods(); - for (int i = 0; i < method.length; i++) { - if (method[i].getModifiers() == Modifier.PUBLIC - && method[i].getName().equals(getMethodByProperty("get",fieldName))) { - return true; - } - } - return false; - } - - public static Object newInstance(String className) { - return Instance.newInstance(className); - } - - public static Object newInstance(Class cls) { - return Instance.newInstance(cls); - } - - public static Object newInstance(String className, Object[] args) { - return Instance.newInstance(className, args); - } - - @SuppressWarnings("unchecked") - public static T newInstance(Class cls, Object[] args) { - return (T) Instance.newInstance(cls, args); - } - public static Object invokeMethod(Object bean, String methodName, Object[] args) - throws Exception { - return MethodInvoke.invokeMethod(bean, methodName, args); - } - - public static Object invokeMethod(Object bean, String methodName) - throws Exception { - return MethodInvoke.invokeMethod(bean, methodName); - } - - public static Object invokeStaticMethod(Class beanClass, String methodName, - Object[] args) throws Exception { - return MethodInvoke.invokeMethod(beanClass, methodName, args); - } - - public static Object invokeStaticMethod(Class beanClass, String methodName) throws Exception { - return MethodInvoke.invokeStaticMethod(beanClass, methodName); - } - - public static Map toMap(Object bean){ - return BeanConvert.bean2Map(bean); - } - - public static Object fillBean(Object bean,HashMap valueMap){ - return BeanConvert.map2Bean(bean, valueMap); - } - public static Map getFields(Class cls) { - Field[] flds = cls.getDeclaredFields(); - Map map = new HashMap(); - for (int i = 0; i < flds.length; i++) { - String name = flds[i].getName(); - map.put(name, flds[i].getType().getName()); - } - return map; - } - - public static Map getFields(Object bean) { - return getFields(bean.getClass()); - } - - public static Map getPropertyFields(Class cls){ - Field[] flds = cls.getDeclaredFields(); - Map map = new HashMap(); - for (int i = 0; i < flds.length; i++) { - String fieldName = flds[i].getName(); - if (isPublicProperty(cls, fieldName)) { - map.put(flds[i].getName(), flds[i].getType().getName()); - } - } - return map; - } - - public static Map getPropertyFields(Object bean) { - return getPropertyFields(bean.getClass()); - } - - public static boolean isEmpty(T entity,Field field){ - return ! isNotEmpty(entity,field); - } - - public static boolean isNotEmpty(T entity,Field field){ - boolean isFieldNotEmpty=true; - String fieldType=field.getType().getName(); - Object value=null; - String fillValue=null; - try { - if(BeanUtil.get(entity, field.getName())==null){ - return false; - }else{ - fillValue = BeanUtil.get(entity, field.getName()).toString(); - } - } catch (IllegalArgumentException e1) { - e1.printStackTrace(); - } - if(fieldType.equals("java.lang.String")){ - if(String.valueOf(fillValue)==null) { - isFieldNotEmpty= false; - } - }else if(fieldType.equals("int")){ - if(Integer.parseInt(fillValue)==0) { - isFieldNotEmpty= false; - } - }else if(fieldType.equals("long")){ - if(Long.parseLong(fillValue)==0) { - isFieldNotEmpty= false; - } - }else if(fieldType.equals("java.lang.Long")){ - if(Long.parseLong(fillValue)==0) { - isFieldNotEmpty= false; - } - }else if(fieldType.equals("double")){ - if(Double.valueOf(fillValue)==0.0d) { - isFieldNotEmpty= false; - } - }else if(fieldType.equals("float")){ - if(Float.parseFloat(fillValue)==0.0f) { - isFieldNotEmpty= false; - } - }else if(fieldType.equals("java.util.Date")){ - try { - value=BeanUtil.get(entity, field.getName()); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } - if(value==null) { - isFieldNotEmpty= false; - } - }else if(fieldType.equals("java.lang.Object")){ - try { - value=BeanUtil.get(entity, field.getName()); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } - if(value==null) { - isFieldNotEmpty= false; - } - }else if(fieldType.equals("char")){ - if(Character.valueOf(fillValue.charAt(0))=='\u0000') { - isFieldNotEmpty= false; - } - }else if(fieldType.equals("boolean")){ - value=Boolean.parseBoolean(fillValue); - }else if(fieldType.equals("short")){ - if(Short.parseShort(fillValue)==0) { - isFieldNotEmpty= false; - } - }else if(fieldType.equals("byte")){ - if(Byte.parseByte(fillValue)==0) { - isFieldNotEmpty= false; - } + + public static void copyBean(Object origin,Object target) { + if( origin == null || target == null) { + return; } - - LogFactory.getLog(BeanUtil.class).debug("isFieldNotEmpty() fieldName : "+field.getName()+", fieldType : "+fieldType+", Value : "+fillValue+", isFieldNotEmpty : "+isFieldNotEmpty); - - return isFieldNotEmpty; - } - - public static void displayValues(Object bean) { - Field[] flds = bean.getClass().getDeclaredFields(); - LogFactory.getLog(BeanUtil.class).debug("displayValues() *******************************************"); - LogFactory.getLog(BeanUtil.class).debug("displayValues() "+bean.getClass().getName()); - for (int i = 0; i < flds.length; i++) { - String name = flds[i].getName(); - if(isGetProperty(bean.getClass(),name)){ - LogFactory.getLog(BeanUtil.class).debug("displayValues() Field "+(i+1)+" : "+name+" = "+BeanUtil.get(bean, name)); - } - } - - LogFactory.getLog(BeanUtils.class).debug("displayValues() *******************************************"); - - } - - public static void beanClone(T target,T origin){ - Field[] flds = target.getClass().getDeclaredFields(); - for (int i = 0; i < flds.length; i++) { - String name = flds[i].getName(); - if(isPublicProperty(origin,name)){ - if(get(origin,name)!=null){ - set(target,name,get(origin,name)); - } - } - } - } - - public static Class[] getMethodParameterTypes(Class c,String methodName){ - Method []methods=c.getMethods(); - for (Method method : methods) { - Class[] parameterTypes = method.getParameterTypes(); - if(method.getName().equals(methodName)){ - return parameterTypes; - } - } - return null; - } - - public static String getMethodByProperty(String getOrSet ,String property){ - String methodName=getOrSet+( - property.length() == 1 ? - (Character.toUpperCase(property.charAt(0)) + "") : - Character.toUpperCase( - property.charAt(0))+ property.substring(1)); - //LogFactory.getLog(BeanUtils.class).debug("getMethodByProperty() methodName : "+methodName); - return methodName; - } - + try { + BeanUtils.copyProperties( origin, target); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static Object cloneSupper(Object origin) { + Object target = null; + if(origin == null) { + return target; + } + try { + target = origin.getClass().getSuperclass().newInstance(); + BeanUtils.copyProperties(target,origin); + } catch (Exception e) { + e.printStackTrace(); + } + return target; + } + + public static String getValue(Object bean,String field ) { + if(bean == null) { + return null; + } + String retVal = ""; + try { + retVal = BeanUtils.getProperty(bean, field); + } catch(Exception e) { + e.printStackTrace(); + } + return retVal; + } + + @SuppressWarnings("rawtypes") + public static boolean isNotNull(Collection collection) { + if(collection != null && collection.size() > 0) { + return true; + } + return false; + } + + @SuppressWarnings("rawtypes") + public static boolean isNotNull(Map map) { + if(map != null && map.size() > 0) { + return true; + } + return false; + } + + public static Object get(Object bean, String fieldName) { + try { + return invokeMethod(bean,getMethodByProperty("get",fieldName)); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object set(Object bean, String fieldName,Object value) { + try { + return invokeMethod(bean,getMethodByProperty("set",fieldName),new Object[]{value}); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object getPublicProperty(Object bean, String fieldName) { + try { + Field field = bean.getClass().getField(fieldName); + return field.get(bean); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static boolean setPublicProperty(Object bean, String fieldName,Object value) { + try { + Field field = bean.getClass().getField(fieldName); + field.set(bean,value); + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public static Boolean isPublicProperty(Class cls, String fieldName) { + if (isSetProperty(cls, fieldName)&& isGetProperty(cls, fieldName)) { + return true; + } else { + return false; + } + } + + public static Boolean isPublicProperty(Object bean, String fieldName) { + if (isSetProperty(bean.getClass(), fieldName) + && isGetProperty(bean.getClass(), fieldName)) { + return true; + } else { + return false; + } + } + + public static Boolean isSetProperty(Class cls, String fieldName) { + Method[] method = cls.getDeclaredMethods(); + for (int i = 0; i < method.length; i++) { + if (method[i].getModifiers() == Modifier.PUBLIC + && method[i].getName().equals(getMethodByProperty("set",fieldName))) { + return true; + } + } + return false; + } + + public static Boolean isGetProperty(Class cls, String fieldName) { + Method[] method = cls.getDeclaredMethods(); + for (int i = 0; i < method.length; i++) { + if (method[i].getModifiers() == Modifier.PUBLIC + && method[i].getName().equals(getMethodByProperty("get",fieldName))) { + return true; + } + } + return false; + } + + public static Object newInstance(String className) { + return Instance.newInstance(className); + } + + public static Object newInstance(Class cls) { + return Instance.newInstance(cls); + } + + public static Object newInstance(String className, Object[] args) { + return Instance.newInstance(className, args); + } + + @SuppressWarnings("unchecked") + public static T newInstance(Class cls, Object[] args) { + return (T) Instance.newInstance(cls, args); + } + public static Object invokeMethod(Object bean, String methodName, Object[] args) + throws Exception { + return MethodInvoke.invokeMethod(bean, methodName, args); + } + + public static Object invokeMethod(Object bean, String methodName) + throws Exception { + return MethodInvoke.invokeMethod(bean, methodName); + } + + public static Object invokeStaticMethod(Class beanClass, String methodName, + Object[] args) throws Exception { + return MethodInvoke.invokeMethod(beanClass, methodName, args); + } + + public static Object invokeStaticMethod(Class beanClass, String methodName) throws Exception { + return MethodInvoke.invokeStaticMethod(beanClass, methodName); + } + + public static Map toMap(Object bean){ + return BeanConvert.bean2Map(bean); + } + + public static Object fillBean(Object bean,HashMap valueMap){ + return BeanConvert.map2Bean(bean, valueMap); + } + public static Map getFields(Class cls) { + Field[] flds = cls.getDeclaredFields(); + Map map = new HashMap(); + for (int i = 0; i < flds.length; i++) { + String name = flds[i].getName(); + map.put(name, flds[i].getType().getName()); + } + return map; + } + + public static Map getFields(Object bean) { + return getFields(bean.getClass()); + } + + public static Map getPropertyFields(Class cls){ + Field[] flds = cls.getDeclaredFields(); + Map map = new HashMap(); + for (int i = 0; i < flds.length; i++) { + String fieldName = flds[i].getName(); + if (isPublicProperty(cls, fieldName)) { + map.put(flds[i].getName(), flds[i].getType().getName()); + } + } + return map; + } + + public static Map getPropertyFields(Object bean) { + return getPropertyFields(bean.getClass()); + } + + public static boolean isEmpty(T entity,Field field){ + return ! isNotEmpty(entity,field); + } + + public static boolean isNotEmpty(T entity,Field field){ + boolean isFieldNotEmpty=true; + String fieldType=field.getType().getName(); + Object value=null; + String fillValue=null; + try { + if(BeanUtil.get(entity, field.getName())==null){ + return false; + }else{ + fillValue = BeanUtil.get(entity, field.getName()).toString(); + } + } catch (IllegalArgumentException e1) { + e1.printStackTrace(); + } + if(fieldType.equals("java.lang.String")){ + if(String.valueOf(fillValue)==null) { + isFieldNotEmpty= false; + } + }else if(fieldType.equals("int")){ + if(Integer.parseInt(fillValue)==0) { + isFieldNotEmpty= false; + } + }else if(fieldType.equals("long")){ + if(Long.parseLong(fillValue)==0) { + isFieldNotEmpty= false; + } + }else if(fieldType.equals("java.lang.Long")){ + if(Long.parseLong(fillValue)==0) { + isFieldNotEmpty= false; + } + }else if(fieldType.equals("double")){ + if(Double.valueOf(fillValue)==0.0d) { + isFieldNotEmpty= false; + } + }else if(fieldType.equals("float")){ + if(Float.parseFloat(fillValue)==0.0f) { + isFieldNotEmpty= false; + } + }else if(fieldType.equals("java.util.Date")){ + try { + value=BeanUtil.get(entity, field.getName()); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } + if(value==null) { + isFieldNotEmpty= false; + } + }else if(fieldType.equals("java.lang.Object")){ + try { + value=BeanUtil.get(entity, field.getName()); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } + if(value==null) { + isFieldNotEmpty= false; + } + }else if(fieldType.equals("char")){ + if(Character.valueOf(fillValue.charAt(0))=='\u0000') { + isFieldNotEmpty= false; + } + }else if(fieldType.equals("boolean")){ + value=Boolean.parseBoolean(fillValue); + }else if(fieldType.equals("short")){ + if(Short.parseShort(fillValue)==0) { + isFieldNotEmpty= false; + } + }else if(fieldType.equals("byte")){ + if(Byte.parseByte(fillValue)==0) { + isFieldNotEmpty= false; + } + } + + LogFactory.getLog(BeanUtil.class).debug("isFieldNotEmpty() fieldName : "+field.getName()+", fieldType : "+fieldType+", Value : "+fillValue+", isFieldNotEmpty : "+isFieldNotEmpty); + + return isFieldNotEmpty; + } + + public static void displayValues(Object bean) { + Field[] flds = bean.getClass().getDeclaredFields(); + LogFactory.getLog(BeanUtil.class).debug("displayValues() *******************************************"); + LogFactory.getLog(BeanUtil.class).debug("displayValues() "+bean.getClass().getName()); + for (int i = 0; i < flds.length; i++) { + String name = flds[i].getName(); + if(isGetProperty(bean.getClass(),name)){ + LogFactory.getLog(BeanUtil.class).debug("displayValues() Field "+(i+1)+" : "+name+" = "+BeanUtil.get(bean, name)); + } + } + + LogFactory.getLog(BeanUtils.class).debug("displayValues() *******************************************"); + + } + + public static void beanClone(T target,T origin){ + Field[] flds = target.getClass().getDeclaredFields(); + for (int i = 0; i < flds.length; i++) { + String name = flds[i].getName(); + if(isPublicProperty(origin,name)){ + if(get(origin,name)!=null){ + set(target,name,get(origin,name)); + } + } + } + } + + public static Class[] getMethodParameterTypes(Class c,String methodName){ + Method []methods=c.getMethods(); + for (Method method : methods) { + Class[] parameterTypes = method.getParameterTypes(); + if(method.getName().equals(methodName)){ + return parameterTypes; + } + } + return null; + } + + public static String getMethodByProperty(String getOrSet ,String property){ + String methodName=getOrSet+( + property.length() == 1 ? + (Character.toUpperCase(property.charAt(0)) + "") : + Character.toUpperCase( + property.charAt(0))+ property.substring(1)); + //LogFactory.getLog(BeanUtils.class).debug("getMethodByProperty() methodName : "+methodName); + return methodName; + } + } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/DateUtils.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/DateUtils.java index 97740df94..36c17daa6 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/DateUtils.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/DateUtils.java @@ -30,337 +30,337 @@ import org.joda.time.chrono.ISOChronology; public class DateUtils { - public static final String FORMAT_DATE_DEFAULT = "yyyy-MM-dd"; + public static final String FORMAT_DATE_DEFAULT = "yyyy-MM-dd"; - public static final String FORMAT_DATE_YYYYMMDD = "yyyyMMdd"; + public static final String FORMAT_DATE_YYYYMMDD = "yyyyMMdd"; - public static final String FORMAT_DATE_YYYY_MM_DD = "yyyy-MM-dd"; - - public static final String FORMAT_DATE_PATTERN_1="yyyy/MM/dd"; - public static final String FORMAT_DATE_PATTERN_2="yyyy/M/dd"; - public static final String FORMAT_DATE_PATTERN_3="yyyy/MM/d"; - public static final String FORMAT_DATE_PATTERN_4="yyyy/M/d"; - public static final String FORMAT_DATE_YYYYMMDDHHMMSS = "yyyyMMddHHmmss"; - - public static final String FORMAT_DATE_ISO_TIMESTAMP="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; + public static final String FORMAT_DATE_YYYY_MM_DD = "yyyy-MM-dd"; + + public static final String FORMAT_DATE_PATTERN_1="yyyy/MM/dd"; + public static final String FORMAT_DATE_PATTERN_2="yyyy/M/dd"; + public static final String FORMAT_DATE_PATTERN_3="yyyy/MM/d"; + public static final String FORMAT_DATE_PATTERN_4="yyyy/M/d"; + public static final String FORMAT_DATE_YYYYMMDDHHMMSS = "yyyyMMddHHmmss"; + + public static final String FORMAT_DATE_ISO_TIMESTAMP="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; - public static final String FORMAT_DATE_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; + public static final String FORMAT_DATE_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; - public static final String FORMAT_DATE_YYYY_MM_DD_HHMM = "yyyy-MM-dd HHmm"; + public static final String FORMAT_DATE_YYYY_MM_DD_HHMM = "yyyy-MM-dd HHmm"; - public static final String FORMAT_DATE_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm"; + public static final String FORMAT_DATE_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm"; - public static final String FORMAT_DATE_HH_MM = "HH:mm"; + public static final String FORMAT_DATE_HH_MM = "HH:mm"; - public static final String FORMAT_DATE_HH_MM_SS = "HH:mm:ss"; + public static final String FORMAT_DATE_HH_MM_SS = "HH:mm:ss"; - public static final String FORMAT_DATE_HHMM = "HHmm"; + public static final String FORMAT_DATE_HHMM = "HHmm"; - public static final String FORMAT_DATE_HHMMSS = "HHmmss"; + public static final String FORMAT_DATE_HHMMSS = "HHmmss"; - public static final String FORMAT_WORK_TIME = "yyyy-MM-dd HHmmss"; - /** - * Compares two Dates from their string value. - * - * @param stringValue1 - * Date 1 as string value. - * @param stringValue2 - * Date 2 as string value. - * - * @return the value 0 if the argument stringValue1 is equal - * to stringValue2; a value less than 0 if this - * stringValue1 is before the stringValue2 as Date; and a value - * greater than 0 if this stringValue1 is after the - * stringValue2. - * @since 1.2 - */ - public static final int compareDate(String stringValue1, String stringValue2) - throws ParseException { - Date date1 = tryParse(stringValue1); - if (date1 == null) { - throw new ParseException("Can not parse " + stringValue1+ " to Date.", 0); - } - Date date2 = tryParse(stringValue2); - if (date2 == null) { - throw new ParseException("Can not parse " + stringValue1+ " to Date.", 0); - } - return date1.compareTo(date2); - } + public static final String FORMAT_WORK_TIME = "yyyy-MM-dd HHmmss"; + /** + * Compares two Dates from their string value. + * + * @param stringValue1 + * Date 1 as string value. + * @param stringValue2 + * Date 2 as string value. + * + * @return the value 0 if the argument stringValue1 is equal + * to stringValue2; a value less than 0 if this + * stringValue1 is before the stringValue2 as Date; and a value + * greater than 0 if this stringValue1 is after the + * stringValue2. + * @since 1.2 + */ + public static final int compareDate(String stringValue1, String stringValue2) + throws ParseException { + Date date1 = tryParse(stringValue1); + if (date1 == null) { + throw new ParseException("Can not parse " + stringValue1+ " to Date.", 0); + } + Date date2 = tryParse(stringValue2); + if (date2 == null) { + throw new ParseException("Can not parse " + stringValue1+ " to Date.", 0); + } + return date1.compareTo(date2); + } - /** - * Returns current system date as formatted string value with default format - * pattern. - * - * @return current system date. - * - * @see #FORMAT_DATE_DEFAULT - */ - public static final String getCurrentDateAsString() { - return getCurrentDateAsString(FORMAT_DATE_DEFAULT); - } - - public static final String getCurrentDateTimeAsString() { - return getCurrentDateAsString(FORMAT_DATE_YYYY_MM_DD_HH_MM_SS); - } + /** + * Returns current system date as formatted string value with default format + * pattern. + * + * @return current system date. + * + * @see #FORMAT_DATE_DEFAULT + */ + public static final String getCurrentDateAsString() { + return getCurrentDateAsString(FORMAT_DATE_DEFAULT); + } + + public static final String getCurrentDateTimeAsString() { + return getCurrentDateAsString(FORMAT_DATE_YYYY_MM_DD_HH_MM_SS); + } - /** - * Returns current system date as formatted string value with given format - * pattern. - * - * @param formatPattern - * format pattern. - * @return current system date. - * - */ - public static final String getCurrentDateAsString(String formatPattern) { - Date date = new Date(); - return format(date, formatPattern); - } - - public static final String getFormtPattern1ToPattern2(String stringValue,String formatPattern1,String formatPattern2){ - Date date = parse(stringValue, formatPattern1); - return format(date, formatPattern2); - } + /** + * Returns current system date as formatted string value with given format + * pattern. + * + * @param formatPattern + * format pattern. + * @return current system date. + * + */ + public static final String getCurrentDateAsString(String formatPattern) { + Date date = new Date(); + return format(date, formatPattern); + } + + public static final String getFormtPattern1ToPattern2(String stringValue,String formatPattern1,String formatPattern2){ + Date date = parse(stringValue, formatPattern1); + return format(date, formatPattern2); + } - /** - * Returns current system date. - * - * @return current system date. - */ - public static final Date getCurrentDate() { - return new Date(); - } + /** + * Returns current system date. + * + * @return current system date. + */ + public static final Date getCurrentDate() { + return new Date(); + } - /** - * 0������, 1����һ, 2���ڶ�, 3������, 4������, 5������,6������ - * @return - */ - public static final String getTodayOfWeek(){ - Calendar calendar = Calendar.getInstance(); - Date date = new Date(); - calendar.setTime(date); - int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)-1; - return dayOfWeek+""; - } - - /** - * �Ƚ�ʱ���ǰ���� 6:00-12:00 - * @param startTime - * @param endTime - * @return - */ - public static final boolean compareTime(String startTime,String endTime) throws ParseException{ - SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss"); - Date start = sdf.parse(startTime); - Date end = sdf.parse(endTime); - if(start.before(end)){ - return true; - } - return false; - } - - /** - * 判断value时间值是否在date时间之前 - * @param value - * @param date - * @param datePattern - * @return - */ - public static boolean compareTime(String endDate,Date startDate,String datePattern) { - Date valueDate = DateUtils.parse(endDate, datePattern); - return valueDate.before(startDate); - } - - /** - * Format Date value as string value with default format pattern. - * - * @param date - * Date value. - * @return formatted date as string value. - * - * @see #FORMAT_DATE_DEFAULT - */ - public static final String format(Date date) { - if (date == null) { - return ""; - } - return format(date, FORMAT_DATE_DEFAULT); - } + /** + * 0������, 1����һ, 2���ڶ�, 3������, 4������, 5������,6������ + * @return + */ + public static final String getTodayOfWeek(){ + Calendar calendar = Calendar.getInstance(); + Date date = new Date(); + calendar.setTime(date); + int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)-1; + return dayOfWeek+""; + } + + /** + * �Ƚ�ʱ���ǰ���� 6:00-12:00 + * @param startTime + * @param endTime + * @return + */ + public static final boolean compareTime(String startTime,String endTime) throws ParseException{ + SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss"); + Date start = sdf.parse(startTime); + Date end = sdf.parse(endTime); + if(start.before(end)){ + return true; + } + return false; + } + + /** + * 判断value时间值是否在date时间之前 + * @param value + * @param date + * @param datePattern + * @return + */ + public static boolean compareTime(String endDate,Date startDate,String datePattern) { + Date valueDate = DateUtils.parse(endDate, datePattern); + return valueDate.before(startDate); + } + + /** + * Format Date value as string value with default format pattern. + * + * @param date + * Date value. + * @return formatted date as string value. + * + * @see #FORMAT_DATE_DEFAULT + */ + public static final String format(Date date) { + if (date == null) { + return ""; + } + return format(date, FORMAT_DATE_DEFAULT); + } - /** - * Format Date value as string value with default format pattern. - * - * @param date - * Date value. - * @return formatted date as string value. - * - * @see #FORMAT_DATE_DEFAULT - */ - public static final String formatDateTime(Date date) { - if (date == null) { - return ""; - } - return format(date, FORMAT_DATE_YYYY_MM_DD_HH_MM_SS); - } + /** + * Format Date value as string value with default format pattern. + * + * @param date + * Date value. + * @return formatted date as string value. + * + * @see #FORMAT_DATE_DEFAULT + */ + public static final String formatDateTime(Date date) { + if (date == null) { + return ""; + } + return format(date, FORMAT_DATE_YYYY_MM_DD_HH_MM_SS); + } - /** - * Format Date value as string value with default format pattern. - * - * @param date - * Date value. - * @return formatted date as string value. - * - * @see #FORMAT_DATE_DEFAULT - */ - public static final String formatTimestamp(Date date) { - if (date == null) { - return ""; - } - return format(date, "yyyy-MM-dd HH:mm:ss.SSS"); - } + /** + * Format Date value as string value with default format pattern. + * + * @param date + * Date value. + * @return formatted date as string value. + * + * @see #FORMAT_DATE_DEFAULT + */ + public static final String formatTimestamp(Date date) { + if (date == null) { + return ""; + } + return format(date, "yyyy-MM-dd HH:mm:ss.SSS"); + } - /** - * Format Date value as string value with default format pattern. - * - * @param date - * Date value. - * @return formatted date as string value. - * - * @see #FORMAT_DATE_DEFAULT - */ - public static final Date parseTimestamp(String date) { - if (date == null) { - return null; - } - return parse(date, "yyyy-MM-dd HH:mm:ss.SSS"); - } + /** + * Format Date value as string value with default format pattern. + * + * @param date + * Date value. + * @return formatted date as string value. + * + * @see #FORMAT_DATE_DEFAULT + */ + public static final Date parseTimestamp(String date) { + if (date == null) { + return null; + } + return parse(date, "yyyy-MM-dd HH:mm:ss.SSS"); + } - /** - * Format Date value as string value with given format pattern. - * - * @param date - * Date value. - * @param formatPattern - * format pattern. - * @return formatted date as string value. - * - * @see #FORMAT_DATE_DEFAULT - * @see #FORMAT_DATE_YYYY_MM_DD - * @see #FORMAT_DATE_YYYY_MM_DD_HH_MM - * @see #FORMAT_DATE_YYYY_MM_DD_HH_MM_SS - * @see #FORMAT_DATE_YYYY_MM_DD_HHMMSS - */ - public static final String format(Date date, String formatPattern) { - if (date == null) { - return ""; - } - return new SimpleDateFormat(formatPattern).format(date); - } + /** + * Format Date value as string value with given format pattern. + * + * @param date + * Date value. + * @param formatPattern + * format pattern. + * @return formatted date as string value. + * + * @see #FORMAT_DATE_DEFAULT + * @see #FORMAT_DATE_YYYY_MM_DD + * @see #FORMAT_DATE_YYYY_MM_DD_HH_MM + * @see #FORMAT_DATE_YYYY_MM_DD_HH_MM_SS + * @see #FORMAT_DATE_YYYY_MM_DD_HHMMSS + */ + public static final String format(Date date, String formatPattern) { + if (date == null) { + return ""; + } + return new SimpleDateFormat(formatPattern).format(date); + } - /** - * Parse string value to Date with default format pattern. - * - * @param stringValue - * date value as string. - * @return Date represents stringValue. - * @see #FORMAT_DATE_DEFAULT - */ - public static final Date parse(String stringValue) { - return parse(stringValue, FORMAT_DATE_DEFAULT); - } + /** + * Parse string value to Date with default format pattern. + * + * @param stringValue + * date value as string. + * @return Date represents stringValue. + * @see #FORMAT_DATE_DEFAULT + */ + public static final Date parse(String stringValue) { + return parse(stringValue, FORMAT_DATE_DEFAULT); + } - /** - * Parse string value to Date with given format pattern. - * - * @param stringValue - * date value as string. - * @param formatPattern - * format pattern. - * @return Date represents stringValue, null while parse exception occurred. - * @see #FORMAT_DATE_DEFAULT - */ - public static final Date parse(String stringValue, String formatPattern) { - SimpleDateFormat format = new SimpleDateFormat(formatPattern); - try { - return format.parse(stringValue); - } catch (ParseException e) { - e.printStackTrace(); - } - return null; - } - + /** + * Parse string value to Date with given format pattern. + * + * @param stringValue + * date value as string. + * @param formatPattern + * format pattern. + * @return Date represents stringValue, null while parse exception occurred. + * @see #FORMAT_DATE_DEFAULT + */ + public static final Date parse(String stringValue, String formatPattern) { + SimpleDateFormat format = new SimpleDateFormat(formatPattern); + try { + return format.parse(stringValue); + } catch (ParseException e) { + e.printStackTrace(); + } + return null; + } + - /** - * Try to parse string value to date. - * - * @param stringValue - * string value. - * @return Date represents stringValue, null while parse exception occurred. - */ - public static final Date tryParse(String stringValue) { - Date date = parse(stringValue, FORMAT_DATE_YYYY_MM_DD); - if (date != null) { - return date; - } - date = parse(stringValue, FORMAT_DATE_YYYYMMDD); - if (date != null) { - return date; - } - date = parse(stringValue, FORMAT_DATE_YYYYMMDDHHMMSS); - if (date != null) { - return date; - } - date = parse(stringValue, FORMAT_DATE_YYYY_MM_DD_HH_MM_SS); - if (date != null) { - return date; - } - date = parse(stringValue, FORMAT_DATE_YYYY_MM_DD_HHMM); - if (date != null) { - return date; - } - date = parse(stringValue,FORMAT_DATE_PATTERN_1); - if (date != null) { - return date; - } - date=parse(stringValue, FORMAT_DATE_PATTERN_2); - if (date != null) { - return date; - } - date=parse(stringValue, FORMAT_DATE_PATTERN_3); - if (date != null) { - return date; - } - date=parse(stringValue, FORMAT_DATE_PATTERN_4); - if (date != null) { - return date; - } - return date; - } + /** + * Try to parse string value to date. + * + * @param stringValue + * string value. + * @return Date represents stringValue, null while parse exception occurred. + */ + public static final Date tryParse(String stringValue) { + Date date = parse(stringValue, FORMAT_DATE_YYYY_MM_DD); + if (date != null) { + return date; + } + date = parse(stringValue, FORMAT_DATE_YYYYMMDD); + if (date != null) { + return date; + } + date = parse(stringValue, FORMAT_DATE_YYYYMMDDHHMMSS); + if (date != null) { + return date; + } + date = parse(stringValue, FORMAT_DATE_YYYY_MM_DD_HH_MM_SS); + if (date != null) { + return date; + } + date = parse(stringValue, FORMAT_DATE_YYYY_MM_DD_HHMM); + if (date != null) { + return date; + } + date = parse(stringValue,FORMAT_DATE_PATTERN_1); + if (date != null) { + return date; + } + date=parse(stringValue, FORMAT_DATE_PATTERN_2); + if (date != null) { + return date; + } + date=parse(stringValue, FORMAT_DATE_PATTERN_3); + if (date != null) { + return date; + } + date=parse(stringValue, FORMAT_DATE_PATTERN_4); + if (date != null) { + return date; + } + return date; + } - /** - * get day of week - * @param SUN_FST_DAY_OF_WEEK - * @return - */ - public static int getDayOfWeek(int SUN_FST_DAY_OF_WEEK) { - if (SUN_FST_DAY_OF_WEEK > 7 || SUN_FST_DAY_OF_WEEK < 1) { - return 0; - } - if (SUN_FST_DAY_OF_WEEK == 1) { - return 7; - } - return SUN_FST_DAY_OF_WEEK - 1; - } + /** + * get day of week + * @param SUN_FST_DAY_OF_WEEK + * @return + */ + public static int getDayOfWeek(int SUN_FST_DAY_OF_WEEK) { + if (SUN_FST_DAY_OF_WEEK > 7 || SUN_FST_DAY_OF_WEEK < 1) { + return 0; + } + if (SUN_FST_DAY_OF_WEEK == 1) { + return 7; + } + return SUN_FST_DAY_OF_WEEK - 1; + } - public static Timestamp parseTimestamp(String stringValue, - String formatPattern) { - return new Timestamp(parse(stringValue, formatPattern).getTime()); - } + public static Timestamp parseTimestamp(String stringValue, + String formatPattern) { + return new Timestamp(parse(stringValue, formatPattern).getTime()); + } - public static Timestamp parseTimestamp(Date d) { - return new Timestamp(d.getTime()); - } - //----------------------------------------------------------------------- + public static Timestamp parseTimestamp(Date d) { + return new Timestamp(d.getTime()); + } + //----------------------------------------------------------------------- /** * Adds a number of milliseconds to a date returning a new object. * The original date object is unchanged. @@ -409,254 +409,254 @@ public class DateUtils { return c.getTime(); } - public static String getExchangeFormat(String dateStr,String sourFormat,String destFormat){ - String dt=""; - try{ - SimpleDateFormat sdf=new SimpleDateFormat(destFormat); - dt=sdf.format(parse(dateStr,sourFormat)); - }catch(Exception e){ - e.printStackTrace(); - } - return dt; - } - - public static Date plugOneDate(Date date) { - return new Date(date.getTime() + 24*60*60*1000L); - } + public static String getExchangeFormat(String dateStr,String sourFormat,String destFormat){ + String dt=""; + try{ + SimpleDateFormat sdf=new SimpleDateFormat(destFormat); + dt=sdf.format(parse(dateStr,sourFormat)); + }catch(Exception e){ + e.printStackTrace(); + } + return dt; + } - /** - * ���date�ĺ�һ�죬��ʱ����ֱ�Ϊ00:00:00 - * @param date - * @return - */ - public static Date getNextDay(Date date) { - Date nextDay = new Date(date.getTime() + 24*60*60*1000L); - // Get Calendar object set to the date and time of the given Date object - Calendar cal = Calendar.getInstance(); - cal.setTime(nextDay); - // Set time fields to zero - cal.set(Calendar.HOUR_OF_DAY, 0); - cal.set(Calendar.MINUTE, 0); - cal.set(Calendar.SECOND, 0); - cal.set(Calendar.MILLISECOND, 0); - // Put it back in the Date object - nextDay = cal.getTime(); - return nextDay; - } - - /** - * ɾ��date�е�ʱ���֡��롢���� - * - * @param date - * @return - */ - public static Date truncateTime(Date date) { - if (date == null) { - return null; - } - - Calendar c = Calendar.getInstance(); - c.setTime(date); - c.set(Calendar.HOUR_OF_DAY, 0); - c.set(Calendar.MINUTE, 0); - c.set(Calendar.SECOND, 0); - c.set(Calendar.MILLISECOND, 0); - - return c.getTime(); - } - - /** - * �Ը�ʱ��date��������ƶ�(��ǰ�ƶ�)���� - * - * @param date - * @param year - * @param month - * @param day - * @param hour - * @param minute - * @param second - * @param milliSecond - * @return - */ - public static Date addDate(Date date, int year, int month, int day, int hour, int minute, int second, int milliSecond) { - if (date == null) { - return null; - } - - Calendar c = Calendar.getInstance(); - c.setTime(date); - c.add(Calendar.YEAR, year); - c.add(Calendar.MONTH, month); - c.add(Calendar.DATE, day); - c.add(Calendar.HOUR_OF_DAY, hour); - c.add(Calendar.MINUTE, minute); - c.add(Calendar.SECOND, second); - c.add(Calendar.MILLISECOND, milliSecond); - - return c.getTime(); - } - - public static Date addDate(Date date, int year, int month, int day, int hour, int minute, int second) { - return addDate(date, year, month, day, hour, minute, second, 0); - } + public static Date plugOneDate(Date date) { + return new Date(date.getTime() + 24*60*60*1000L); + } + + /** + * ���date�ĺ�һ�죬��ʱ����ֱ�Ϊ00:00:00 + * @param date + * @return + */ + public static Date getNextDay(Date date) { + Date nextDay = new Date(date.getTime() + 24*60*60*1000L); + // Get Calendar object set to the date and time of the given Date object + Calendar cal = Calendar.getInstance(); + cal.setTime(nextDay); + // Set time fields to zero + cal.set(Calendar.HOUR_OF_DAY, 0); + cal.set(Calendar.MINUTE, 0); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MILLISECOND, 0); + // Put it back in the Date object + nextDay = cal.getTime(); + return nextDay; + } + + /** + * ɾ��date�е�ʱ���֡��롢���� + * + * @param date + * @return + */ + public static Date truncateTime(Date date) { + if (date == null) { + return null; + } + + Calendar c = Calendar.getInstance(); + c.setTime(date); + c.set(Calendar.HOUR_OF_DAY, 0); + c.set(Calendar.MINUTE, 0); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + * �Ը�ʱ��date��������ƶ�(��ǰ�ƶ�)���� + * + * @param date + * @param year + * @param month + * @param day + * @param hour + * @param minute + * @param second + * @param milliSecond + * @return + */ + public static Date addDate(Date date, int year, int month, int day, int hour, int minute, int second, int milliSecond) { + if (date == null) { + return null; + } + + Calendar c = Calendar.getInstance(); + c.setTime(date); + c.add(Calendar.YEAR, year); + c.add(Calendar.MONTH, month); + c.add(Calendar.DATE, day); + c.add(Calendar.HOUR_OF_DAY, hour); + c.add(Calendar.MINUTE, minute); + c.add(Calendar.SECOND, second); + c.add(Calendar.MILLISECOND, milliSecond); + + return c.getTime(); + } + + public static Date addDate(Date date, int year, int month, int day, int hour, int minute, int second) { + return addDate(date, year, month, day, hour, minute, second, 0); + } - public static Date addDate(Date date, int hour, int minute, int second) { - return addDate(date, 0, 0, 0, hour, minute, second, 0); - } - - /** - * ����day1��day2�������(day1-day2)������ - * - * @param day1 - * @param day2 - * @return - */ - public static int getIntervalDays(Date day1, Date day2) { - if (day1 == null || day2 == null) { - throw new IllegalArgumentException("Argument day1 or day2 must be not null."); - } - - Date day1ToUse = truncateTime(day1); - Date day2ToUse = truncateTime(day2); - long intervalMilliSecond = getIntervalMilliSeconds(day1ToUse, day2ToUse); - - return (int) (intervalMilliSecond / (24 * 60 * 60 * 1000)); - } + public static Date addDate(Date date, int hour, int minute, int second) { + return addDate(date, 0, 0, 0, hour, minute, second, 0); + } + + /** + * ����day1��day2�������(day1-day2)������ + * + * @param day1 + * @param day2 + * @return + */ + public static int getIntervalDays(Date day1, Date day2) { + if (day1 == null || day2 == null) { + throw new IllegalArgumentException("Argument day1 or day2 must be not null."); + } + + Date day1ToUse = truncateTime(day1); + Date day2ToUse = truncateTime(day2); + long intervalMilliSecond = getIntervalMilliSeconds(day1ToUse, day2ToUse); + + return (int) (intervalMilliSecond / (24 * 60 * 60 * 1000)); + } - /** - * ����day1��day2�������(day1-day2)���·� - * - * @param day1 - * @param day2 - * @return - */ - public static int getIntervalMonths(Date day1, Date day2) { - if (day1 == null || day2 == null) { - throw new IllegalArgumentException("Argument day1 or day2 must be not null."); - } + /** + * ����day1��day2�������(day1-day2)���·� + * + * @param day1 + * @param day2 + * @return + */ + public static int getIntervalMonths(Date day1, Date day2) { + if (day1 == null || day2 == null) { + throw new IllegalArgumentException("Argument day1 or day2 must be not null."); + } - Calendar calDay1 = Calendar.getInstance(); - calDay1.setTime(day1); - Calendar calDay2 = Calendar.getInstance(); - calDay2.setTime(day2); - - int yearInterval = calDay1.get(Calendar.YEAR) - calDay2.get(Calendar.YEAR); - int monthInterval = calDay1.get(Calendar.MONTH) - calDay2.get(Calendar.MONTH); - - return yearInterval * 12 + monthInterval; - } + Calendar calDay1 = Calendar.getInstance(); + calDay1.setTime(day1); + Calendar calDay2 = Calendar.getInstance(); + calDay2.setTime(day2); + + int yearInterval = calDay1.get(Calendar.YEAR) - calDay2.get(Calendar.YEAR); + int monthInterval = calDay1.get(Calendar.MONTH) - calDay2.get(Calendar.MONTH); + + return yearInterval * 12 + monthInterval; + } - /** - * ����day1��day2�������(day1-day2)���� - * - * @param day1 - * @param day2 - * @return - */ - public static int getIntervalYears(Date day1, Date day2) { - if (day1 == null || day2 == null) { - throw new IllegalArgumentException("Argument day1 or day2 must be not null."); - } + /** + * ����day1��day2�������(day1-day2)���� + * + * @param day1 + * @param day2 + * @return + */ + public static int getIntervalYears(Date day1, Date day2) { + if (day1 == null || day2 == null) { + throw new IllegalArgumentException("Argument day1 or day2 must be not null."); + } - Calendar calDay1 = Calendar.getInstance(); - calDay1.setTime(day1); - Calendar calDay2 = Calendar.getInstance(); - calDay2.setTime(day2); - - return calDay1.get(Calendar.YEAR) - calDay2.get(Calendar.YEAR); - } - - private static long MILLISECOND_ONE_MINUTE = 60 * 1000; - private static long MILLISECOND_ONE_HOUR = 3600 * 1000; - private static long MILLISECOND_ONE_DAY = MILLISECOND_ONE_HOUR * 24; - - /** - * ��ʽ��(**��**Сʱ**��**��**����)��ʾstart��end��ʱ���(end-start) - * - * @param start - * @param end - * @return - */ - public static String intervalFormatDisplay(Date start, Date end) { - long minus = getIntervalMilliSeconds(end, start); - if (minus < 0) { - throw new IllegalArgumentException("The date end must great than or equal the date start."); - } + Calendar calDay1 = Calendar.getInstance(); + calDay1.setTime(day1); + Calendar calDay2 = Calendar.getInstance(); + calDay2.setTime(day2); + + return calDay1.get(Calendar.YEAR) - calDay2.get(Calendar.YEAR); + } + + private static long MILLISECOND_ONE_MINUTE = 60 * 1000; + private static long MILLISECOND_ONE_HOUR = 3600 * 1000; + private static long MILLISECOND_ONE_DAY = MILLISECOND_ONE_HOUR * 24; + + /** + * ��ʽ��(**��**Сʱ**��**��**����)��ʾstart��end��ʱ���(end-start) + * + * @param start + * @param end + * @return + */ + public static String intervalFormatDisplay(Date start, Date end) { + long minus = getIntervalMilliSeconds(end, start); + if (minus < 0) { + throw new IllegalArgumentException("The date end must great than or equal the date start."); + } - StringBuilder interval = new StringBuilder(); - long days = minus / MILLISECOND_ONE_DAY; - if (days > 0) { - interval.append(days).append("��"); - } - - minus -= days * MILLISECOND_ONE_DAY; - long hours = minus / MILLISECOND_ONE_HOUR; - if (hours > 0) { - interval.append(hours).append("Сʱ"); - } - - minus -= hours * MILLISECOND_ONE_HOUR; - long minutes = minus / MILLISECOND_ONE_MINUTE; - if (minutes > 0) { - interval.append(minutes).append("��"); - } - - minus -= minutes * MILLISECOND_ONE_MINUTE; - long seconds = minus / 1000; - if (seconds > 0) { - interval.append(seconds).append("��"); - } - - long millis = minus - seconds * 1000; - if (millis > 0) { - interval.append(millis).append("����"); - } - - return interval.toString(); - } + StringBuilder interval = new StringBuilder(); + long days = minus / MILLISECOND_ONE_DAY; + if (days > 0) { + interval.append(days).append("��"); + } + + minus -= days * MILLISECOND_ONE_DAY; + long hours = minus / MILLISECOND_ONE_HOUR; + if (hours > 0) { + interval.append(hours).append("Сʱ"); + } + + minus -= hours * MILLISECOND_ONE_HOUR; + long minutes = minus / MILLISECOND_ONE_MINUTE; + if (minutes > 0) { + interval.append(minutes).append("��"); + } + + minus -= minutes * MILLISECOND_ONE_MINUTE; + long seconds = minus / 1000; + if (seconds > 0) { + interval.append(seconds).append("��"); + } + + long millis = minus - seconds * 1000; + if (millis > 0) { + interval.append(millis).append("����"); + } + + return interval.toString(); + } - /** - * ����day1��day2ʱ�����ĺ�����(day1-day2) - * - * @param day1 - * @param day2 - * @return - */ - public static long getIntervalMilliSeconds(Date day1, Date day2) { - if (day1 == null || day2 == null) { - throw new IllegalArgumentException("Argument day1 or day2 must be not null."); - } - - return day1.getTime()-day2.getTime(); - } - - public static String toUtc(java.util.Date date){ - DateTime datetime=new DateTime(date, ISOChronology.getInstanceUTC()); - return datetime.toString(); - } - - public static String toUtc(DateTime dateTime){ - return dateTime.toString(); - } - - public static String toUtc(String date){ - DateTime datetime=new DateTime(date, ISOChronology.getInstanceUTC()); - return datetime.toString(); - } + /** + * ����day1��day2ʱ�����ĺ�����(day1-day2) + * + * @param day1 + * @param day2 + * @return + */ + public static long getIntervalMilliSeconds(Date day1, Date day2) { + if (day1 == null || day2 == null) { + throw new IllegalArgumentException("Argument day1 or day2 must be not null."); + } + + return day1.getTime()-day2.getTime(); + } + + public static String toUtc(java.util.Date date){ + DateTime datetime=new DateTime(date, ISOChronology.getInstanceUTC()); + return datetime.toString(); + } + + public static String toUtc(DateTime dateTime){ + return dateTime.toString(); + } + + public static String toUtc(String date){ + DateTime datetime=new DateTime(date, ISOChronology.getInstanceUTC()); + return datetime.toString(); + } - public static DateTime toUtcDate(String date){ - DateTime datetime=new DateTime(date, ISOChronology.getInstanceUTC()); - return datetime; - } - - public static String toUtcLocal(java.util.Date date){ - DateTime datetime=new DateTime(date,ISOChronology.getInstance()); - return datetime.toString(); - } - - public static String toUtcLocal(String date){ - DateTime datetime=new DateTime(date,ISOChronology.getInstance()); - return datetime.toString(); - } + public static DateTime toUtcDate(String date){ + DateTime datetime=new DateTime(date, ISOChronology.getInstanceUTC()); + return datetime; + } + + public static String toUtcLocal(java.util.Date date){ + DateTime datetime=new DateTime(date,ISOChronology.getInstance()); + return datetime.toString(); + } + + public static String toUtcLocal(String date){ + DateTime datetime=new DateTime(date,ISOChronology.getInstance()); + return datetime.toString(); + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/DynaBean.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/DynaBean.java index 932bad17b..ba0bc4ef5 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/DynaBean.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/DynaBean.java @@ -30,77 +30,77 @@ import org.apache.commons.logging.LogFactory; * */ public class DynaBean { - - HashMap beanMap; - /** - * - */ - public DynaBean() { - beanMap=new HashMap(); - } - - /** - * - */ - public DynaBean(Map map) { - beanMap=new HashMap(); - mapToDynaBean(map); - } - - public void set(String name,Object value){ - beanMap.put(name, value); - } - - public Object get(String name){ - return beanMap.get(name); - } - - public void remove(String name){ - beanMap.remove(name); - } - - @SuppressWarnings("rawtypes") + + HashMap beanMap; + /** + * + */ + public DynaBean() { + beanMap=new HashMap(); + } + + /** + * + */ + public DynaBean(Map map) { + beanMap=new HashMap(); + mapToDynaBean(map); + } + + public void set(String name,Object value){ + beanMap.put(name, value); + } + + public Object get(String name){ + return beanMap.get(name); + } + + public void remove(String name){ + beanMap.remove(name); + } + + @SuppressWarnings("rawtypes") public void displayValues(){ - Iterator beanMapit = beanMap.entrySet().iterator(); - int i=1; - LogFactory.getLog(DynaBean.class).debug("displayValues() *******************************************"); - while (beanMapit.hasNext()) { - Map.Entry entry = (Map.Entry) beanMapit.next(); - String fieldName = entry.getKey().toString(); - LogFactory.getLog(DynaBean.class).debug("displayValues() Field "+(i++)+" "+fieldName+" : "+beanMap.get(fieldName)); - } - LogFactory.getLog(DynaBean.class).debug("displayValues() *******************************************"); - } - - public Object convertToBean(T bean){ - return BeanConvert.map2Bean((T)bean, beanMap); - } - @SuppressWarnings("unchecked") - public Object createBean(T cls){ - T bean=(T)Instance.newInstance((Class)cls); - return BeanConvert.map2Bean(bean, beanMap); - } - - public Map toMap(){ - return beanMap; - } - - @SuppressWarnings("rawtypes") + Iterator beanMapit = beanMap.entrySet().iterator(); + int i=1; + LogFactory.getLog(DynaBean.class).debug("displayValues() *******************************************"); + while (beanMapit.hasNext()) { + Map.Entry entry = (Map.Entry) beanMapit.next(); + String fieldName = entry.getKey().toString(); + LogFactory.getLog(DynaBean.class).debug("displayValues() Field "+(i++)+" "+fieldName+" : "+beanMap.get(fieldName)); + } + LogFactory.getLog(DynaBean.class).debug("displayValues() *******************************************"); + } + + public Object convertToBean(T bean){ + return BeanConvert.map2Bean((T)bean, beanMap); + } + @SuppressWarnings("unchecked") + public Object createBean(T cls){ + T bean=(T)Instance.newInstance((Class)cls); + return BeanConvert.map2Bean(bean, beanMap); + } + + public Map toMap(){ + return beanMap; + } + + @SuppressWarnings("rawtypes") public DynaBean mapToDynaBean(Map map){ - - if(map.getClass().getName()=="java.util.HashMap"){ - beanMap=(HashMap)map; - }else{ - Iterator mapIt = map.entrySet().iterator(); - int i=1; - while (mapIt.hasNext()) { - Map.Entry entry = (Map.Entry) mapIt.next(); - String fieldName = entry.getKey().toString(); - beanMap.put(fieldName, map.get(fieldName)); - LogFactory.getLog(DynaBean.class).debug("mapToDynaBean() Field "+(i++)+" "+fieldName+" : "+beanMap.get(fieldName)); - } - } - return this; - } + + if(map.getClass().getName()=="java.util.HashMap"){ + beanMap=(HashMap)map; + }else{ + Iterator mapIt = map.entrySet().iterator(); + int i=1; + while (mapIt.hasNext()) { + Map.Entry entry = (Map.Entry) mapIt.next(); + String fieldName = entry.getKey().toString(); + beanMap.put(fieldName, map.get(fieldName)); + LogFactory.getLog(DynaBean.class).debug("mapToDynaBean() Field "+(i++)+" "+fieldName+" : "+beanMap.get(fieldName)); + } + } + return this; + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/EthernetAddress.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/EthernetAddress.java index c961b224e..f08e2d29c 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/EthernetAddress.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/EthernetAddress.java @@ -29,7 +29,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class EthernetAddress - implements Serializable, Cloneable, Comparable + implements Serializable, Cloneable, Comparable { private static final Logger _logger = LoggerFactory.getLogger(EthernetAddress.class); @@ -420,13 +420,13 @@ public class EthernetAddress public boolean equals(Object o) { if (o == this) { - return true; + return true; } if (o == null) { - return false; + return false; } if (o.getClass() != getClass()) { - return false; + return false; } return ((EthernetAddress) o)._address == _address; } @@ -445,7 +445,7 @@ public class EthernetAddress { long l = _address - other._address; if (l < 0L) { - return -1; + return -1; } return (l == 0L) ? 0 : 1; } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/ExcelUtils.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/ExcelUtils.java index 791be7bd6..08d08abc6 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/ExcelUtils.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/ExcelUtils.java @@ -26,32 +26,32 @@ import org.apache.poi.ss.usermodel.Row; public class ExcelUtils { - /** - * 根据数据格式返回数据 - * - * @param cell - * @return - */ - public static String getValue(Cell cell) { + /** + * 根据数据格式返回数据 + * + * @param cell + * @return + */ + public static String getValue(Cell cell) { - if (cell == null) { - return ""; - } else if (cell.getCellType() == CellType.BOOLEAN) { - return String.valueOf(cell.getBooleanCellValue()); - } else if (cell.getCellType() == CellType.NUMERIC) { - if ("General".equals(cell.getCellStyle().getDataFormatString())) { - return new DecimalFormat("0").format(cell.getNumericCellValue()); - } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) { - return new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue()); - } else { - return new DecimalFormat("0").format(cell.getNumericCellValue()); - } - } else { - return String.valueOf(cell.getStringCellValue().trim()); - } - } - - public static String getValue(Row row,int i) { - return getValue(row.getCell(i)); - } + if (cell == null) { + return ""; + } else if (cell.getCellType() == CellType.BOOLEAN) { + return String.valueOf(cell.getBooleanCellValue()); + } else if (cell.getCellType() == CellType.NUMERIC) { + if ("General".equals(cell.getCellStyle().getDataFormatString())) { + return new DecimalFormat("0").format(cell.getNumericCellValue()); + } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) { + return new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue()); + } else { + return new DecimalFormat("0").format(cell.getNumericCellValue()); + } + } else { + return String.valueOf(cell.getStringCellValue().trim()); + } + } + + public static String getValue(Row row,int i) { + return getValue(row.getCell(i)); + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/HttpEncoder.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/HttpEncoder.java index 34bcae4b6..79ed15ad4 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/HttpEncoder.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/HttpEncoder.java @@ -43,7 +43,7 @@ public abstract class HttpEncoder { encoded = applyRule(encoded, rule.getKey(), rule.getValue()); } } catch (UnsupportedEncodingException uee) { - uee.printStackTrace(); + uee.printStackTrace(); } return encoded; diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/HttpsTrusts.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/HttpsTrusts.java index 72e8ee78c..0efb50855 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/HttpsTrusts.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/HttpsTrusts.java @@ -24,57 +24,57 @@ import javax.net.ssl.SSLSession; public class HttpsTrusts { private static void trustAllHttpsCertificates() throws Exception { - javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; - javax.net.ssl.TrustManager tm = new HttpsTrustsTM(); - trustAllCerts[0] = tm; - javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL"); - sc.init(null, trustAllCerts, null); - javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); - } + javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; + javax.net.ssl.TrustManager tm = new HttpsTrustsTM(); + trustAllCerts[0] = tm; + javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, null); + javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + } /** * https ssl auto trust */ - public static void beforeConnection() { - try { - trustAllHttpsCertificates(); - HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { - @Override - public boolean verify(String urlHostName, SSLSession session) { - System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost()); - return true; - } - }); - } catch(Exception e) { - e.printStackTrace(); - } - } - - static class HttpsTrustsTM implements javax.net.ssl.TrustManager,javax.net.ssl.X509TrustManager { - @Override - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return null; - } + public static void beforeConnection() { + try { + trustAllHttpsCertificates(); + HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { + @Override + public boolean verify(String urlHostName, SSLSession session) { + System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost()); + return true; + } + }); + } catch(Exception e) { + e.printStackTrace(); + } + } + + static class HttpsTrustsTM implements javax.net.ssl.TrustManager,javax.net.ssl.X509TrustManager { + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } - public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) { - return true; - } + public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) { + return true; + } - public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) { - return true; - } + public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) { + return true; + } - @Override - public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) - throws java.security.cert.CertificateException { - return; - } + @Override + public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) + throws java.security.cert.CertificateException { + return; + } - @Override - public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) - throws java.security.cert.CertificateException { - return; - } - } + @Override + public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) + throws java.security.cert.CertificateException { + return; + } + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/IdGenerator.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/IdGenerator.java index a7546122c..f6c2429c6 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/IdGenerator.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/IdGenerator.java @@ -19,68 +19,68 @@ package org.dromara.maxkey.util; public class IdGenerator { - String strategy = "uuid"; + String strategy = "uuid"; - int datacenterId; - - int machineId; - - SnowFlakeId snowFlakeId = new SnowFlakeId(0,0); - - StringGenerator stringGenerator = new StringGenerator(); + int datacenterId; + + int machineId; + + SnowFlakeId snowFlakeId = new SnowFlakeId(0,0); + + StringGenerator stringGenerator = new StringGenerator(); - - public String generate(){ - if(strategy.equalsIgnoreCase("uuid")) { - return stringGenerator.uuidGenerate(); - }else if(strategy.equalsIgnoreCase("SnowFlake")) { - return snowFlakeId.nextId()+""; - }else { - return stringGenerator.randomGenerate(); - } - } - - - public IdGenerator() { - super(); - } - - public IdGenerator(String strategy) { - super(); - this.strategy = strategy; - } + + public String generate(){ + if(strategy.equalsIgnoreCase("uuid")) { + return stringGenerator.uuidGenerate(); + }else if(strategy.equalsIgnoreCase("SnowFlake")) { + return snowFlakeId.nextId()+""; + }else { + return stringGenerator.randomGenerate(); + } + } + + + public IdGenerator() { + super(); + } + + public IdGenerator(String strategy) { + super(); + this.strategy = strategy; + } - public int getDatacenterId() { - return datacenterId; - } + public int getDatacenterId() { + return datacenterId; + } - public void setDatacenterId(int datacenterId) { - this.datacenterId = datacenterId; - } + public void setDatacenterId(int datacenterId) { + this.datacenterId = datacenterId; + } - public int getMachineId() { - return machineId; - } + public int getMachineId() { + return machineId; + } - public void setMachineId(int machineId) { - this.machineId = machineId; - } + public void setMachineId(int machineId) { + this.machineId = machineId; + } - public SnowFlakeId getSnowFlakeId() { - return snowFlakeId; - } + public SnowFlakeId getSnowFlakeId() { + return snowFlakeId; + } - public void setSnowFlakeId(SnowFlakeId snowFlakeId) { - this.snowFlakeId = snowFlakeId; - } + public void setSnowFlakeId(SnowFlakeId snowFlakeId) { + this.snowFlakeId = snowFlakeId; + } - public StringGenerator getStringGenerator() { - return stringGenerator; - } + public StringGenerator getStringGenerator() { + return stringGenerator; + } - public void setStringGenerator(StringGenerator stringGenerator) { - this.stringGenerator = stringGenerator; - } + public void setStringGenerator(StringGenerator stringGenerator) { + this.stringGenerator = stringGenerator; + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/IdSequence.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/IdSequence.java index 856f5834c..e8439d9f0 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/IdSequence.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/IdSequence.java @@ -32,109 +32,109 @@ import org.slf4j.LoggerFactory; * */ public class IdSequence { - - public static String OLD_DATETIME=""; - /** - * 静态属性 - */ - public static int STATIC_SEQUENCE=0; - - /** - * 默认节点 - */ - public static String DEFAULT_NODE_NUMBER="01"; - - public static String STATIC_NODE_NUMBER="--"; - - /** - * 生成20位的流水号 - * @return 流水号 - */ - public static synchronized String next(){ - String currentDateTime=getCurrentSystemDateTime(); - - if(null==currentDateTime){ - LoggerFactory.getLogger(IdSequence.class).error("获取系统日期失败"); - return null; - } - - StringBuffer sequenceNumber=new StringBuffer(); - - sequenceNumber.append(currentDateTime.substring(0, 8)); - sequenceNumber.append(getNodeNumber()); - sequenceNumber.append(currentDateTime.substring(8)); - sequenceNumber.append(nextSequence()); - return sequenceNumber.toString(); - } - - public static final String initNodeNumber(String nodeNumbers){ - if(STATIC_NODE_NUMBER.equals("--")){ - if(null!=nodeNumbers&&!nodeNumbers.equals("")){ - - String ipAddressConfigValue=nodeNumbers; - LoggerFactory.getLogger(IdSequence.class).info("ARE config.node.number : "+ipAddressConfigValue); - if(ipAddressConfigValue.indexOf(",")>-1){ - - String hostIpAddress=MacAddress.getAllHostMacAddress();//获得本机IP - - LoggerFactory.getLogger(IdSequence.class).info("hostIpAddress : "+hostIpAddress); - - String []ipAddressValues=ipAddressConfigValue.split(","); - for(String ipvalue : ipAddressValues){ - String[] ipNode=ipvalue.split("="); - if(ipNode!=null&&ipNode.length>0&&hostIpAddress.indexOf(ipNode[0])>-1){ - STATIC_NODE_NUMBER=ipNode[1]; - } - } - - if(STATIC_NODE_NUMBER.equals("--")){ - LoggerFactory.getLogger(IdSequence.class).error("GET MAC BIND NODE ERROR . "); - STATIC_NODE_NUMBER=DEFAULT_NODE_NUMBER; - } - - }else{ - STATIC_NODE_NUMBER=nodeNumbers; - } - LoggerFactory.getLogger(IdSequence.class).info("STATIC_NODE_SEQUENCE_NUMBER : "+STATIC_NODE_NUMBER); - if(STATIC_NODE_NUMBER.length()!=2){ - LoggerFactory.getLogger(IdSequence.class).error("系统节点号必须2位"); - } - }else{ - STATIC_NODE_NUMBER=DEFAULT_NODE_NUMBER; - } - } - return STATIC_NODE_NUMBER; - } - - public static final String getNodeNumber(){ - return STATIC_NODE_NUMBER; - } - /** - * 同一时刻只有一个访问 - * @return - */ - private static final synchronized String nextSequence(){ - STATIC_SEQUENCE=(STATIC_SEQUENCE+1)%10000; - return String.format("%04d", STATIC_SEQUENCE); - } - - /** - * 获取系统当前日期,格式为yyyyMMddHHmmSS - * @return 当前系统日期 - */ - private static synchronized String getCurrentSystemDateTime(){ - String currentdatetime=null; - synchronized(OLD_DATETIME) - { - currentdatetime=(new java.text.SimpleDateFormat("yyyyMMddHHmmss")).format(new Date()); - /** - * 判断是否是新的时间,如果是新时间则STATIC_SEQUENCE从0开始计数 - */ - if(!currentdatetime.equals(OLD_DATETIME)){ - STATIC_SEQUENCE=0; - OLD_DATETIME=currentdatetime; - } - } - return currentdatetime; - } + + public static String OLD_DATETIME=""; + /** + * 静态属性 + */ + public static int STATIC_SEQUENCE=0; + + /** + * 默认节点 + */ + public static String DEFAULT_NODE_NUMBER="01"; + + public static String STATIC_NODE_NUMBER="--"; + + /** + * 生成20位的流水号 + * @return 流水号 + */ + public static synchronized String next(){ + String currentDateTime=getCurrentSystemDateTime(); + + if(null==currentDateTime){ + LoggerFactory.getLogger(IdSequence.class).error("获取系统日期失败"); + return null; + } + + StringBuffer sequenceNumber=new StringBuffer(); + + sequenceNumber.append(currentDateTime.substring(0, 8)); + sequenceNumber.append(getNodeNumber()); + sequenceNumber.append(currentDateTime.substring(8)); + sequenceNumber.append(nextSequence()); + return sequenceNumber.toString(); + } + + public static final String initNodeNumber(String nodeNumbers){ + if(STATIC_NODE_NUMBER.equals("--")){ + if(null!=nodeNumbers&&!nodeNumbers.equals("")){ + + String ipAddressConfigValue=nodeNumbers; + LoggerFactory.getLogger(IdSequence.class).info("ARE config.node.number : "+ipAddressConfigValue); + if(ipAddressConfigValue.indexOf(",")>-1){ + + String hostIpAddress=MacAddress.getAllHostMacAddress();//获得本机IP + + LoggerFactory.getLogger(IdSequence.class).info("hostIpAddress : "+hostIpAddress); + + String []ipAddressValues=ipAddressConfigValue.split(","); + for(String ipvalue : ipAddressValues){ + String[] ipNode=ipvalue.split("="); + if(ipNode!=null&&ipNode.length>0&&hostIpAddress.indexOf(ipNode[0])>-1){ + STATIC_NODE_NUMBER=ipNode[1]; + } + } + + if(STATIC_NODE_NUMBER.equals("--")){ + LoggerFactory.getLogger(IdSequence.class).error("GET MAC BIND NODE ERROR . "); + STATIC_NODE_NUMBER=DEFAULT_NODE_NUMBER; + } + + }else{ + STATIC_NODE_NUMBER=nodeNumbers; + } + LoggerFactory.getLogger(IdSequence.class).info("STATIC_NODE_SEQUENCE_NUMBER : "+STATIC_NODE_NUMBER); + if(STATIC_NODE_NUMBER.length()!=2){ + LoggerFactory.getLogger(IdSequence.class).error("系统节点号必须2位"); + } + }else{ + STATIC_NODE_NUMBER=DEFAULT_NODE_NUMBER; + } + } + return STATIC_NODE_NUMBER; + } + + public static final String getNodeNumber(){ + return STATIC_NODE_NUMBER; + } + /** + * 同一时刻只有一个访问 + * @return + */ + private static final synchronized String nextSequence(){ + STATIC_SEQUENCE=(STATIC_SEQUENCE+1)%10000; + return String.format("%04d", STATIC_SEQUENCE); + } + + /** + * 获取系统当前日期,格式为yyyyMMddHHmmSS + * @return 当前系统日期 + */ + private static synchronized String getCurrentSystemDateTime(){ + String currentdatetime=null; + synchronized(OLD_DATETIME) + { + currentdatetime=(new java.text.SimpleDateFormat("yyyyMMddHHmmss")).format(new Date()); + /** + * 判断是否是新的时间,如果是新时间则STATIC_SEQUENCE从0开始计数 + */ + if(!currentdatetime.equals(OLD_DATETIME)){ + STATIC_SEQUENCE=0; + OLD_DATETIME=currentdatetime; + } + } + return currentdatetime; + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/Instance.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/Instance.java index 77473bad6..efc5ed236 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/Instance.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/Instance.java @@ -28,70 +28,70 @@ import java.lang.reflect.Constructor; */ public class Instance { - /** - * - */ - public Instance() { - } + /** + * + */ + public Instance() { + } - public static Object newInstance(String className) { - Class cls; - try { - cls = Class.forName(className); - Constructor constructor = cls.getConstructor(); - return constructor.newInstance(); - } catch (Exception e) { - e.printStackTrace(); - } - return null; + public static Object newInstance(String className) { + Class cls; + try { + cls = Class.forName(className); + Constructor constructor = cls.getConstructor(); + return constructor.newInstance(); + } catch (Exception e) { + e.printStackTrace(); + } + return null; - } + } - public static Object newInstance(Class cls) { - try { - Constructor constructor = cls.getConstructor(); - return constructor.newInstance(); - }catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object newInstance(String className, Object[] args) { - Class newClass; - try { - newClass = Class.forName(className); - Class[] argsClass = new Class[args.length]; + public static Object newInstance(Class cls) { + try { + Constructor constructor = cls.getConstructor(); + return constructor.newInstance(); + }catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object newInstance(String className, Object[] args) { + Class newClass; + try { + newClass = Class.forName(className); + Class[] argsClass = new Class[args.length]; - for (int i = 0, j = args.length; i < j; i++) { - argsClass[i] = args[i].getClass(); - } + for (int i = 0, j = args.length; i < j; i++) { + argsClass[i] = args[i].getClass(); + } - Constructor cons = newClass.getConstructor(argsClass); - return cons.newInstance(args); - } catch (Exception e) { - e.printStackTrace(); - } - return null; + Constructor cons = newClass.getConstructor(argsClass); + return cons.newInstance(args); + } catch (Exception e) { + e.printStackTrace(); + } + return null; - } + } - public static Object newInstance(Class cls, Object[] args) { - try { - Class[] argsClass = new Class[args.length]; + public static Object newInstance(Class cls, Object[] args) { + try { + Class[] argsClass = new Class[args.length]; - for (int i = 0, j = args.length; i < j; i++) { - argsClass[i] = args[i].getClass(); - } + for (int i = 0, j = args.length; i < j; i++) { + argsClass[i] = args[i].getClass(); + } - Constructor cons = cls.getConstructor(argsClass); - return cons.newInstance(args); - } catch (Exception e) { - e.printStackTrace(); - } + Constructor cons = cls.getConstructor(argsClass); + return cons.newInstance(args); + } catch (Exception e) { + e.printStackTrace(); + } - return null; + return null; - } + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/JdbcUtils.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/JdbcUtils.java index 74019b1be..2f482c0a6 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/JdbcUtils.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/JdbcUtils.java @@ -30,113 +30,113 @@ import org.dromara.maxkey.entity.DbTableMetaData; public class JdbcUtils { - public static Connection connect(String url, String user, String pwd, String driverClass) { - Connection conn = null; - try { - Class.forName(driverClass); - conn = java.sql.DriverManager.getConnection(url, user, pwd); - return conn; - } catch (ClassNotFoundException e) { - System.out.println("ClassNotFoundException"); - return null; - } catch (SQLException e) { - System.out.println("SQLException"); - } - return null; - } + public static Connection connect(String url, String user, String pwd, String driverClass) { + Connection conn = null; + try { + Class.forName(driverClass); + conn = java.sql.DriverManager.getConnection(url, user, pwd); + return conn; + } catch (ClassNotFoundException e) { + System.out.println("ClassNotFoundException"); + return null; + } catch (SQLException e) { + System.out.println("SQLException"); + } + return null; + } - public void release(Connection conn) { - if (conn != null) { - try { - conn.close(); - } catch (SQLException e) { - System.out.println("SQLException"); - } - } - } + public void release(Connection conn) { + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) { + System.out.println("SQLException"); + } + } + } - public static void release(Connection conn, Statement stmt, ResultSet rs) { - if (rs != null) { - try { - rs.close(); - rs = null; - } catch (SQLException e) { - System.out.println("SQLException"); - } - } - if (stmt != null) { - try { - stmt.close(); - stmt = null; - } catch (SQLException e) { - System.out.println("SQLException"); - } - } - if (conn != null) { - try { - conn.close(); - conn = null; - } catch (SQLException e) { - System.out.println("SQLException"); - } - } - } - - public static void release(Connection conn, Statement stmt, PreparedStatement pstmt, ResultSet rs) { - if (rs != null) { - try { - rs.close(); - rs = null; - } catch (SQLException e) { - System.out.println("ResultSet Close Exception"); - } - } - if (stmt != null) { - try { - stmt.close(); - stmt = null; - } catch (SQLException e) { - System.out.println("Statement Close Exception"); - } - } - if (pstmt != null) { - try { - pstmt.close(); - pstmt = null; - } catch (SQLException e) { - System.out.println("PreparedStatement Close Exception"); - } - } - if (conn != null) { - try { - conn.close(); - conn = null; - } catch (SQLException e) { - System.out.println("Connection Close Exception"); - } - } - } - - public static DbTableMetaData getMetaData(ResultSet rs) { - try { - ResultSetMetaData metaData = rs.getMetaData(); - DbTableMetaData meta = new DbTableMetaData(metaData.getTableName(1)); - int count = metaData.getColumnCount(); - for (int i = 1; i <= count; i++) { - DbTableColumn column = new DbTableColumn( - metaData.getColumnName(i).toLowerCase(), - metaData.getColumnTypeName(i), - metaData.getPrecision(i), - metaData.getScale(i) - ); - meta.getColumns().add(column); - meta.getColumnsMap().put(column.getColumn(), column); - } - return meta; - } catch (SQLException e) { - e.printStackTrace(); - } - return null; - } - + public static void release(Connection conn, Statement stmt, ResultSet rs) { + if (rs != null) { + try { + rs.close(); + rs = null; + } catch (SQLException e) { + System.out.println("SQLException"); + } + } + if (stmt != null) { + try { + stmt.close(); + stmt = null; + } catch (SQLException e) { + System.out.println("SQLException"); + } + } + if (conn != null) { + try { + conn.close(); + conn = null; + } catch (SQLException e) { + System.out.println("SQLException"); + } + } + } + + public static void release(Connection conn, Statement stmt, PreparedStatement pstmt, ResultSet rs) { + if (rs != null) { + try { + rs.close(); + rs = null; + } catch (SQLException e) { + System.out.println("ResultSet Close Exception"); + } + } + if (stmt != null) { + try { + stmt.close(); + stmt = null; + } catch (SQLException e) { + System.out.println("Statement Close Exception"); + } + } + if (pstmt != null) { + try { + pstmt.close(); + pstmt = null; + } catch (SQLException e) { + System.out.println("PreparedStatement Close Exception"); + } + } + if (conn != null) { + try { + conn.close(); + conn = null; + } catch (SQLException e) { + System.out.println("Connection Close Exception"); + } + } + } + + public static DbTableMetaData getMetaData(ResultSet rs) { + try { + ResultSetMetaData metaData = rs.getMetaData(); + DbTableMetaData meta = new DbTableMetaData(metaData.getTableName(1)); + int count = metaData.getColumnCount(); + for (int i = 1; i <= count; i++) { + DbTableColumn column = new DbTableColumn( + metaData.getColumnName(i).toLowerCase(), + metaData.getColumnTypeName(i), + metaData.getPrecision(i), + metaData.getScale(i) + ); + meta.getColumns().add(column); + meta.getColumnsMap().put(column.getColumn(), column); + } + return meta; + } catch (SQLException e) { + e.printStackTrace(); + } + return null; + } + } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/MacAddress.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/MacAddress.java index 5ece170de..909aa1a9c 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/MacAddress.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/MacAddress.java @@ -33,60 +33,60 @@ import org.slf4j.LoggerFactory; * */ public class MacAddress { - public static String os; - - static{ - Properties prop = System.getProperties(); - os = prop.getProperty("os.name"); - LoggerFactory.getLogger(MacAddress.class).info("OS : "+os); - } - - public static String getAllHostMacAddress(){ - String hostIpAddress=""; - try { - Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces(); - InetAddress inetAddress = null; - while (netInterfaces.hasMoreElements()) { - NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement(); - if(ni.getInetAddresses().hasMoreElements()){ - inetAddress = (InetAddress) ni.getInetAddresses().nextElement(); - if(!inetAddress.isLoopbackAddress()){ - hostIpAddress += getMac(inetAddress)+","; - LoggerFactory.getLogger(MacAddress.class).info("host MAC : "+getMac(inetAddress)); - } - } - } - } catch (SocketException e) { - e.printStackTrace(); - } - return hostIpAddress; - } - - - public static String getMac(InetAddress ia) throws SocketException { - //获取网卡,获取地址 - byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress(); - //LoggerFactory.getLogger(MacAddress.class).info("mac数组长度:"+mac.length); - - - StringBuffer sb = new StringBuffer(""); - for(int i=0; i netInterfaces = NetworkInterface.getNetworkInterfaces(); + InetAddress inetAddress = null; + while (netInterfaces.hasMoreElements()) { + NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement(); + if(ni.getInetAddresses().hasMoreElements()){ + inetAddress = (InetAddress) ni.getInetAddresses().nextElement(); + if(!inetAddress.isLoopbackAddress()){ + hostIpAddress += getMac(inetAddress)+","; + LoggerFactory.getLogger(MacAddress.class).info("host MAC : "+getMac(inetAddress)); + } + } + } + } catch (SocketException e) { + e.printStackTrace(); + } + return hostIpAddress; + } + + + public static String getMac(InetAddress ia) throws SocketException { + //获取网卡,获取地址 + byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress(); + //LoggerFactory.getLogger(MacAddress.class).info("mac数组长度:"+mac.length); + + + StringBuffer sb = new StringBuffer(""); + for(int i=0; i beanClass = bean.getClass(); - Class[] argsClass = new Class[args.length]; - for (int i = 0, j = args.length; i < j; i++) { - argsClass[i] = args[i].getClass(); - //LogFactory.getLog(MethodInvoke.class).debug("invokeMethod args : "+args[i]+" argsClass:"+argsClass[i]); - } + public static Object invokeMethod(Object bean, String methodName, + Object[] args) throws Exception { + Class beanClass = bean.getClass(); + Class[] argsClass = new Class[args.length]; + for (int i = 0, j = args.length; i < j; i++) { + argsClass[i] = args[i].getClass(); + //LogFactory.getLog(MethodInvoke.class).debug("invokeMethod args : "+args[i]+" argsClass:"+argsClass[i]); + } - Method method = beanClass.getMethod(methodName, argsClass); - //LogFactory.getLog(MethodInvoke.class).debug("invokeMethod methodName:"+methodName); - return method.invoke(bean, args); - } + Method method = beanClass.getMethod(methodName, argsClass); + //LogFactory.getLog(MethodInvoke.class).debug("invokeMethod methodName:"+methodName); + return method.invoke(bean, args); + } - public static Object invokeMethod(Object bean, String methodName) - throws Exception { - Class beanClass = bean.getClass(); - Method method = beanClass.getMethod(methodName); - //LogFactory.getLog(MethodInvoke.class).debug("invokeMethod methodName:"+methodName); - return method.invoke(bean, new Object[] {}); - } + public static Object invokeMethod(Object bean, String methodName) + throws Exception { + Class beanClass = bean.getClass(); + Method method = beanClass.getMethod(methodName); + //LogFactory.getLog(MethodInvoke.class).debug("invokeMethod methodName:"+methodName); + return method.invoke(bean, new Object[] {}); + } - public static Object invokeStaticMethod(Class beanClass, String methodName, - Object[] args) throws Exception { - Class[] argsClass = new Class[args.length]; - for (int i = 0, j = args.length; i < j; i++) { - argsClass[i] = args[i].getClass(); - //LogFactory.getLog(MethodInvoke.class).debug("invokeStaticMethod args : "+args[i]+" argsClass:"+argsClass[i]); - } + public static Object invokeStaticMethod(Class beanClass, String methodName, + Object[] args) throws Exception { + Class[] argsClass = new Class[args.length]; + for (int i = 0, j = args.length; i < j; i++) { + argsClass[i] = args[i].getClass(); + //LogFactory.getLog(MethodInvoke.class).debug("invokeStaticMethod args : "+args[i]+" argsClass:"+argsClass[i]); + } - Method method = beanClass.getMethod(methodName, argsClass); - //LogFactory.getLog(MethodInvoke.class).debug("invokeStaticMethod methodName:"+methodName); - return method.invoke(null, args); - } + Method method = beanClass.getMethod(methodName, argsClass); + //LogFactory.getLog(MethodInvoke.class).debug("invokeStaticMethod methodName:"+methodName); + return method.invoke(null, args); + } - public static Object invokeStaticMethod(Class beanClass, String methodName) - throws Exception { - Method method = beanClass.getMethod(methodName); - //LogFactory.getLog(MethodInvoke.class).debug("invokeStaticMethod methodName:"+methodName); - return method.invoke(null, new Object[] {}); - } + public static Object invokeStaticMethod(Class beanClass, String methodName) + throws Exception { + Method method = beanClass.getMethod(methodName); + //LogFactory.getLog(MethodInvoke.class).debug("invokeStaticMethod methodName:"+methodName); + return method.invoke(null, new Object[] {}); + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/ObjectTransformer.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/ObjectTransformer.java index 5246f40bf..0dae5d7cc 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/ObjectTransformer.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/ObjectTransformer.java @@ -35,27 +35,27 @@ import org.dromara.maxkey.crypto.HexUtils; */ public class ObjectTransformer { - - /** - * serialize Serializable Object 2 HEX String - * @param Serializable Object - * @return String - */ - public static final String serialize(Serializable s){ - return HexUtils.hex2String(SerializationUtils.serialize(s)); - } - - /** - * deserialize 2 Object - * @param HEX String - * @return Object - */ - public static final T deserialize(String hex) { - return SerializationUtils.deserialize(HexUtils.hex2Bytes(hex)); - } - + + /** + * serialize Serializable Object 2 HEX String + * @param Serializable Object + * @return String + */ + public static final String serialize(Serializable s){ + return HexUtils.hex2String(SerializationUtils.serialize(s)); + } + + /** + * deserialize 2 Object + * @param HEX String + * @return Object + */ + public static final T deserialize(String hex) { + return SerializationUtils.deserialize(HexUtils.hex2Bytes(hex)); + } + - - - + + + } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/PathUtils.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/PathUtils.java index b776eeadf..f3ec176d4 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/PathUtils.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/PathUtils.java @@ -44,10 +44,10 @@ public class PathUtils { * PathUtils. */ public PathUtils() { - appPath =System.getProperty("user.dir"); - if(StringUtils.isBlank(appPath)) { - appPath = Paths.get("").toAbsolutePath().toString(); - } + appPath =System.getProperty("user.dir"); + if(StringUtils.isBlank(appPath)) { + appPath = Paths.get("").toAbsolutePath().toString(); + } System.setProperty("APP_PATH", appPath); _logger.trace("PathUtils App Path : {} " ,appPath); } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/QRCodeUtils.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/QRCodeUtils.java index cbae20f91..0ebe90833 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/QRCodeUtils.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/QRCodeUtils.java @@ -28,57 +28,57 @@ import com.google.zxing.common.BitMatrix; public class QRCodeUtils { - public static void write2File(String path,String rqCodeText,String format,int width, int height ){ - try { - BitMatrix byteMatrix=genRQCode(rqCodeText,width,height); + public static void write2File(String path,String rqCodeText,String format,int width, int height ){ + try { + BitMatrix byteMatrix=genRQCode(rqCodeText,width,height); - File file = new File(path); + File file = new File(path); - QRCode.writeToPath(byteMatrix, format, file); - } catch (Exception e) { + QRCode.writeToPath(byteMatrix, format, file); + } catch (Exception e) { e.printStackTrace(); } - } + } - public static BufferedImage write2BufferedImage(String rqCodeText,String format,int width, int height){ - try { - BitMatrix byteMatrix=genRQCode(rqCodeText,width,height); + public static BufferedImage write2BufferedImage(String rqCodeText,String format,int width, int height){ + try { + BitMatrix byteMatrix=genRQCode(rqCodeText,width,height); - return QRCode.toBufferedImage(byteMatrix); - } catch (Exception e) { + return QRCode.toBufferedImage(byteMatrix); + } catch (Exception e) { e.printStackTrace(); } - return null; - } + return null; + } - public static void write2OutputStream(OutputStream stream,String rqCodeText,String format,int width, int height ){ - try { - BitMatrix byteMatrix=genRQCode(rqCodeText,width,height); + public static void write2OutputStream(OutputStream stream,String rqCodeText,String format,int width, int height ){ + try { + BitMatrix byteMatrix=genRQCode(rqCodeText,width,height); - QRCode.writeToStream(byteMatrix, format, stream); - } catch (Exception e) { + QRCode.writeToStream(byteMatrix, format, stream); + } catch (Exception e) { e.printStackTrace(); } - } + } - public static BitMatrix genRQCode(String rqCodeText,int width, int height){ - if(width==0){ - width=200; - } - if(height==0){ - height=200; - } - try { - return new MultiFormatWriter().encode( - rqCodeText, - BarcodeFormat.QR_CODE, - width, - height); - } catch (Exception e) { + public static BitMatrix genRQCode(String rqCodeText,int width, int height){ + if(width==0){ + width=200; + } + if(height==0){ + height=200; + } + try { + return new MultiFormatWriter().encode( + rqCodeText, + BarcodeFormat.QR_CODE, + width, + height); + } catch (Exception e) { e.printStackTrace(); } - return null; - } + return null; + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/RequestTokenUtils.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/RequestTokenUtils.java index 085de613b..d40e6a018 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/RequestTokenUtils.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/RequestTokenUtils.java @@ -35,34 +35,34 @@ import jakarta.servlet.http.HttpServletRequest; */ public class RequestTokenUtils { - - public static String TOKEN = "token"; - - public static String ACCESS_TOKEN = "access_token"; - /** - * 从请求中获取token令牌信息,优先级顺序如下 - *

- * 1) 参数 access_token
- * 2) header 的Authorization或者authorization
- * 3) 参数 token
- *

- * - * @param request - * @return access_token - */ - public static String resolveAccessToken(HttpServletRequest request) { - String accessToken = request.getParameter(ACCESS_TOKEN); - - if(StringUtils.isBlank(accessToken)) { - accessToken = request.getParameter(TOKEN); - } - - if(StringUtils.isBlank(accessToken)) { - //for header authorization bearer - accessToken = AuthorizationHeaderUtils.resolveBearer(request); - } - - return accessToken; - } + + public static String TOKEN = "token"; + + public static String ACCESS_TOKEN = "access_token"; + /** + * 从请求中获取token令牌信息,优先级顺序如下 + *

+ * 1) 参数 access_token
+ * 2) header 的Authorization或者authorization
+ * 3) 参数 token
+ *

+ * + * @param request + * @return access_token + */ + public static String resolveAccessToken(HttpServletRequest request) { + String accessToken = request.getParameter(ACCESS_TOKEN); + + if(StringUtils.isBlank(accessToken)) { + accessToken = request.getParameter(TOKEN); + } + + if(StringUtils.isBlank(accessToken)) { + //for header authorization bearer + accessToken = AuthorizationHeaderUtils.resolveBearer(request); + } + + return accessToken; + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/SerializationUtils.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/SerializationUtils.java index 967822eef..015a66f7a 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/SerializationUtils.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/SerializationUtils.java @@ -21,54 +21,54 @@ import java.io.*; public class SerializationUtils { - public static byte[] serialize(Object state) { - ObjectOutputStream oos = null; - try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(512); - oos = new ObjectOutputStream(bos); - oos.writeObject(state); - oos.flush(); - return bos.toByteArray(); - } - catch (IOException e) { - throw new IllegalArgumentException(e); - } - finally { - if (oos != null) { - try { - oos.close(); - } - catch (IOException e) { - - } - } - } - } + public static byte[] serialize(Object state) { + ObjectOutputStream oos = null; + try { + ByteArrayOutputStream bos = new ByteArrayOutputStream(512); + oos = new ObjectOutputStream(bos); + oos.writeObject(state); + oos.flush(); + return bos.toByteArray(); + } + catch (IOException e) { + throw new IllegalArgumentException(e); + } + finally { + if (oos != null) { + try { + oos.close(); + } + catch (IOException e) { + + } + } + } + } - public static T deserialize(byte[] byteArray) { - ObjectInputStream oip = null; - try { - oip = new ObjectInputStream(new ByteArrayInputStream(byteArray)); - @SuppressWarnings("unchecked") - T result = (T) oip.readObject(); - return result; - } - catch (IOException e) { - throw new IllegalArgumentException(e); - } - catch (ClassNotFoundException e) { - throw new IllegalArgumentException(e); - } - finally { - if (oip != null) { - try { - oip.close(); - } - catch (IOException e) { - - } - } - } - } + public static T deserialize(byte[] byteArray) { + ObjectInputStream oip = null; + try { + oip = new ObjectInputStream(new ByteArrayInputStream(byteArray)); + @SuppressWarnings("unchecked") + T result = (T) oip.readObject(); + return result; + } + catch (IOException e) { + throw new IllegalArgumentException(e); + } + catch (ClassNotFoundException e) { + throw new IllegalArgumentException(e); + } + finally { + if (oip != null) { + try { + oip.close(); + } + catch (IOException e) { + + } + } + } + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/SnowFlakeId.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/SnowFlakeId.java index e964e2651..a540041c2 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/SnowFlakeId.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/SnowFlakeId.java @@ -72,15 +72,15 @@ public class SnowFlakeId { } public SnowFlakeId(long datacenterId, long machineId, long sequence, long lastStmp) { - super(); - this.datacenterId = datacenterId; - this.machineId = machineId; - this.sequence = sequence; - this.lastStmp = lastStmp; - dateTime =DateUtils.toUtc( fromatTime(lastStmp)); - } + super(); + this.datacenterId = datacenterId; + this.machineId = machineId; + this.sequence = sequence; + this.lastStmp = lastStmp; + dateTime =DateUtils.toUtc( fromatTime(lastStmp)); + } - /** + /** * 产生下一个ID * * @return @@ -165,42 +165,42 @@ public class SnowFlakeId { public long getDatacenterId() { - return datacenterId; - } + return datacenterId; + } - public void setDatacenterId(long datacenterId) { - this.datacenterId = datacenterId; - } + public void setDatacenterId(long datacenterId) { + this.datacenterId = datacenterId; + } - public long getMachineId() { - return machineId; - } + public long getMachineId() { + return machineId; + } - public void setMachineId(long machineId) { - this.machineId = machineId; - } + public void setMachineId(long machineId) { + this.machineId = machineId; + } - public long getSequence() { - return sequence; - } + public long getSequence() { + return sequence; + } - public void setSequence(long sequence) { - this.sequence = sequence; - } + public void setSequence(long sequence) { + this.sequence = sequence; + } - public long getLastStmp() { - return lastStmp; - } + public long getLastStmp() { + return lastStmp; + } - public void setLastStmp(long lastStmp) { - this.lastStmp = lastStmp; - } + public void setLastStmp(long lastStmp) { + this.lastStmp = lastStmp; + } - public String getDateTime() { - return dateTime; - } + public String getDateTime() { + return dateTime; + } - public void setDateTime(String dateTime) { - this.dateTime = dateTime; - } + public void setDateTime(String dateTime) { + this.dateTime = dateTime; + } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/UUIDGenerator.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/UUIDGenerator.java index d25ef3473..107578d80 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/UUIDGenerator.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/util/UUIDGenerator.java @@ -319,10 +319,10 @@ public final class UUIDGenerator { @Override public boolean equals(Object o) { if (this == o) { - return true; + return true; } if (o == null || getClass() != o.getClass()) { - return false; + return false; } UUIDGenerator that = (UUIDGenerator) o; @@ -346,7 +346,7 @@ public final class UUIDGenerator { private static byte[] macAddress() { try { - //old + //old //byte[] mac = NetworkInterface.getNetworkInterfaces().nextElement().getHardwareAddress(); byte[] mac = EthernetAddress.fromInterface().toByteArray(); // if the machine is not connected to a network it has no active MAC address @@ -378,7 +378,7 @@ public final class UUIDGenerator { public static void version(org.dromara.maxkey.util.UUIDGenerator generated){ - System.out.println("UUID : " + generated.toString()); + System.out.println("UUID : " + generated.toString()); System.out.println("raw bytes : " + Arrays.toString(generated.getBytes())); System.out.println("process id : " + generated.getProcessId()); System.out.println("MAC fragment : " + Arrays.toString(generated.getMacFragment())); diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/NodeIDGetter.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/NodeIDGetter.java index db8c01cc3..13695bcf7 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/NodeIDGetter.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/NodeIDGetter.java @@ -45,31 +45,31 @@ public class NodeIDGetter public static byte[] getNodeID() { - if(nodeID == null) { - synchronized(lock) { - if(nodeID == null) { - try { - byte[] data = new UUID("00000000-0000-0000-0000-" - + System.getProperty("org.apache.tsik.uuid.nodeid")).toByteArray(); - nodeID = new byte[6]; - System.arraycopy(data, 10, nodeID, 0, 6); - return nodeID; - } catch(Exception ex) { - // phooey. - } + if(nodeID == null) { + synchronized(lock) { + if(nodeID == null) { + try { + byte[] data = new UUID("00000000-0000-0000-0000-" + + System.getProperty("org.apache.tsik.uuid.nodeid")).toByteArray(); + nodeID = new byte[6]; + System.arraycopy(data, 10, nodeID, 0, 6); + return nodeID; + } catch(Exception ex) { + // phooey. + } - try { - System.loadLibrary("NodeIDGetter"); - nodeID = new byte[6]; - getNodeID(nodeID); - } catch(LinkageError ex) { - // phooey again. - } + try { + System.loadLibrary("NodeIDGetter"); + nodeID = new byte[6]; + getNodeID(nodeID); + } catch(LinkageError ex) { + // phooey again. + } - nodeID = UUIDRandomness.randomNodeID(); - } - } - } - return nodeID; + nodeID = UUIDRandomness.randomNodeID(); + } + } + } + return nodeID; } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/TimestampUUIDGenerator.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/TimestampUUIDGenerator.java index 23b78e233..5019377bb 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/TimestampUUIDGenerator.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/TimestampUUIDGenerator.java @@ -52,9 +52,9 @@ public class TimestampUUIDGenerator * range or node.length != 6 */ public TimestampUUIDGenerator(int clock_sequence, - byte[] node) + byte[] node) { - super(clock_sequence, node); + super(clock_sequence, node); } /** @@ -65,10 +65,10 @@ public class TimestampUUIDGenerator @Override public UUID nextUUID() { - synchronized(this) { - checkSystemTime(); - return super.nextUUID(); - } + synchronized(this) { + checkSystemTime(); + return super.nextUUID(); + } } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/UUID.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/UUID.java index 9a0a6d4d0..a11d0575e 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/UUID.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/UUID.java @@ -53,9 +53,9 @@ import java.util.Arrays; public final class UUID implements Serializable { /** - * - */ - private static final long serialVersionUID = 687078561200656066L; + * + */ + private static final long serialVersionUID = 687078561200656066L; // Format variants. public static final int VARIANT_NCS = 0x00; public static final int VARIANT_NCS_MASK = 0x80; @@ -112,10 +112,10 @@ public final class UUID implements Serializable throws NullPointerException, IllegalArgumentException { if(node == null) { - throw new NullPointerException(); + throw new NullPointerException(); } if(node.length != 6) { - throw new IllegalArgumentException(); + throw new IllegalArgumentException(); } this.time_low = time_low; @@ -140,27 +140,27 @@ public final class UUID implements Serializable NumberFormatException { if(s == null) { - throw new NullPointerException(); + throw new NullPointerException(); } if(s.length() != 36) { - throw new IllegalArgumentException(); + throw new IllegalArgumentException(); } time_low = parseHex(s.substring(0, 8)); if(s.charAt(8) != '-') { - throw new IllegalArgumentException(); + throw new IllegalArgumentException(); } time_mid = (short) parseHex(s.substring(9, 13)); if(s.charAt(13) != '-') { - throw new IllegalArgumentException(); + throw new IllegalArgumentException(); } time_hi_and_version = (short) parseHex(s.substring(14, 18)); if(s.charAt(18) != '-') { - throw new IllegalArgumentException(); + throw new IllegalArgumentException(); } clock_seq_hi_and_reserved = (byte) parseHex(s.substring(19, 21)); clock_seq_low = (byte) parseHex(s.substring(21, 23)); if(s.charAt(23) != '-') { - throw new IllegalArgumentException(); + throw new IllegalArgumentException(); } node = new byte[6]; for(int i = 0; i < 6; i++) { @@ -178,7 +178,7 @@ public final class UUID implements Serializable public UUID(DataInput in) throws IOException { if(in == null) { - throw new NullPointerException(); + throw new NullPointerException(); } readData(in); } @@ -192,10 +192,10 @@ public final class UUID implements Serializable public UUID(byte[] data) { if(data == null) { - throw new NullPointerException(); + throw new NullPointerException(); } if(data.length != 16) { - throw new IllegalArgumentException(); + throw new IllegalArgumentException(); } try { readData(new DataInputStream(new ByteArrayInputStream(data))); @@ -252,7 +252,7 @@ public final class UUID implements Serializable UUID other = (UUID) obj; if(this == other) { - return true; + return true; } if(hash_code != 0 && diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/UUIDRandomness.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/UUIDRandomness.java index 9be1bf1e2..c9b157b34 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/UUIDRandomness.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/UUIDRandomness.java @@ -43,35 +43,35 @@ public final class UUIDRandomness private UUIDRandomness() { - throw new Error(); + throw new Error(); } public static byte[] randomNodeID() { - byte[] id = new byte[6]; - synchronized(random) { - random.nextBytes(id); - } - id[0] |= 0x01; - return id; + byte[] id = new byte[6]; + synchronized(random) { + random.nextBytes(id); + } + id[0] |= 0x01; + return id; } public static int randomClockSequence() { - synchronized(random) { - return random.nextInt(16384); - } + synchronized(random) { + return random.nextInt(16384); + } } public static int nextRandomClockSequence(int prev) { - int next; - synchronized(random) { - next = random.nextInt(16383); - } - if(next >= prev) { - next++; - } - return next; + int next; + synchronized(random) { + next = random.nextInt(16383); + } + if(next >= prev) { + next++; + } + return next; } } diff --git a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/UnsynchronizedTimestampUUIDGenerator.java b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/UnsynchronizedTimestampUUIDGenerator.java index be787b2fd..b63cc93b8 100644 --- a/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/UnsynchronizedTimestampUUIDGenerator.java +++ b/maxkey-commons/maxkey-common/src/main/java/org/dromara/maxkey/uuid/UnsynchronizedTimestampUUIDGenerator.java @@ -124,7 +124,7 @@ public class UnsynchronizedTimestampUUIDGenerator implements UUIDGenerator { long unique_time = (last_time + EPOCH_OFFSET) * CLOCK_RES + clock_adj; if(++clock_adj > CLOCK_RES) { - adjustmentOverflow(); + adjustmentOverflow(); } return new UUID((int) (unique_time & 0xFFFFFFFF), diff --git a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/DateExpirationTest.java b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/DateExpirationTest.java index 5ed345d67..c4d585dc2 100644 --- a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/DateExpirationTest.java +++ b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/DateExpirationTest.java @@ -25,19 +25,19 @@ import org.joda.time.DateTime; public class DateExpirationTest { - public static void main(String[] args) { - // 当前时间 - Date now = DateTime.now().toDate(); - // 用户时间 - Date uDate = DateUtils.parse("2025-01-04 16:59:53",DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS); - - System.out.println("user time " + DateUtils.formatDateTime(uDate)); - System.out.println("now time " + DateUtils.formatDateTime(now)); - - //用户时间 > 当前时间 - System.out.println("after "+uDate.after(now)); - //用户时间 < 当前时间 - System.out.println("before "+uDate.before(now)); - } + public static void main(String[] args) { + // 当前时间 + Date now = DateTime.now().toDate(); + // 用户时间 + Date uDate = DateUtils.parse("2025-01-04 16:59:53",DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS); + + System.out.println("user time " + DateUtils.formatDateTime(uDate)); + System.out.println("now time " + DateUtils.formatDateTime(now)); + + //用户时间 > 当前时间 + System.out.println("after "+uDate.after(now)); + //用户时间 < 当前时间 + System.out.println("before "+uDate.before(now)); + } } diff --git a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/mail/MailTest.java b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/mail/MailTest.java index 8dd7d9cda..7428a5bdb 100644 --- a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/mail/MailTest.java +++ b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/mail/MailTest.java @@ -19,26 +19,26 @@ package org.maxkey.mail; public class MailTest { - - //@Test - public void test() throws Exception { - String username="test@connsec.com"; - String password="3&8Ujbnm5hkjhFD"; - String smtpHost="smtp.exmail.qq.com"; - int port=465; - boolean ssl=true; - String senderMail="test@connsec.com"; - /* - Email email = new SimpleEmail(); - email.setHostName(smtpHost); - email.setSmtpPort(port); - email.setAuthenticator(new DefaultAuthenticator(username, password)); - email.setSSLOnConnect(ssl); - email.setFrom(senderMail); - email.setSubject("One Time PassWord"); - email.setMsg("You Token is "+111+" , it validity in "+5 +" minutes"); - email.addTo("shimingxy@qq.com"); - email.send(); - */ - } + + //@Test + public void test() throws Exception { + String username="test@connsec.com"; + String password="3&8Ujbnm5hkjhFD"; + String smtpHost="smtp.exmail.qq.com"; + int port=465; + boolean ssl=true; + String senderMail="test@connsec.com"; + /* + Email email = new SimpleEmail(); + email.setHostName(smtpHost); + email.setSmtpPort(port); + email.setAuthenticator(new DefaultAuthenticator(username, password)); + email.setSSLOnConnect(ssl); + email.setFrom(senderMail); + email.setSubject("One Time PassWord"); + email.setMsg("You Token is "+111+" , it validity in "+5 +" minutes"); + email.addTo("shimingxy@qq.com"); + email.send(); + */ + } } diff --git a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/otp/algorithm/QRcodeTest.java b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/otp/algorithm/QRcodeTest.java index c4adf2c19..d3dab455a 100644 --- a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/otp/algorithm/QRcodeTest.java +++ b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/otp/algorithm/QRcodeTest.java @@ -31,79 +31,79 @@ import com.google.zxing.common.BitMatrix; * * * BEGIN:VCARD - VERSION:3.0 - N:Gump;Forrest;;Mr. - FN:Forrest Gump - ORG:Bubba Gump Shrimp Co. - TITLE:Shrimp Man - PHOTO;VALUE=URL;TYPE=GIF:http://www.example.com/dir_photos/my_photo.gif - TEL;TYPE=WORK,VOICE:(111) 555-12121 - TEL;TYPE=HOME,VOICE:(404) 555-1212 - ADR;TYPE=WORK:;;100 Waters Edge;Baytown;LA;30314;United States of America - LABEL;TYPE=WORK:100 Waters Edge\nBaytown, LA 30314\nUnited States of America - ADR;TYPE=HOME:;;42 Plantation St.;Baytown;LA;30314;United States of America - LABEL;TYPE=HOME:42 Plantation St.\nBaytown, LA 30314\nUnited States of America - EMAIL;TYPE=PREF,INTERNET:forrestgump@example.com - REV:2008-04-24T19:52:43Z - END:VCARD + VERSION:3.0 + N:Gump;Forrest;;Mr. + FN:Forrest Gump + ORG:Bubba Gump Shrimp Co. + TITLE:Shrimp Man + PHOTO;VALUE=URL;TYPE=GIF:http://www.example.com/dir_photos/my_photo.gif + TEL;TYPE=WORK,VOICE:(111) 555-12121 + TEL;TYPE=HOME,VOICE:(404) 555-1212 + ADR;TYPE=WORK:;;100 Waters Edge;Baytown;LA;30314;United States of America + LABEL;TYPE=WORK:100 Waters Edge\nBaytown, LA 30314\nUnited States of America + ADR;TYPE=HOME:;;42 Plantation St.;Baytown;LA;30314;United States of America + LABEL;TYPE=HOME:42 Plantation St.\nBaytown, LA 30314\nUnited States of America + EMAIL;TYPE=PREF,INTERNET:forrestgump@example.com + REV:2008-04-24T19:52:43Z + END:VCARD - BEGIN:VCARD - VERSION:4.0 - N:Gump;Forrest;;; - FN:Forrest Gump - ORG:Bubba Gump Shrimp Co. - TITLE:Shrimp Man - PHOTO;MEDIATYPE=image/gif:http://www.example.com/dir_photos/my_photo.gif - TEL;TYPE=work,voice;VALUE=uri:tel:+1-111-555-1212 - TEL;TYPE=home,voice;VALUE=uri:tel:+1-404-555-1212 - ADR;TYPE=work;LABEL="100 Waters Edge\nBaytown, LA 30314\nUnited States of America" - :;;100 Waters Edge;Baytown;LA;30314;United States of America - ADR;TYPE=home;LABEL="42 Plantation St.\nBaytown, LA 30314\nUnited States of America" - :;;42 Plantation St.;Baytown;LA;30314;United States of America - EMAIL:forrestgump@example.com - REV:20080424T195243Z - END:VCARD + BEGIN:VCARD + VERSION:4.0 + N:Gump;Forrest;;; + FN:Forrest Gump + ORG:Bubba Gump Shrimp Co. + TITLE:Shrimp Man + PHOTO;MEDIATYPE=image/gif:http://www.example.com/dir_photos/my_photo.gif + TEL;TYPE=work,voice;VALUE=uri:tel:+1-111-555-1212 + TEL;TYPE=home,voice;VALUE=uri:tel:+1-404-555-1212 + ADR;TYPE=work;LABEL="100 Waters Edge\nBaytown, LA 30314\nUnited States of America" + :;;100 Waters Edge;Baytown;LA;30314;United States of America + ADR;TYPE=home;LABEL="42 Plantation St.\nBaytown, LA 30314\nUnited States of America" + :;;42 Plantation St.;Baytown;LA;30314;United States of America + EMAIL:forrestgump@example.com + REV:20080424T195243Z + END:VCARD */ public class QRcodeTest { - // 编码 - public static void main(String[] args) { + // 编码 + public static void main(String[] args) { try { - - String str = """ - BEGIN:VCARD - VERSION:3.0 - N:石鸣 - EMAIL:shimh@qq.com - TEL:15618726256 - TEL;CELL:12345678912 - ADR:上海 - ORG: - Connsec - TITLE:技术总监 - URL:http://blog.csdn.net/lidew521 - NOTE:呼呼测试下吧。。。 - END:VCARD - """; - - String str1 = """ - BEGIN:VCARD - VERSION:3.0 - N:Gump;Forrest;;Mr. - ORG:Bubba Gump Shrimp Co. - TITLE:Shrimp Man - TEL;TYPE=WORK,VOICE:(111) 555-12121 - ADR;TYPE=WORK:;;100 Waters Edge;Baytown;LA;30314;United States of America - EMAIL;TYPE=PREF,INTERNET:forrestgump@example.com - URL:http://www.johndoe.com - GENDER:F - REV:2008-04-24T19:52:43Z - END:VCARD - """; - - System.out.println(str); + + String str = """ + BEGIN:VCARD + VERSION:3.0 + N:石鸣 + EMAIL:shimh@qq.com + TEL:15618726256 + TEL;CELL:12345678912 + ADR:上海 + ORG: + Connsec + TITLE:技术总监 + URL:http://blog.csdn.net/lidew521 + NOTE:呼呼测试下吧。。。 + END:VCARD + """; + + String str1 = """ + BEGIN:VCARD + VERSION:3.0 + N:Gump;Forrest;;Mr. + ORG:Bubba Gump Shrimp Co. + TITLE:Shrimp Man + TEL;TYPE=WORK,VOICE:(111) 555-12121 + ADR;TYPE=WORK:;;100 Waters Edge;Baytown;LA;30314;United States of America + EMAIL;TYPE=PREF,INTERNET:forrestgump@example.com + URL:http://www.johndoe.com + GENDER:F + REV:2008-04-24T19:52:43Z + END:VCARD + """; + + System.out.println(str); //String str = "CN:男;COP:公司;ZW:职务";// 二维码内容 String path = "D:\\hwy.png"; BitMatrix byteMatrix; diff --git a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/rest/AuthorizationHeaderTest.java b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/rest/AuthorizationHeaderTest.java index d68055aff..21b1dcb57 100644 --- a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/rest/AuthorizationHeaderTest.java +++ b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/rest/AuthorizationHeaderTest.java @@ -22,20 +22,20 @@ import org.dromara.maxkey.util.AuthorizationHeaderUtils; import org.junit.Test; public class AuthorizationHeaderTest { - - @Test - public void test() { - - String basic =AuthorizationHeaderUtils.createBasic("Aladdin", "open sesame"); - System.out.println(basic); - - String ahc_basic ="Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="; - System.out.println(AuthorizationHeaderUtils.resolve(ahc_basic)); - - AuthorizationHeader ahc =new AuthorizationHeader("Aladdin"); - System.out.println(ahc.transform()); - - System.out.println(AuthorizationHeaderUtils.resolve(ahc.transform())); - - } + + @Test + public void test() { + + String basic =AuthorizationHeaderUtils.createBasic("Aladdin", "open sesame"); + System.out.println(basic); + + String ahc_basic ="Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="; + System.out.println(AuthorizationHeaderUtils.resolve(ahc_basic)); + + AuthorizationHeader ahc =new AuthorizationHeader("Aladdin"); + System.out.println(ahc.transform()); + + System.out.println(AuthorizationHeaderUtils.resolve(ahc.transform())); + + } } diff --git a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/DateUtilsTest.java b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/DateUtilsTest.java index dc3622398..c50f0160e 100644 --- a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/DateUtilsTest.java +++ b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/DateUtilsTest.java @@ -22,60 +22,60 @@ import java.util.Date; import org.dromara.maxkey.util.DateUtils; public class DateUtilsTest { - - /** - * Main method for test. - * - * @param args - * @throws EncryptException - */ - public static void main(String[] args) throws Exception { - String stringValue = "20110610090519"; - System.out.println(stringValue); -// System.out.println("Parse \"" + stringValue -// + "\" using format pattern \"" + DateUtils.FORMAT_DATE_DEFAULT -// + "\" with method \"DateUtils.parse()\", result: " -// + DateUtils.parse(stringValue)); -// stringValue = "20080506"; -// System.out.println("Parse \"" + stringValue -// + "\" using method \"DateUtils.tryParse()\", result: " -// + DateUtils.tryParse(stringValue)); -// String s = DateUtils.getExchangeFormat(stringValue,FORMAT_DATE_YYYYMMDDHHMMSS,DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS); -// System.out.print("--->>>"+s); - -// String str = "2011-08-09"; -// System.out.println(UserPasswordUtil.decrypt("PVuyeIHtXnXv5oSPwPUug66w==")); -// System.out.println(DateUtils.getFormtPattern1ToPattern2(str, DateUtils.FORMAT_DATE_YYYY_MM_DD, DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS)); -// str = "aaa\r\nbbb"; -// List list = StringUtil.strToList(str, "\r\n"); -// System.out.println(list.size()); -// System.out.println(StringUtil.listToStr(null, ",")); - -// String value = "a,b,,c,,"; -// System.out.println(value.split("\\,").length); -// System.out.println(StringUtil.removeSplit(value, ",")); - -// Class clazz = TmEmployeeUserInfo.class; -// Field field = clazz.getDeclaredField("spellName"); -// System.out.println(field.getName()); - -// System.out.println(UserPasswordUtil.encrypt("oscwebadmin@163.com")); - //System.out.println(JCEnDecrypt.randomDecrypt("2AF5022B2E78478A9761FD3381BB")); -// System.out.println(JCEnDecrypt.randomEncrypt("aaa")); 41l2Iw4V -// String regEx="[1]{1}[3,5,8,6]{1}[0-9]{9}"; //��ʾa��f -// System.out.println(Pattern.compile(regEx).matcher("18258842633").find()); -// Date lockoutDate = DateUtils.addDate(new Date(), 0, 30, 0); //解锁时间 -// System.out.println(DateUtils.format(lockoutDate, DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS)); - Date date = new Date(); - System.out.println(DateUtils.format(DateUtils.addDate(date, 0, 0, 1, 0, 0, 0),DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS)); - - System.out.println(DateUtils.format(DateUtils.addMinutes(new Date(), Integer.parseInt("2")*1000),DateUtils.FORMAT_DATE_ISO_TIMESTAMP)); - System.out.println(DateUtils.toUtc(date)); - - System.out.println(DateUtils.toUtcLocal("2015-11-04T16:00:22.875Z")); - System.out.println(DateUtils.toUtcLocal("2015-11-04T23:58:14.286+08:00")); - - System.out.println(DateUtils.formatDateTime(new Date())); - - } + + /** + * Main method for test. + * + * @param args + * @throws EncryptException + */ + public static void main(String[] args) throws Exception { + String stringValue = "20110610090519"; + System.out.println(stringValue); +// System.out.println("Parse \"" + stringValue +// + "\" using format pattern \"" + DateUtils.FORMAT_DATE_DEFAULT +// + "\" with method \"DateUtils.parse()\", result: " +// + DateUtils.parse(stringValue)); +// stringValue = "20080506"; +// System.out.println("Parse \"" + stringValue +// + "\" using method \"DateUtils.tryParse()\", result: " +// + DateUtils.tryParse(stringValue)); +// String s = DateUtils.getExchangeFormat(stringValue,FORMAT_DATE_YYYYMMDDHHMMSS,DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS); +// System.out.print("--->>>"+s); + +// String str = "2011-08-09"; +// System.out.println(UserPasswordUtil.decrypt("PVuyeIHtXnXv5oSPwPUug66w==")); +// System.out.println(DateUtils.getFormtPattern1ToPattern2(str, DateUtils.FORMAT_DATE_YYYY_MM_DD, DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS)); +// str = "aaa\r\nbbb"; +// List list = StringUtil.strToList(str, "\r\n"); +// System.out.println(list.size()); +// System.out.println(StringUtil.listToStr(null, ",")); + +// String value = "a,b,,c,,"; +// System.out.println(value.split("\\,").length); +// System.out.println(StringUtil.removeSplit(value, ",")); + +// Class clazz = TmEmployeeUserInfo.class; +// Field field = clazz.getDeclaredField("spellName"); +// System.out.println(field.getName()); + +// System.out.println(UserPasswordUtil.encrypt("oscwebadmin@163.com")); + //System.out.println(JCEnDecrypt.randomDecrypt("2AF5022B2E78478A9761FD3381BB")); +// System.out.println(JCEnDecrypt.randomEncrypt("aaa")); 41l2Iw4V +// String regEx="[1]{1}[3,5,8,6]{1}[0-9]{9}"; //��ʾa��f +// System.out.println(Pattern.compile(regEx).matcher("18258842633").find()); +// Date lockoutDate = DateUtils.addDate(new Date(), 0, 30, 0); //解锁时间 +// System.out.println(DateUtils.format(lockoutDate, DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS)); + Date date = new Date(); + System.out.println(DateUtils.format(DateUtils.addDate(date, 0, 0, 1, 0, 0, 0),DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS)); + + System.out.println(DateUtils.format(DateUtils.addMinutes(new Date(), Integer.parseInt("2")*1000),DateUtils.FORMAT_DATE_ISO_TIMESTAMP)); + System.out.println(DateUtils.toUtc(date)); + + System.out.println(DateUtils.toUtcLocal("2015-11-04T16:00:22.875Z")); + System.out.println(DateUtils.toUtcLocal("2015-11-04T23:58:14.286+08:00")); + + System.out.println(DateUtils.formatDateTime(new Date())); + + } } diff --git a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/EthernetAddressTest.java b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/EthernetAddressTest.java index 1e0748c54..0e43e7cbc 100644 --- a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/EthernetAddressTest.java +++ b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/EthernetAddressTest.java @@ -21,9 +21,9 @@ import org.dromara.maxkey.util.EthernetAddress; public class EthernetAddressTest { - public static void main(String[] args) { - System.out.println(EthernetAddress.fromInterface()); + public static void main(String[] args) { + System.out.println(EthernetAddress.fromInterface()); - } + } } diff --git a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/IdSequenceTest.java b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/IdSequenceTest.java index a7d1ce1ca..3e7051fc5 100644 --- a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/IdSequenceTest.java +++ b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/IdSequenceTest.java @@ -19,14 +19,14 @@ package org.maxkey.util; public class IdSequenceTest { - public static void main(String[] args) { - long s =System.currentTimeMillis(); - int k; - for(int i=1;i<=10010;i++){ - k=(i)%10000; - System.out.println(k); - } - System.out.println(System.currentTimeMillis()-s); - } + public static void main(String[] args) { + long s =System.currentTimeMillis(); + int k; + for(int i=1;i<=10010;i++){ + k=(i)%10000; + System.out.println(k); + } + System.out.println(System.currentTimeMillis()-s); + } } diff --git a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/MacAddressTest.java b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/MacAddressTest.java index be7a61c13..b9873435a 100644 --- a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/MacAddressTest.java +++ b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/MacAddressTest.java @@ -21,8 +21,8 @@ import org.dromara.maxkey.util.MacAddress; public class MacAddressTest { - public static void main(String[] args) { - System.out.println(MacAddress.getAllHostMacAddress()); - } + public static void main(String[] args) { + System.out.println(MacAddress.getAllHostMacAddress()); + } } diff --git a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/ObjectTransformerTest.java b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/ObjectTransformerTest.java index e29f07d16..c3b1e32f7 100644 --- a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/ObjectTransformerTest.java +++ b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/ObjectTransformerTest.java @@ -23,26 +23,26 @@ import org.dromara.maxkey.util.ObjectTransformer; public class ObjectTransformerTest { - /** - * @param args - */ - public static void main(String[] args) { - HashMap ut=new HashMap(); - - ut.put("username","shimingxy"); - ut.put("password","test"); - ut.put("department","我的部门"); - - String hexString =ObjectTransformer.serialize(ut); - - System.out.println("hexString "+hexString); - System.out.println(hexString.length()); - - HashMap u2=ObjectTransformer.deserialize(hexString); - - System.out.println("deserialize "+u2.toString()); - - System.out.println("{’id’:’be90f66d-95df-4daf-93c1-ece002542702’,’tid’:null,’tname’:null,’description’:null,’status’:0,’sortOrder’:0,’createdBy’:’admin’,’createdDate’:’2014-11-07 21:27:38’,’modifiedBy’:null,’modifiedDate’:null,’startDate’:null,’endDate’:null,’username’:’yyyyy’,’password’:’Pt3dCf6Zad9h3g7q/DI0e7jQ5evO2Jn+tk2TjtdJ0eY=’,’decipherable’:’yaOLYlcdjfF5hFOskBOOxQ==’,’sharedSecret’:null,’sharedCounter’:null,’userType’:’EMPLOYEE’,’windowsAccount’:null,’displayName’:’test’,’nickName’:null,’nameZHSpell’:’test’,’nameZHShortSpell’:’test’,’givenName’:null,’middleName’:null,’familyName’:null,’honorificPrefix’:null,’honorificSuffix’:null,’formattedName’:null,’married’:0,’gender’:1,’birthDate’:null,’idType’:0,’idCardNo’:null,’webSite’:null,’startWorkDate’:null,’authnType’:0,’email’:null,’emailVerified’:0,’mobile’:null,’mobileVerified’:0,’passwordQuestion’:null,’passwordAnswer’:null,’appLoginAuthnType’:0,’appLoginPassword’:null,’protectedApps’:null,’passwordLastSetTime’:’2014-11-07 21:27:38’,’badPasswordCount’:0,’unLockTime’:null,’isLocked’:0,’lastLoginTime’:null,’lastLogoffTime’:null,’passwordSetType’:0,’locale’:’zh_CN’,’timeZone’:’Asia/Shanghai’,’preferredLanguage’:’zh_CN’,’workCountry’:’CHN’,’workRegion’:null,’workLocality’:null,’workStreetAddress’:null,’workAddressFormatted’:null,’workEmail’:null,’workPhoneNumber’:null,’workPostalCode’:null,’workFax’:null,’homeCountry’:’CHN’,’homeRegion’:null,’homeLocality’:null,’homeStreetAddress’:null,’homeAddressFormatted’:null,’homeEmail’:null,’homePhoneNumber’:null,’homePostalCode’:null,’homeFax’:null,’employeeNumber’:null,’costCenter’:null,’organization’:null,’division’:null,’departmentId’:null,’department’:null,’jobTitle’:null,’jobLevel’:null,’managerId’:null,’manager’:null,’assistantId’:null,’assistant’:null,’entryDate’:null,’quitDate’:null,’ims’:’QQ:\r\nWeiXin:\r\nSinaWeibo:\r\nGtalk:\r\nYiXin:\r\nIMessage:\r\nSkype:\r\nYahoo:\r\nMSN:\r\nAim:\r\nICQ :\r\nXmpp :’,’extraAttribute’:null,’extraAttributeName’:null,’extraAttributeValue’:null,’online’:0,’ldapDn’:null}".length()); - } + /** + * @param args + */ + public static void main(String[] args) { + HashMap ut=new HashMap(); + + ut.put("username","shimingxy"); + ut.put("password","test"); + ut.put("department","我的部门"); + + String hexString =ObjectTransformer.serialize(ut); + + System.out.println("hexString "+hexString); + System.out.println(hexString.length()); + + HashMap u2=ObjectTransformer.deserialize(hexString); + + System.out.println("deserialize "+u2.toString()); + + System.out.println("{’id’:’be90f66d-95df-4daf-93c1-ece002542702’,’tid’:null,’tname’:null,’description’:null,’status’:0,’sortOrder’:0,’createdBy’:’admin’,’createdDate’:’2014-11-07 21:27:38’,’modifiedBy’:null,’modifiedDate’:null,’startDate’:null,’endDate’:null,’username’:’yyyyy’,’password’:’Pt3dCf6Zad9h3g7q/DI0e7jQ5evO2Jn+tk2TjtdJ0eY=’,’decipherable’:’yaOLYlcdjfF5hFOskBOOxQ==’,’sharedSecret’:null,’sharedCounter’:null,’userType’:’EMPLOYEE’,’windowsAccount’:null,’displayName’:’test’,’nickName’:null,’nameZHSpell’:’test’,’nameZHShortSpell’:’test’,’givenName’:null,’middleName’:null,’familyName’:null,’honorificPrefix’:null,’honorificSuffix’:null,’formattedName’:null,’married’:0,’gender’:1,’birthDate’:null,’idType’:0,’idCardNo’:null,’webSite’:null,’startWorkDate’:null,’authnType’:0,’email’:null,’emailVerified’:0,’mobile’:null,’mobileVerified’:0,’passwordQuestion’:null,’passwordAnswer’:null,’appLoginAuthnType’:0,’appLoginPassword’:null,’protectedApps’:null,’passwordLastSetTime’:’2014-11-07 21:27:38’,’badPasswordCount’:0,’unLockTime’:null,’isLocked’:0,’lastLoginTime’:null,’lastLogoffTime’:null,’passwordSetType’:0,’locale’:’zh_CN’,’timeZone’:’Asia/Shanghai’,’preferredLanguage’:’zh_CN’,’workCountry’:’CHN’,’workRegion’:null,’workLocality’:null,’workStreetAddress’:null,’workAddressFormatted’:null,’workEmail’:null,’workPhoneNumber’:null,’workPostalCode’:null,’workFax’:null,’homeCountry’:’CHN’,’homeRegion’:null,’homeLocality’:null,’homeStreetAddress’:null,’homeAddressFormatted’:null,’homeEmail’:null,’homePhoneNumber’:null,’homePostalCode’:null,’homeFax’:null,’employeeNumber’:null,’costCenter’:null,’organization’:null,’division’:null,’departmentId’:null,’department’:null,’jobTitle’:null,’jobLevel’:null,’managerId’:null,’manager’:null,’assistantId’:null,’assistant’:null,’entryDate’:null,’quitDate’:null,’ims’:’QQ:\r\nWeiXin:\r\nSinaWeibo:\r\nGtalk:\r\nYiXin:\r\nIMessage:\r\nSkype:\r\nYahoo:\r\nMSN:\r\nAim:\r\nICQ :\r\nXmpp :’,’extraAttribute’:null,’extraAttributeName’:null,’extraAttributeValue’:null,’online’:0,’ldapDn’:null}".length()); + } } diff --git a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/PathUtilsTest.java b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/PathUtilsTest.java index 23334bb1f..c05d16f64 100644 --- a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/PathUtilsTest.java +++ b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/PathUtilsTest.java @@ -20,10 +20,10 @@ package org.maxkey.util; import org.junit.Test; public class PathUtilsTest { - @Test - public void test() { - //System.out.println(PathUtils.getInstance().getAppPath()); - //System.out.println(PathUtils.getInstance().getWebInf()); - //System.out.println(PathUtils.getInstance().getClassPath()); - } + @Test + public void test() { + //System.out.println(PathUtils.getInstance().getAppPath()); + //System.out.println(PathUtils.getInstance().getWebInf()); + //System.out.println(PathUtils.getInstance().getClassPath()); + } } diff --git a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/SonwFlakeIdTest.java b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/SonwFlakeIdTest.java index 47ab5059e..02adda677 100644 --- a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/SonwFlakeIdTest.java +++ b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/SonwFlakeIdTest.java @@ -23,20 +23,20 @@ import org.junit.Test; public class SonwFlakeIdTest { - - @Test - public void UidGenerator() { - DateTime d= new DateTime("2020-01-01T01:01:01"); - System.out.println("time "+d.getMillis()); - SnowFlakeId snowFlake = new SnowFlakeId(1, 1,8,d.getMillis()); - long seq = snowFlake.nextId(); - - System.out.println(seq); - System.out.println(snowFlake.parse(seq).getDateTime()); - } - - @Test - public void performance() { + + @Test + public void UidGenerator() { + DateTime d= new DateTime("2020-01-01T01:01:01"); + System.out.println("time "+d.getMillis()); + SnowFlakeId snowFlake = new SnowFlakeId(1, 1,8,d.getMillis()); + long seq = snowFlake.nextId(); + + System.out.println(seq); + System.out.println(snowFlake.parse(seq).getDateTime()); + } + + @Test + public void performance() { SnowFlakeId snowFlake = new SnowFlakeId(1, 1); long start = System.currentTimeMillis(); @@ -45,5 +45,5 @@ public class SonwFlakeIdTest { } System.out.println(System.currentTimeMillis() - start); - } + } } diff --git a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/SqlPrettyTest.java b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/SqlPrettyTest.java index a1690d604..63620ad83 100644 --- a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/SqlPrettyTest.java +++ b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/SqlPrettyTest.java @@ -22,14 +22,14 @@ import org.junit.Test; public class SqlPrettyTest { - public SqlPrettyTest() { - - } - - @Test - public void testSqlFormat() { - String sqlString="select * from userinfo where t='111' order by t,s,t"; - System.out.println(PrettyFactory.getSqlPretty().format(sqlString)); - } + public SqlPrettyTest() { + + } + + @Test + public void testSqlFormat() { + String sqlString="select * from userinfo where t='111' order by t,s,t"; + System.out.println(PrettyFactory.getSqlPretty().format(sqlString)); + } } diff --git a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/StringGeneratorTest.java b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/StringGeneratorTest.java index 88f02dfe5..35fdc81c9 100644 --- a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/StringGeneratorTest.java +++ b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/StringGeneratorTest.java @@ -23,11 +23,11 @@ import org.dromara.maxkey.util.StringGenerator; import org.junit.Test; public class StringGeneratorTest { - @Test - public void test() { - StringGenerator stringGenerator=new StringGenerator(); - System.out.println(stringGenerator.uuidGenerate()); - System.out.println(stringGenerator.uuidGenerate().length()); + @Test + public void test() { + StringGenerator stringGenerator=new StringGenerator(); + System.out.println(stringGenerator.uuidGenerate()); + System.out.println(stringGenerator.uuidGenerate().length()); System.out.println(stringGenerator.uniqueGenerate()); System.out.println(stringGenerator.uniqueGenerate().length()); @@ -36,5 +36,5 @@ public class StringGeneratorTest { System.out.println(StringGenerator.uuidMatches("408192be-cab9-4b5b-8d41-4cd827cc4091")); - } + } } diff --git a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/UUIDGeneratorTest.java b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/UUIDGeneratorTest.java index e58630521..f05eeea80 100644 --- a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/UUIDGeneratorTest.java +++ b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/UUIDGeneratorTest.java @@ -25,18 +25,18 @@ import org.dromara.maxkey.uuid.UUID; import org.junit.Test; public class UUIDGeneratorTest { - - @Test - public void test() { - Date sd=new Date(); - - //for(int i=0;i<100000;i++){ - UUIDGenerator generated=new UUIDGenerator(); - generated.toString(); - //System.out.println(generated.toString()); - - //} - Date ed=new Date(); + + @Test + public void test() { + Date sd=new Date(); + + //for(int i=0;i<100000;i++){ + UUIDGenerator generated=new UUIDGenerator(); + generated.toString(); + //System.out.println(generated.toString()); + + //} + Date ed=new Date(); System.out.println("usertime "+(ed.getTime()-sd.getTime())); // UUIDGenerator.version(generated); @@ -45,9 +45,9 @@ public class UUIDGeneratorTest { System.out.println("JDK UUID"); Date ssd=new Date(); // for(int i=0;i<100000;i++){ - //UUID.randomUUID().toString(); - UUID.generate().toString(); - // System.out.println(UUID.randomUUID().toString()); + //UUID.randomUUID().toString(); + UUID.generate().toString(); + // System.out.println(UUID.randomUUID().toString()); //} Date sed=new Date(); System.out.println("usertime "+(sed.getTime()-ssd.getTime())); @@ -56,5 +56,5 @@ public class UUIDGeneratorTest { } - + } diff --git a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/XMLHelperTest.java b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/XMLHelperTest.java index 49406dac4..a77e027fe 100644 --- a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/XMLHelperTest.java +++ b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/util/XMLHelperTest.java @@ -22,11 +22,11 @@ import org.junit.Test; public class XMLHelperTest { - @Test - public void testSqlFormat() { - String sqlString="maxkey"; - System.out.println(XMLHelper.prettyPrintXML(sqlString)); - System.out.println(XMLHelper.transformer(sqlString)); - } + @Test + public void testSqlFormat() { + String sqlString="maxkey"; + System.out.println(XMLHelper.prettyPrintXML(sqlString)); + System.out.println(XMLHelper.transformer(sqlString)); + } } diff --git a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/word/CharacterCase.java b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/word/CharacterCase.java index 2462c938c..49fedceb4 100644 --- a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/word/CharacterCase.java +++ b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/word/CharacterCase.java @@ -19,14 +19,14 @@ package org.maxkey.word; public class CharacterCase { - /** - * @param args - */ - public static void main(String[] args) { - String word="partner "; - - System.out.println(word.toUpperCase()); - System.out.println(word.toLowerCase()); - } + /** + * @param args + */ + public static void main(String[] args) { + String word="partner "; + + System.out.println(word.toUpperCase()); + System.out.println(word.toLowerCase()); + } } diff --git a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/word/SubStr.java b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/word/SubStr.java index 25cff791d..1618186ff 100644 --- a/maxkey-commons/maxkey-common/src/test/java/org/maxkey/word/SubStr.java +++ b/maxkey-commons/maxkey-common/src/test/java/org/maxkey/word/SubStr.java @@ -19,14 +19,14 @@ package org.maxkey.word; public class SubStr { - /** - * @param args - */ - public static void main(String[] args) { - String browser="Chrome/44.0.2369.0"; - System.out.println(browser.indexOf('.')); - String passwordAlgorithm = "MD5-HEX"; - System.out.println(passwordAlgorithm.substring(0,passwordAlgorithm.indexOf("-HEX"))); - } + /** + * @param args + */ + public static void main(String[] args) { + String browser="Chrome/44.0.2369.0"; + System.out.println(browser.indexOf('.')); + String passwordAlgorithm = "MD5-HEX"; + System.out.println(passwordAlgorithm.substring(0,passwordAlgorithm.indexOf("-HEX"))); + } } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/ApplicationConfig.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/ApplicationConfig.java index 1d04597ef..2bbd598fa 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/ApplicationConfig.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/ApplicationConfig.java @@ -38,7 +38,7 @@ import org.springframework.stereotype.Component; @Configuration public class ApplicationConfig { - @Value("${maxkey.server.basedomain}") + @Value("${maxkey.server.basedomain}") String baseDomainName; @Value("${maxkey.server.domain}") @@ -75,8 +75,8 @@ public class ApplicationConfig { private boolean noticesVisible; static String databaseProduct = ConstsDatabase.MYSQL; - - @Autowired + + @Autowired EmailConfig emailConfig; @Autowired @@ -139,14 +139,14 @@ public class ApplicationConfig { } public String getFrontendUri() { - return frontendUri; - } + return frontendUri; + } - public void setFrontendUri(String frontendUri) { - this.frontendUri = frontendUri; - } + public void setFrontendUri(String frontendUri) { + this.frontendUri = frontendUri; + } - /** + /** * @return the domainName */ public String getDomainName() { @@ -194,66 +194,66 @@ public class ApplicationConfig { } public boolean isProvision() { - return provision; - } + return provision; + } - public void setProvision(boolean provision) { - this.provision = provision; - } + public void setProvision(boolean provision) { + this.provision = provision; + } - public boolean isProvisionSupport() { - return provision; - } + public boolean isProvisionSupport() { + return provision; + } - public int getPersistence() { - return persistence; - } + public int getPersistence() { + return persistence; + } - public void setPersistence(int persistence) { - this.persistence = persistence; - } + public void setPersistence(int persistence) { + this.persistence = persistence; + } - public boolean isPersistenceRedis() { - return persistence == ConstsPersistence.REDIS; - } - - public boolean isPersistenceInmemory() { - return persistence == ConstsPersistence.INMEMORY; - } - - public String getMgtUri() { - return mgtUri; - } + public boolean isPersistenceRedis() { + return persistence == ConstsPersistence.REDIS; + } + + public boolean isPersistenceInmemory() { + return persistence == ConstsPersistence.INMEMORY; + } + + public String getMgtUri() { + return mgtUri; + } - public void setMgtUri(String mgtUri) { - this.mgtUri = mgtUri; - } + public void setMgtUri(String mgtUri) { + this.mgtUri = mgtUri; + } - public String getAuthzUri() { - return authzUri; - } + public String getAuthzUri() { + return authzUri; + } - public void setAuthzUri(String authzUri) { - this.authzUri = authzUri; - } + public void setAuthzUri(String authzUri) { + this.authzUri = authzUri; + } - public boolean isNoticesVisible() { - return noticesVisible; - } + public boolean isNoticesVisible() { + return noticesVisible; + } - public void setNoticesVisible(boolean noticesVisible) { - this.noticesVisible = noticesVisible; - } + public void setNoticesVisible(boolean noticesVisible) { + this.noticesVisible = noticesVisible; + } - public static String getDatabaseProduct() { - return databaseProduct; - } + public static String getDatabaseProduct() { + return databaseProduct; + } - public static void setDatabaseProduct(String databaseProduct) { - ApplicationConfig.databaseProduct = databaseProduct; - } + public static void setDatabaseProduct(String databaseProduct) { + ApplicationConfig.databaseProduct = databaseProduct; + } - @Override + @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ApplicationConfig [emailConfig="); diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/AuthJwkConfig.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/AuthJwkConfig.java index 74563394f..f4529e06c 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/AuthJwkConfig.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/AuthJwkConfig.java @@ -25,77 +25,77 @@ import org.springframework.stereotype.Component; @Configuration public class AuthJwkConfig { - @Value("${maxkey.auth.jwt.expires:28800}") - int expires; - - @Value("${maxkey.auth.jwt.secret}") - String secret; - - @Value("${maxkey.auth.jwt.refresh.expires:86400}") - int refreshExpires; - - @Value("${maxkey.auth.jwt.refresh.secret}") - String refreshSecret; - - @Value("${maxkey.auth.jwt.issuer:https://sso.maxkey.top/}") - String issuer; + @Value("${maxkey.auth.jwt.expires:28800}") + int expires; + + @Value("${maxkey.auth.jwt.secret}") + String secret; + + @Value("${maxkey.auth.jwt.refresh.expires:86400}") + int refreshExpires; + + @Value("${maxkey.auth.jwt.refresh.secret}") + String refreshSecret; + + @Value("${maxkey.auth.jwt.issuer:https://sso.maxkey.top/}") + String issuer; - public AuthJwkConfig() { - super(); - } + public AuthJwkConfig() { + super(); + } - public String getIssuer() { - return issuer; - } + public String getIssuer() { + return issuer; + } - public void setIssuer(String issuer) { - this.issuer = issuer; - } + public void setIssuer(String issuer) { + this.issuer = issuer; + } - public int getExpires() { - return expires; - } + public int getExpires() { + return expires; + } - public void setExpires(int expires) { - this.expires = expires; - } + public void setExpires(int expires) { + this.expires = expires; + } - public String getSecret() { - return secret; - } + public String getSecret() { + return secret; + } - public void setSecret(String secret) { - this.secret = secret; - } - - public int getRefreshExpires() { - return refreshExpires; - } + public void setSecret(String secret) { + this.secret = secret; + } + + public int getRefreshExpires() { + return refreshExpires; + } - public void setRefreshExpires(int refreshExpires) { - this.refreshExpires = refreshExpires; - } + public void setRefreshExpires(int refreshExpires) { + this.refreshExpires = refreshExpires; + } - public String getRefreshSecret() { - return refreshSecret; - } + public String getRefreshSecret() { + return refreshSecret; + } - public void setRefreshSecret(String refreshSecret) { - this.refreshSecret = refreshSecret; - } + public void setRefreshSecret(String refreshSecret) { + this.refreshSecret = refreshSecret; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("AuthJwkConfig [issuer="); - builder.append(issuer); - builder.append(", expires="); - builder.append(expires); - builder.append(", secret="); - builder.append(secret); - builder.append("]"); - return builder.toString(); - } - + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("AuthJwkConfig [issuer="); + builder.append(issuer); + builder.append(", expires="); + builder.append(expires); + builder.append(", secret="); + builder.append(secret); + builder.append("]"); + return builder.toString(); + } + } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/EmailConfig.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/EmailConfig.java index cb4911978..9c07d026c 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/EmailConfig.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/EmailConfig.java @@ -45,16 +45,16 @@ public class EmailConfig { } public EmailConfig(String username, String password, String smtpHost, Integer port, boolean ssl, String sender) { - super(); - this.username = username; - this.password = password; - this.smtpHost = smtpHost; - this.port = port; - this.ssl = ssl; - this.sender = sender; - } + super(); + this.username = username; + this.password = password; + this.smtpHost = smtpHost; + this.port = port; + this.ssl = ssl; + this.sender = sender; + } - /* + /* * @return the username */ public String getUsername() { diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/LoginConfig.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/LoginConfig.java index 153debc50..773ba64c4 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/LoginConfig.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/LoginConfig.java @@ -23,12 +23,12 @@ import org.springframework.context.annotation.Configuration; @Configuration public class LoginConfig { - @Value("${maxkey.login.captcha:true}") + @Value("${maxkey.login.captcha:true}") boolean captcha; - - @Value("${maxkey.login.captcha.type:TEXT}") + + @Value("${maxkey.login.captcha.type:TEXT}") String captchaType; - + @Value("${maxkey.login.mfa:false}") boolean mfa; @@ -54,14 +54,14 @@ public class LoginConfig { } public boolean isCaptcha() { - return captcha; - } + return captcha; + } - public void setCaptcha(boolean captcha) { - this.captcha = captcha; - } + public void setCaptcha(boolean captcha) { + this.captcha = captcha; + } - public boolean isKerberos() { + public boolean isKerberos() { return kerberos; } @@ -96,42 +96,42 @@ public class LoginConfig { } public String getCasServerUrlPrefix() { - return casServerUrlPrefix; - } + return casServerUrlPrefix; + } - public void setCasServerUrlPrefix(String casServerUrlPrefix) { - this.casServerUrlPrefix = casServerUrlPrefix; - } + public void setCasServerUrlPrefix(String casServerUrlPrefix) { + this.casServerUrlPrefix = casServerUrlPrefix; + } - public String getCasService() { - return casService; - } + public String getCasService() { + return casService; + } - public void setCasService(String casService) { - this.casService = casService; - } + public void setCasService(String casService) { + this.casService = casService; + } - public String getCaptchaType() { - return captchaType; - } + public String getCaptchaType() { + return captchaType; + } - public void setCaptchaType(String captchaType) { - this.captchaType = captchaType; - } + public void setCaptchaType(String captchaType) { + this.captchaType = captchaType; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("LoginConfig [mfa="); - builder.append(mfa); - builder.append(", kerberos="); - builder.append(kerberos); - builder.append(", remeberMe="); - builder.append(remeberMe); - builder.append(", wsFederation="); - builder.append(wsFederation); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("LoginConfig [mfa="); + builder.append(mfa); + builder.append(", kerberos="); + builder.append(kerberos); + builder.append(", remeberMe="); + builder.append(remeberMe); + builder.append(", wsFederation="); + builder.append(wsFederation); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/oidc/OIDCProviderMetadata.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/oidc/OIDCProviderMetadata.java index e1a132b5a..ddc286ec6 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/oidc/OIDCProviderMetadata.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/configuration/oidc/OIDCProviderMetadata.java @@ -22,36 +22,36 @@ import java.util.Set; public interface OIDCProviderMetadata { - public String getIssuer(); + public String getIssuer(); - public void setIssuer(String issuer); + public void setIssuer(String issuer); - public URI getAuthorizationEndpoint(); + public URI getAuthorizationEndpoint(); - public void setAuthorizationEndpoint(URI authorizationEndpoint); + public void setAuthorizationEndpoint(URI authorizationEndpoint); - public URI getTokenEndpoint(); + public URI getTokenEndpoint(); - public void setTokenEndpoint(URI tokenEndpoint); + public void setTokenEndpoint(URI tokenEndpoint); - public URI getUserinfoEndpoint(); + public URI getUserinfoEndpoint(); - public void setUserinfoEndpoint(URI userinfoEndpoint); + public void setUserinfoEndpoint(URI userinfoEndpoint); - public URI getJwksUri(); + public URI getJwksUri(); - public void setJwksUri(URI jwksUri); + public void setJwksUri(URI jwksUri); - public URI getRegistrationEndpoint(); + public URI getRegistrationEndpoint(); - public void setRegistrationEndpoint(URI registrationEndpoint); + public void setRegistrationEndpoint(URI registrationEndpoint); - public Set getScopesSupported(); + public Set getScopesSupported(); - public void setScopesSupported(Set scopesSupported); + public void setScopesSupported(Set scopesSupported); - public Set getResponseTypesSupported(); + public Set getResponseTypesSupported(); - public void setResponseTypesSupported(Set responseTypesSupported); + public void setResponseTypesSupported(Set responseTypesSupported); } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/exception/NameException.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/exception/NameException.java index 7b5137259..dd61352c0 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/exception/NameException.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/exception/NameException.java @@ -27,38 +27,38 @@ import org.dromara.maxkey.web.WebContext; */ public class NameException extends Exception { - public NameException(String field, String key, String value) { - super(); - this.field = field; - this.key = key; - this.value = value; - } + public NameException(String field, String key, String value) { + super(); + this.field = field; + this.key = key; + this.value = value; + } - private static final long serialVersionUID = -5425015701816705662L; - private String field; - private String key; - private String value; + private static final long serialVersionUID = -5425015701816705662L; + private String field; + private String key; + private String value; - /** - * @return 返回异常属性 - */ - public String getField() { - return field; - } + /** + * @return 返回异常属性 + */ + public String getField() { + return field; + } - /** - * @return 返回属性文件的key对应值 - */ - public String getKey() { - return WebContext - .getI18nValue("ui.enterprises.enterprises.message." - + key); - } + /** + * @return 返回属性文件的key对应值 + */ + public String getKey() { + return WebContext + .getI18nValue("ui.enterprises.enterprises.message." + + key); + } - /** - * @return 错误数据 - */ - public String getValue() { - return value; - } - } + /** + * @return 错误数据 + */ + public String getValue() { + return value; + } + } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/exception/OperaterSqlException.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/exception/OperaterSqlException.java index 6fbd82500..774004cd4 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/exception/OperaterSqlException.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/exception/OperaterSqlException.java @@ -19,13 +19,13 @@ package org.dromara.maxkey.exception; public class OperaterSqlException extends Exception { - private static final long serialVersionUID = -5596610890188994830L; - - public OperaterSqlException() { - super(); - } + private static final long serialVersionUID = -5596610890188994830L; + + public OperaterSqlException() { + super(); + } - public OperaterSqlException(String message) { - super(message); - } + public OperaterSqlException(String message) { + super(message); + } } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/exception/PasswordPolicyException.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/exception/PasswordPolicyException.java index 0a77446a4..327b43b07 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/exception/PasswordPolicyException.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/exception/PasswordPolicyException.java @@ -21,38 +21,38 @@ import org.dromara.maxkey.web.WebContext; public class PasswordPolicyException extends Exception { - /** - * - */ - private static final long serialVersionUID = -253274228039876768L; - private String errorCode; - private Object filedValue; - public PasswordPolicyException(String errorCode,Object filedValue) { - super(); - this.errorCode = errorCode; - this.filedValue = filedValue; - } - public PasswordPolicyException(String errorCode) { - super(); - this.errorCode = errorCode; - } - public Object getFiledValue() { - return filedValue; - } + /** + * + */ + private static final long serialVersionUID = -253274228039876768L; + private String errorCode; + private Object filedValue; + public PasswordPolicyException(String errorCode,Object filedValue) { + super(); + this.errorCode = errorCode; + this.filedValue = filedValue; + } + public PasswordPolicyException(String errorCode) { + super(); + this.errorCode = errorCode; + } + public Object getFiledValue() { + return filedValue; + } - public String getKey() { - return "message.passwordpolicy."+errorCode.toLowerCase(); - } - public String getErrorCode() { - return errorCode; - } + public String getKey() { + return "message.passwordpolicy."+errorCode.toLowerCase(); + } + public String getErrorCode() { + return errorCode; + } - @Override - public String getMessage() { - if(filedValue!=null) - return WebContext.getI18nValue(getKey(), new Object[]{filedValue}); - else - return WebContext.getI18nValue(getKey()); - } - + @Override + public String getMessage() { + if(filedValue!=null) + return WebContext.getI18nValue(getKey(), new Object[]{filedValue}); + else + return WebContext.getI18nValue(getKey()); + } + } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/schedule/ScheduleAdapter.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/schedule/ScheduleAdapter.java index 0a680ebd2..3f7a1e1c2 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/schedule/ScheduleAdapter.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/schedule/ScheduleAdapter.java @@ -21,27 +21,27 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ScheduleAdapter { - private static final Logger _logger = LoggerFactory.getLogger(ScheduleAdapter.class); - - JobExecutionContext context; - - protected int jobStatus = JOBSTATUS.STOP; - + private static final Logger _logger = LoggerFactory.getLogger(ScheduleAdapter.class); + + JobExecutionContext context; + + protected int jobStatus = JOBSTATUS.STOP; + public static final class JOBSTATUS{ - public static final int STOP = 0; - public static final int RUNNING = 1; - public static final int ERROR = 2; - public static final int FINISHED = 3; + public static final int STOP = 0; + public static final int RUNNING = 1; + public static final int ERROR = 2; + public static final int FINISHED = 3; } protected void init(JobExecutionContext context){ - this.context = context; + this.context = context; } @SuppressWarnings("unchecked") - public T getParameter(String name, Class requiredType) { - _logger.trace("requiredType {}",requiredType); - return (T) context.getMergedJobDataMap().get(name); + public T getParameter(String name, Class requiredType) { + _logger.trace("requiredType {}",requiredType); + return (T) context.getMergedJobDataMap().get(name); } } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/schedule/ScheduleAdapterBuilder.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/schedule/ScheduleAdapterBuilder.java index 9294e64ce..94d095bd1 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/schedule/ScheduleAdapterBuilder.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/schedule/ScheduleAdapterBuilder.java @@ -31,85 +31,85 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ScheduleAdapterBuilder { - private static final Logger _logger = LoggerFactory.getLogger(ScheduleAdapterBuilder.class); - - Scheduler scheduler ; - - String cron; - - Class jobClass; - - JobDataMap jobDataMap; - - String identity ; - + private static final Logger _logger = LoggerFactory.getLogger(ScheduleAdapterBuilder.class); + + Scheduler scheduler ; + + String cron; + + Class jobClass; + + JobDataMap jobDataMap; + + String identity ; + public void addListener( - Scheduler scheduler , - Class jobClass, - String cronSchedule, - JobDataMap jobDataMap - ) throws SchedulerException { - this.cron = cronSchedule; - this.scheduler = scheduler; - this.jobClass = jobClass; - this.jobDataMap = jobDataMap; - this.build(); - } + Scheduler scheduler , + Class jobClass, + String cronSchedule, + JobDataMap jobDataMap + ) throws SchedulerException { + this.cron = cronSchedule; + this.scheduler = scheduler; + this.jobClass = jobClass; + this.jobDataMap = jobDataMap; + this.build(); + } public ScheduleAdapterBuilder setIdentity(String identity) { - this.identity = identity; - return this; + this.identity = identity; + return this; } public ScheduleAdapterBuilder setScheduler(Scheduler scheduler) { - this.scheduler = scheduler; - return this; + this.scheduler = scheduler; + return this; } public ScheduleAdapterBuilder setJobDataMap(JobDataMap jobDataMap) { - this.jobDataMap = jobDataMap; - return this; + this.jobDataMap = jobDataMap; + return this; } public ScheduleAdapterBuilder setJobData(String key,Object data) { - if(this.jobDataMap == null) { - jobDataMap = new JobDataMap(); - } - this.jobDataMap.put(key, data); - return this; + if(this.jobDataMap == null) { + jobDataMap = new JobDataMap(); + } + this.jobDataMap.put(key, data); + return this; } public ScheduleAdapterBuilder setCron(String cron) { - this.cron = cron; - return this; + this.cron = cron; + return this; } public ScheduleAdapterBuilder setJobClass(Class jobClass) { - this.jobClass = jobClass; - return this; + this.jobClass = jobClass; + return this; } public void build() throws SchedulerException { - if(StringUtils.isBlank(identity)) { - identity = jobClass.getSimpleName(); - } - _logger.debug("Job schedule {} ,Cron {} ", identity ,cron); - - JobDetail jobDetail = - JobBuilder.newJob(jobClass) - .withIdentity(identity, identity + "Group") - .build(); - - CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron); - - CronTrigger cronTrigger = - TriggerBuilder.newTrigger() - .withIdentity("trigger" + identity, identity + "TriggerGroup") - .usingJobData(jobDataMap) - .withSchedule(scheduleBuilder) - .build(); - - scheduler.scheduleJob(jobDetail,cronTrigger); + if(StringUtils.isBlank(identity)) { + identity = jobClass.getSimpleName(); + } + _logger.debug("Job schedule {} ,Cron {} ", identity ,cron); + + JobDetail jobDetail = + JobBuilder.newJob(jobClass) + .withIdentity(identity, identity + "Group") + .build(); + + CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron); + + CronTrigger cronTrigger = + TriggerBuilder.newTrigger() + .withIdentity("trigger" + identity, identity + "TriggerGroup") + .usingJobData(jobDataMap) + .withSchedule(scheduleBuilder) + .build(); + + scheduler.scheduleJob(jobDetail,cronTrigger); } } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/ConfigurerFreeMarker.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/ConfigurerFreeMarker.java index 4a16d536c..a9a7428a2 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/ConfigurerFreeMarker.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/ConfigurerFreeMarker.java @@ -35,28 +35,28 @@ import jakarta.annotation.PostConstruct; @Component public class ConfigurerFreeMarker implements ApplicationContextAware { - private static final Logger _logger = LoggerFactory.getLogger(ConfigurerFreeMarker.class); - - ApplicationContext applicationContext ; - - @Autowired - Configuration configuration; + private static final Logger _logger = LoggerFactory.getLogger(ConfigurerFreeMarker.class); + + ApplicationContext applicationContext ; + + @Autowired + Configuration configuration; - @PostConstruct // 在项目启动时执行方法 - public void setSharedVariable() throws TemplateException { - // 根据注解FreemarkerTag获取bean ,key is bean name ,value is bean object - Map map = this.applicationContext.getBeansWithAnnotation(FreemarkerTag.class); - for (Map.Entry entry : map.entrySet()) { - configuration.setSharedVariable(entry.getKey(), entry.getValue()); - _logger.trace("FreeMarker Template {}" , entry.getKey()); - } + @PostConstruct // 在项目启动时执行方法 + public void setSharedVariable() throws TemplateException { + // 根据注解FreemarkerTag获取bean ,key is bean name ,value is bean object + Map map = this.applicationContext.getBeansWithAnnotation(FreemarkerTag.class); + for (Map.Entry entry : map.entrySet()) { + configuration.setSharedVariable(entry.getKey(), entry.getValue()); + _logger.trace("FreeMarker Template {}" , entry.getKey()); + } - } + } - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - - } + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + + } } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/GlobalExceptionHandler.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/GlobalExceptionHandler.java index 4cc3a6614..96350024b 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/GlobalExceptionHandler.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/GlobalExceptionHandler.java @@ -52,7 +52,7 @@ import java.util.Objects; */ @RestControllerAdvice public class GlobalExceptionHandler { - private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); + private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 缺少请求体异常处理器 @@ -105,9 +105,9 @@ public class GlobalExceptionHandler { String requestURI = request.getRequestURI(); logger.info("Request IpAddress : {} " , WebContext.getRequestIpAddress(request)); if(e instanceof NoHandlerFoundException) { - //NoHandlerFoundException + //NoHandlerFoundException }else { - logger.error("请求地址'{}',发生系统异常.", requestURI, e); + logger.error("请求地址'{}',发生系统异常.", requestURI, e); } return new Message<>(Message.FAIL, HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()); } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/HttpRequestAdapter.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/HttpRequestAdapter.java index c56b4a54c..e362a90b6 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/HttpRequestAdapter.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/HttpRequestAdapter.java @@ -52,8 +52,8 @@ import org.springframework.stereotype.Component; @Component public class HttpRequestAdapter { - private static final Logger _logger = LoggerFactory.getLogger(HttpRequestAdapter.class); - + private static final Logger _logger = LoggerFactory.getLogger(HttpRequestAdapter.class); + private String mediaType = ContentType.APPLICATION_FORM; HashMap headers = new HashMap(); @@ -64,31 +64,31 @@ public class HttpRequestAdapter { this.mediaType = mediaType; } - public String post(String url,Map parameterMap) { - setContentType(ContentType.APPLICATION_FORM); - return post(url , parameterMap , headers); - } - - public HttpRequestAdapter addHeaderAuthorizationBearer(String token ) { - headers.put("Authorization", AuthorizationHeaderUtils.createBearer(token)); - return this; - } - - public HttpRequestAdapter addHeaderAuthorizationBasic(String username, String password) { - headers.put("Authorization", AuthorizationHeaderUtils.createBasic(username,password)); - return this; - } - - public HttpRequestAdapter setContentType(String contentType) { - headers.put("Content-Type", contentType); - return this; - } - - public HttpRequestAdapter addHeader(String name , String value ) { - headers.put(name, value); - return this; - } - + public String post(String url,Map parameterMap) { + setContentType(ContentType.APPLICATION_FORM); + return post(url , parameterMap , headers); + } + + public HttpRequestAdapter addHeaderAuthorizationBearer(String token ) { + headers.put("Authorization", AuthorizationHeaderUtils.createBearer(token)); + return this; + } + + public HttpRequestAdapter addHeaderAuthorizationBasic(String username, String password) { + headers.put("Authorization", AuthorizationHeaderUtils.createBasic(username,password)); + return this; + } + + public HttpRequestAdapter setContentType(String contentType) { + headers.put("Content-Type", contentType); + return this; + } + + public HttpRequestAdapter addHeader(String name , String value ) { + headers.put(name, value); + return this; + } + public String post(String url,Map parameterMap,HashMap headers) { // 创建httpClient实例 CloseableHttpClient httpClient = HttpClients.createDefault(); @@ -105,7 +105,7 @@ public class HttpRequestAdapter { if(mediaType.equals(ContentType.APPLICATION_FORM)) { // 为httpPost设置封装好的请求参数 try { - httpMethod.setEntity(buildFormEntity(parameterMap)); + httpMethod.setEntity(buildFormEntity(parameterMap)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } @@ -126,7 +126,7 @@ public class HttpRequestAdapter { } catch (Exception e) { e.printStackTrace(); } finally { - close(httpClient,httpResponse);// 关闭资源 + close(httpClient,httpResponse);// 关闭资源 } return null; } @@ -158,7 +158,7 @@ public class HttpRequestAdapter { } catch (Exception e) { e.printStackTrace(); } finally { - close(httpClient,httpResponse);// 关闭资源 + close(httpClient,httpResponse);// 关闭资源 } return null; } @@ -189,17 +189,17 @@ public class HttpRequestAdapter { } catch (Exception e) { e.printStackTrace(); } finally { - close(httpClient,httpResponse);// 关闭资源 + close(httpClient,httpResponse);// 关闭资源 } return null; } - public String get(String url) { - headers.put("Content-Type", ContentType.APPLICATION_FORM); - return get(url , headers); - } - + public String get(String url) { + headers.put("Content-Type", ContentType.APPLICATION_FORM); + return get(url , headers); + } + public String get(String url,HashMap headers) { // 创建httpClient实例 CloseableHttpClient httpClient = HttpClients.createDefault(); @@ -219,13 +219,13 @@ public class HttpRequestAdapter { } catch (Exception e) { e.printStackTrace(); } finally { - close(httpClient,httpResponse);// 关闭资源 + close(httpClient,httpResponse);// 关闭资源 } return null; } public String delete(String url) { - // 创建httpClient实例 + // 创建httpClient实例 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse = null; // 创建HttpDelete远程连接实例 @@ -243,13 +243,13 @@ public class HttpRequestAdapter { } catch (Exception e) { e.printStackTrace(); } finally { - close(httpClient,httpResponse);// 关闭资源 + close(httpClient,httpResponse);// 关闭资源 } return null; - } + } String resolveHttpResponse(CloseableHttpResponse httpResponse) throws ParseException, IOException { - HttpEntity entity = httpResponse.getEntity(); + HttpEntity entity = httpResponse.getEntity(); String content = EntityUtils.toString(entity); HttpStatus httpStatus = HttpStatus.valueOf(httpResponse.getStatusLine().getStatusCode()); _logger.debug("Http Response HttpStatus {} " , httpStatus); @@ -262,9 +262,9 @@ public class HttpRequestAdapter { * @param headers */ void buildHeader(HttpRequestBase httpRequest,HashMap headers) { - // 设置请求头 + // 设置请求头 if (null != headers && headers.size() > 0) { - Set> entrySet = headers.entrySet(); + Set> entrySet = headers.entrySet(); // 循环遍历,获取迭代器 Iterator> iterator = entrySet.iterator(); while (iterator.hasNext()) { @@ -276,8 +276,8 @@ public class HttpRequestAdapter { } UrlEncodedFormEntity buildFormEntity(Map parameterMap) - throws UnsupportedEncodingException { - List nvps = new ArrayList(); + throws UnsupportedEncodingException { + List nvps = new ArrayList(); // 通过map集成entrySet方法获取entity Set> entrySet = parameterMap.entrySet(); // 循环遍历,获取迭代器 @@ -293,7 +293,7 @@ public class HttpRequestAdapter { } void setRequestConfig(HttpRequestBase httpMethod){ - RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间 + RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间 .setConnectionRequestTimeout(35000)// 设置连接请求超时时间 .setSocketTimeout(60000)// 设置读取数据连接超时时间 .build(); diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/HttpResponseAdapter.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/HttpResponseAdapter.java index 09687403a..2e364781a 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/HttpResponseAdapter.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/HttpResponseAdapter.java @@ -39,10 +39,10 @@ public class HttpResponseAdapter { } } - public void write(HttpServletResponse response,String content, String format) { + public void write(HttpServletResponse response,String content, String format) { - setContentType(response , format); - + setContentType(response , format); + // Set to expire far in the past. response.setDateHeader("Expires", 0); // Set standard HTTP/1.1 no-cache headers. @@ -52,21 +52,21 @@ public class HttpResponseAdapter { ServletOutputStream out = null; try { - out = response.getOutputStream(); - // write the data out + out = response.getOutputStream(); + // write the data out out.write(content.getBytes()); out.flush(); }catch (IOException e) { - e.printStackTrace(); - } finally { + e.printStackTrace(); + } finally { try { - if(out != null) { - out.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } + if(out != null) { + out.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } } - } + } } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/HttpResponseConstants.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/HttpResponseConstants.java index 54f9dd174..fe30acfdf 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/HttpResponseConstants.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/HttpResponseConstants.java @@ -18,16 +18,16 @@ package org.dromara.maxkey.web; public class HttpResponseConstants { - - public static final class FORMAT_TYPE { - /** - * Default XML response. - */ - public static final String XML="xml"; - /** - * Render response in JSON. - */ - public static final String JSON="json"; - } - + + public static final class FORMAT_TYPE { + /** + * Default XML response. + */ + public static final String XML="xml"; + /** + * Render response in JSON. + */ + public static final String JSON="json"; + } + } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/InitializeContext.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/InitializeContext.java index c27e30e6d..70950dd40 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/InitializeContext.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/InitializeContext.java @@ -131,7 +131,7 @@ public class InitializeContext extends HttpServlet { Iterator> it =WebContext.properties.getPropertySources().iterator(); while(it.hasNext()) { - logger.debug("propertySource {}" , it.next()); + logger.debug("propertySource {}" , it.next()); } logger.trace(WebConstants.DELIMITER); @@ -148,8 +148,8 @@ public class InitializeContext extends HttpServlet { WebContext.properties.getProperty("application.formatted-version")); logger.info(""); logger.info(" {}Copyright 2018 - {} https://www.maxkey.top/", - (char)0xA9 , new DateTime().getYear() - ); + (char)0xA9 , new DateTime().getYear() + ); logger.info("+ Licensed under the Apache License, Version 2.0 "); logger.info(WebConstants.DELIMITER); } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/MetadataEndpoint.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/MetadataEndpoint.java index ffd344c5b..2a7bc3517 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/MetadataEndpoint.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/MetadataEndpoint.java @@ -28,9 +28,9 @@ import jakarta.servlet.http.HttpServletResponse; @Controller public class MetadataEndpoint { - @GetMapping(value = "/metadata/version",produces = ContentType.TEXT_PLAIN_UTF8) - @ResponseBody - public String metadata(HttpServletRequest request,HttpServletResponse response) { - return WebContext.version(); - } + @GetMapping(value = "/metadata/version",produces = ContentType.TEXT_PLAIN_UTF8) + @ResponseBody + public String metadata(HttpServletRequest request,HttpServletResponse response) { + return WebContext.version(); + } } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/ProductEnvironment.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/ProductEnvironment.java index 21f2c77bf..8a9f48705 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/ProductEnvironment.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/ProductEnvironment.java @@ -31,16 +31,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ProductEnvironment { - private static final Logger logger = LoggerFactory.getLogger(ProductEnvironment.class); + private static final Logger logger = LoggerFactory.getLogger(ProductEnvironment.class); - ProductEnvironment(){} - + ProductEnvironment(){} + /** * List Environment Variables. */ public static void listEnvVars() { - logger.info(WebConstants.DELIMITER); - logger.info("List Environment Variables "); + logger.info(WebConstants.DELIMITER); + logger.info("List Environment Variables "); Map map = System.getenv(); SortedSet keyValueSet = new TreeSet<>(); for (Iterator itr = map.keySet().iterator(); itr.hasNext();) { @@ -56,7 +56,7 @@ public class ProductEnvironment { Processor processor = ArchUtils.getProcessor(); if (Objects.isNull(processor)){ - processor = new Processor(Processor.Arch.UNKNOWN, Processor.Type.UNKNOWN); + processor = new Processor(Processor.Arch.UNKNOWN, Processor.Type.UNKNOWN); } logger.info("OS : {}({} {}), version {}", SystemUtils.OS_NAME, diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/ProductVersionEndpoint.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/ProductVersionEndpoint.java index 1e0462197..c58b9ff37 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/ProductVersionEndpoint.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/ProductVersionEndpoint.java @@ -40,57 +40,57 @@ import jakarta.servlet.http.HttpServletResponse; @Controller public class ProductVersionEndpoint { - private static final Logger _logger = LoggerFactory.getLogger(ProductVersionEndpoint.class); - - static final String VERSION_STRING =""" - - - - - - - MaxKey Single Sign-On - - -
-
- Maxkey Community Edition
- Single Sign On ( SSO )
- Version %s
-
- © Copyright 2018 - %d https://www.maxkey.top/
- Licensed under the Apache License, Version 2.0
- .                     - All rights reserved -                     .
-
- JAVA    :    %s java version %s, class %s
- %s (build %s, %s)
-
-
- - - """; + private static final Logger _logger = LoggerFactory.getLogger(ProductVersionEndpoint.class); + + static final String VERSION_STRING =""" + + + + + + + MaxKey Single Sign-On + + +
+
+ Maxkey Community Edition
+ Single Sign On ( SSO )
+ Version %s
+
+ © Copyright 2018 - %d https://www.maxkey.top/
+ Licensed under the Apache License, Version 2.0
+ .                     + All rights reserved +                     .
+
+ JAVA    :    %s java version %s, class %s
+ %s (build %s, %s)
+
+
+ + + """; - @GetMapping(value={"/"}) - public void version(HttpServletRequest request,HttpServletResponse response) throws IOException { - _logger.debug("ProductVersion /"); - ServletOutputStream out = response.getOutputStream(); - String contextPath = request.getContextPath(); - out.println( - String.format( - VERSION_STRING, - contextPath, - contextPath, - WebContext.getProperty("application.formatted-version"), - new DateTime().getYear(), - SystemUtils.JAVA_VENDOR, + @GetMapping(value={"/"}) + public void version(HttpServletRequest request,HttpServletResponse response) throws IOException { + _logger.debug("ProductVersion /"); + ServletOutputStream out = response.getOutputStream(); + String contextPath = request.getContextPath(); + out.println( + String.format( + VERSION_STRING, + contextPath, + contextPath, + WebContext.getProperty("application.formatted-version"), + new DateTime().getYear(), + SystemUtils.JAVA_VENDOR, SystemUtils.JAVA_VERSION, SystemUtils.JAVA_CLASS_VERSION, SystemUtils.JAVA_VM_NAME, SystemUtils.JAVA_VM_VERSION, SystemUtils.JAVA_VM_INFO)); - out.close(); - } - + out.close(); + } + } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/WebConstants.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/WebConstants.java index 09a75da6f..ba1564c31 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/WebConstants.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/WebConstants.java @@ -28,11 +28,11 @@ public class WebConstants { public static final String CURRENT_USER_PASSWORD_SET_TYPE = "current_user_password_set_type"; - public static final String CURRENT_MESSAGE = "current_message"; + public static final String CURRENT_MESSAGE = "current_message"; - public static final String CURRENT_INST = "current_inst"; + public static final String CURRENT_INST = "current_inst"; - public static final String INST_COOKIE_NAME = "mxk_inst"; + public static final String INST_COOKIE_NAME = "mxk_inst"; // SPRING_SECURITY_SAVED_REQUEST public static final String FIRST_SAVED_REQUEST_PARAMETER @@ -74,15 +74,15 @@ public class WebConstants { public static final String ONLINE_TICKET_NAME = "online_ticket"; - public static final String MXK_METADATA_PREFIX = "mxk_metadata_"; - + public static final String MXK_METADATA_PREFIX = "mxk_metadata_"; + public static final class LOGIN_RESULT{ - public static final String SUCCESS = "success"; - public static final String FAIL = "fail"; - public static final String PASSWORD_ERROE = "password error"; - public static final String USER_NOT_EXIST = "user not exist"; - public static final String USER_LOCKED = "locked"; - public static final String USER_INACTIVE = "inactive"; + public static final String SUCCESS = "success"; + public static final String FAIL = "fail"; + public static final String PASSWORD_ERROE = "password error"; + public static final String USER_NOT_EXIST = "user not exist"; + public static final String USER_LOCKED = "locked"; + public static final String USER_INACTIVE = "inactive"; } public static final String DELIMITER = "-----------------------------------------------------------"; diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/WebContext.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/WebContext.java index dc2c6f527..8b8495c23 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/WebContext.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/WebContext.java @@ -60,7 +60,7 @@ import jakarta.servlet.http.HttpSession; * */ public final class WebContext { - static final Logger _logger = LoggerFactory.getLogger(WebContext.class); + static final Logger _logger = LoggerFactory.getLogger(WebContext.class); public static StandardEnvironment properties; @@ -100,11 +100,11 @@ public final class WebContext { } public static void init(ApplicationContext context) { - applicationContext = context; + applicationContext = context; } public static void initProperties(StandardEnvironment standardEnvironment) { - properties = standardEnvironment; + properties = standardEnvironment; } /** @@ -140,7 +140,7 @@ public final class WebContext { } public static T getBean(String name, Class requiredType) throws BeansException{ - if(applicationContext==null) { + if(applicationContext==null) { return getApplicationContext().getBean(name,requiredType); }else { return applicationContext.getBean(name,requiredType); @@ -148,11 +148,11 @@ public final class WebContext { } public static String getProperty(String key) { - return properties.getProperty(key); + return properties.getProperty(key); } public static String getServerPort() { - return getProperty("server.port"); + return getProperty("server.port"); } // below method is common HttpServlet method @@ -186,11 +186,11 @@ public final class WebContext { * http://www.website.com/webcontext */ public static String getContextPath(HttpServletRequest request,boolean isContextPath) { - String fullRequestUrl = UrlUtils.buildFullRequestUrl(request); - StringBuilder url = new StringBuilder(fullRequestUrl.substring(0, fullRequestUrl.indexOf(request.getContextPath()))); + String fullRequestUrl = UrlUtils.buildFullRequestUrl(request); + StringBuilder url = new StringBuilder(fullRequestUrl.substring(0, fullRequestUrl.indexOf(request.getContextPath()))); if(isContextPath) { - url.append(request.getContextPath()); + url.append(request.getContextPath()); } _logger.trace("http ContextPath {}" , url); @@ -203,12 +203,12 @@ public final class WebContext { * @param request */ public static void printRequest(final HttpServletRequest request) { - _logger.info("getContextPath : {}" , request.getContextPath()); - _logger.info("getRequestURL : {} " , request.getRequestURL()); - _logger.info("URL : {}" , request.getRequestURI().substring(request.getContextPath().length())); - _logger.info("getMethod : {} " , request.getMethod()); - _logger.info("Request IpAddress : {} " , getRequestIpAddress(request)); - + _logger.info("getContextPath : {}" , request.getContextPath()); + _logger.info("getRequestURL : {} " , request.getRequestURL()); + _logger.info("URL : {}" , request.getRequestURI().substring(request.getContextPath().length())); + _logger.info("getMethod : {} " , request.getMethod()); + _logger.info("Request IpAddress : {} " , getRequestIpAddress(request)); + Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = headerNames.nextElement(); @@ -307,7 +307,7 @@ public final class WebContext { Locale locale = null; try { CookieLocaleResolver cookieLocaleResolver = - getBean("localeResolver",CookieLocaleResolver.class); + getBean("localeResolver",CookieLocaleResolver.class); locale = cookieLocaleResolver.resolveLocale(getRequest()); } catch (Exception e) { @@ -339,7 +339,7 @@ public final class WebContext { public static Cookie getCookie(HttpServletRequest request, String name) { Map cookieMap = getCookieAll(request); if (cookieMap.containsKey(name)) { - return cookieMap.get(name); + return cookieMap.get(name); } else { return null; } @@ -462,7 +462,7 @@ public final class WebContext { */ public static boolean captchaValid(String captcha) { return (captcha != null && - captcha.equals(WebContext.getSession().getAttribute( + captcha.equals(WebContext.getSession().getAttribute( WebConstants.KAPTCHA_SESSION_KEY).toString())); } @@ -519,17 +519,17 @@ public final class WebContext { * @return String */ public static String genId() { - if(idGenerator == null) { - idGenerator = new IdGenerator(); - } + if(idGenerator == null) { + idGenerator = new IdGenerator(); + } return idGenerator.generate(); } public static void setIdGenerator(IdGenerator idGenerator) { - WebContext.idGenerator = idGenerator; - } + WebContext.idGenerator = idGenerator; + } - public static ModelAndView redirect(String redirectUrl) { + public static ModelAndView redirect(String redirectUrl) { return new ModelAndView("redirect:" + redirectUrl); } @@ -538,22 +538,22 @@ public final class WebContext { } public static boolean compare(String databaseProduct) { - return databaseProduct.equalsIgnoreCase(ApplicationConfig.getDatabaseProduct()); + return databaseProduct.equalsIgnoreCase(ApplicationConfig.getDatabaseProduct()); } public static String version() { - StringBuffer version = new StringBuffer(); - version.append("-----------------------------------------------------------"); - version.append("+ MaxKey Community Edition "); - version.append("+ Single Sign On ( SSO ) "); - version.append("+ Version %s".formatted( + StringBuffer version = new StringBuffer(); + version.append("-----------------------------------------------------------"); + version.append("+ MaxKey Community Edition "); + version.append("+ Single Sign On ( SSO ) "); + version.append("+ Version %s".formatted( WebContext.properties.getProperty("application.formatted-version"))); - version.append("+"); - version.append("+ {}Copyright 2018 - {} https://www.maxkey.top/", - (char)0xA9 , new DateTime().getYear() - ); - version.append("+ . All rights reserved . "); - version.append("-----------------------------------------------------------"); - return version.toString(); + version.append("+"); + version.append("+ {}Copyright 2018 - {} https://www.maxkey.top/", + (char)0xA9 , new DateTime().getYear() + ); + version.append("+ . All rights reserved . "); + version.append("-----------------------------------------------------------"); + return version.toString(); } } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/BasePathTagDirective.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/BasePathTagDirective.java index 9770eea2e..aa2d88233 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/BasePathTagDirective.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/BasePathTagDirective.java @@ -41,16 +41,16 @@ import jakarta.servlet.http.HttpServletRequest; @FreemarkerTag("basePath") public class BasePathTagDirective implements TemplateDirectiveModel { - @Autowired + @Autowired private HttpServletRequest request; - - @Override - @SuppressWarnings("rawtypes") - public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) - throws TemplateException, IOException { - - env.getOut().append(WebContext.getContextPath(request,true)); - - } + + @Override + @SuppressWarnings("rawtypes") + public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) + throws TemplateException, IOException { + + env.getOut().append(WebContext.getContextPath(request,true)); + + } } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/BaseTagDirective.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/BaseTagDirective.java index 43c106bcb..b3be7d4e0 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/BaseTagDirective.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/BaseTagDirective.java @@ -37,20 +37,20 @@ import jakarta.servlet.http.HttpServletRequest; @FreemarkerTag("base") public class BaseTagDirective implements TemplateDirectiveModel { - @Autowired + @Autowired private HttpServletRequest request; - @Override - @SuppressWarnings("rawtypes") - public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) - throws TemplateException, IOException { - //String url = params.get(URL).toString(); + @Override + @SuppressWarnings("rawtypes") + public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) + throws TemplateException, IOException { + //String url = params.get(URL).toString(); - String base=request.getContextPath(); - - env.getOut().append(base); - + String base=request.getContextPath(); + + env.getOut().append(base); + - } + } } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/BrowserTagDirective.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/BrowserTagDirective.java index 9f9c0cbed..56a377109 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/BrowserTagDirective.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/BrowserTagDirective.java @@ -37,20 +37,20 @@ import jakarta.servlet.http.HttpServletRequest; @FreemarkerTag("browser") public class BrowserTagDirective implements TemplateDirectiveModel { - @Autowired + @Autowired private HttpServletRequest request; - - @Override - @SuppressWarnings("rawtypes") - public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) - throws TemplateException, IOException { - String browser = params.get("name").toString(); - String userAgent = request.getHeader("User-Agent"); - env.getOut().append(""); - - if(userAgent.indexOf(browser)>0){ - body.render(env.getOut()); - } - } + + @Override + @SuppressWarnings("rawtypes") + public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) + throws TemplateException, IOException { + String browser = params.get("name").toString(); + String userAgent = request.getHeader("User-Agent"); + env.getOut().append(""); + + if(userAgent.indexOf(browser)>0){ + body.render(env.getOut()); + } + } } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/FreemarkerTag.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/FreemarkerTag.java index e44550584..c1183d2d6 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/FreemarkerTag.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/FreemarkerTag.java @@ -28,5 +28,5 @@ import org.springframework.stereotype.Component; @Retention(RetentionPolicy.RUNTIME) @Component public @interface FreemarkerTag { - String value() default ""; + String value() default ""; } diff --git a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/LocaleTagDirective.java b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/LocaleTagDirective.java index 9f178e870..1d69412fd 100644 --- a/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/LocaleTagDirective.java +++ b/maxkey-commons/maxkey-core/src/main/java/org/dromara/maxkey/web/tag/LocaleTagDirective.java @@ -69,11 +69,11 @@ public class LocaleTagDirective implements TemplateDirectiveModel { message = WebContext.properties.getProperty("application.formatted-version"); } else if (code.equals("global.logo")) { - if(!message.startsWith("http")) { - message = request.getContextPath() + message; + if(!message.startsWith("http")) { + message = request.getContextPath() + message; } }else if (code.equals("global.title") - ||code.equals("global.consoleTitle")) { + ||code.equals("global.consoleTitle")) { } else { try { diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/Base64Utils.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/Base64Utils.java index 3579e4911..4ce9e73a6 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/Base64Utils.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/Base64Utils.java @@ -62,22 +62,22 @@ public final class Base64Utils { } public static String encodeImage(BufferedImage bufferedImage) { - try { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - ImageIO.write(bufferedImage, "png", stream); - String b64Image = "data:image/png;base64," + - java.util.Base64.getEncoder().encodeToString(stream.toByteArray()); - stream.close(); - return b64Image; - }catch (Exception e) { - e.printStackTrace(); - } - return ""; + try { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + ImageIO.write(bufferedImage, "png", stream); + String b64Image = "data:image/png;base64," + + java.util.Base64.getEncoder().encodeToString(stream.toByteArray()); + stream.close(); + return b64Image; + }catch (Exception e) { + e.printStackTrace(); + } + return ""; } public static String encodeImage(byte[] byteImage) { - return "data:image/png;base64," + - java.util.Base64.getEncoder().encodeToString(byteImage); + return "data:image/png;base64," + + java.util.Base64.getEncoder().encodeToString(byteImage); } /** diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/BytesUtils.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/BytesUtils.java index 13b0401e0..e95e04953 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/BytesUtils.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/BytesUtils.java @@ -22,16 +22,16 @@ import java.io.IOException; import java.io.InputStream; public final class BytesUtils { - - public static String bytes2String(byte[] bytesArray) { - String result = ""; - for (Byte bts : bytesArray) { - result += (char) bts.intValue(); - } - return result; - } - - public static byte[] toByteArray(InputStream input) throws IOException { + + public static String bytes2String(byte[] bytesArray) { + String result = ""; + for (Byte bts : bytesArray) { + result += (char) bts.intValue(); + } + return result; + } + + public static byte[] toByteArray(InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 4]; int n = 0; diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/DigestUtils.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/DigestUtils.java index dcc271bd0..620b37dc5 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/DigestUtils.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/DigestUtils.java @@ -31,38 +31,38 @@ import java.security.NoSuchAlgorithmException; */ public final class DigestUtils { - public final class Algorithm { - - public static final String MD5 = "MD5"; - public static final String SHA = "SHA"; - public static final String SHA1 = "SHA-1"; - public static final String SHA256 = "SHA-256"; - public static final String SHA384 = "SHA-384"; - public static final String SHA512 = "SHA-512"; - - public static final String Base64 = "Base64"; - - } - /** - * @param simple - * @param algorithm MD5,SHA,SHA-1|SHA-256|SHA-384|SHA-512 then encodeBase64 - * @return cipher - */ - public static String digestBase64(String simple,String algorithm) { - MessageDigest messageDigest; - String cipherBASE64=""; - try { - messageDigest = MessageDigest.getInstance(algorithm.toUpperCase()); - messageDigest.update(simple.getBytes()); - byte[] bCipher=messageDigest.digest(); - cipherBASE64=Base64Utils.encodeBase64(bCipher); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } - return cipherBASE64; - } - - /** + public final class Algorithm { + + public static final String MD5 = "MD5"; + public static final String SHA = "SHA"; + public static final String SHA1 = "SHA-1"; + public static final String SHA256 = "SHA-256"; + public static final String SHA384 = "SHA-384"; + public static final String SHA512 = "SHA-512"; + + public static final String Base64 = "Base64"; + + } + /** + * @param simple + * @param algorithm MD5,SHA,SHA-1|SHA-256|SHA-384|SHA-512 then encodeBase64 + * @return cipher + */ + public static String digestBase64(String simple,String algorithm) { + MessageDigest messageDigest; + String cipherBASE64=""; + try { + messageDigest = MessageDigest.getInstance(algorithm.toUpperCase()); + messageDigest.update(simple.getBytes()); + byte[] bCipher=messageDigest.digest(); + cipherBASE64=Base64Utils.encodeBase64(bCipher); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + return cipherBASE64; + } + + /** * @param simple * @param algorithm MD5,SHA,SHA-1|SHA-256|SHA-384|SHA-512 then encodeBase64 * @return cipher @@ -81,80 +81,80 @@ public final class DigestUtils { return cipherBASE64; } - //B64 - public static String md5B64(String simple) { - return digestBase64(simple,Algorithm.MD5); - } - - public static String shaB64(String simple) { - return digestBase64(simple,Algorithm.SHA); - } - - public static String sha1B64(String simple) { - return digestBase64(simple,Algorithm.SHA1); - } - - public static String sha256B64(String simple) { - return digestBase64(simple,Algorithm.SHA256); - } - - public static String sha384B64(String simple) { - return digestBase64(simple,Algorithm.SHA384); - } - - public static String sha512B64(String simple) { - return digestBase64(simple,Algorithm.SHA512); - } - - public static String digestHex(String simple,String algorithm) { - return digestHex( simple.getBytes(),algorithm); - } - - /** - * @param simple - * @param algorithm MD5,SHA,SHA-1|SHA-256|SHA-384|SHA-512 then encodeHexString - * @return cipher - */ - public static String digestHex(byte[] simpleBytes,String algorithm) { - MessageDigest messageDigest; - String cipherHex=""; - try { - messageDigest = MessageDigest.getInstance(algorithm.toUpperCase()); - messageDigest.update(simpleBytes); - byte[] bCipher=messageDigest.digest(); - cipherHex=HexUtils.bytes2HexString(bCipher); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } - return cipherHex; - } - - - //HEX - public static String md5Hex(String simple) { - return digestHex(simple,Algorithm.MD5); - } - - public static String shaHex(String simple) { - return digestHex(simple,Algorithm.SHA); - } - - public static String sha1Hex(String simple) { - return digestHex(simple,Algorithm.SHA1); - } - - public static String sha256Hex(String simple) { - return digestHex(simple,Algorithm.SHA256); - } - - public static String sha384Hex(String simple) { - return digestHex(simple,Algorithm.SHA384); - } - - public static String sha512Hex(String simple) { - return digestHex(simple,Algorithm.SHA512); - } - - - + //B64 + public static String md5B64(String simple) { + return digestBase64(simple,Algorithm.MD5); + } + + public static String shaB64(String simple) { + return digestBase64(simple,Algorithm.SHA); + } + + public static String sha1B64(String simple) { + return digestBase64(simple,Algorithm.SHA1); + } + + public static String sha256B64(String simple) { + return digestBase64(simple,Algorithm.SHA256); + } + + public static String sha384B64(String simple) { + return digestBase64(simple,Algorithm.SHA384); + } + + public static String sha512B64(String simple) { + return digestBase64(simple,Algorithm.SHA512); + } + + public static String digestHex(String simple,String algorithm) { + return digestHex( simple.getBytes(),algorithm); + } + + /** + * @param simple + * @param algorithm MD5,SHA,SHA-1|SHA-256|SHA-384|SHA-512 then encodeHexString + * @return cipher + */ + public static String digestHex(byte[] simpleBytes,String algorithm) { + MessageDigest messageDigest; + String cipherHex=""; + try { + messageDigest = MessageDigest.getInstance(algorithm.toUpperCase()); + messageDigest.update(simpleBytes); + byte[] bCipher=messageDigest.digest(); + cipherHex=HexUtils.bytes2HexString(bCipher); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + return cipherHex; + } + + + //HEX + public static String md5Hex(String simple) { + return digestHex(simple,Algorithm.MD5); + } + + public static String shaHex(String simple) { + return digestHex(simple,Algorithm.SHA); + } + + public static String sha1Hex(String simple) { + return digestHex(simple,Algorithm.SHA1); + } + + public static String sha256Hex(String simple) { + return digestHex(simple,Algorithm.SHA256); + } + + public static String sha384Hex(String simple) { + return digestHex(simple,Algorithm.SHA384); + } + + public static String sha512Hex(String simple) { + return digestHex(simple,Algorithm.SHA512); + } + + + } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/HexUtils.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/HexUtils.java index 1f986da1a..652865e52 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/HexUtils.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/HexUtils.java @@ -28,54 +28,54 @@ import java.io.UnsupportedEncodingException; */ public final class HexUtils { - static final byte[] HEX_CHAR_TABLE = { - (byte) '0', (byte) '1', (byte) '2',(byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', - (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', (byte) 'c',(byte) 'd', (byte) 'e', (byte) 'f' - }; - - - public static String hex2String(byte[] b) { - String result = ""; - for (int i = 0; i < b.length; i++) { - result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1); - } - return result; - } + static final byte[] HEX_CHAR_TABLE = { + (byte) '0', (byte) '1', (byte) '2',(byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', + (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', (byte) 'c',(byte) 'd', (byte) 'e', (byte) 'f' + }; + + + public static String hex2String(byte[] b) { + String result = ""; + for (int i = 0; i < b.length; i++) { + result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1); + } + return result; + } - public static String bytes2HexString(byte[] raw) { - byte[] hex = new byte[2 * raw.length]; - int index = 0; + public static String bytes2HexString(byte[] raw) { + byte[] hex = new byte[2 * raw.length]; + int index = 0; - for (byte b : raw) { - int v = b & 0xFF; - hex[index++] = HEX_CHAR_TABLE[v >>> 4]; - hex[index++] = HEX_CHAR_TABLE[v & 0xF]; - } - String s = ""; - try { - s = new String(hex, "ASCII"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - return s; - } - - public static byte[] hex2Bytes(char[] hex) { - int length = hex.length / 2; - byte[] raw = new byte[length]; - for (int i = 0; i < length; i++) { - int high = Character.digit(hex[i * 2], 16); - int low = Character.digit(hex[i * 2 + 1], 16); - int value = (high << 4) | low; - if (value > 127) { - value -= 256; - } - raw[i] = (byte) value; - } - return raw; - } - - public static byte[] hex2Bytes(String hex) { - return hex2Bytes(hex.toCharArray()); - } + for (byte b : raw) { + int v = b & 0xFF; + hex[index++] = HEX_CHAR_TABLE[v >>> 4]; + hex[index++] = HEX_CHAR_TABLE[v & 0xF]; + } + String s = ""; + try { + s = new String(hex, "ASCII"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return s; + } + + public static byte[] hex2Bytes(char[] hex) { + int length = hex.length / 2; + byte[] raw = new byte[length]; + for (int i = 0; i < length; i++) { + int high = Character.digit(hex[i * 2], 16); + int low = Character.digit(hex[i * 2 + 1], 16); + int value = (high << 4) | low; + if (value > 127) { + value -= 256; + } + raw[i] = (byte) value; + } + return raw; + } + + public static byte[] hex2Bytes(String hex) { + return hex2Bytes(hex.toCharArray()); + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/KeyPairSize.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/KeyPairSize.java index d12378325..daf832fd5 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/KeyPairSize.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/KeyPairSize.java @@ -18,9 +18,9 @@ package org.dromara.maxkey.crypto; public class KeyPairSize { - - public static final int KEY_SIZE_1024 = 1024; - - public static final int KEY_SIZE_2048 = 2048; - + + public static final int KEY_SIZE_1024 = 1024; + + public static final int KEY_SIZE_2048 = 2048; + } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/KeyPairType.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/KeyPairType.java index e957625c8..6b852e523 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/KeyPairType.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/KeyPairType.java @@ -29,10 +29,10 @@ package org.dromara.maxkey.crypto; * Standard Names */ public enum KeyPairType { - /** RSA key pair type. */ - RSA, - /** DSA key pair type. */ - DSA, - /** ECDSA key pair type. */ - ECDSA; + /** RSA key pair type. */ + RSA, + /** DSA key pair type. */ + DSA, + /** ECDSA key pair type. */ + ECDSA; } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/KeyPairUtil.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/KeyPairUtil.java index 59759e22d..5b5b88fdd 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/KeyPairUtil.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/KeyPairUtil.java @@ -56,191 +56,191 @@ import org.slf4j.LoggerFactory; */ public final class KeyPairUtil { - /** Logger */ - private static final Logger _logger = LoggerFactory.getLogger(KeyPairUtil.class); + /** Logger */ + private static final Logger _logger = LoggerFactory.getLogger(KeyPairUtil.class); - /** Constant representing unknown key size */ - public static final int UNKNOWN_KEY_SIZE = -1; - - public static final int DEFAULT_KEY_SIZE = 1024; - - public static final String PUBLIC_KEY = "publicKey"; + /** Constant representing unknown key size */ + public static final int UNKNOWN_KEY_SIZE = -1; + + public static final int DEFAULT_KEY_SIZE = 1024; + + public static final String PUBLIC_KEY = "publicKey"; - public static final String PRIVATE_KEY = "privateKey"; + public static final String PRIVATE_KEY = "privateKey"; - /** - * Private to prevent construction. - */ - private KeyPairUtil() - { - // Nothing to do - } - - - public static KeyPair genKeyPair(KeyPairType keyPairType) throws CryptoException, NoSuchProviderException{ - return genKeyPair( keyPairType, DEFAULT_KEY_SIZE); - } - /** - * Generate a key pair. - * - * @param keyPairType Key pair type to generate - * @param iKeySize Key size of key pair - * @return A key pair - * @throws CryptoException If there was a problem generating the key pair - * @throws NoSuchProviderException - */ - public static KeyPair genKeyPair(KeyPairType keyPairType, int keySize)throws CryptoException, NoSuchProviderException - { - try{ - return genKeyPair(keyPairType,null,keySize); - }catch (InvalidParameterException ex){ - ex.printStackTrace(); - throw new CryptoException("Invalid parameter for a ''"+keyPairType+"'' key pair." , ex); - } - } - - public static KeyPair genKeyPair(KeyPairType keyPairType,String provider)throws CryptoException, NoSuchProviderException{ - return genKeyPair(keyPairType,provider,DEFAULT_KEY_SIZE); - } - - /** - * Generate a key pair. - * - * @param keyPairType Key pair type to generate - * @param iKeySize Key size of key pair - * @return A key pair - * @throws CryptoException If there was a problem generating the key pair - * @throws NoSuchProviderException - */ - public static KeyPair genKeyPair(KeyPairType keyPairType,String provider, int keySize)throws CryptoException, NoSuchProviderException - { - try{ - - if(keyPairType==KeyPairType.ECDSA){ - throw new CryptoException("Could not support ''"+keyPairType+"'' key pair."); - } + /** + * Private to prevent construction. + */ + private KeyPairUtil() + { + // Nothing to do + } + + + public static KeyPair genKeyPair(KeyPairType keyPairType) throws CryptoException, NoSuchProviderException{ + return genKeyPair( keyPairType, DEFAULT_KEY_SIZE); + } + /** + * Generate a key pair. + * + * @param keyPairType Key pair type to generate + * @param iKeySize Key size of key pair + * @return A key pair + * @throws CryptoException If there was a problem generating the key pair + * @throws NoSuchProviderException + */ + public static KeyPair genKeyPair(KeyPairType keyPairType, int keySize)throws CryptoException, NoSuchProviderException + { + try{ + return genKeyPair(keyPairType,null,keySize); + }catch (InvalidParameterException ex){ + ex.printStackTrace(); + throw new CryptoException("Invalid parameter for a ''"+keyPairType+"'' key pair." , ex); + } + } + + public static KeyPair genKeyPair(KeyPairType keyPairType,String provider)throws CryptoException, NoSuchProviderException{ + return genKeyPair(keyPairType,provider,DEFAULT_KEY_SIZE); + } + + /** + * Generate a key pair. + * + * @param keyPairType Key pair type to generate + * @param iKeySize Key size of key pair + * @return A key pair + * @throws CryptoException If there was a problem generating the key pair + * @throws NoSuchProviderException + */ + public static KeyPair genKeyPair(KeyPairType keyPairType,String provider, int keySize)throws CryptoException, NoSuchProviderException + { + try{ + + if(keyPairType==KeyPairType.ECDSA){ + throw new CryptoException("Could not support ''"+keyPairType+"'' key pair."); + } - KeyPairGenerator keyPairGenerator =null; - if(provider==null){ - keyPairGenerator = KeyPairGenerator.getInstance(keyPairType.name()); - }else{ - keyPairGenerator = KeyPairGenerator.getInstance(keyPairType.name(),provider); - } - - // Create a SecureRandom - SecureRandom rand = SecureRandom.getInstance("SHA1PRNG"); - //SecureRandom rand = new SecureRandom(); - // Initialize key pair generator with key strength and a randomness - keyPairGenerator.initialize(keySize, rand); + KeyPairGenerator keyPairGenerator =null; + if(provider==null){ + keyPairGenerator = KeyPairGenerator.getInstance(keyPairType.name()); + }else{ + keyPairGenerator = KeyPairGenerator.getInstance(keyPairType.name(),provider); + } + + // Create a SecureRandom + SecureRandom rand = SecureRandom.getInstance("SHA1PRNG"); + //SecureRandom rand = new SecureRandom(); + // Initialize key pair generator with key strength and a randomness + keyPairGenerator.initialize(keySize, rand); - // Generate and return the key pair - return keyPairGenerator.generateKeyPair(); - }catch (NoSuchAlgorithmException ex){ - ex.printStackTrace(); - throw new CryptoException("Could not generate ''"+keyPairType+"'' key pair.", ex); - }catch (InvalidParameterException ex){ - ex.printStackTrace(); - throw new CryptoException("Invalid parameter for a ''"+keyPairType+"'' key pair." , ex); - } - } - - - public static Map genKeyPairMap(KeyPairType keyPairType) throws Exception { - return genKeyPairMap(keyPairType,DEFAULT_KEY_SIZE); - } - - - public static Map genKeyPairMap(KeyPairType keyPairType, int keySize) throws Exception { - Map keyMap = new HashMap(2); - - if(keyPairType==KeyPairType.RSA){ - KeyPair keyPair=genKeyPair(keyPairType,keySize); - RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); - RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); - keyMap.put(PUBLIC_KEY , publicKey); - keyMap.put(PRIVATE_KEY, privateKey); - - }else if(keyPairType==KeyPairType.DSA){ - KeyPair keyPair=genKeyPair(keyPairType,keySize); - DSAPublicKey publicKey = (DSAPublicKey) keyPair.getPublic(); - DSAPrivateKey privateKey = (DSAPrivateKey) keyPair.getPrivate(); - keyMap.put(PUBLIC_KEY , publicKey); - keyMap.put(PRIVATE_KEY, privateKey); - } - - return keyMap; - } - - + // Generate and return the key pair + return keyPairGenerator.generateKeyPair(); + }catch (NoSuchAlgorithmException ex){ + ex.printStackTrace(); + throw new CryptoException("Could not generate ''"+keyPairType+"'' key pair.", ex); + }catch (InvalidParameterException ex){ + ex.printStackTrace(); + throw new CryptoException("Invalid parameter for a ''"+keyPairType+"'' key pair." , ex); + } + } + + + public static Map genKeyPairMap(KeyPairType keyPairType) throws Exception { + return genKeyPairMap(keyPairType,DEFAULT_KEY_SIZE); + } + + + public static Map genKeyPairMap(KeyPairType keyPairType, int keySize) throws Exception { + Map keyMap = new HashMap(2); + + if(keyPairType==KeyPairType.RSA){ + KeyPair keyPair=genKeyPair(keyPairType,keySize); + RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); + RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); + keyMap.put(PUBLIC_KEY , publicKey); + keyMap.put(PRIVATE_KEY, privateKey); + + }else if(keyPairType==KeyPairType.DSA){ + KeyPair keyPair=genKeyPair(keyPairType,keySize); + DSAPublicKey publicKey = (DSAPublicKey) keyPair.getPublic(); + DSAPrivateKey privateKey = (DSAPrivateKey) keyPair.getPrivate(); + keyMap.put(PUBLIC_KEY , publicKey); + keyMap.put(PRIVATE_KEY, privateKey); + } + + return keyMap; + } + + - public static String getPublicKey(Map keyMap) throws Exception { - Key key = (Key) keyMap.get(PUBLIC_KEY); - return Base64Utils.encoder(key.getEncoded()); - } + public static String getPublicKey(Map keyMap) throws Exception { + Key key = (Key) keyMap.get(PUBLIC_KEY); + return Base64Utils.encoder(key.getEncoded()); + } - - public static String getPrivateKey(Map keyMap) throws Exception { - Key key = (Key) keyMap.get(PRIVATE_KEY); - return Base64Utils.encoder(key.getEncoded()); - } + + public static String getPrivateKey(Map keyMap) throws Exception { + Key key = (Key) keyMap.get(PRIVATE_KEY); + return Base64Utils.encoder(key.getEncoded()); + } - /** - * Get the key size of a public key. - * - * @param pubKey The public key - * @return The key size, {@link #UNKNOWN_KEY_SIZE} if not known - */ - public static int getKeyLength(PublicKey pubKey) - { - if (pubKey instanceof RSAKey) - { - return ((RSAKey) pubKey).getModulus().bitLength(); - } - else if (pubKey instanceof DSAKey) - { - return ((DSAKey) pubKey).getParams().getP().bitLength(); - } - else if (pubKey instanceof DHKey) - { - return ((DHKey) pubKey).getParams().getP().bitLength(); - } - else if (pubKey instanceof ECKey) - { - // how to get key size from these? - return UNKNOWN_KEY_SIZE; - } + /** + * Get the key size of a public key. + * + * @param pubKey The public key + * @return The key size, {@link #UNKNOWN_KEY_SIZE} if not known + */ + public static int getKeyLength(PublicKey pubKey) + { + if (pubKey instanceof RSAKey) + { + return ((RSAKey) pubKey).getModulus().bitLength(); + } + else if (pubKey instanceof DSAKey) + { + return ((DSAKey) pubKey).getParams().getP().bitLength(); + } + else if (pubKey instanceof DHKey) + { + return ((DHKey) pubKey).getParams().getP().bitLength(); + } + else if (pubKey instanceof ECKey) + { + // how to get key size from these? + return UNKNOWN_KEY_SIZE; + } - _logger.warn("Don't know how to get key size from key " + pubKey); - return UNKNOWN_KEY_SIZE; - } + _logger.warn("Don't know how to get key size from key " + pubKey); + return UNKNOWN_KEY_SIZE; + } - /** - * Get the key size of a key represented by key parameters. - * - * @param keyParams The key parameters - * @return The key size, {@link #UNKNOWN_KEY_SIZE} if not known - */ - public static int getKeyLength(AsymmetricKeyParameter keyParams) - { - if (keyParams instanceof RSAKeyParameters) - { - return ((RSAKeyParameters) keyParams).getModulus().bitLength(); - } - else if (keyParams instanceof DSAKeyParameters) - { - return ((DSAKeyParameters) keyParams).getParameters().getP().bitLength(); - } - else if (keyParams instanceof DHKeyParameters) - { - return ((DHKeyParameters) keyParams).getParameters().getP().bitLength(); - } - else if (keyParams instanceof ECKeyParameters) - { - // how to get key length from these? - return UNKNOWN_KEY_SIZE; - } + /** + * Get the key size of a key represented by key parameters. + * + * @param keyParams The key parameters + * @return The key size, {@link #UNKNOWN_KEY_SIZE} if not known + */ + public static int getKeyLength(AsymmetricKeyParameter keyParams) + { + if (keyParams instanceof RSAKeyParameters) + { + return ((RSAKeyParameters) keyParams).getModulus().bitLength(); + } + else if (keyParams instanceof DSAKeyParameters) + { + return ((DSAKeyParameters) keyParams).getParameters().getP().bitLength(); + } + else if (keyParams instanceof DHKeyParameters) + { + return ((DHKeyParameters) keyParams).getParameters().getP().bitLength(); + } + else if (keyParams instanceof ECKeyParameters) + { + // how to get key length from these? + return UNKNOWN_KEY_SIZE; + } - _logger.warn("Don't know how to get key size from parameters " + keyParams); - return UNKNOWN_KEY_SIZE; - } + _logger.warn("Don't know how to get key size from parameters " + keyParams); + return UNKNOWN_KEY_SIZE; + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/Md5Sum.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/Md5Sum.java index 143a859e2..4baf15776 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/Md5Sum.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/Md5Sum.java @@ -37,95 +37,95 @@ import org.springframework.core.io.ClassPathResource; * */ public class Md5Sum { - - static String passSum ="$2a$10$Yju1npqje5sMN/CYhXjogO4e707d7318e6ba7b763098f03779fd47877a7bf4780c1c219be9c280646eace0f44dc4d426be8fa50415e507786424e887c2b266add267cea005a0daf9f019a152f16b30a8631e4872def2e9a9872d44"; - - /** - * - */ - public Md5Sum() { + + static String passSum ="$2a$10$Yju1npqje5sMN/CYhXjogO4e707d7318e6ba7b763098f03779fd47877a7bf4780c1c219be9c280646eace0f44dc4d426be8fa50415e507786424e887c2b266add267cea005a0daf9f019a152f16b30a8631e4872def2e9a9872d44"; + + /** + * + */ + public Md5Sum() { - } + } - public static String produce(File file) { - String md5value = null; - FileInputStream in = null; - try { - in = new FileInputStream(file); - MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length()); - MessageDigest messageDigest = MessageDigest.getInstance("MD5"); - messageDigest.update(byteBuffer); - byte[] bCipher=messageDigest.digest(); - md5value=HexUtils.bytes2HexString(bCipher); - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (null != in) { - try { - in.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - md5value += " *"+file.getName(); - return md5value; - } - - public static String produce(InputStream is,String fileName) { - String md5value = ""; - try { - MessageDigest messageDigest = MessageDigest.getInstance("MD5"); - messageDigest.update(BytesUtils.toByteArray(is)); - byte[] bCipher=messageDigest.digest(); - md5value=HexUtils.bytes2HexString(bCipher); - md5value += " *"+fileName; - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (null != is) { - try { - is.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - return md5value; - } - - public static boolean check(File file,String md5String) { - String md5value = produce(file); - - return md5value.equals(md5String)?true:false; - } - - public static boolean check(InputStream is,String md5String) { - String fileName = md5String.split("\\*")[1]; - String md5value = produce(is,fileName); - - return md5value.equals(md5String)?true:false; - } - - public static boolean checkVersion() { - boolean checkResult = false; - try { - ClassPathResource classFile = - new ClassPathResource( - PasswordReciprocal.getInstance().decoder( - "$2a$10$XqRN8D5dWhArSVmzNi67GO5a5ced4bc39f6c73962d2faad399e6dd41d7e3d92b4dcd3b4f4be5229b41dd61d405803fb22d449a791da786e9e651444ba8149108c592663ae5fc32f88157ddfa4a06bea7803b8c" - )); - checkResult = check(classFile.getInputStream(),PasswordReciprocal.getInstance().decoder(passSum)); - } catch (IOException e) { - e.printStackTrace(); - } - - if( !checkResult ) { - System.exit(0); - } - - return checkResult; - } + public static String produce(File file) { + String md5value = null; + FileInputStream in = null; + try { + in = new FileInputStream(file); + MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length()); + MessageDigest messageDigest = MessageDigest.getInstance("MD5"); + messageDigest.update(byteBuffer); + byte[] bCipher=messageDigest.digest(); + md5value=HexUtils.bytes2HexString(bCipher); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (null != in) { + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + md5value += " *"+file.getName(); + return md5value; + } + + public static String produce(InputStream is,String fileName) { + String md5value = ""; + try { + MessageDigest messageDigest = MessageDigest.getInstance("MD5"); + messageDigest.update(BytesUtils.toByteArray(is)); + byte[] bCipher=messageDigest.digest(); + md5value=HexUtils.bytes2HexString(bCipher); + md5value += " *"+fileName; + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (null != is) { + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + return md5value; + } + + public static boolean check(File file,String md5String) { + String md5value = produce(file); + + return md5value.equals(md5String)?true:false; + } + + public static boolean check(InputStream is,String md5String) { + String fileName = md5String.split("\\*")[1]; + String md5value = produce(is,fileName); + + return md5value.equals(md5String)?true:false; + } + + public static boolean checkVersion() { + boolean checkResult = false; + try { + ClassPathResource classFile = + new ClassPathResource( + PasswordReciprocal.getInstance().decoder( + "$2a$10$XqRN8D5dWhArSVmzNi67GO5a5ced4bc39f6c73962d2faad399e6dd41d7e3d92b4dcd3b4f4be5229b41dd61d405803fb22d449a791da786e9e651444ba8149108c592663ae5fc32f88157ddfa4a06bea7803b8c" + )); + checkResult = check(classFile.getInputStream(),PasswordReciprocal.getInstance().decoder(passSum)); + } catch (IOException e) { + e.printStackTrace(); + } + + if( !checkResult ) { + System.exit(0); + } + + return checkResult; + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/RSAUtils.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/RSAUtils.java index 3bb59c58f..f5df88d6c 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/RSAUtils.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/RSAUtils.java @@ -39,269 +39,269 @@ import org.apache.commons.lang3.StringUtils; * */ public final class RSAUtils { - - public static final String KEY_ALGORTHM = "RSA"; - - public static final String LINE_SEPARATOR = "\n"; - - public static final int KEY_SIZE = 1024; - - public static final int PEM_ARRAY_SIZE = 64; - - /** - * gen RSA KeyPair - * @return KeyPair - * @throws Exception - */ - public static KeyPair genRSAKeyPair() throws Exception { - KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORTHM); - keyPairGenerator.initialize(KEY_SIZE); - return keyPairGenerator.generateKeyPair(); - } - - /** - * 通过keyBytes构建私钥 - * @param keyBytes - * @return - * @throws Exception - */ - public static PrivateKey privateKey(byte[] keyBytes)throws Exception { - PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes); - KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); - return keyFactory.generatePrivate(pkcs8EncodedKeySpec); - } - - /** - * 通过keyBytes构建公钥 - * @param keyBytes - * @return - * @throws Exception - */ - public static PublicKey publicKey(byte[] keyBytes)throws Exception { - X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes); - KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); - return keyFactory.generatePublic(x509EncodedKeySpec); - } - - /** - * 私钥加密 - * @param data 明文数据 - * @param hexKey 私钥HEX编码 - * @return - * @throws Exception - */ - public static byte[] encryptByPrivateKey(byte[] data, String hexKey)throws Exception { - byte[] keyBytes = HexUtils.hex2Bytes(hexKey); - return encryptByPrivateKey(data,keyBytes); - } - - /** - * 私钥加密 - * @param data 明文数据 - * @param hexKey 私钥 - * @return - * @throws Exception - */ - public static byte[] encryptByPrivateKey(byte[] data, byte[] keyBytes)throws Exception { - KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); - Key privateKey = privateKey(keyBytes); + + public static final String KEY_ALGORTHM = "RSA"; + + public static final String LINE_SEPARATOR = "\n"; + + public static final int KEY_SIZE = 1024; + + public static final int PEM_ARRAY_SIZE = 64; + + /** + * gen RSA KeyPair + * @return KeyPair + * @throws Exception + */ + public static KeyPair genRSAKeyPair() throws Exception { + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORTHM); + keyPairGenerator.initialize(KEY_SIZE); + return keyPairGenerator.generateKeyPair(); + } + + /** + * 通过keyBytes构建私钥 + * @param keyBytes + * @return + * @throws Exception + */ + public static PrivateKey privateKey(byte[] keyBytes)throws Exception { + PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes); + KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); + return keyFactory.generatePrivate(pkcs8EncodedKeySpec); + } + + /** + * 通过keyBytes构建公钥 + * @param keyBytes + * @return + * @throws Exception + */ + public static PublicKey publicKey(byte[] keyBytes)throws Exception { + X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes); + KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); + return keyFactory.generatePublic(x509EncodedKeySpec); + } + + /** + * 私钥加密 + * @param data 明文数据 + * @param hexKey 私钥HEX编码 + * @return + * @throws Exception + */ + public static byte[] encryptByPrivateKey(byte[] data, String hexKey)throws Exception { + byte[] keyBytes = HexUtils.hex2Bytes(hexKey); + return encryptByPrivateKey(data,keyBytes); + } + + /** + * 私钥加密 + * @param data 明文数据 + * @param hexKey 私钥 + * @return + * @throws Exception + */ + public static byte[] encryptByPrivateKey(byte[] data, byte[] keyBytes)throws Exception { + KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); + Key privateKey = privateKey(keyBytes); - Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); - cipher.init(Cipher.ENCRYPT_MODE, privateKey); + Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); + cipher.init(Cipher.ENCRYPT_MODE, privateKey); - return cipher.doFinal(data); - } - + return cipher.doFinal(data); + } + - /** - * 私钥解密 - * @param data 解密数据 - * @param hexKey 私钥HEX编码 - * @return 明文数据 - * @throws Exception - */ - public static byte[] decryptByPrivateKey(byte[] data, String hexKey)throws Exception { - // 私钥HEX编码转换为byte - byte[] keyBytes = HexUtils.hex2Bytes(hexKey); - - return decryptByPrivateKey(data,keyBytes); - } - - /** - * 私钥解密 - * @param data 解密数据 - * @param keyBytes 私钥 - * @return 明文数据 - * @throws Exception - */ - public static byte[] decryptByPrivateKey(byte[] data, byte[] keyBytes)throws Exception { - KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); - Key privateKey = privateKey(keyBytes); - // 解密 - Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); - cipher.init(Cipher.DECRYPT_MODE, privateKey); + /** + * 私钥解密 + * @param data 解密数据 + * @param hexKey 私钥HEX编码 + * @return 明文数据 + * @throws Exception + */ + public static byte[] decryptByPrivateKey(byte[] data, String hexKey)throws Exception { + // 私钥HEX编码转换为byte + byte[] keyBytes = HexUtils.hex2Bytes(hexKey); + + return decryptByPrivateKey(data,keyBytes); + } + + /** + * 私钥解密 + * @param data 解密数据 + * @param keyBytes 私钥 + * @return 明文数据 + * @throws Exception + */ + public static byte[] decryptByPrivateKey(byte[] data, byte[] keyBytes)throws Exception { + KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); + Key privateKey = privateKey(keyBytes); + // 解密 + Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); + cipher.init(Cipher.DECRYPT_MODE, privateKey); - return cipher.doFinal(data); - } + return cipher.doFinal(data); + } - /** - * 公钥解密 - * @param data 明文数据 - * @param hexKey 公钥HEX - * @return 密文 - * @throws Exception - */ - public static byte[] encryptByPublicKey(byte[] data, String hexKey)throws Exception { - // �Թ�Կ���� - byte[] keyBytes = HexUtils.hex2Bytes(hexKey); - return encryptByPublicKey(data,keyBytes); - } - - /** - * 公钥解密 - * @param data 明文数据 - * @param hexKey 公钥 - * @return 密文 - * @throws Exception - */ - public static byte[] encryptByPublicKey(byte[] data, byte[] keyBytes)throws Exception { - KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); - Key publicKey = publicKey(keyBytes); + /** + * 公钥解密 + * @param data 明文数据 + * @param hexKey 公钥HEX + * @return 密文 + * @throws Exception + */ + public static byte[] encryptByPublicKey(byte[] data, String hexKey)throws Exception { + // �Թ�Կ���� + byte[] keyBytes = HexUtils.hex2Bytes(hexKey); + return encryptByPublicKey(data,keyBytes); + } + + /** + * 公钥解密 + * @param data 明文数据 + * @param hexKey 公钥 + * @return 密文 + * @throws Exception + */ + public static byte[] encryptByPublicKey(byte[] data, byte[] keyBytes)throws Exception { + KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); + Key publicKey = publicKey(keyBytes); - // ����ݽ��� - Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); - cipher.init(Cipher.ENCRYPT_MODE, publicKey); + // ����ݽ��� + Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); + cipher.init(Cipher.ENCRYPT_MODE, publicKey); - return cipher.doFinal(data); - } + return cipher.doFinal(data); + } - /** - * 公钥解密 - * @param data 密文数据 - * @param hexKey 公钥HEX - * @return 明文 - * @throws Exception - */ - public static byte[] decryptByPublicKey(byte[] data, String hexKey)throws Exception { - // hexKey 公钥HEX转换为byte - byte[] keyBytes = HexUtils.hex2Bytes(hexKey); - return decryptByPublicKey(data,keyBytes); - } - - /** - * 公钥解密 - * @param data 密文数据 - * @param keyBytes 公钥 - * @return 明文 - * @throws Exception - */ - public static byte[] decryptByPublicKey(byte[] data, byte[] keyBytes)throws Exception { - - KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); - Key publicKey = publicKey(keyBytes); + /** + * 公钥解密 + * @param data 密文数据 + * @param hexKey 公钥HEX + * @return 明文 + * @throws Exception + */ + public static byte[] decryptByPublicKey(byte[] data, String hexKey)throws Exception { + // hexKey 公钥HEX转换为byte + byte[] keyBytes = HexUtils.hex2Bytes(hexKey); + return decryptByPublicKey(data,keyBytes); + } + + /** + * 公钥解密 + * @param data 密文数据 + * @param keyBytes 公钥 + * @return 明文 + * @throws Exception + */ + public static byte[] decryptByPublicKey(byte[] data, byte[] keyBytes)throws Exception { + + KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); + Key publicKey = publicKey(keyBytes); - // 解密 - Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); - cipher.init(Cipher.DECRYPT_MODE, publicKey); + // 解密 + Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); + cipher.init(Cipher.DECRYPT_MODE, publicKey); - return cipher.doFinal(data); - } - - public static byte[] sign(byte[] src, RSAPrivateKey privateKey, String algorithm) { - if(StringUtils.isBlank(algorithm)) { - algorithm = "SHA1withRSA"; - } - try { - Signature signature = Signature.getInstance(algorithm); - signature.initSign(privateKey); - signature.update(src); - return signature.sign(); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - public static boolean verify(byte[] sign, byte[] src, RSAPublicKey publicKey, String algorithm) { - try { - if(StringUtils.isBlank(algorithm)) { - algorithm = "SHA1withRSA"; - } - - Signature signature = Signature.getInstance(algorithm); - signature.initVerify(publicKey); - signature.update(src); - return signature.verify(sign); - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - /** - * 获取公钥的PEM格式 - * @param encoded 公钥 - * @return PEM格式公钥 - */ - public static String getPublicKeyPEM(byte[] encoded) { - StringBuffer base64String = - new StringBuffer(""); - base64String.append("-----BEGIN PUBLIC KEY-----").append(LINE_SEPARATOR); - base64String.append(getBase64PEM(encoded)).append(LINE_SEPARATOR); - base64String.append("-----END PUBLIC KEY-----").append(LINE_SEPARATOR); - return base64String.toString(); - } - - /** - * 获取私钥的PEM格式 - * @param encoded 私钥 - * @return PEM格式私钥 - */ - public static String getPrivateKeyPEM(byte[] encoded) { - StringBuffer base64String = - new StringBuffer(""); - base64String.append("-----BEGIN RSA PRIVATE KEY-----").append(LINE_SEPARATOR); - base64String.append(getBase64PEM(encoded)).append(LINE_SEPARATOR); - base64String.append("-----END RSA PRIVATE KEY-----").append(LINE_SEPARATOR); - return base64String.toString(); - } - - /** - * 获取Certificate的PEM格式 - * @param encoded 公钥 - * @return PEM格式公钥 - */ - public static String getCertificatePEM(byte[] encoded) { - StringBuffer base64String = - new StringBuffer(""); - base64String.append("-----BEGIN CERTIFICATE-----").append(LINE_SEPARATOR); - base64String.append(getBase64PEM(encoded)).append(LINE_SEPARATOR); - base64String.append("-----END CERTIFICATE-----").append(LINE_SEPARATOR); - return base64String.toString(); - } - - /** - * 获取密钥的PEM格式 - * @param encoded 密钥 - * @return PEM格式密钥 - */ - public static String getBase64PEM(byte[] encoded) { - String base64String = - Base64.getMimeEncoder(PEM_ARRAY_SIZE,LINE_SEPARATOR.getBytes()).encodeToString(encoded); - //StringBuffer base64ArrayString = new StringBuffer(""); - //int startPosition = 0; - //int endPosition = PEM_ARRAY_SIZE; - //while(endPosition < base64String.length()) { - // base64ArrayString.append(base64String.substring(startPosition, endPosition)).append("\n"); - // startPosition = endPosition; - // endPosition = endPosition + PEM_ARRAY_SIZE; - //} - //if(startPosition < base64String.length()) { - // base64ArrayString.append(base64String.substring(startPosition)).append("\n"); - //} - - //return base64ArrayString.toString(); - return base64String; - } + return cipher.doFinal(data); + } + + public static byte[] sign(byte[] src, RSAPrivateKey privateKey, String algorithm) { + if(StringUtils.isBlank(algorithm)) { + algorithm = "SHA1withRSA"; + } + try { + Signature signature = Signature.getInstance(algorithm); + signature.initSign(privateKey); + signature.update(src); + return signature.sign(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static boolean verify(byte[] sign, byte[] src, RSAPublicKey publicKey, String algorithm) { + try { + if(StringUtils.isBlank(algorithm)) { + algorithm = "SHA1withRSA"; + } + + Signature signature = Signature.getInstance(algorithm); + signature.initVerify(publicKey); + signature.update(src); + return signature.verify(sign); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 获取公钥的PEM格式 + * @param encoded 公钥 + * @return PEM格式公钥 + */ + public static String getPublicKeyPEM(byte[] encoded) { + StringBuffer base64String = + new StringBuffer(""); + base64String.append("-----BEGIN PUBLIC KEY-----").append(LINE_SEPARATOR); + base64String.append(getBase64PEM(encoded)).append(LINE_SEPARATOR); + base64String.append("-----END PUBLIC KEY-----").append(LINE_SEPARATOR); + return base64String.toString(); + } + + /** + * 获取私钥的PEM格式 + * @param encoded 私钥 + * @return PEM格式私钥 + */ + public static String getPrivateKeyPEM(byte[] encoded) { + StringBuffer base64String = + new StringBuffer(""); + base64String.append("-----BEGIN RSA PRIVATE KEY-----").append(LINE_SEPARATOR); + base64String.append(getBase64PEM(encoded)).append(LINE_SEPARATOR); + base64String.append("-----END RSA PRIVATE KEY-----").append(LINE_SEPARATOR); + return base64String.toString(); + } + + /** + * 获取Certificate的PEM格式 + * @param encoded 公钥 + * @return PEM格式公钥 + */ + public static String getCertificatePEM(byte[] encoded) { + StringBuffer base64String = + new StringBuffer(""); + base64String.append("-----BEGIN CERTIFICATE-----").append(LINE_SEPARATOR); + base64String.append(getBase64PEM(encoded)).append(LINE_SEPARATOR); + base64String.append("-----END CERTIFICATE-----").append(LINE_SEPARATOR); + return base64String.toString(); + } + + /** + * 获取密钥的PEM格式 + * @param encoded 密钥 + * @return PEM格式密钥 + */ + public static String getBase64PEM(byte[] encoded) { + String base64String = + Base64.getMimeEncoder(PEM_ARRAY_SIZE,LINE_SEPARATOR.getBytes()).encodeToString(encoded); + //StringBuffer base64ArrayString = new StringBuffer(""); + //int startPosition = 0; + //int endPosition = PEM_ARRAY_SIZE; + //while(endPosition < base64String.length()) { + // base64ArrayString.append(base64String.substring(startPosition, endPosition)).append("\n"); + // startPosition = endPosition; + // endPosition = endPosition + PEM_ARRAY_SIZE; + //} + //if(startPosition < base64String.length()) { + // base64ArrayString.append(base64String.substring(startPosition)).append("\n"); + //} + + //return base64ArrayString.toString(); + return base64String; + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/ReciprocalUtils.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/ReciprocalUtils.java index 6b05e4edd..66cbfdba2 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/ReciprocalUtils.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/ReciprocalUtils.java @@ -178,13 +178,13 @@ public final class ReciprocalUtils { } public static String encode2Hex(String simple, String secretKey) { - String key = generatorDefaultKey(secretKey + defaultKey,Algorithm.DESede); - return encode2Hex(simple,key, Algorithm.DESede); + String key = generatorDefaultKey(secretKey + defaultKey,Algorithm.DESede); + return encode2Hex(simple,key, Algorithm.DESede); } public static String decoderHex(String ciphers, String secretKey) { - String key = generatorDefaultKey(secretKey + defaultKey,Algorithm.DESede); - return decoderHex(ciphers,key,Algorithm.DESede); + String key = generatorDefaultKey(secretKey + defaultKey,Algorithm.DESede); + return decoderHex(ciphers,key,Algorithm.DESede); } private static boolean keyLengthCheck(String secretKey, String algorithm) { @@ -234,16 +234,16 @@ public final class ReciprocalUtils { return decoderHex(ciphers, secretKey, Algorithm.AES); } - public static Object newInstance(String className) { - Class cls; - try { - cls = Class.forName(className); - Constructor constructor = cls.getConstructor(); - return constructor.newInstance(); - } catch (Exception e) { - e.printStackTrace(); - } - return null; + public static Object newInstance(String className) { + Class cls; + try { + cls = Class.forName(className); + Constructor constructor = cls.getConstructor(); + return constructor.newInstance(); + } catch (Exception e) { + e.printStackTrace(); + } + return null; - } + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/CertCrypto.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/CertCrypto.java index a4cc8e664..f0848bce9 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/CertCrypto.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/CertCrypto.java @@ -408,19 +408,19 @@ public class CertCrypto { return bytes; } public static void main(String[] args) throws Exception { -// String result = encryptFileToBase64ByPrivateKey("C:\\sp.cer", "C:\\sp-keystore.jks", "sp", "secret"); -// System.out.println(result); - //Certificate certificate = getCertificate("C:\\sp-keystore.jks", "sp", "secret"); - // System.out.println("certificate 1:"+certificate); - - //File file = new File("C:\\para-keystore.jks"); - //byte[] content = getBytesFromFile(file); - // System.out.println("base64keystore:\n"+Base64.encodeBase64String(content)); - - KeyStore ks = KeyStore.getInstance("JKS"); - String b64EncodedKeystore = "/u3+7QAAAAIAAAACAAAAAQACc3AAAAErlmk7hAAAArowggK2MA4GCisGAQQBKgIRAQEFAASCAqIw4jynaKwOlOP74OM2+0lnYX8MOhvk0r71kvcbv9cusyIua3FJaIg1NBmgDrvF2JcUNcAhnyuBrafzW+3INGs8NNnmsPNgSPQ5cIMKRZ+44xxEmafy+FYPgw5RlmL+gXB/buiK1FzVuukjCR7/GCbQB2T0I1bZn5Ok/U0AlfGnAGBcXOR3efjdtKKImPBtMHQ9kBoCIlgROVKPEcSxPi7fm2SlN+tVjv1y9toYw2wRP+zsW5CAfY2mnRkQg58BtE2LhYhedSUUuaJAWTlWaWqA9rbTZmXlYqqOB/t86aYNuadT8nAu468MIucL3F2RQdMt9xDD3qRidT+h1I7ShnaF7pkUvynE5QKW3EIPhTaiRvMSUf6a984G4WerpdgmbzYEHUC9Kfw6WHcgKcGB5oAg4R2nlyEGLd2SBFv2vMRnXucwuofECK15YqCbu6wZGhQDKiGZo8MNcu8mPCq7vujOl4Azkjx1YyU1VHTQTyHP9BoOqS4lA8SjdEEGOm6p3R+CrwRratgET0UlopMInxuIvnuxXp5Vq4fHuY0GI65MRVQt9mSp5zeYvAYPYLSPmhcE2KchIR1Cb7NPbPID8D/EkNuCxG9FNPBhhtgMRdbOejJ3NPpt43DDt3nTpn/5pgBLsBxQ7hlPOb3Y4hsKCEI4UyVl+fTQieNIyEaAnt2Q/NNVGDJlc4aIAdDEfbOVbVdyYDViHskwTiKDdin4mAqTGj+qr0MVpoye6daZduftG85yx/1AnEjvPqUhKvi1kMKBi6q3z6XUMIq09RaQepx6xMboaiiqCU+Bi9kvdh3XNbnQ64DNPOhzytLAiBApb2IRaY1fkKSYOz+hFj0HbxF1cn5ITaQT1KeestiS+PuBO8JUR1yxTU0JQ4Tea0quTB+ragAAAAEABVguNTA5AAACSjCCAkYwggGvAgRMscTWMA0GCSqGSIb3DQEBBQUAMGoxJDAiBgkqhkiG9w0BCQEWFWphbWVzLnMuY294QGdtYWlsLmNvbTELMAkGA1UEBhMCVVMxGTAXBgNVBAoMEFNlcnZpY2UgUHJvdmlkZXIxCzAJBgNVBAsMAnNwMQ0wCwYDVQQDDARqY294MB4XDTEwMTAxMDEzNTExOFoXDTIwMTAwNzEzNTExOFowajEkMCIGCSqGSIb3DQEJARYVamFtZXMucy5jb3hAZ21haWwuY29tMQswCQYDVQQGEwJVUzEZMBcGA1UECgwQU2VydmljZSBQcm92aWRlcjELMAkGA1UECwwCc3AxDTALBgNVBAMMBGpjb3gwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIvtAFv5pWA6oRlLz/JhEG1Y7+6Wcvc2aU4rAH4PdWlmr5YkpA/gEd/J25AilVIE+c8nQwIzn5rDgJFGoBfjN/jUkKWLcB5jZC8SFzEx5zvGnR9wWgnbBL+jWQTal8M10ilhbRfklYLpkyTrwYWQdpDmMqVrN9wbNgU2imTihooNAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAdwn3tIk3612PRNtkxcuW/O5MKQyoy6KTS7V95KklJX452zebWDeM6/dR+XWVJLhRfN8+87cyos5HMYjIFVUJFNl9W5+UnRK75ku2hHBvPuU3ZTuW3/vGrNOLuaroPqELp+bNbfZkr2hezpeQl/4JKRFE418dvJJXW2OxE4A1K0sAAAACAANpZHAAAAErlm6iEQAFWC41MDkAAAJOMIICSjCCAbMCBEyxxXgwDQYJKoZIhvcNAQEFBQAwbDEkMCIGCSqGSIb3DQEJARYVamFtZXMucy5jb3hAZ21haWwuY29tMQswCQYDVQQGEwJVUzEaMBgGA1UECgwRSWRlbnRpdHkgUHJvdmlkZXIxDDAKBgNVBAsMA2lkcDENMAsGA1UEAwwEamNveDAeFw0xMDEwMTAxMzU0MDBaFw0yMDEwMDcxMzU0MDBaMGwxJDAiBgkqhkiG9w0BCQEWFWphbWVzLnMuY294QGdtYWlsLmNvbTELMAkGA1UEBhMCVVMxGjAYBgNVBAoMEUlkZW50aXR5IFByb3ZpZGVyMQwwCgYDVQQLDANpZHAxDTALBgNVBAMMBGpjb3gwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIt33orAL6MajhA8jeXaf8aPbIX24dlv0HwBBmdLBzkrO0I3bELtKSzbKFBkIwQZKaFHYdT7cxmy1epwffYsX2Ipguz99wGgH92GiWCLuPr14HqMAz/wx/1pAFFERa5rxadq0Jxmk1SF8gdz7FtoQOT0WUnIcs20yXta0Abqd1AxAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAOCsgCB7zc/OrY8u54nUb2apJEZ20sSO48ilzn5PoGBQxFZJIg0E0eBTfCTNGQuF5anI4NZ7Q0gTRT8IBxeiPhksz+5NG4eCb6+4VyKJszx6rY7S6uq/08N3EMru5jyNVEn/o3F1QpwtlMDipH8s+dpuR6sEAcpugQYBH6F1MfI1iptlkKubwxS31ebaol0N4M5BFyA=="; - String keystorePassword = "secret"; - ks.load(new ByteArrayInputStream(Base64Utils.decoder(b64EncodedKeystore)), keystorePassword.toCharArray()); - System.out.println("certificate 2:"+ks.getCertificate("sp")); - } +// String result = encryptFileToBase64ByPrivateKey("C:\\sp.cer", "C:\\sp-keystore.jks", "sp", "secret"); +// System.out.println(result); + //Certificate certificate = getCertificate("C:\\sp-keystore.jks", "sp", "secret"); + // System.out.println("certificate 1:"+certificate); + + //File file = new File("C:\\para-keystore.jks"); + //byte[] content = getBytesFromFile(file); + // System.out.println("base64keystore:\n"+Base64.encodeBase64String(content)); + + KeyStore ks = KeyStore.getInstance("JKS"); + String b64EncodedKeystore = "/u3+7QAAAAIAAAACAAAAAQACc3AAAAErlmk7hAAAArowggK2MA4GCisGAQQBKgIRAQEFAASCAqIw4jynaKwOlOP74OM2+0lnYX8MOhvk0r71kvcbv9cusyIua3FJaIg1NBmgDrvF2JcUNcAhnyuBrafzW+3INGs8NNnmsPNgSPQ5cIMKRZ+44xxEmafy+FYPgw5RlmL+gXB/buiK1FzVuukjCR7/GCbQB2T0I1bZn5Ok/U0AlfGnAGBcXOR3efjdtKKImPBtMHQ9kBoCIlgROVKPEcSxPi7fm2SlN+tVjv1y9toYw2wRP+zsW5CAfY2mnRkQg58BtE2LhYhedSUUuaJAWTlWaWqA9rbTZmXlYqqOB/t86aYNuadT8nAu468MIucL3F2RQdMt9xDD3qRidT+h1I7ShnaF7pkUvynE5QKW3EIPhTaiRvMSUf6a984G4WerpdgmbzYEHUC9Kfw6WHcgKcGB5oAg4R2nlyEGLd2SBFv2vMRnXucwuofECK15YqCbu6wZGhQDKiGZo8MNcu8mPCq7vujOl4Azkjx1YyU1VHTQTyHP9BoOqS4lA8SjdEEGOm6p3R+CrwRratgET0UlopMInxuIvnuxXp5Vq4fHuY0GI65MRVQt9mSp5zeYvAYPYLSPmhcE2KchIR1Cb7NPbPID8D/EkNuCxG9FNPBhhtgMRdbOejJ3NPpt43DDt3nTpn/5pgBLsBxQ7hlPOb3Y4hsKCEI4UyVl+fTQieNIyEaAnt2Q/NNVGDJlc4aIAdDEfbOVbVdyYDViHskwTiKDdin4mAqTGj+qr0MVpoye6daZduftG85yx/1AnEjvPqUhKvi1kMKBi6q3z6XUMIq09RaQepx6xMboaiiqCU+Bi9kvdh3XNbnQ64DNPOhzytLAiBApb2IRaY1fkKSYOz+hFj0HbxF1cn5ITaQT1KeestiS+PuBO8JUR1yxTU0JQ4Tea0quTB+ragAAAAEABVguNTA5AAACSjCCAkYwggGvAgRMscTWMA0GCSqGSIb3DQEBBQUAMGoxJDAiBgkqhkiG9w0BCQEWFWphbWVzLnMuY294QGdtYWlsLmNvbTELMAkGA1UEBhMCVVMxGTAXBgNVBAoMEFNlcnZpY2UgUHJvdmlkZXIxCzAJBgNVBAsMAnNwMQ0wCwYDVQQDDARqY294MB4XDTEwMTAxMDEzNTExOFoXDTIwMTAwNzEzNTExOFowajEkMCIGCSqGSIb3DQEJARYVamFtZXMucy5jb3hAZ21haWwuY29tMQswCQYDVQQGEwJVUzEZMBcGA1UECgwQU2VydmljZSBQcm92aWRlcjELMAkGA1UECwwCc3AxDTALBgNVBAMMBGpjb3gwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIvtAFv5pWA6oRlLz/JhEG1Y7+6Wcvc2aU4rAH4PdWlmr5YkpA/gEd/J25AilVIE+c8nQwIzn5rDgJFGoBfjN/jUkKWLcB5jZC8SFzEx5zvGnR9wWgnbBL+jWQTal8M10ilhbRfklYLpkyTrwYWQdpDmMqVrN9wbNgU2imTihooNAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAdwn3tIk3612PRNtkxcuW/O5MKQyoy6KTS7V95KklJX452zebWDeM6/dR+XWVJLhRfN8+87cyos5HMYjIFVUJFNl9W5+UnRK75ku2hHBvPuU3ZTuW3/vGrNOLuaroPqELp+bNbfZkr2hezpeQl/4JKRFE418dvJJXW2OxE4A1K0sAAAACAANpZHAAAAErlm6iEQAFWC41MDkAAAJOMIICSjCCAbMCBEyxxXgwDQYJKoZIhvcNAQEFBQAwbDEkMCIGCSqGSIb3DQEJARYVamFtZXMucy5jb3hAZ21haWwuY29tMQswCQYDVQQGEwJVUzEaMBgGA1UECgwRSWRlbnRpdHkgUHJvdmlkZXIxDDAKBgNVBAsMA2lkcDENMAsGA1UEAwwEamNveDAeFw0xMDEwMTAxMzU0MDBaFw0yMDEwMDcxMzU0MDBaMGwxJDAiBgkqhkiG9w0BCQEWFWphbWVzLnMuY294QGdtYWlsLmNvbTELMAkGA1UEBhMCVVMxGjAYBgNVBAoMEUlkZW50aXR5IFByb3ZpZGVyMQwwCgYDVQQLDANpZHAxDTALBgNVBAMMBGpjb3gwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIt33orAL6MajhA8jeXaf8aPbIX24dlv0HwBBmdLBzkrO0I3bELtKSzbKFBkIwQZKaFHYdT7cxmy1epwffYsX2Ipguz99wGgH92GiWCLuPr14HqMAz/wx/1pAFFERa5rxadq0Jxmk1SF8gdz7FtoQOT0WUnIcs20yXta0Abqd1AxAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAOCsgCB7zc/OrY8u54nUb2apJEZ20sSO48ilzn5PoGBQxFZJIg0E0eBTfCTNGQuF5anI4NZ7Q0gTRT8IBxeiPhksz+5NG4eCb6+4VyKJszx6rY7S6uq/08N3EMru5jyNVEn/o3F1QpwtlMDipH8s+dpuR6sEAcpugQYBH6F1MfI1iptlkKubwxS31ebaol0N4M5BFyA=="; + String keystorePassword = "secret"; + ks.load(new ByteArrayInputStream(Base64Utils.decoder(b64EncodedKeystore)), keystorePassword.toCharArray()); + System.out.println("certificate 2:"+ks.getCertificate("sp")); + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/CryptoException.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/CryptoException.java index 9b80dfb89..688261d0c 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/CryptoException.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/CryptoException.java @@ -25,48 +25,48 @@ package org.dromara.maxkey.crypto.cert; * Represents a cryptographic exception. */ public class CryptoException extends Exception { - /** - * - */ - private static final long serialVersionUID = -1879905141025077248L; + /** + * + */ + private static final long serialVersionUID = -1879905141025077248L; - /** - * Creates a new CryptoException. - */ - public CryptoException() { - super(); - } + /** + * Creates a new CryptoException. + */ + public CryptoException() { + super(); + } - /** - * Creates a new CryptoException with the specified message. - * - * @param sMessage - * Exception message - */ - public CryptoException(String sMessage) { - super(sMessage); - } + /** + * Creates a new CryptoException with the specified message. + * + * @param sMessage + * Exception message + */ + public CryptoException(String sMessage) { + super(sMessage); + } - /** - * Creates a new CryptoException with the specified message and cause - * throwable. - * - * @param causeThrowable - * The throwable that caused this exception to be thrown - * @param sMessage - * Exception message - */ - public CryptoException(String sMessage, Throwable causeThrowable) { - super(sMessage, causeThrowable); - } + /** + * Creates a new CryptoException with the specified message and cause + * throwable. + * + * @param causeThrowable + * The throwable that caused this exception to be thrown + * @param sMessage + * Exception message + */ + public CryptoException(String sMessage, Throwable causeThrowable) { + super(sMessage, causeThrowable); + } - /** - * Creates a new CryptoException with the specified cause throwable. - * - * @param causeThrowable - * The throwable that caused this exception to be thrown - */ - public CryptoException(Throwable causeThrowable) { - super(causeThrowable); - } + /** + * Creates a new CryptoException with the specified cause throwable. + * + * @param causeThrowable + * The throwable that caused this exception to be thrown + */ + public CryptoException(Throwable causeThrowable) { + super(causeThrowable); + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/NetUtil.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/NetUtil.java index f8e894181..f9c4c2d79 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/NetUtil.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/NetUtil.java @@ -43,165 +43,165 @@ import org.slf4j.LoggerFactory; */ public final class NetUtil { - /** Logger */ - private static final Logger _logger = LoggerFactory.getLogger(NetUtil.class); + /** Logger */ + private static final Logger _logger = LoggerFactory.getLogger(NetUtil.class); - // make this configurable - private static final int CONNECT_TIMEOUT = 10000; + // make this configurable + private static final int CONNECT_TIMEOUT = 10000; - // make this configurable - private static final int READ_TIMEOUT = 20000; + // make this configurable + private static final int READ_TIMEOUT = 20000; - /** - * Private to prevent construction. - */ - private NetUtil() - { - // Nothing to do - } + /** + * Private to prevent construction. + */ + private NetUtil() + { + // Nothing to do + } - /** - * Open an input stream to a GET(-like) operation on an URL. - * - * @param url The URL - * @return Input stream to the URL connection - * @throws IOException If an I/O error occurs - */ - public static InputStream openGetStream(URL url) - throws IOException - { - URLConnection conn = url.openConnection(); + /** + * Open an input stream to a GET(-like) operation on an URL. + * + * @param url The URL + * @return Input stream to the URL connection + * @throws IOException If an I/O error occurs + */ + public static InputStream openGetStream(URL url) + throws IOException + { + URLConnection conn = url.openConnection(); - conn.setConnectTimeout(CONNECT_TIMEOUT); - conn.setReadTimeout(READ_TIMEOUT); + conn.setConnectTimeout(CONNECT_TIMEOUT); + conn.setReadTimeout(READ_TIMEOUT); - // User-Agent? + // User-Agent? - return conn.getInputStream(); - } + return conn.getInputStream(); + } - /** - * Open an input stream to a POST(-like) operation on an URL. - * - * @param url The URL - * @param content Content to POST - * @param contentType Content type - * @return Input stream to the URL connection - * @throws IOException If an I/O error occurs - */ - public static InputStream openPostStream(URL url, byte[] content, String contentType) - throws IOException - { - URLConnection conn = url.openConnection(); - conn.setDoOutput(true); + /** + * Open an input stream to a POST(-like) operation on an URL. + * + * @param url The URL + * @param content Content to POST + * @param contentType Content type + * @return Input stream to the URL connection + * @throws IOException If an I/O error occurs + */ + public static InputStream openPostStream(URL url, byte[] content, String contentType) + throws IOException + { + URLConnection conn = url.openConnection(); + conn.setDoOutput(true); - conn.setConnectTimeout(CONNECT_TIMEOUT); - conn.setReadTimeout(READ_TIMEOUT); + conn.setConnectTimeout(CONNECT_TIMEOUT); + conn.setReadTimeout(READ_TIMEOUT); - // User-Agent? + // User-Agent? - if (contentType != null) - { - conn.setRequestProperty("Content-Type", contentType); - } + if (contentType != null) + { + conn.setRequestProperty("Content-Type", contentType); + } - conn.setRequestProperty("Content-Length", String.valueOf(content.length)); + conn.setRequestProperty("Content-Length", String.valueOf(content.length)); - OutputStream out = conn.getOutputStream(); - try - { - out.write(content); - } - finally - { - out.close(); - } + OutputStream out = conn.getOutputStream(); + try + { + out.write(content); + } + finally + { + out.close(); + } - return conn.getInputStream(); - } + return conn.getInputStream(); + } - /** - * Download the given URL to a temporary local file. The temporary file is marked for deletion at exit. - * - * @param url - * @return URL pointing to the temporary file, url itself if it's a file: one. - * @throws IOException - */ - public static URL download(URL url) - throws IOException - { - if ("file".equals(url.getProtocol())) - { - return url; - } + /** + * Download the given URL to a temporary local file. The temporary file is marked for deletion at exit. + * + * @param url + * @return URL pointing to the temporary file, url itself if it's a file: one. + * @throws IOException + */ + public static URL download(URL url) + throws IOException + { + if ("file".equals(url.getProtocol())) + { + return url; + } - InputStream in = openGetStream(url); - File tempFile = null; - OutputStream out = null; + InputStream in = openGetStream(url); + File tempFile = null; + OutputStream out = null; - try - { - tempFile = Files.createTempFile("portecle",null).toFile(); - out = new BufferedOutputStream(new FileOutputStream(tempFile)); - byte[] buf = new byte[2048]; - int n; - while ((n = in.read(buf)) != -1) - { - out.write(buf, 0, n); - } - out.flush(); - out.close(); - } - catch (IOException e) - { - try - { - if (out != null) - { - out.close(); - } - } - finally - { - if (tempFile != null && !tempFile.delete()) - { - _logger.info("Could not delete temporary file " + tempFile); - } - } - throw e; - } - finally - { - in.close(); - } + try + { + tempFile = Files.createTempFile("portecle",null).toFile(); + out = new BufferedOutputStream(new FileOutputStream(tempFile)); + byte[] buf = new byte[2048]; + int n; + while ((n = in.read(buf)) != -1) + { + out.write(buf, 0, n); + } + out.flush(); + out.close(); + } + catch (IOException e) + { + try + { + if (out != null) + { + out.close(); + } + } + finally + { + if (tempFile != null && !tempFile.delete()) + { + _logger.info("Could not delete temporary file " + tempFile); + } + } + throw e; + } + finally + { + in.close(); + } - tempFile.deleteOnExit(); + tempFile.deleteOnExit(); - return tempFile.toURI().toURL(); - } + return tempFile.toURI().toURL(); + } - /** - * Creates a URL pointing to a URL, URI or a File object. - * - * @param obj Object to create a URI to - * @return URL - * @throws ClassCastException if obj is not a supported object - * @throws MalformedURLException if converting obj to a URL fails - */ - public static URL toURL(Object obj) - throws MalformedURLException - { - if (obj instanceof File) - { - return ((File) obj).toURI().toURL(); - } - else if (obj instanceof URI) - { - return ((URI) obj).toURL(); - } - else - { - return (URL) obj; - } - } + /** + * Creates a URL pointing to a URL, URI or a File object. + * + * @param obj Object to create a URI to + * @return URL + * @throws ClassCastException if obj is not a supported object + * @throws MalformedURLException if converting obj to a URL fails + */ + public static URL toURL(Object obj) + throws MalformedURLException + { + if (obj instanceof File) + { + return ((File) obj).toURI().toURL(); + } + else if (obj instanceof URI) + { + return ((URI) obj).toURL(); + } + else + { + return (URL) obj; + } + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/SignatureType.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/SignatureType.java index 0124463ba..e243c3227 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/SignatureType.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/SignatureType.java @@ -43,147 +43,147 @@ import org.dromara.maxkey.crypto.KeyPairType; */ public enum SignatureType { - /** MD2 with RSA Signature Type */ - MD2withRSA(PKCSObjectIdentifiers.md2WithRSAEncryption.getId()), - /** MD5 with RSA Signature Type */ - MD5withRSA(PKCSObjectIdentifiers.md5WithRSAEncryption.getId()), - /** SHA-1 with RSA Signature Type */ - SHA1withRSA(PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()), - /** SHA-224 with RSA Signature Type */ - SHA224withRSA(PKCSObjectIdentifiers.sha224WithRSAEncryption.getId()), - /** SHA-256 with RSA Signature Type */ - SHA256withRSA(PKCSObjectIdentifiers.sha256WithRSAEncryption.getId()), - /** SHA-384 with RSA Signature Type */ - SHA384withRSA(PKCSObjectIdentifiers.sha384WithRSAEncryption.getId()), - /** SHA-512 with RSA Signature Type */ - SHA512withRSA(PKCSObjectIdentifiers.sha512WithRSAEncryption.getId()), - /** RIPEMD128 with RSA Signature Type */ - RIPEMD128withRSA(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128.getId()), - /** RIPEMD160 with RSA Signature Type */ - RIPEMD160withRSA(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160.getId()), - /** RIPEMD256 with RSA Signature Type */ - RIPEMD256withRSA(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256.getId()), - /** SHA-1 with DSA Signature Type */ - SHA1withDSA(X9ObjectIdentifiers.id_dsa_with_sha1.getId()), - /** SHA-224 with DSA signature type */ - SHA224withDSA(NISTObjectIdentifiers.dsa_with_sha224.getId()), - /** SHA-256 with DSA signature type */ - SHA256withDSA(NISTObjectIdentifiers.dsa_with_sha256.getId()), - /** SHA-384 with DSA signature type */ - SHA384withDSA(NISTObjectIdentifiers.dsa_with_sha384.getId()), - /** SHA-512 with DSA signature type */ - SHA512withDSA(NISTObjectIdentifiers.dsa_with_sha512.getId()), - /** SHA-1 with ECDSA Signature Type */ - SHA1withECDSA(X9ObjectIdentifiers.ecdsa_with_SHA1.getId()), - /** SHA-224 with ECDSA Signature Type */ - SHA224withECDSA(X9ObjectIdentifiers.ecdsa_with_SHA224.getId()), - /** SHA-256 with ECDSA Signature Type */ - SHA256withECDSA(X9ObjectIdentifiers.ecdsa_with_SHA256.getId()), - /** SHA-384 with ECDSA Signature Type */ - SHA384withECDSA(X9ObjectIdentifiers.ecdsa_with_SHA384.getId()), - /** SHA-512 with ECDSA Signature Type */ - SHA512withECDSA(X9ObjectIdentifiers.ecdsa_with_SHA512.getId()); + /** MD2 with RSA Signature Type */ + MD2withRSA(PKCSObjectIdentifiers.md2WithRSAEncryption.getId()), + /** MD5 with RSA Signature Type */ + MD5withRSA(PKCSObjectIdentifiers.md5WithRSAEncryption.getId()), + /** SHA-1 with RSA Signature Type */ + SHA1withRSA(PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()), + /** SHA-224 with RSA Signature Type */ + SHA224withRSA(PKCSObjectIdentifiers.sha224WithRSAEncryption.getId()), + /** SHA-256 with RSA Signature Type */ + SHA256withRSA(PKCSObjectIdentifiers.sha256WithRSAEncryption.getId()), + /** SHA-384 with RSA Signature Type */ + SHA384withRSA(PKCSObjectIdentifiers.sha384WithRSAEncryption.getId()), + /** SHA-512 with RSA Signature Type */ + SHA512withRSA(PKCSObjectIdentifiers.sha512WithRSAEncryption.getId()), + /** RIPEMD128 with RSA Signature Type */ + RIPEMD128withRSA(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128.getId()), + /** RIPEMD160 with RSA Signature Type */ + RIPEMD160withRSA(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160.getId()), + /** RIPEMD256 with RSA Signature Type */ + RIPEMD256withRSA(TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256.getId()), + /** SHA-1 with DSA Signature Type */ + SHA1withDSA(X9ObjectIdentifiers.id_dsa_with_sha1.getId()), + /** SHA-224 with DSA signature type */ + SHA224withDSA(NISTObjectIdentifiers.dsa_with_sha224.getId()), + /** SHA-256 with DSA signature type */ + SHA256withDSA(NISTObjectIdentifiers.dsa_with_sha256.getId()), + /** SHA-384 with DSA signature type */ + SHA384withDSA(NISTObjectIdentifiers.dsa_with_sha384.getId()), + /** SHA-512 with DSA signature type */ + SHA512withDSA(NISTObjectIdentifiers.dsa_with_sha512.getId()), + /** SHA-1 with ECDSA Signature Type */ + SHA1withECDSA(X9ObjectIdentifiers.ecdsa_with_SHA1.getId()), + /** SHA-224 with ECDSA Signature Type */ + SHA224withECDSA(X9ObjectIdentifiers.ecdsa_with_SHA224.getId()), + /** SHA-256 with ECDSA Signature Type */ + SHA256withECDSA(X9ObjectIdentifiers.ecdsa_with_SHA256.getId()), + /** SHA-384 with ECDSA Signature Type */ + SHA384withECDSA(X9ObjectIdentifiers.ecdsa_with_SHA384.getId()), + /** SHA-512 with ECDSA Signature Type */ + SHA512withECDSA(X9ObjectIdentifiers.ecdsa_with_SHA512.getId()); - /** OID-to-type map */ - private static final Map OID_MAP; - static - { - HashMap oidMap = new HashMap(); - for (SignatureType st : values()) - { - oidMap.put(st.oid, st); - } - OID_MAP = Collections.unmodifiableMap(oidMap); - } + /** OID-to-type map */ + private static final Map OID_MAP; + static + { + HashMap oidMap = new HashMap(); + for (SignatureType st : values()) + { + oidMap.put(st.oid, st); + } + OID_MAP = Collections.unmodifiableMap(oidMap); + } - private static final Map> KEYPAIR_MAP; - static - { - HashMap> kpMap = - new HashMap>(); + private static final Map> KEYPAIR_MAP; + static + { + HashMap> kpMap = + new HashMap>(); - // X509V1CertificateGenerator doesn't like SHA384withDSA and SHA512withDSA as of BC 1.44 - kpMap.put(KeyPairType.DSA, - Collections.unmodifiableSet(EnumSet.of(SHA1withDSA, SHA224withDSA, SHA256withDSA))); + // X509V1CertificateGenerator doesn't like SHA384withDSA and SHA512withDSA as of BC 1.44 + kpMap.put(KeyPairType.DSA, + Collections.unmodifiableSet(EnumSet.of(SHA1withDSA, SHA224withDSA, SHA256withDSA))); - kpMap.put(KeyPairType.RSA, Collections.unmodifiableSet(EnumSet.of(MD2withRSA, MD5withRSA, - SHA1withRSA, SHA224withRSA, SHA256withRSA, SHA384withRSA, SHA512withRSA, RIPEMD128withRSA, - RIPEMD160withRSA, RIPEMD256withRSA))); + kpMap.put(KeyPairType.RSA, Collections.unmodifiableSet(EnumSet.of(MD2withRSA, MD5withRSA, + SHA1withRSA, SHA224withRSA, SHA256withRSA, SHA384withRSA, SHA512withRSA, RIPEMD128withRSA, + RIPEMD160withRSA, RIPEMD256withRSA))); - kpMap.put(KeyPairType.ECDSA, Collections.unmodifiableSet(EnumSet.of(SHA1withECDSA, SHA224withECDSA, - SHA256withECDSA, SHA384withECDSA, SHA512withECDSA))); + kpMap.put(KeyPairType.ECDSA, Collections.unmodifiableSet(EnumSet.of(SHA1withECDSA, SHA224withECDSA, + SHA256withECDSA, SHA384withECDSA, SHA512withECDSA))); - KEYPAIR_MAP = Collections.unmodifiableMap(kpMap); - } + KEYPAIR_MAP = Collections.unmodifiableMap(kpMap); + } - private final String oid; + private final String oid; - private SignatureType(String oid) - { - this.oid = oid; - } + private SignatureType(String oid) + { + this.oid = oid; + } - /** - * Gets supported signature types for given key pair type. - * - * @param keyPairType - * @return signature types for key pair type - */ - public static Collection valuesFor(KeyPairType keyPairType) - { - Collection values = KEYPAIR_MAP.get(keyPairType); - if (values == null) - { - values = Collections.emptySet(); - } - return values; - } + /** + * Gets supported signature types for given key pair type. + * + * @param keyPairType + * @return signature types for key pair type + */ + public static Collection valuesFor(KeyPairType keyPairType) + { + Collection values = KEYPAIR_MAP.get(keyPairType); + if (values == null) + { + values = Collections.emptySet(); + } + return values; + } - /** - * Gets a default signature type for given key pair type. - * - * @param keyPairType - * @return default signature type for key pair type - */ - public static SignatureType defaultFor(KeyPairType keyPairType) - { - switch (keyPairType) - { - case RSA: - return SHA1withRSA; - case DSA: - return SHA1withDSA; - case ECDSA: - return SHA1withECDSA; - default: - return null; - } - } + /** + * Gets a default signature type for given key pair type. + * + * @param keyPairType + * @return default signature type for key pair type + */ + public static SignatureType defaultFor(KeyPairType keyPairType) + { + switch (keyPairType) + { + case RSA: + return SHA1withRSA; + case DSA: + return SHA1withDSA; + case ECDSA: + return SHA1withECDSA; + default: + return null; + } + } - /** - * Gets a SignatureType corresponding to the given object identifier. - * - * @param oid the object identifier - * @return the corresponding SignatureType, null if unknown - */ - public static SignatureType valueOfOid(String oid) - { - return OID_MAP.get(oid); - } + /** + * Gets a SignatureType corresponding to the given object identifier. + * + * @param oid the object identifier + * @return the corresponding SignatureType, null if unknown + */ + public static SignatureType valueOfOid(String oid) + { + return OID_MAP.get(oid); + } - /** - * Gets a string representation of signature type corresponding to the given object identifier. - * - * @param oid the object identifier - * @return the corresponding signature type as string, oid itself if unknown - */ - public static String toString(String oid) - { - SignatureType type = valueOfOid(oid); - if (type != null) - { - return type.toString(); - } - return oid; - } + /** + * Gets a string representation of signature type corresponding to the given object identifier. + * + * @param oid the object identifier + * @return the corresponding signature type as string, oid itself if unknown + */ + public static String toString(String oid) + { + SignatureType type = valueOfOid(oid); + if (type != null) + { + return type.toString(); + } + return oid; + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/StringUtil.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/StringUtil.java index 431939ded..9e3dcbbb9 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/StringUtil.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/StringUtil.java @@ -38,88 +38,88 @@ import org.bouncycastle.asn1.ASN1Integer; */ public class StringUtil { - /** - * Convert the supplied object to hex characters sub-divided by spaces every given number of characters, - * and left-padded with zeros to fill group size. - * - * @param obj Object (byte array, BigInteger, DERInteger) - * @param groupSize number of characters to group hex characters by - * @param separator grouping separator - * @return Hex string - * @throws IllegalArgumentException if obj is not a BigInteger, byte array, or a DERInteger, or groupSize - * < 0 - */ - public static StringBuilder toHex(Object obj, int groupSize, String separator) - { - if (groupSize < 0) - { - throw new IllegalArgumentException("Group size must be >= 0"); - } - BigInteger bigInt; - if (obj instanceof BigInteger) - { - bigInt = (BigInteger) obj; - } - else if (obj instanceof byte[]) - { - bigInt = new BigInteger(1, (byte[]) obj); - } - else if (obj instanceof ASN1Integer) - { - bigInt = ((ASN1Integer) obj).getValue(); - } - else - { - throw new IllegalArgumentException("Don't know how to convert " + obj.getClass().getName() + - " to a hex string"); - } + /** + * Convert the supplied object to hex characters sub-divided by spaces every given number of characters, + * and left-padded with zeros to fill group size. + * + * @param obj Object (byte array, BigInteger, DERInteger) + * @param groupSize number of characters to group hex characters by + * @param separator grouping separator + * @return Hex string + * @throws IllegalArgumentException if obj is not a BigInteger, byte array, or a DERInteger, or groupSize + * < 0 + */ + public static StringBuilder toHex(Object obj, int groupSize, String separator) + { + if (groupSize < 0) + { + throw new IllegalArgumentException("Group size must be >= 0"); + } + BigInteger bigInt; + if (obj instanceof BigInteger) + { + bigInt = (BigInteger) obj; + } + else if (obj instanceof byte[]) + { + bigInt = new BigInteger(1, (byte[]) obj); + } + else if (obj instanceof ASN1Integer) + { + bigInt = ((ASN1Integer) obj).getValue(); + } + else + { + throw new IllegalArgumentException("Don't know how to convert " + obj.getClass().getName() + + " to a hex string"); + } - // Convert to hex + // Convert to hex - StringBuilder sb = new StringBuilder(bigInt.toString(16).toUpperCase(Locale.ENGLISH)); + StringBuilder sb = new StringBuilder(bigInt.toString(16).toUpperCase(Locale.ENGLISH)); - // Left-pad if asked and necessary + // Left-pad if asked and necessary - if (groupSize != 0) - { - int len = groupSize - (sb.length() % groupSize); - if (len != groupSize) - { - for (int i = 0; i < len; i++) - { - sb.insert(0, '0'); - } - } - } + if (groupSize != 0) + { + int len = groupSize - (sb.length() % groupSize); + if (len != groupSize) + { + for (int i = 0; i < len; i++) + { + sb.insert(0, '0'); + } + } + } - // Place separator at every groupSize characters + // Place separator at every groupSize characters - if (sb.length() > groupSize && !separator.isEmpty()) - { - for (int i = groupSize; i < sb.length(); i += groupSize + separator.length()) - { - sb.insert(i, separator); - } - } + if (sb.length() > groupSize && !separator.isEmpty()) + { + for (int i = groupSize; i < sb.length(); i += groupSize + separator.length()) + { + sb.insert(i, separator); + } + } - return sb; - } - - // 1. String --> InputStream - public static InputStream String2InputStream(String str) { - ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes()); - return stream; - } + return sb; + } + + // 1. String --> InputStream + public static InputStream String2InputStream(String str) { + ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes()); + return stream; + } - // 2. InputStream --> String - public static String inputStream2String(InputStream is) throws IOException { - BufferedReader in = new BufferedReader(new InputStreamReader(is)); - StringBuffer buffer = new StringBuffer(); - String line = ""; - while ((line = in.readLine()) != null) { - buffer.append(line); - } - return buffer.toString(); - } - + // 2. InputStream --> String + public static String inputStream2String(InputStream is) throws IOException { + BufferedReader in = new BufferedReader(new InputStreamReader(is)); + StringBuffer buffer = new StringBuffer(); + String line = ""; + while ((line = in.readLine()) != null) { + buffer.append(line); + } + return buffer.toString(); + } + } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/X509CertUtils.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/X509CertUtils.java index a484f3483..0c58fd619 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/X509CertUtils.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/X509CertUtils.java @@ -57,540 +57,540 @@ import org.slf4j.LoggerFactory; * Provides utility methods relating to X509 Certificates, CRLs and CSRs. */ public final class X509CertUtils { - /** Logger */ - // private static final Logger LOG = - // Logger.getLogger(X509CertUtil.class.getCanonicalName()); - private static final Logger _logger = LoggerFactory.getLogger(X509CertUtils.class); - /** PKCS #7 encoding name */ - public static final String PKCS7_ENCODING = "PKCS7"; + /** Logger */ + // private static final Logger LOG = + // Logger.getLogger(X509CertUtil.class.getCanonicalName()); + private static final Logger _logger = LoggerFactory.getLogger(X509CertUtils.class); + /** PKCS #7 encoding name */ + public static final String PKCS7_ENCODING = "PKCS7"; - /** PkiPath encoding name */ - public static final String PKIPATH_ENCODING = "PkiPath"; + /** PkiPath encoding name */ + public static final String PKIPATH_ENCODING = "PkiPath"; - /** OpenSSL PEM encoding name */ - public static final String OPENSSL_PEM_ENCODING = "OpenSSL_PEM"; + /** OpenSSL PEM encoding name */ + public static final String OPENSSL_PEM_ENCODING = "OpenSSL_PEM"; - /** Type name for X.509 certificates */ - public static final String X509_CERT_TYPE = "X.509"; + /** Type name for X.509 certificates */ + public static final String X509_CERT_TYPE = "X.509"; - /** - * Private to prevent construction. - */ - private X509CertUtils() { - // Nothing to do - } + /** + * Private to prevent construction. + */ + private X509CertUtils() { + // Nothing to do + } - public static X509Certificate loadCertFromPEM(String strPEM) { - StringReader stringReader = new StringReader(strPEM); - return loadCertFromReader(stringReader); - } + public static X509Certificate loadCertFromPEM(String strPEM) { + StringReader stringReader = new StringReader(strPEM); + return loadCertFromReader(stringReader); + } - public static X509Certificate loadCertFromReader(Reader reader) { - Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); - PEMParser pEMReader = new PEMParser(reader); - try { - X509Certificate cert = null; - Object pemObject = pEMReader.readObject(); - if (pemObject instanceof X509Certificate) { - cert = (X509Certificate) pemObject; - } - pEMReader.close(); - return cert; - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } + public static X509Certificate loadCertFromReader(Reader reader) { + Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); + PEMParser pEMReader = new PEMParser(reader); + try { + X509Certificate cert = null; + Object pemObject = pEMReader.readObject(); + if (pemObject instanceof X509Certificate) { + cert = (X509Certificate) pemObject; + } + pEMReader.close(); + return cert; + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } - public static X509Certificate loadCertFromB64Encoded(String certB64Encoded) - throws Exception { - byte[] keyStoreB64 = Base64.decodeBase64(certB64Encoded.getBytes()); - ByteArrayInputStream keyStoreBAIS = new ByteArrayInputStream( - keyStoreB64); - return loadCertFromInputStream(keyStoreBAIS); - } + public static X509Certificate loadCertFromB64Encoded(String certB64Encoded) + throws Exception { + byte[] keyStoreB64 = Base64.decodeBase64(certB64Encoded.getBytes()); + ByteArrayInputStream keyStoreBAIS = new ByteArrayInputStream( + keyStoreB64); + return loadCertFromInputStream(keyStoreBAIS); + } - public static X509Certificate loadCertFromInputStream( - InputStream inputStream) throws Exception { - CertificateFactory certificateFactory; - try { - certificateFactory = CertificateFactory.getInstance("X.509"); - X509Certificate x509Certificate = (X509Certificate) certificateFactory - .generateCertificate(inputStream); - return x509Certificate; - } catch (CertificateException e) { - _logger.error("证书无法识别,证书类型必须是X.509"); - throw new Exception("证书无法识别,证书类型必须是X.509", e); - } - } + public static X509Certificate loadCertFromInputStream( + InputStream inputStream) throws Exception { + CertificateFactory certificateFactory; + try { + certificateFactory = CertificateFactory.getInstance("X.509"); + X509Certificate x509Certificate = (X509Certificate) certificateFactory + .generateCertificate(inputStream); + return x509Certificate; + } catch (CertificateException e) { + _logger.error("证书无法识别,证书类型必须是X.509"); + throw new Exception("证书无法识别,证书类型必须是X.509", e); + } + } - + - /** - * Load a CRL from the specified URL. - * - * @param url - * The URL to load CRL from - * @return The CRL - * @throws CryptoException - * Problem encountered while loading the CRL - * @throws FileNotFoundException - * If the CRL file does not exist, is a directory rather than a - * regular file, or for some other reason cannot be opened for - * reading - * @throws IOException - * An I/O error occurred - */ - public static X509CRL loadCRL(URL url) throws CryptoException, IOException { - InputStream in = NetUtil.openGetStream(url); - try { - CertificateFactory cf = CertificateFactory - .getInstance(X509_CERT_TYPE); - X509CRL crl = (X509CRL) cf.generateCRL(in); - return crl; - } catch (GeneralSecurityException ex) { - throw new CryptoException("Could not load CRL.", ex); - } finally { - try { - in.close(); - } catch (IOException e) { - _logger.warn("Could not close input stream from " + url, e); - // LOG.log(Level.WARNING, "Could not close input stream from "+ - // url, e); - } - } - } + /** + * Load a CRL from the specified URL. + * + * @param url + * The URL to load CRL from + * @return The CRL + * @throws CryptoException + * Problem encountered while loading the CRL + * @throws FileNotFoundException + * If the CRL file does not exist, is a directory rather than a + * regular file, or for some other reason cannot be opened for + * reading + * @throws IOException + * An I/O error occurred + */ + public static X509CRL loadCRL(URL url) throws CryptoException, IOException { + InputStream in = NetUtil.openGetStream(url); + try { + CertificateFactory cf = CertificateFactory + .getInstance(X509_CERT_TYPE); + X509CRL crl = (X509CRL) cf.generateCRL(in); + return crl; + } catch (GeneralSecurityException ex) { + throw new CryptoException("Could not load CRL.", ex); + } finally { + try { + in.close(); + } catch (IOException e) { + _logger.warn("Could not close input stream from " + url, e); + // LOG.log(Level.WARNING, "Could not close input stream from "+ + // url, e); + } + } + } - /** - * Convert the supplied array of certificate objects into X509Certificate - * objects. - * - * @param certsIn - * The Certificate objects - * @return The converted X509Certificate objects - * @throws CryptoException - * A problem occurred during the conversion - */ - public static X509Certificate[] convertCertificates(Certificate[] certsIn) - throws CryptoException { - X509Certificate[] certsOut = new X509Certificate[certsIn.length]; + /** + * Convert the supplied array of certificate objects into X509Certificate + * objects. + * + * @param certsIn + * The Certificate objects + * @return The converted X509Certificate objects + * @throws CryptoException + * A problem occurred during the conversion + */ + public static X509Certificate[] convertCertificates(Certificate[] certsIn) + throws CryptoException { + X509Certificate[] certsOut = new X509Certificate[certsIn.length]; - for (int iCnt = 0; iCnt < certsIn.length; iCnt++) { - certsOut[iCnt] = convertCertificate(certsIn[iCnt]); - } + for (int iCnt = 0; iCnt < certsIn.length; iCnt++) { + certsOut[iCnt] = convertCertificate(certsIn[iCnt]); + } - return certsOut; - } + return certsOut; + } - /** - * Convert the supplied certificate object into an X509Certificate object. - * - * @param certIn - * The Certificate object - * @return The converted X509Certificate object - * @throws CryptoException - * A problem occurred during the conversion - */ - public static X509Certificate convertCertificate(Certificate certIn) - throws CryptoException { - try { - CertificateFactory cf = CertificateFactory - .getInstance(X509_CERT_TYPE); - ByteArrayInputStream bais = new ByteArrayInputStream( - certIn.getEncoded()); - return (X509Certificate) cf.generateCertificate(bais); - } catch (CertificateException ex) { - throw new CryptoException("Could not convert certificate.", ex); - } - } + /** + * Convert the supplied certificate object into an X509Certificate object. + * + * @param certIn + * The Certificate object + * @return The converted X509Certificate object + * @throws CryptoException + * A problem occurred during the conversion + */ + public static X509Certificate convertCertificate(Certificate certIn) + throws CryptoException { + try { + CertificateFactory cf = CertificateFactory + .getInstance(X509_CERT_TYPE); + ByteArrayInputStream bais = new ByteArrayInputStream( + certIn.getEncoded()); + return (X509Certificate) cf.generateCertificate(bais); + } catch (CertificateException ex) { + throw new CryptoException("Could not convert certificate.", ex); + } + } - /** - * Attempt to order the supplied array of X.509 certificates in issued to to - * issued from order. - * - * @param certs - * The X.509 certificates in order - * @return The ordered X.509 certificates - */ - public static X509Certificate[] orderX509CertChain(X509Certificate[] certs) { - int iOrdered = 0; - X509Certificate[] tmpCerts = certs.clone(); - X509Certificate[] orderedCerts = new X509Certificate[certs.length]; + /** + * Attempt to order the supplied array of X.509 certificates in issued to to + * issued from order. + * + * @param certs + * The X.509 certificates in order + * @return The ordered X.509 certificates + */ + public static X509Certificate[] orderX509CertChain(X509Certificate[] certs) { + int iOrdered = 0; + X509Certificate[] tmpCerts = certs.clone(); + X509Certificate[] orderedCerts = new X509Certificate[certs.length]; - X509Certificate issuerCert = null; + X509Certificate issuerCert = null; - // Find the root issuer (i.e. certificate where issuer is the same as - // subject) - for (X509Certificate aCert : tmpCerts) { - if (aCert.getIssuerDN().equals(aCert.getSubjectDN())) { - issuerCert = aCert; - orderedCerts[iOrdered] = issuerCert; - iOrdered++; - } - } + // Find the root issuer (i.e. certificate where issuer is the same as + // subject) + for (X509Certificate aCert : tmpCerts) { + if (aCert.getIssuerDN().equals(aCert.getSubjectDN())) { + issuerCert = aCert; + orderedCerts[iOrdered] = issuerCert; + iOrdered++; + } + } - // Couldn't find a root issuer so just return the unordered array - if (issuerCert == null) { - return certs; - } + // Couldn't find a root issuer so just return the unordered array + if (issuerCert == null) { + return certs; + } - // Keep making passes through the array of certificates looking for the - // next certificate in the chain - // until the links run out - while (true) { - boolean bFoundNext = false; - for (X509Certificate aCert : tmpCerts) { - // Is this certificate the next in the chain? - if (aCert.getIssuerDN().equals(issuerCert.getSubjectDN()) - && aCert != issuerCert) { - // Yes - issuerCert = aCert; - orderedCerts[iOrdered] = issuerCert; - iOrdered++; - bFoundNext = true; - break; - } - } - if (!bFoundNext) { - break; - } - } + // Keep making passes through the array of certificates looking for the + // next certificate in the chain + // until the links run out + while (true) { + boolean bFoundNext = false; + for (X509Certificate aCert : tmpCerts) { + // Is this certificate the next in the chain? + if (aCert.getIssuerDN().equals(issuerCert.getSubjectDN()) + && aCert != issuerCert) { + // Yes + issuerCert = aCert; + orderedCerts[iOrdered] = issuerCert; + iOrdered++; + bFoundNext = true; + break; + } + } + if (!bFoundNext) { + break; + } + } - // Resize array - tmpCerts = new X509Certificate[iOrdered]; - System.arraycopy(orderedCerts, 0, tmpCerts, 0, iOrdered); + // Resize array + tmpCerts = new X509Certificate[iOrdered]; + System.arraycopy(orderedCerts, 0, tmpCerts, 0, iOrdered); - // Reverse the order of the array - orderedCerts = new X509Certificate[iOrdered]; + // Reverse the order of the array + orderedCerts = new X509Certificate[iOrdered]; - for (int iCnt = 0; iCnt < iOrdered; iCnt++) { - orderedCerts[iCnt] = tmpCerts[tmpCerts.length - 1 - iCnt]; - } + for (int iCnt = 0; iCnt < iOrdered; iCnt++) { + orderedCerts[iCnt] = tmpCerts[tmpCerts.length - 1 - iCnt]; + } - return orderedCerts; - } + return orderedCerts; + } - /** - * DER encode a certificate. - * - * @return The binary encoding - * @param cert - * The certificate - * @throws CryptoException - * If there was a problem encoding the certificate - */ - public static byte[] getCertEncodedDer(X509Certificate cert) - throws CryptoException { - try { - return cert.getEncoded(); - } catch (CertificateException ex) { - throw new CryptoException("Could not DER encode certificate.", ex); - } - } + /** + * DER encode a certificate. + * + * @return The binary encoding + * @param cert + * The certificate + * @throws CryptoException + * If there was a problem encoding the certificate + */ + public static byte[] getCertEncodedDer(X509Certificate cert) + throws CryptoException { + try { + return cert.getEncoded(); + } catch (CertificateException ex) { + throw new CryptoException("Could not DER encode certificate.", ex); + } + } - /** - * PKCS #7 encode a certificate. - * - * @return The PKCS #7 encoded certificate - * @param cert - * The certificate - * @throws CryptoException - * If there was a problem encoding the certificate - */ - public static byte[] getCertEncodedPkcs7(X509Certificate cert) - throws CryptoException { - return getCertsEncodedPkcs7(new X509Certificate[] { cert }); - } + /** + * PKCS #7 encode a certificate. + * + * @return The PKCS #7 encoded certificate + * @param cert + * The certificate + * @throws CryptoException + * If there was a problem encoding the certificate + */ + public static byte[] getCertEncodedPkcs7(X509Certificate cert) + throws CryptoException { + return getCertsEncodedPkcs7(new X509Certificate[] { cert }); + } - /** - * PKCS #7 encode a number of certificates. - * - * @return The PKCS #7 encoded certificates - * @param certs - * The certificates - * @throws CryptoException - * If there was a problem encoding the certificates - */ - public static byte[] getCertsEncodedPkcs7(X509Certificate[] certs) - throws CryptoException { - return getCertsEncoded(certs, PKCS7_ENCODING, - "Could not PKCS #7 encode certificate(s)."); - } + /** + * PKCS #7 encode a number of certificates. + * + * @return The PKCS #7 encoded certificates + * @param certs + * The certificates + * @throws CryptoException + * If there was a problem encoding the certificates + */ + public static byte[] getCertsEncodedPkcs7(X509Certificate[] certs) + throws CryptoException { + return getCertsEncoded(certs, PKCS7_ENCODING, + "Could not PKCS #7 encode certificate(s)."); + } - /** - * PkiPath encode a certificate. - * - * @return The PkiPath encoded certificate - * @param cert - * The certificate - * @throws CryptoException - * If there was a problem encoding the certificate - */ - public static byte[] getCertEncodedPkiPath(X509Certificate cert) - throws CryptoException { - return getCertsEncodedPkiPath(new X509Certificate[] { cert }); - } + /** + * PkiPath encode a certificate. + * + * @return The PkiPath encoded certificate + * @param cert + * The certificate + * @throws CryptoException + * If there was a problem encoding the certificate + */ + public static byte[] getCertEncodedPkiPath(X509Certificate cert) + throws CryptoException { + return getCertsEncodedPkiPath(new X509Certificate[] { cert }); + } - /** - * PkiPath encode a number of certificates. - * - * @return The PkiPath encoded certificates - * @param certs - * The certificates - * @throws CryptoException - * If there was a problem encoding the certificates - */ - public static byte[] getCertsEncodedPkiPath(X509Certificate[] certs) - throws CryptoException { - return getCertsEncoded(certs, PKIPATH_ENCODING, - "Could not PkiPath encode certificate(s)."); - } + /** + * PkiPath encode a number of certificates. + * + * @return The PkiPath encoded certificates + * @param certs + * The certificates + * @throws CryptoException + * If there was a problem encoding the certificates + */ + public static byte[] getCertsEncodedPkiPath(X509Certificate[] certs) + throws CryptoException { + return getCertsEncoded(certs, PKIPATH_ENCODING, + "Could not PkiPath encode certificate(s)."); + } - /** - * Encode a number of certificates using the given encoding. - * - * @return The encoded certificates - * @param certs - * The certificates - * @param encoding - * The encoding - * @param errkey - * The error message key to use in the possibly occurred - * exception - * @throws CryptoException - * If there was a problem encoding the certificates - */ - private static byte[] getCertsEncoded(X509Certificate[] certs, - String encoding, String errkey) throws CryptoException { - try { - CertificateFactory cf = CertificateFactory - .getInstance(X509_CERT_TYPE); - return cf.generateCertPath(Arrays.asList(certs)).getEncoded( - encoding); - } catch (CertificateException ex) { - throw new CryptoException(errkey, ex); - } - } + /** + * Encode a number of certificates using the given encoding. + * + * @return The encoded certificates + * @param certs + * The certificates + * @param encoding + * The encoding + * @param errkey + * The error message key to use in the possibly occurred + * exception + * @throws CryptoException + * If there was a problem encoding the certificates + */ + private static byte[] getCertsEncoded(X509Certificate[] certs, + String encoding, String errkey) throws CryptoException { + try { + CertificateFactory cf = CertificateFactory + .getInstance(X509_CERT_TYPE); + return cf.generateCertPath(Arrays.asList(certs)).getEncoded( + encoding); + } catch (CertificateException ex) { + throw new CryptoException(errkey, ex); + } + } - /** - * Verify that one X.509 certificate was signed using the private key that - * corresponds to the public key of a second certificate. - * - * @return True if the first certificate was signed by private key - * corresponding to the second signature - * @param signedCert - * The signed certificate - * @param signingCert - * The signing certificate - * @throws CryptoException - * If there was a problem verifying the signature. - */ - public static boolean verifyCertificate(X509Certificate signedCert, - X509Certificate signingCert) throws CryptoException { - try { - signedCert.verify(signingCert.getPublicKey()); - } - // Verification failed - catch (InvalidKeyException ex) { - return false; - } - // Verification failed - catch (SignatureException ex) { - return false; - } - // Problem verifying - catch (GeneralSecurityException ex) { - throw new CryptoException("Could not verify certificate.", ex); - } - return true; - } + /** + * Verify that one X.509 certificate was signed using the private key that + * corresponds to the public key of a second certificate. + * + * @return True if the first certificate was signed by private key + * corresponding to the second signature + * @param signedCert + * The signed certificate + * @param signingCert + * The signing certificate + * @throws CryptoException + * If there was a problem verifying the signature. + */ + public static boolean verifyCertificate(X509Certificate signedCert, + X509Certificate signingCert) throws CryptoException { + try { + signedCert.verify(signingCert.getPublicKey()); + } + // Verification failed + catch (InvalidKeyException ex) { + return false; + } + // Verification failed + catch (SignatureException ex) { + return false; + } + // Problem verifying + catch (GeneralSecurityException ex) { + throw new CryptoException("Could not verify certificate.", ex); + } + return true; + } - /** - * Check whether or not a trust path exists between the supplied X.509 - * certificate and and the supplied keystores based on the trusted - * certificates contained therein, i.e. that a chain of trust exists between - * the supplied certificate and a self-signed trusted certificate in the - * keystores. - * - * @return The trust chain, or null if trust could not be established - * @param cert - * The certificate - * @param keyStores - * The keystores - * @throws CryptoException - * If there is a problem establishing trust - */ - public static X509Certificate[] establishTrust(KeyStore[] keyStores, - X509Certificate cert) throws CryptoException { - // Extract all certificates from the Keystores creating - ArrayList ksCerts = new ArrayList(); - for (KeyStore ks : keyStores) { - ksCerts.addAll(extractCertificates(ks)); - } + /** + * Check whether or not a trust path exists between the supplied X.509 + * certificate and and the supplied keystores based on the trusted + * certificates contained therein, i.e. that a chain of trust exists between + * the supplied certificate and a self-signed trusted certificate in the + * keystores. + * + * @return The trust chain, or null if trust could not be established + * @param cert + * The certificate + * @param keyStores + * The keystores + * @throws CryptoException + * If there is a problem establishing trust + */ + public static X509Certificate[] establishTrust(KeyStore[] keyStores, + X509Certificate cert) throws CryptoException { + // Extract all certificates from the Keystores creating + ArrayList ksCerts = new ArrayList(); + for (KeyStore ks : keyStores) { + ksCerts.addAll(extractCertificates(ks)); + } - // Try and establish trust against the set of all certificates - return establishTrust(ksCerts, cert); - } + // Try and establish trust against the set of all certificates + return establishTrust(ksCerts, cert); + } - /** - * Check whether or not a trust path exists between the supplied X.509 - * certificate and and the supplied comparison certificates based on the - * trusted certificates contained therein, i.e. that a chain of trust exists - * between the supplied certificate and a self-signed trusted certificate in - * the comparison set. - * - * @return The trust chain, or null if trust could not be established - * @param cert - * The certificate - * @param vCompCerts - * The comparison set of certificates - * @throws CryptoException - * If there is a problem establishing trust - */ - private static X509Certificate[] establishTrust( - List vCompCerts, X509Certificate cert) - throws CryptoException { - // For each comparison certificate... - for (X509Certificate compCert : vCompCerts) { - // Check if the Comparison certificate's subject is the same as the - // certificate's issuer - if (cert.getIssuerDN().equals(compCert.getSubjectDN())) { - // If so verify with the comparison certificate's corresponding - // private key was used to sign - // the certificate - if (X509CertUtils.verifyCertificate(cert, compCert)) { - // If the keystore certificate is self-signed then a chain - // of trust exists - if (compCert.getSubjectDN().equals(compCert.getIssuerDN())) { - return new X509Certificate[] { cert, compCert }; - } - // Otherwise try and establish a chain of trust for the - // comparison certificate against the - // other comparison certificates - X509Certificate[] tmpChain = establishTrust(vCompCerts, - compCert); - if (tmpChain != null) { - X509Certificate[] trustChain = new X509Certificate[tmpChain.length + 1]; - trustChain[0] = cert; - System.arraycopy(tmpChain, 0, trustChain, 1, - tmpChain.length); - return trustChain; - } - } - } - } + /** + * Check whether or not a trust path exists between the supplied X.509 + * certificate and and the supplied comparison certificates based on the + * trusted certificates contained therein, i.e. that a chain of trust exists + * between the supplied certificate and a self-signed trusted certificate in + * the comparison set. + * + * @return The trust chain, or null if trust could not be established + * @param cert + * The certificate + * @param vCompCerts + * The comparison set of certificates + * @throws CryptoException + * If there is a problem establishing trust + */ + private static X509Certificate[] establishTrust( + List vCompCerts, X509Certificate cert) + throws CryptoException { + // For each comparison certificate... + for (X509Certificate compCert : vCompCerts) { + // Check if the Comparison certificate's subject is the same as the + // certificate's issuer + if (cert.getIssuerDN().equals(compCert.getSubjectDN())) { + // If so verify with the comparison certificate's corresponding + // private key was used to sign + // the certificate + if (X509CertUtils.verifyCertificate(cert, compCert)) { + // If the keystore certificate is self-signed then a chain + // of trust exists + if (compCert.getSubjectDN().equals(compCert.getIssuerDN())) { + return new X509Certificate[] { cert, compCert }; + } + // Otherwise try and establish a chain of trust for the + // comparison certificate against the + // other comparison certificates + X509Certificate[] tmpChain = establishTrust(vCompCerts, + compCert); + if (tmpChain != null) { + X509Certificate[] trustChain = new X509Certificate[tmpChain.length + 1]; + trustChain[0] = cert; + System.arraycopy(tmpChain, 0, trustChain, 1, + tmpChain.length); + return trustChain; + } + } + } + } - // No chain of trust - return null; - } + // No chain of trust + return null; + } - /** - * Extract a copy of all trusted certificates contained within the supplied - * keystore. - * - * @param keyStore - * The keystore - * @return The extracted certificates - * @throws CryptoException - * If a problem is encountered extracting the certificates - */ - private static Collection extractCertificates( - KeyStore keyStore) throws CryptoException { - try { - ArrayList vCerts = new ArrayList(); + /** + * Extract a copy of all trusted certificates contained within the supplied + * keystore. + * + * @param keyStore + * The keystore + * @return The extracted certificates + * @throws CryptoException + * If a problem is encountered extracting the certificates + */ + private static Collection extractCertificates( + KeyStore keyStore) throws CryptoException { + try { + ArrayList vCerts = new ArrayList(); - for (Enumeration en = keyStore.aliases(); en - .hasMoreElements();) { - String sAlias = en.nextElement(); - if (keyStore.isCertificateEntry(sAlias)) { - vCerts.add(X509CertUtils.convertCertificate(keyStore - .getCertificate(sAlias))); - } - } + for (Enumeration en = keyStore.aliases(); en + .hasMoreElements();) { + String sAlias = en.nextElement(); + if (keyStore.isCertificateEntry(sAlias)) { + vCerts.add(X509CertUtils.convertCertificate(keyStore + .getCertificate(sAlias))); + } + } - return vCerts; - } catch (KeyStoreException ex) { - throw new CryptoException( - "Could not extract trusted certificates from Keystore.", ex); - } - } + return vCerts; + } catch (KeyStoreException ex) { + throw new CryptoException( + "Could not extract trusted certificates from Keystore.", ex); + } + } - /** - * Check whether or not a trusted certificate in the supplied keystore - * matches the the supplied X.509 certificate. - * - * @return The alias of the matching certificate in the keystore or null if - * there is no match - * @param cert - * The certificate - * @param keyStore - * The keystore - * @throws CryptoException - * If there is a problem establishing trust - */ - public static String matchCertificate(KeyStore keyStore, - X509Certificate cert) throws CryptoException { - try { - for (Enumeration en = keyStore.aliases(); en - .hasMoreElements();) { - String sAlias = en.nextElement(); - if (keyStore.isCertificateEntry(sAlias)) { - X509Certificate compCert = X509CertUtils - .convertCertificate(keyStore.getCertificate(sAlias)); + /** + * Check whether or not a trusted certificate in the supplied keystore + * matches the the supplied X.509 certificate. + * + * @return The alias of the matching certificate in the keystore or null if + * there is no match + * @param cert + * The certificate + * @param keyStore + * The keystore + * @throws CryptoException + * If there is a problem establishing trust + */ + public static String matchCertificate(KeyStore keyStore, + X509Certificate cert) throws CryptoException { + try { + for (Enumeration en = keyStore.aliases(); en + .hasMoreElements();) { + String sAlias = en.nextElement(); + if (keyStore.isCertificateEntry(sAlias)) { + X509Certificate compCert = X509CertUtils + .convertCertificate(keyStore.getCertificate(sAlias)); - if (cert.equals(compCert)) { - return sAlias; - } - } - } - return null; - } catch (KeyStoreException ex) { - throw new CryptoException("Could not match certificate.", ex); - } - } + if (cert.equals(compCert)) { + return sAlias; + } + } + } + return null; + } catch (KeyStoreException ex) { + throw new CryptoException("Could not match certificate.", ex); + } + } - /** - * For a given X.509 certificate get a representative alias for it in a - * keystore. For a self-signed certificate this will be the subject's common - * name (if any). For a non-self-signed certificate it will be the subject's - * common name followed by the issuer's common name in parenthesis. - * - * @param cert - * The certificate - * @return The alias or a blank string if none could be worked out - */ - public static String getCertificateAlias(X509Certificate cert) { - X500Principal subject = cert.getSubjectX500Principal(); - X500Principal issuer = cert.getIssuerX500Principal(); + /** + * For a given X.509 certificate get a representative alias for it in a + * keystore. For a self-signed certificate this will be the subject's common + * name (if any). For a non-self-signed certificate it will be the subject's + * common name followed by the issuer's common name in parenthesis. + * + * @param cert + * The certificate + * @return The alias or a blank string if none could be worked out + */ + public static String getCertificateAlias(X509Certificate cert) { + X500Principal subject = cert.getSubjectX500Principal(); + X500Principal issuer = cert.getIssuerX500Principal(); - String sSubjectCN = getCommonName(subject); + String sSubjectCN = getCommonName(subject); - // Could not get a subject CN - return blank - if (sSubjectCN == null) { - return ""; - } + // Could not get a subject CN - return blank + if (sSubjectCN == null) { + return ""; + } - String sIssuerCN = getCommonName(issuer); + String sIssuerCN = getCommonName(issuer); - // Self-signed certificate or could not get an issuer CN - if (subject.equals(issuer) || sIssuerCN == null) { - // Alias is the subject CN - return sSubjectCN; - } - _logger.debug("{0} ({1})", sSubjectCN, sIssuerCN); - // else non-self-signed certificate - // Alias is the subject CN followed by the issuer CN in parenthesis - return MessageFormat.format("{0} ({1})", sSubjectCN, sIssuerCN); - } - - - public static String getCommonName(X500Principal name) { + // Self-signed certificate or could not get an issuer CN + if (subject.equals(issuer) || sIssuerCN == null) { + // Alias is the subject CN + return sSubjectCN; + } + _logger.debug("{0} ({1})", sSubjectCN, sIssuerCN); + // else non-self-signed certificate + // Alias is the subject CN followed by the issuer CN in parenthesis + return MessageFormat.format("{0} ({1})", sSubjectCN, sIssuerCN); + } + + + public static String getCommonName(X500Principal name) { if (name == null) { return null; } @@ -606,5 +606,5 @@ public final class X509CertUtils { return value; } - + } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/X509V3CertGen.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/X509V3CertGen.java index 829c4becf..ad5ab3e14 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/X509V3CertGen.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/cert/X509V3CertGen.java @@ -46,60 +46,60 @@ import org.dromara.maxkey.crypto.KeyPairUtil; * Provides utility methods relating to X509 Certificates Gen */ public final class X509V3CertGen { - - public static X509Certificate genV3Certificate(String issuerName,String subjectName,Date notBefore,Date notAfter,KeyPair keyPair) throws Exception { - - - //issuer same as subject is CA - BigInteger serial=BigInteger.valueOf(System.currentTimeMillis()); - - X500Name x500Name =new X500Name(issuerName); - - X500Name subject =new X500Name(subjectName); - - PublicKey publicKey =keyPair.getPublic(); - PrivateKey privateKey=keyPair.getPrivate(); - - SubjectPublicKeyInfo subjectPublicKeyInfo = null; - ASN1InputStream publicKeyInputStream =null; - try { - publicKeyInputStream =new ASN1InputStream(publicKey.getEncoded()); - Object aiStream=publicKeyInputStream.readObject(); - subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(aiStream); - } catch (IOException e1) { - e1.printStackTrace(); - } finally { - if(publicKeyInputStream !=null) { - publicKeyInputStream.close(); - } - } - - - X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(x500Name, - serial, - notBefore, - notAfter, - subject, - subjectPublicKeyInfo); - - ContentSigner sigGen = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(privateKey); - //certBuilder.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); - //certBuilder.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature| KeyUsage.keyEncipherment)); - //certBuilder.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); - //certBuilder.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "connsec@163.com"))); + + public static X509Certificate genV3Certificate(String issuerName,String subjectName,Date notBefore,Date notAfter,KeyPair keyPair) throws Exception { + + + //issuer same as subject is CA + BigInteger serial=BigInteger.valueOf(System.currentTimeMillis()); + + X500Name x500Name =new X500Name(issuerName); + + X500Name subject =new X500Name(subjectName); + + PublicKey publicKey =keyPair.getPublic(); + PrivateKey privateKey=keyPair.getPrivate(); + + SubjectPublicKeyInfo subjectPublicKeyInfo = null; + ASN1InputStream publicKeyInputStream =null; + try { + publicKeyInputStream =new ASN1InputStream(publicKey.getEncoded()); + Object aiStream=publicKeyInputStream.readObject(); + subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(aiStream); + } catch (IOException e1) { + e1.printStackTrace(); + } finally { + if(publicKeyInputStream !=null) { + publicKeyInputStream.close(); + } + } + + + X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(x500Name, + serial, + notBefore, + notAfter, + subject, + subjectPublicKeyInfo); + + ContentSigner sigGen = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(privateKey); + //certBuilder.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); + //certBuilder.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature| KeyUsage.keyEncipherment)); + //certBuilder.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); + //certBuilder.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "connsec@163.com"))); - X509CertificateHolder x509CertificateHolder = certBuilder.build(sigGen); - CertificateFactory certificateFactory = CertificateFactory.class.newInstance(); - InputStream inputStream = new ByteArrayInputStream(x509CertificateHolder.toASN1Structure().getEncoded()); - X509Certificate x509Certificate = (X509Certificate) certificateFactory.engineGenerateCertificate(inputStream); - inputStream.close(); + X509CertificateHolder x509CertificateHolder = certBuilder.build(sigGen); + CertificateFactory certificateFactory = CertificateFactory.class.newInstance(); + InputStream inputStream = new ByteArrayInputStream(x509CertificateHolder.toASN1Structure().getEncoded()); + X509Certificate x509Certificate = (X509Certificate) certificateFactory.engineGenerateCertificate(inputStream); + inputStream.close(); - return x509Certificate; - } + return x509Certificate; + } - public static KeyPair genRSAKeyPair() throws Exception { - return KeyPairUtil.genKeyPair(KeyPairType.RSA, "BC"); - } + public static KeyPair genRSAKeyPair() throws Exception { + return KeyPairUtil.genKeyPair(KeyPairType.RSA, "BC"); + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jose/JWEAlgorithmEmbed.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jose/JWEAlgorithmEmbed.java index 355174bd6..fafd7f5fb 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jose/JWEAlgorithmEmbed.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jose/JWEAlgorithmEmbed.java @@ -32,74 +32,74 @@ import com.nimbusds.jose.JWEAlgorithm; public class JWEAlgorithmEmbed { - public static final JWEAlgorithmEmbed NONE = getForAlgorithmName("none"); + public static final JWEAlgorithmEmbed NONE = getForAlgorithmName("none"); - private JWEAlgorithm algorithm; + private JWEAlgorithm algorithm; - public JWEAlgorithmEmbed() { + public JWEAlgorithmEmbed() { - } + } - public JWEAlgorithmEmbed(JWEAlgorithm algorithm) { - this.algorithm = algorithm; - } + public JWEAlgorithmEmbed(JWEAlgorithm algorithm) { + this.algorithm = algorithm; + } - public static JWEAlgorithmEmbed getForAlgorithmName (String algorithmName) { - JWEAlgorithmEmbed ent = new JWEAlgorithmEmbed(); - ent.setAlgorithmName(algorithmName); - if (ent.getAlgorithm() == null) { - return null; - } else { - return ent; - } - } + public static JWEAlgorithmEmbed getForAlgorithmName (String algorithmName) { + JWEAlgorithmEmbed ent = new JWEAlgorithmEmbed(); + ent.setAlgorithmName(algorithmName); + if (ent.getAlgorithm() == null) { + return null; + } else { + return ent; + } + } - /** - * Get the name of this algorithm, return null if no algorithm set. - * @return - */ + /** + * Get the name of this algorithm, return null if no algorithm set. + * @return + */ - public String getAlgorithmName() { - if (algorithm != null) { - return algorithm.getName(); - } else { - return null; - } - } + public String getAlgorithmName() { + if (algorithm != null) { + return algorithm.getName(); + } else { + return null; + } + } - /** - * Set the name of this algorithm. - * Calls JWEAlgorithm.parse() - * @param algorithmName - */ - public void setAlgorithmName(String algorithmName) { - if (!Strings.isNullOrEmpty(algorithmName)) { - algorithm = JWEAlgorithm.parse(algorithmName); - } else { - algorithm = null; - } - } + /** + * Set the name of this algorithm. + * Calls JWEAlgorithm.parse() + * @param algorithmName + */ + public void setAlgorithmName(String algorithmName) { + if (!Strings.isNullOrEmpty(algorithmName)) { + algorithm = JWEAlgorithm.parse(algorithmName); + } else { + algorithm = null; + } + } - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "JWEAlgorithmEmbed [algorithm=" + algorithm + "]"; - } + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "JWEAlgorithmEmbed [algorithm=" + algorithm + "]"; + } - /** - * @return the algorithm - */ - public JWEAlgorithm getAlgorithm() { - return algorithm; - } + /** + * @return the algorithm + */ + public JWEAlgorithm getAlgorithm() { + return algorithm; + } - /** - * @param algorithm the algorithm to set - */ - public void setAlgorithm(JWEAlgorithm algorithm) { - this.algorithm = algorithm; - } + /** + * @param algorithm the algorithm to set + */ + public void setAlgorithm(JWEAlgorithm algorithm) { + this.algorithm = algorithm; + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jose/JWEEncryptionMethodEmbed.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jose/JWEEncryptionMethodEmbed.java index 1f46ef56f..facbd55ff 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jose/JWEEncryptionMethodEmbed.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jose/JWEEncryptionMethodEmbed.java @@ -30,76 +30,76 @@ import com.nimbusds.jose.EncryptionMethod; public class JWEEncryptionMethodEmbed { - public static final JWEEncryptionMethodEmbed NONE = getForAlgorithmName("none"); + public static final JWEEncryptionMethodEmbed NONE = getForAlgorithmName("none"); - private EncryptionMethod algorithm; + private EncryptionMethod algorithm; - public JWEEncryptionMethodEmbed() { + public JWEEncryptionMethodEmbed() { - } + } - public JWEEncryptionMethodEmbed(EncryptionMethod algorithm) { - this.algorithm = algorithm; - } + public JWEEncryptionMethodEmbed(EncryptionMethod algorithm) { + this.algorithm = algorithm; + } - public static JWEEncryptionMethodEmbed getForAlgorithmName (String algorithmName) { - JWEEncryptionMethodEmbed ent = new JWEEncryptionMethodEmbed(); - ent.setAlgorithmName(algorithmName); - if (ent.getAlgorithm() == null) { - return null; - } else { - return ent; - } - } + public static JWEEncryptionMethodEmbed getForAlgorithmName (String algorithmName) { + JWEEncryptionMethodEmbed ent = new JWEEncryptionMethodEmbed(); + ent.setAlgorithmName(algorithmName); + if (ent.getAlgorithm() == null) { + return null; + } else { + return ent; + } + } - /** - * Get the name of this algorithm, return null if no algorithm set. - * @return - */ + /** + * Get the name of this algorithm, return null if no algorithm set. + * @return + */ - public String getAlgorithmName() { - if (algorithm != null) { - return algorithm.getName(); - } else { - return null; - } - } + public String getAlgorithmName() { + if (algorithm != null) { + return algorithm.getName(); + } else { + return null; + } + } - /** - * Set the name of this algorithm. - * Calls EncryptionMethod.parse() - * @param algorithmName - */ - public void setAlgorithmName(String algorithmName) { - if (!Strings.isNullOrEmpty(algorithmName)) { - algorithm = EncryptionMethod.parse(algorithmName); - } else { - algorithm = null; - } - } + /** + * Set the name of this algorithm. + * Calls EncryptionMethod.parse() + * @param algorithmName + */ + public void setAlgorithmName(String algorithmName) { + if (!Strings.isNullOrEmpty(algorithmName)) { + algorithm = EncryptionMethod.parse(algorithmName); + } else { + algorithm = null; + } + } - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "JWEEncryptionMethodEmbed [algorithm=" + algorithm + "]"; - } + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "JWEEncryptionMethodEmbed [algorithm=" + algorithm + "]"; + } - /** - * @return the algorithm - */ + /** + * @return the algorithm + */ - public EncryptionMethod getAlgorithm() { - return algorithm; - } + public EncryptionMethod getAlgorithm() { + return algorithm; + } - /** - * @param algorithm the algorithm to set - */ - public void setAlgorithm(EncryptionMethod algorithm) { - this.algorithm = algorithm; - } + /** + * @param algorithm the algorithm to set + */ + public void setAlgorithm(EncryptionMethod algorithm) { + this.algorithm = algorithm; + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jose/JWSAlgorithmEmbed.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jose/JWSAlgorithmEmbed.java index cfe1b119e..0f96b955f 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jose/JWSAlgorithmEmbed.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jose/JWSAlgorithmEmbed.java @@ -32,81 +32,81 @@ import com.nimbusds.jose.JWSAlgorithm; public class JWSAlgorithmEmbed { - public static final JWSAlgorithmEmbed NONE = getForAlgorithmName("none"); + public static final JWSAlgorithmEmbed NONE = getForAlgorithmName("none"); - private JWSAlgorithm algorithm; + private JWSAlgorithm algorithm; - public JWSAlgorithmEmbed() { + public JWSAlgorithmEmbed() { - } + } - public JWSAlgorithmEmbed(JWSAlgorithm algorithm) { - this.algorithm = algorithm; - } + public JWSAlgorithmEmbed(JWSAlgorithm algorithm) { + this.algorithm = algorithm; + } - /** - * - * @param algorithmName - * @return null if algorithmName is empty or null - */ - public static JWSAlgorithmEmbed getForAlgorithmName (String algorithmName) { - JWSAlgorithmEmbed ent = new JWSAlgorithmEmbed(); - ent.setAlgorithmName(algorithmName); - if (ent.getAlgorithm() == null) { - return null; - } else { - return ent; - } - } + /** + * + * @param algorithmName + * @return null if algorithmName is empty or null + */ + public static JWSAlgorithmEmbed getForAlgorithmName (String algorithmName) { + JWSAlgorithmEmbed ent = new JWSAlgorithmEmbed(); + ent.setAlgorithmName(algorithmName); + if (ent.getAlgorithm() == null) { + return null; + } else { + return ent; + } + } - /** - * Get the name of this algorithm, return null if no algorithm set. - * @return - */ + /** + * Get the name of this algorithm, return null if no algorithm set. + * @return + */ - public String getAlgorithmName() { - if (algorithm != null) { - return algorithm.getName(); - } else { - return null; - } - } + public String getAlgorithmName() { + if (algorithm != null) { + return algorithm.getName(); + } else { + return null; + } + } - /** - * Set the name of this algorithm. - * Calls JWSAlgorithm.parse() - * @param algorithmName - */ - public void setAlgorithmName(String algorithmName) { - if (!Strings.isNullOrEmpty(algorithmName)) { - algorithm = JWSAlgorithm.parse(algorithmName); - } else { - algorithm = null; - } - } + /** + * Set the name of this algorithm. + * Calls JWSAlgorithm.parse() + * @param algorithmName + */ + public void setAlgorithmName(String algorithmName) { + if (!Strings.isNullOrEmpty(algorithmName)) { + algorithm = JWSAlgorithm.parse(algorithmName); + } else { + algorithm = null; + } + } - /** - * @return the algorithm - */ + /** + * @return the algorithm + */ - public JWSAlgorithm getAlgorithm() { - return algorithm; - } + public JWSAlgorithm getAlgorithm() { + return algorithm; + } - /** - * @param algorithm the algorithm to set - */ - public void setAlgorithm(JWSAlgorithm algorithm) { - this.algorithm = algorithm; - } + /** + * @param algorithm the algorithm to set + */ + public void setAlgorithm(JWSAlgorithm algorithm) { + this.algorithm = algorithm; + } - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "JWSAlgorithmEmbed [algorithm=" + algorithm + "]"; - } + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "JWSAlgorithmEmbed [algorithm=" + algorithm + "]"; + } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jose/keystore/JWKSetKeyStore.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jose/keystore/JWKSetKeyStore.java index f22844fb7..64d06926a 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jose/keystore/JWKSetKeyStore.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jose/keystore/JWKSetKeyStore.java @@ -60,10 +60,10 @@ public class JWKSetKeyStore { public JWKSetKeyStore(String jwkSetJsonString) { try { - this.jwkSet = JWKSet.parse(jwkSetJsonString); - } catch (ParseException e) { - _logger.error("ParseException", e); - } + this.jwkSet = JWKSet.parse(jwkSetJsonString); + } catch (ParseException e) { + _logger.error("ParseException", e); + } initializeJwkSet(); } @@ -143,64 +143,64 @@ public class JWKSetKeyStore { } public String toString(String mediaType){ - StringBuffer metaDataString = new StringBuffer(""); - //RSA Only - if(jwkSet.getKeys().get(0).getKeyType().getValue().equalsIgnoreCase("RSA")) { - - if(StringUtils.isNotBlank(mediaType) && mediaType.equalsIgnoreCase("XML")) { - - metaDataString.append("").append("\n"); - for(JWK jwk : jwkSet.getKeys()) { - RSAKey rsaKey = jwk.toRSAKey(); - PublicKey publicKey; - try { - publicKey = rsaKey.toPublicKey(); - metaDataString.append("").append("\n"); - metaDataString.append(RSAUtils.getPublicKeyPEM(publicKey.getEncoded())); - metaDataString.append("").append("\n"); - //keyID - metaDataString.append(""); - metaDataString.append(rsaKey.getAlgorithm()); - metaDataString.append("").append("\n"); - - metaDataString.append(""); - metaDataString.append(rsaKey.getKeyID()); - metaDataString.append("").append("\n"); - - metaDataString.append(""); - metaDataString.append(rsaKey.getKeyType()); - metaDataString.append("").append("\n"); - - metaDataString.append(""); - metaDataString.append(publicKey.getFormat()); - metaDataString.append(""); - - metaDataString.append(""); - metaDataString.append(rsaKey.getPublicExponent()); - metaDataString.append("").append("\n"); - } catch (JOSEException e) { - _logger.error("JOSEException ", mediaType); - } - } - metaDataString.append(""); - - }else { - //RSA Only - metaDataString.append(format(jwkSet.toPublicJWKSet().toString())); - } - }else { - metaDataString.append("RSA Only"); - } - return metaDataString.toString(); - } + StringBuffer metaDataString = new StringBuffer(""); + //RSA Only + if(jwkSet.getKeys().get(0).getKeyType().getValue().equalsIgnoreCase("RSA")) { + + if(StringUtils.isNotBlank(mediaType) && mediaType.equalsIgnoreCase("XML")) { + + metaDataString.append("").append("\n"); + for(JWK jwk : jwkSet.getKeys()) { + RSAKey rsaKey = jwk.toRSAKey(); + PublicKey publicKey; + try { + publicKey = rsaKey.toPublicKey(); + metaDataString.append("").append("\n"); + metaDataString.append(RSAUtils.getPublicKeyPEM(publicKey.getEncoded())); + metaDataString.append("").append("\n"); + //keyID + metaDataString.append(""); + metaDataString.append(rsaKey.getAlgorithm()); + metaDataString.append("").append("\n"); + + metaDataString.append(""); + metaDataString.append(rsaKey.getKeyID()); + metaDataString.append("").append("\n"); + + metaDataString.append(""); + metaDataString.append(rsaKey.getKeyType()); + metaDataString.append("").append("\n"); + + metaDataString.append(""); + metaDataString.append(publicKey.getFormat()); + metaDataString.append(""); + + metaDataString.append(""); + metaDataString.append(rsaKey.getPublicExponent()); + metaDataString.append("").append("\n"); + } catch (JOSEException e) { + _logger.error("JOSEException ", mediaType); + } + } + metaDataString.append(""); + + }else { + //RSA Only + metaDataString.append(format(jwkSet.toPublicJWKSet().toString())); + } + }else { + metaDataString.append("RSA Only"); + } + return metaDataString.toString(); + } - /** - * - * @param jsonString - * @return formated json string - */ - public String format(String jsonString){ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - return gson.toJson(JsonParser.parseString(jsonString)); - } + /** + * + * @param jsonString + * @return formated json string + */ + public String format(String jsonString){ + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + return gson.toJson(JsonParser.parseString(jsonString)); + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/Hmac512Service.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/Hmac512Service.java index 4770b6e3f..8e9babe42 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/Hmac512Service.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/Hmac512Service.java @@ -33,60 +33,60 @@ import com.nimbusds.jose.util.Base64URL; public class Hmac512Service { - public static final String MXK_AUTH_JWK = "mxk_auth_jwk"; - - JWSSigner signer; - - MACVerifier verifier; - - public Hmac512Service() { - super(); - } - - public Hmac512Service(String secretString) throws JOSEException { - Base64URL secret=new Base64URL(secretString); - OctetSequenceKey octKey= new OctetSequenceKey.Builder(secret) - .keyID(MXK_AUTH_JWK) - .keyUse(KeyUse.SIGNATURE) - .algorithm(JWSAlgorithm.HS512) - .build(); - signer = new MACSigner(octKey); - verifier = new MACVerifier(octKey); - } - - public String sign(Payload payload) { - try { - // Prepare JWS object with payload - JWSObject jwsObject = new JWSObject(new JWSHeader(JWSAlgorithm.HS512), payload); - // Apply the HMAC - jwsObject.sign(signer); - String jwt = jwsObject.serialize(); - return jwt; - } catch (JOSEException e) { - e.printStackTrace(); - } - - return null; - } + public static final String MXK_AUTH_JWK = "mxk_auth_jwk"; + + JWSSigner signer; + + MACVerifier verifier; + + public Hmac512Service() { + super(); + } + + public Hmac512Service(String secretString) throws JOSEException { + Base64URL secret=new Base64URL(secretString); + OctetSequenceKey octKey= new OctetSequenceKey.Builder(secret) + .keyID(MXK_AUTH_JWK) + .keyUse(KeyUse.SIGNATURE) + .algorithm(JWSAlgorithm.HS512) + .build(); + signer = new MACSigner(octKey); + verifier = new MACVerifier(octKey); + } + + public String sign(Payload payload) { + try { + // Prepare JWS object with payload + JWSObject jwsObject = new JWSObject(new JWSHeader(JWSAlgorithm.HS512), payload); + // Apply the HMAC + jwsObject.sign(signer); + String jwt = jwsObject.serialize(); + return jwt; + } catch (JOSEException e) { + e.printStackTrace(); + } + + return null; + } - public String sign(String payload) { - return sign(new Payload(payload)); - } - - - public boolean verify(String jwt) { - try { - JWSObject jwsObjected =JWSObject.parse(jwt); - boolean isVerifier = verifier.verify( - jwsObjected.getHeader(), - jwsObjected.getSigningInput(), - jwsObjected.getSignature()); - return isVerifier; - }catch(JOSEException JOSEException) { - - }catch(ParseException ParseException) { - - } - return false; - } + public String sign(String payload) { + return sign(new Payload(payload)); + } + + + public boolean verify(String jwt) { + try { + JWSObject jwsObjected =JWSObject.parse(jwt); + boolean isVerifier = verifier.verify( + jwsObjected.getHeader(), + jwsObjected.getSigningInput(), + jwsObjected.getSignature()); + return isVerifier; + }catch(JOSEException JOSEException) { + + }catch(ParseException ParseException) { + + } + return false; + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/encryption/service/JwtEncryptionAndDecryptionService.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/encryption/service/JwtEncryptionAndDecryptionService.java index 4abe1dbf7..133d61756 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/encryption/service/JwtEncryptionAndDecryptionService.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/encryption/service/JwtEncryptionAndDecryptionService.java @@ -30,41 +30,41 @@ import com.nimbusds.jose.jwk.JWK; */ public interface JwtEncryptionAndDecryptionService { - /** - * Encrypts the JWT in place with the default encrypter. - * If an arbitrary payload is used, then pass in a JWEObject. - * Otherwise, if JWT claims are the payload, then use the JWEObject subclass EncryptedJWT instead. - * @param jwt - */ - public void encryptJwt(JWEObject jwt); + /** + * Encrypts the JWT in place with the default encrypter. + * If an arbitrary payload is used, then pass in a JWEObject. + * Otherwise, if JWT claims are the payload, then use the JWEObject subclass EncryptedJWT instead. + * @param jwt + */ + public void encryptJwt(JWEObject jwt); - /** - * Decrypts the JWT in place with the default decrypter. - * If an arbitrary payload is used, then pass in a JWEObject. - * Otherwise, if JWT claims are the payload, then use the JWEObject subclass EncryptedJWT instead. - * @param jwt - */ - public void decryptJwt(JWEObject jwt); + /** + * Decrypts the JWT in place with the default decrypter. + * If an arbitrary payload is used, then pass in a JWEObject. + * Otherwise, if JWT claims are the payload, then use the JWEObject subclass EncryptedJWT instead. + * @param jwt + */ + public void decryptJwt(JWEObject jwt); - /** - * Get all public keys for this service, mapped by their Key ID - */ - public Map getAllPublicKeys(); + /** + * Get all public keys for this service, mapped by their Key ID + */ + public Map getAllPublicKeys(); - /** - * Get the list of all encryption algorithms supported by this service. - * @return - */ - public Collection getAllEncryptionAlgsSupported(); + /** + * Get the list of all encryption algorithms supported by this service. + * @return + */ + public Collection getAllEncryptionAlgsSupported(); - /** - * Get the list of all encryption methods supported by this service. - * @return - */ - public Collection getAllEncryptionEncsSupported(); + /** + * Get the list of all encryption methods supported by this service. + * @return + */ + public Collection getAllEncryptionEncsSupported(); - /** - * add functionality for encrypting and decrypting using a specified key id. - * Example: public void encryptJwt(EncryptedJWT jwt, String kid); - */ + /** + * add functionality for encrypting and decrypting using a specified key id. + * Example: public void encryptJwt(EncryptedJWT jwt, String kid); + */ } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/encryption/service/impl/DefaultJwtEncryptionAndDecryptionService.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/encryption/service/impl/DefaultJwtEncryptionAndDecryptionService.java index a86105db3..d70472137 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/encryption/service/impl/DefaultJwtEncryptionAndDecryptionService.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/encryption/service/impl/DefaultJwtEncryptionAndDecryptionService.java @@ -53,299 +53,299 @@ import jakarta.annotation.PostConstruct; */ public class DefaultJwtEncryptionAndDecryptionService implements JwtEncryptionAndDecryptionService { - private static Logger _logger = LoggerFactory.getLogger(DefaultJwtEncryptionAndDecryptionService.class); + private static Logger _logger = LoggerFactory.getLogger(DefaultJwtEncryptionAndDecryptionService.class); - // map of identifier to encrypter - private Map encrypters = new HashMap(); + // map of identifier to encrypter + private Map encrypters = new HashMap(); - // map of identifier to decrypter - private Map decrypters = new HashMap(); + // map of identifier to decrypter + private Map decrypters = new HashMap(); - private String defaultEncryptionKeyId; + private String defaultEncryptionKeyId; - private String defaultDecryptionKeyId; + private String defaultDecryptionKeyId; - private JWEAlgorithm defaultAlgorithm; + private JWEAlgorithm defaultAlgorithm; - // map of identifier to key - private Map keys = new HashMap(); + // map of identifier to key + private Map keys = new HashMap(); - /** - * Build this service based on the keys given. All public keys will be used to make encrypters, - * all private keys will be used to make decrypters. - * - * @param keys - * @throws NoSuchAlgorithmException - * @throws InvalidKeySpecException - * @throws JOSEException - */ - public DefaultJwtEncryptionAndDecryptionService(Map keys) throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException { - this.keys = keys; - buildEncryptersAndDecrypters(); - } + /** + * Build this service based on the keys given. All public keys will be used to make encrypters, + * all private keys will be used to make decrypters. + * + * @param keys + * @throws NoSuchAlgorithmException + * @throws InvalidKeySpecException + * @throws JOSEException + */ + public DefaultJwtEncryptionAndDecryptionService(Map keys) throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException { + this.keys = keys; + buildEncryptersAndDecrypters(); + } - /** - * Build this service based on the given keystore. All keys must have a key - * id ({@code kid}) field in order to be used. - * - * @param keyStore - * @throws NoSuchAlgorithmException - * @throws InvalidKeySpecException - * @throws JOSEException - */ - public DefaultJwtEncryptionAndDecryptionService(JWKSetKeyStore keyStore) throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException { + /** + * Build this service based on the given keystore. All keys must have a key + * id ({@code kid}) field in order to be used. + * + * @param keyStore + * @throws NoSuchAlgorithmException + * @throws InvalidKeySpecException + * @throws JOSEException + */ + public DefaultJwtEncryptionAndDecryptionService(JWKSetKeyStore keyStore) throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException { - // convert all keys in the keystore to a map based on key id - for (JWK key : keyStore.getKeys()) { - if (!Strings.isNullOrEmpty(key.getKeyID())) { - this.keys.put(key.getKeyID(), key); - } else { - throw new IllegalArgumentException("Tried to load a key from a keystore without a 'kid' field: " + key); - } - } + // convert all keys in the keystore to a map based on key id + for (JWK key : keyStore.getKeys()) { + if (!Strings.isNullOrEmpty(key.getKeyID())) { + this.keys.put(key.getKeyID(), key); + } else { + throw new IllegalArgumentException("Tried to load a key from a keystore without a 'kid' field: " + key); + } + } - buildEncryptersAndDecrypters(); + buildEncryptersAndDecrypters(); - } - - public DefaultJwtEncryptionAndDecryptionService(String jwkSetString, String defaultEncryptionKeyId,String defaultAlgorithm) throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException { - JWKSetKeyStore keyStore = new JWKSetKeyStore("{\"keys\": [" + jwkSetString + "]}"); - this.defaultEncryptionKeyId = defaultEncryptionKeyId; - this.defaultAlgorithm = JWEAlgorithm.parse(defaultAlgorithm); - _logger.trace(" encryptAlgorithm {}" , defaultAlgorithm); - - // convert all keys in the keystore to a map based on key id - for (JWK key : keyStore.getKeys()) { - if (!Strings.isNullOrEmpty(key.getKeyID())) { - this.keys.put(key.getKeyID(), key); - } else { - throw new IllegalArgumentException("Tried to load a key from a keystore without a 'kid' field: " + key); - } - } + } + + public DefaultJwtEncryptionAndDecryptionService(String jwkSetString, String defaultEncryptionKeyId,String defaultAlgorithm) throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException { + JWKSetKeyStore keyStore = new JWKSetKeyStore("{\"keys\": [" + jwkSetString + "]}"); + this.defaultEncryptionKeyId = defaultEncryptionKeyId; + this.defaultAlgorithm = JWEAlgorithm.parse(defaultAlgorithm); + _logger.trace(" encryptAlgorithm {}" , defaultAlgorithm); + + // convert all keys in the keystore to a map based on key id + for (JWK key : keyStore.getKeys()) { + if (!Strings.isNullOrEmpty(key.getKeyID())) { + this.keys.put(key.getKeyID(), key); + } else { + throw new IllegalArgumentException("Tried to load a key from a keystore without a 'kid' field: " + key); + } + } - buildEncryptersAndDecrypters(); + buildEncryptersAndDecrypters(); - } + } - @PostConstruct - public void afterPropertiesSet() { + @PostConstruct + public void afterPropertiesSet() { - if (keys == null) { - throw new IllegalArgumentException("Encryption and decryption service must have at least one key configured."); - } - try { - buildEncryptersAndDecrypters(); - } catch (NoSuchAlgorithmException e) { - throw new IllegalArgumentException("Encryption and decryption service could not find given algorithm."); - } catch (InvalidKeySpecException e) { - throw new IllegalArgumentException("Encryption and decryption service saw an invalid key specification."); - } catch (JOSEException e) { - throw new IllegalArgumentException("Encryption and decryption service was unable to process JOSE object."); - } - } + if (keys == null) { + throw new IllegalArgumentException("Encryption and decryption service must have at least one key configured."); + } + try { + buildEncryptersAndDecrypters(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalArgumentException("Encryption and decryption service could not find given algorithm."); + } catch (InvalidKeySpecException e) { + throw new IllegalArgumentException("Encryption and decryption service saw an invalid key specification."); + } catch (JOSEException e) { + throw new IllegalArgumentException("Encryption and decryption service was unable to process JOSE object."); + } + } - public String getDefaultEncryptionKeyId() { - if (defaultEncryptionKeyId != null) { - return defaultEncryptionKeyId; - } else if (keys.size() == 1) { - // if there's only one key in the map, it's the default - return keys.keySet().iterator().next(); - } else { - return null; - } - } + public String getDefaultEncryptionKeyId() { + if (defaultEncryptionKeyId != null) { + return defaultEncryptionKeyId; + } else if (keys.size() == 1) { + // if there's only one key in the map, it's the default + return keys.keySet().iterator().next(); + } else { + return null; + } + } - public void setDefaultEncryptionKeyId(String defaultEncryptionKeyId) { - this.defaultEncryptionKeyId = defaultEncryptionKeyId; - } + public void setDefaultEncryptionKeyId(String defaultEncryptionKeyId) { + this.defaultEncryptionKeyId = defaultEncryptionKeyId; + } - public String getDefaultDecryptionKeyId() { - if (defaultDecryptionKeyId != null) { - return defaultDecryptionKeyId; - } else if (keys.size() == 1) { - // if there's only one key in the map, it's the default - return keys.keySet().iterator().next(); - } else { - return null; - } - } + public String getDefaultDecryptionKeyId() { + if (defaultDecryptionKeyId != null) { + return defaultDecryptionKeyId; + } else if (keys.size() == 1) { + // if there's only one key in the map, it's the default + return keys.keySet().iterator().next(); + } else { + return null; + } + } - public void setDefaultDecryptionKeyId(String defaultDecryptionKeyId) { - this.defaultDecryptionKeyId = defaultDecryptionKeyId; - } + public void setDefaultDecryptionKeyId(String defaultDecryptionKeyId) { + this.defaultDecryptionKeyId = defaultDecryptionKeyId; + } - public JWEAlgorithm getDefaultAlgorithm() { - return defaultAlgorithm; - } - - public JWEAlgorithm getDefaultAlgorithm(String algorithm) { - if(algorithm.startsWith("RSA")) { - return defaultAlgorithm; - }else { - return JWEAlgorithm.DIR; - } - } + public JWEAlgorithm getDefaultAlgorithm() { + return defaultAlgorithm; + } + + public JWEAlgorithm getDefaultAlgorithm(String algorithm) { + if(algorithm.startsWith("RSA")) { + return defaultAlgorithm; + }else { + return JWEAlgorithm.DIR; + } + } - public void setDefaultAlgorithm(String algorithm) { - defaultAlgorithm = JWEAlgorithm.parse(algorithm); - } - - public void setDefaultAlgorithm(JWEAlgorithm defaultAlgorithm) { - this.defaultAlgorithm = defaultAlgorithm; - } + public void setDefaultAlgorithm(String algorithm) { + defaultAlgorithm = JWEAlgorithm.parse(algorithm); + } + + public void setDefaultAlgorithm(JWEAlgorithm defaultAlgorithm) { + this.defaultAlgorithm = defaultAlgorithm; + } - /* (non-Javadoc) - * @see org.mitre.jwt.encryption.service.JwtEncryptionAndDecryptionService#encryptJwt(com.nimbusds.jwt.EncryptedJWT) - */ - @Override - public void encryptJwt(JWEObject jwt) { - if (getDefaultEncryptionKeyId() == null) { - throw new IllegalStateException("Tried to call default encryption with no default encrypter ID set"); - } + /* (non-Javadoc) + * @see org.mitre.jwt.encryption.service.JwtEncryptionAndDecryptionService#encryptJwt(com.nimbusds.jwt.EncryptedJWT) + */ + @Override + public void encryptJwt(JWEObject jwt) { + if (getDefaultEncryptionKeyId() == null) { + throw new IllegalStateException("Tried to call default encryption with no default encrypter ID set"); + } - JWEEncrypter encrypter = encrypters.get(getDefaultEncryptionKeyId()); + JWEEncrypter encrypter = encrypters.get(getDefaultEncryptionKeyId()); - try { - jwt.encrypt(encrypter); - } catch (JOSEException e) { + try { + jwt.encrypt(encrypter); + } catch (JOSEException e) { - _logger.error("Failed to encrypt JWT, error was: ", e); - } + _logger.error("Failed to encrypt JWT, error was: ", e); + } - } + } - /* (non-Javadoc) - * @see org.mitre.jwt.encryption.service.JwtEncryptionAndDecryptionService#decryptJwt(com.nimbusds.jwt.EncryptedJWT) - */ - @Override - public void decryptJwt(JWEObject jwt) { - if (getDefaultDecryptionKeyId() == null) { - throw new IllegalStateException("Tried to call default decryption with no default decrypter ID set"); - } + /* (non-Javadoc) + * @see org.mitre.jwt.encryption.service.JwtEncryptionAndDecryptionService#decryptJwt(com.nimbusds.jwt.EncryptedJWT) + */ + @Override + public void decryptJwt(JWEObject jwt) { + if (getDefaultDecryptionKeyId() == null) { + throw new IllegalStateException("Tried to call default decryption with no default decrypter ID set"); + } - JWEDecrypter decrypter = decrypters.get(getDefaultDecryptionKeyId()); + JWEDecrypter decrypter = decrypters.get(getDefaultDecryptionKeyId()); - try { - jwt.decrypt(decrypter); - } catch (JOSEException e) { + try { + jwt.decrypt(decrypter); + } catch (JOSEException e) { - _logger.error("Failed to decrypt JWT, error was: ", e); - } + _logger.error("Failed to decrypt JWT, error was: ", e); + } - } + } - /** - * Builds all the encrypters and decrypters for this service based on the key map. - * @throws - * @throws InvalidKeySpecException - * @throws NoSuchAlgorithmException - * @throws JOSEException - */ - private void buildEncryptersAndDecrypters() throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException { + /** + * Builds all the encrypters and decrypters for this service based on the key map. + * @throws + * @throws InvalidKeySpecException + * @throws NoSuchAlgorithmException + * @throws JOSEException + */ + private void buildEncryptersAndDecrypters() throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException { - for (Map.Entry jwkEntry : keys.entrySet()) { + for (Map.Entry jwkEntry : keys.entrySet()) { - String id = jwkEntry.getKey(); - JWK jwk = jwkEntry.getValue(); + String id = jwkEntry.getKey(); + JWK jwk = jwkEntry.getValue(); - if (jwk instanceof RSAKey) { - // build RSA encrypters and decrypters + if (jwk instanceof RSAKey) { + // build RSA encrypters and decrypters - RSAEncrypter encrypter = new RSAEncrypter(((RSAKey) jwk).toRSAPublicKey()); // there should always at least be the public key - encrypters.put(id, encrypter); + RSAEncrypter encrypter = new RSAEncrypter(((RSAKey) jwk).toRSAPublicKey()); // there should always at least be the public key + encrypters.put(id, encrypter); - if (jwk.isPrivate()) { // we can decrypt! - RSADecrypter decrypter = new RSADecrypter(((RSAKey) jwk).toRSAPrivateKey()); - decrypters.put(id, decrypter); - } else { - _logger.warn("No private key for key #" + jwk.getKeyID()); - } + if (jwk.isPrivate()) { // we can decrypt! + RSADecrypter decrypter = new RSADecrypter(((RSAKey) jwk).toRSAPrivateKey()); + decrypters.put(id, decrypter); + } else { + _logger.warn("No private key for key #" + jwk.getKeyID()); + } - // add support for EC keys + // add support for EC keys - } else if (jwk instanceof OctetSequenceKey) { - // build symmetric encrypters and decrypters + } else if (jwk instanceof OctetSequenceKey) { + // build symmetric encrypters and decrypters - DirectEncrypter encrypter = new DirectEncrypter(((OctetSequenceKey) jwk).toByteArray()); - DirectDecrypter decrypter = new DirectDecrypter(((OctetSequenceKey) jwk).toByteArray()); + DirectEncrypter encrypter = new DirectEncrypter(((OctetSequenceKey) jwk).toByteArray()); + DirectDecrypter decrypter = new DirectDecrypter(((OctetSequenceKey) jwk).toByteArray()); - encrypters.put(id, encrypter); - decrypters.put(id, decrypter); + encrypters.put(id, encrypter); + decrypters.put(id, decrypter); - } else { - _logger.warn("Unknown key type: " + jwk); - } + } else { + _logger.warn("Unknown key type: " + jwk); + } - } - } + } + } - @Override - public Map getAllPublicKeys() { - Map pubKeys = new HashMap(); + @Override + public Map getAllPublicKeys() { + Map pubKeys = new HashMap(); - // pull out all public keys - for (String keyId : keys.keySet()) { - JWK key = keys.get(keyId); - JWK pub = key.toPublicJWK(); - if (pub != null) { - pubKeys.put(keyId, pub); - } - } + // pull out all public keys + for (String keyId : keys.keySet()) { + JWK key = keys.get(keyId); + JWK pub = key.toPublicJWK(); + if (pub != null) { + pubKeys.put(keyId, pub); + } + } - return pubKeys; - } + return pubKeys; + } - @Override - public Collection getAllEncryptionAlgsSupported() { - Set algs = new HashSet(); + @Override + public Collection getAllEncryptionAlgsSupported() { + Set algs = new HashSet(); - for (JWEEncrypter encrypter : encrypters.values()) { - algs.addAll(encrypter.supportedJWEAlgorithms()); - } + for (JWEEncrypter encrypter : encrypters.values()) { + algs.addAll(encrypter.supportedJWEAlgorithms()); + } - for (JWEDecrypter decrypter : decrypters.values()) { - algs.addAll(decrypter.supportedJWEAlgorithms()); - } + for (JWEDecrypter decrypter : decrypters.values()) { + algs.addAll(decrypter.supportedJWEAlgorithms()); + } - return algs; - } + return algs; + } - /* (non-Javadoc) - * @see org.mitre.jwt.encryption.service.JwtEncryptionAndDecryptionService#getAllEncryptionEncsSupported() - */ - @Override - public Collection getAllEncryptionEncsSupported() { - Set encs = new HashSet(); + /* (non-Javadoc) + * @see org.mitre.jwt.encryption.service.JwtEncryptionAndDecryptionService#getAllEncryptionEncsSupported() + */ + @Override + public Collection getAllEncryptionEncsSupported() { + Set encs = new HashSet(); - for (JWEEncrypter encrypter : encrypters.values()) { - encs.addAll(encrypter.supportedEncryptionMethods()); - } + for (JWEEncrypter encrypter : encrypters.values()) { + encs.addAll(encrypter.supportedEncryptionMethods()); + } - for (JWEDecrypter decrypter : decrypters.values()) { - encs.addAll(decrypter.supportedEncryptionMethods()); - } + for (JWEDecrypter decrypter : decrypters.values()) { + encs.addAll(decrypter.supportedEncryptionMethods()); + } - return encs; - } + return encs; + } - public EncryptionMethod parseEncryptionMethod(String encryptionMethodName) { - EncryptionMethod encryptionMethod = null; - if(encryptionMethodName.equalsIgnoreCase("A128GCM")) { - encryptionMethod = EncryptionMethod.A128GCM; - }else if(encryptionMethodName.equalsIgnoreCase("A192GCM")) { - encryptionMethod = EncryptionMethod.A192GCM; - }else if(encryptionMethodName.equalsIgnoreCase("A256GCM")) { - encryptionMethod = EncryptionMethod.A256GCM; - }else if(encryptionMethodName.equalsIgnoreCase("A128CBC_HS256")) { - encryptionMethod = EncryptionMethod.A128CBC_HS256; - }else if(encryptionMethodName.equalsIgnoreCase("A192CBC_HS384")) { - encryptionMethod = EncryptionMethod.A192CBC_HS384; - }else if(encryptionMethodName.equalsIgnoreCase("A256CBC_HS512")) { - encryptionMethod = EncryptionMethod.A256CBC_HS512; - }else if(encryptionMethodName.equalsIgnoreCase("XC20P")) { - encryptionMethod = EncryptionMethod.XC20P; - } - return encryptionMethod; - } + public EncryptionMethod parseEncryptionMethod(String encryptionMethodName) { + EncryptionMethod encryptionMethod = null; + if(encryptionMethodName.equalsIgnoreCase("A128GCM")) { + encryptionMethod = EncryptionMethod.A128GCM; + }else if(encryptionMethodName.equalsIgnoreCase("A192GCM")) { + encryptionMethod = EncryptionMethod.A192GCM; + }else if(encryptionMethodName.equalsIgnoreCase("A256GCM")) { + encryptionMethod = EncryptionMethod.A256GCM; + }else if(encryptionMethodName.equalsIgnoreCase("A128CBC_HS256")) { + encryptionMethod = EncryptionMethod.A128CBC_HS256; + }else if(encryptionMethodName.equalsIgnoreCase("A192CBC_HS384")) { + encryptionMethod = EncryptionMethod.A192CBC_HS384; + }else if(encryptionMethodName.equalsIgnoreCase("A256CBC_HS512")) { + encryptionMethod = EncryptionMethod.A256CBC_HS512; + }else if(encryptionMethodName.equalsIgnoreCase("XC20P")) { + encryptionMethod = EncryptionMethod.XC20P; + } + return encryptionMethod; + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/encryption/service/impl/RecipientJwtEncryptionAndDecryptionServiceBuilder.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/encryption/service/impl/RecipientJwtEncryptionAndDecryptionServiceBuilder.java index 6c28c7db5..64e289630 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/encryption/service/impl/RecipientJwtEncryptionAndDecryptionServiceBuilder.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/encryption/service/impl/RecipientJwtEncryptionAndDecryptionServiceBuilder.java @@ -37,45 +37,45 @@ import com.nimbusds.jose.jwk.JWKSet; * */ public class RecipientJwtEncryptionAndDecryptionServiceBuilder { - static final Logger _logger = LoggerFactory.getLogger(RecipientJwtEncryptionAndDecryptionServiceBuilder.class); - - //private HttpClient httpClient = HttpClientBuilder.create().useSystemProperties().build(); - //private HttpComponentsClientHttpRequestFactory httpFactory = new HttpComponentsClientHttpRequestFactory(httpClient); - //private RestTemplate restTemplate = new RestTemplate(httpFactory); - - /** - * - */ - public RecipientJwtEncryptionAndDecryptionServiceBuilder() { - - } - - public JwtEncryptionAndDecryptionService serviceBuilder(String jwksUri){ - - _logger.debug("jwksUri : {}" , jwksUri); - - String jsonString ="";//= restTemplate.getForObject(jwksUri, String.class); - - _logger.debug("jwks json String : {}" , jsonString); - JwtEncryptionAndDecryptionService recipientJwtEncryptionAndDecryptionService; - try { - JWKSet jwkSet = JWKSet.parse(jsonString); + static final Logger _logger = LoggerFactory.getLogger(RecipientJwtEncryptionAndDecryptionServiceBuilder.class); + + //private HttpClient httpClient = HttpClientBuilder.create().useSystemProperties().build(); + //private HttpComponentsClientHttpRequestFactory httpFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + //private RestTemplate restTemplate = new RestTemplate(httpFactory); + + /** + * + */ + public RecipientJwtEncryptionAndDecryptionServiceBuilder() { + + } + + public JwtEncryptionAndDecryptionService serviceBuilder(String jwksUri){ + + _logger.debug("jwksUri : {}" , jwksUri); + + String jsonString ="";//= restTemplate.getForObject(jwksUri, String.class); + + _logger.debug("jwks json String : {}" , jsonString); + JwtEncryptionAndDecryptionService recipientJwtEncryptionAndDecryptionService; + try { + JWKSet jwkSet = JWKSet.parse(jsonString); - JWKSetKeyStore keyStore = new JWKSetKeyStore(jwkSet); - recipientJwtEncryptionAndDecryptionService = new DefaultJwtEncryptionAndDecryptionService(keyStore); - - return recipientJwtEncryptionAndDecryptionService; - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } catch (InvalidKeySpecException e) { - e.printStackTrace(); - } catch (JOSEException e) { - e.printStackTrace(); - } catch (ParseException e) { - e.printStackTrace(); - } - - return null; - } + JWKSetKeyStore keyStore = new JWKSetKeyStore(jwkSet); + recipientJwtEncryptionAndDecryptionService = new DefaultJwtEncryptionAndDecryptionService(keyStore); + + return recipientJwtEncryptionAndDecryptionService; + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (InvalidKeySpecException e) { + e.printStackTrace(); + } catch (JOSEException e) { + e.printStackTrace(); + } catch (ParseException e) { + e.printStackTrace(); + } + + return null; + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/JwtSigningAndValidationService.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/JwtSigningAndValidationService.java index cb5b661db..6cc9860be 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/JwtSigningAndValidationService.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/JwtSigningAndValidationService.java @@ -26,57 +26,57 @@ import com.nimbusds.jwt.SignedJWT; public interface JwtSigningAndValidationService { - /** - * Get all public keys for this service, mapped by their Key ID - */ - public Map getAllPublicKeys(); + /** + * Get all public keys for this service, mapped by their Key ID + */ + public Map getAllPublicKeys(); - /** - * Checks the signature of the given JWT against all configured signers, - * returns true if at least one of the signers validates it. - * - * @param jwtString - * the string representation of the JWT as sent on the wire - * @return true if the signature is valid, false if not - * @throws NoSuchAlgorithmException - */ - public boolean validateSignature(SignedJWT jwtString); + /** + * Checks the signature of the given JWT against all configured signers, + * returns true if at least one of the signers validates it. + * + * @param jwtString + * the string representation of the JWT as sent on the wire + * @return true if the signature is valid, false if not + * @throws NoSuchAlgorithmException + */ + public boolean validateSignature(SignedJWT jwtString); - /** - * Called to sign a jwt in place for a client that hasn't registered a preferred signing algorithm. - * Use the default algorithm to sign. - * - * @param jwt the jwt to sign - * @return the signed jwt - * @throws NoSuchAlgorithmException - */ - public void signJwt(SignedJWT jwt); + /** + * Called to sign a jwt in place for a client that hasn't registered a preferred signing algorithm. + * Use the default algorithm to sign. + * + * @param jwt the jwt to sign + * @return the signed jwt + * @throws NoSuchAlgorithmException + */ + public void signJwt(SignedJWT jwt); - /** - * Get the default signing algorithm for use when nothing else has been specified. - * @return - */ - public JWSAlgorithm getDefaultSigningAlgorithm(); + /** + * Get the default signing algorithm for use when nothing else has been specified. + * @return + */ + public JWSAlgorithm getDefaultSigningAlgorithm(); - /** - * Get the list of all signing algorithms supported by this service. - * @return - */ - public Collection getAllSigningAlgsSupported(); + /** + * Get the list of all signing algorithms supported by this service. + * @return + */ + public Collection getAllSigningAlgsSupported(); - /** - * Sign a jwt using the selected algorithm. The algorithm is selected using the String parameter values specified - * in the JWT spec, section 6. I.E., "HS256" means HMAC with SHA-256 and corresponds to our HmacSigner class. - * - * @param jwt the jwt to sign - * @param alg the name of the algorithm to use, as specified in JWS s.6 - * @return the signed jwt - */ - public void signJwt(SignedJWT jwt, JWSAlgorithm alg); + /** + * Sign a jwt using the selected algorithm. The algorithm is selected using the String parameter values specified + * in the JWT spec, section 6. I.E., "HS256" means HMAC with SHA-256 and corresponds to our HmacSigner class. + * + * @param jwt the jwt to sign + * @param alg the name of the algorithm to use, as specified in JWS s.6 + * @return the signed jwt + */ + public void signJwt(SignedJWT jwt, JWSAlgorithm alg); - public String getDefaultSignerKeyId(); + public String getDefaultSignerKeyId(); - /** - * method to sign a jwt using a specified algorithm and a key id - */ + /** + * method to sign a jwt using a specified algorithm and a key id + */ } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/impl/DefaultJwtSigningAndValidationService.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/impl/DefaultJwtSigningAndValidationService.java index dee828442..7ed79c87f 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/impl/DefaultJwtSigningAndValidationService.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/impl/DefaultJwtSigningAndValidationService.java @@ -46,288 +46,288 @@ import com.nimbusds.jose.jwk.RSAKey; import com.nimbusds.jwt.SignedJWT; public class DefaultJwtSigningAndValidationService implements JwtSigningAndValidationService { - static final Logger _logger = LoggerFactory.getLogger(DefaultJwtSigningAndValidationService.class); - - // map of identifier to signer - private Map signers = new HashMap(); + static final Logger _logger = LoggerFactory.getLogger(DefaultJwtSigningAndValidationService.class); + + // map of identifier to signer + private Map signers = new HashMap(); - // map of identifier to verifier - private Map verifiers = new HashMap(); + // map of identifier to verifier + private Map verifiers = new HashMap(); - private static Logger logger = LoggerFactory.getLogger(DefaultJwtSigningAndValidationService.class); + private static Logger logger = LoggerFactory.getLogger(DefaultJwtSigningAndValidationService.class); - private String defaultSignerKeyId; + private String defaultSignerKeyId; - private JWSAlgorithm defaultAlgorithm; + private JWSAlgorithm defaultAlgorithm; - // map of identifier to key - private Map keys = new HashMap(); + // map of identifier to key + private Map keys = new HashMap(); - /** - * Build this service based on the keys given. All public keys will be used - * to make verifiers, all private keys will be used to make signers. - * - * @param keys - * A map of key identifier to key - * - * @throws InvalidKeySpecException - * If the keys in the JWKs are not valid - * @throws NoSuchAlgorithmException - * If there is no appropriate algorithm to tie the keys to. - * @throws JOSEException - */ - public DefaultJwtSigningAndValidationService(Map keys) throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException { - this.keys = keys; - buildSignersAndVerifiers(); - } + /** + * Build this service based on the keys given. All public keys will be used + * to make verifiers, all private keys will be used to make signers. + * + * @param keys + * A map of key identifier to key + * + * @throws InvalidKeySpecException + * If the keys in the JWKs are not valid + * @throws NoSuchAlgorithmException + * If there is no appropriate algorithm to tie the keys to. + * @throws JOSEException + */ + public DefaultJwtSigningAndValidationService(Map keys) throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException { + this.keys = keys; + buildSignersAndVerifiers(); + } - /** - * Build this service based on the given keystore. All keys must have a key - * id ({@code kid}) field in order to be used. - * - * @param keyStore - * the keystore to load all keys from - * - * @throws InvalidKeySpecException - * If the keys in the JWKs are not valid - * @throws NoSuchAlgorithmException - * If there is no appropriate algorithm to tie the keys to. - * @throws JOSEException - */ - public DefaultJwtSigningAndValidationService(JWKSetKeyStore keyStore) throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException { - // convert all keys in the keystore to a map based on key id - if (keyStore!= null && keyStore.getJwkSet() != null) { - for (JWK key : keyStore.getKeys()) { - if (!Strings.isNullOrEmpty(key.getKeyID())) { - // use the key ID that's built into the key itself - // (#641): deal with JWK thumbprints - this.keys.put(key.getKeyID(), key); - } else { - // create a random key id - String fakeKid = UUID.randomUUID().toString(); - this.keys.put(fakeKid, key); - } - } - } - buildSignersAndVerifiers(); - } + /** + * Build this service based on the given keystore. All keys must have a key + * id ({@code kid}) field in order to be used. + * + * @param keyStore + * the keystore to load all keys from + * + * @throws InvalidKeySpecException + * If the keys in the JWKs are not valid + * @throws NoSuchAlgorithmException + * If there is no appropriate algorithm to tie the keys to. + * @throws JOSEException + */ + public DefaultJwtSigningAndValidationService(JWKSetKeyStore keyStore) throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException { + // convert all keys in the keystore to a map based on key id + if (keyStore!= null && keyStore.getJwkSet() != null) { + for (JWK key : keyStore.getKeys()) { + if (!Strings.isNullOrEmpty(key.getKeyID())) { + // use the key ID that's built into the key itself + // (#641): deal with JWK thumbprints + this.keys.put(key.getKeyID(), key); + } else { + // create a random key id + String fakeKid = UUID.randomUUID().toString(); + this.keys.put(fakeKid, key); + } + } + } + buildSignersAndVerifiers(); + } - /** - * Build this service based on the given keystore. All keys must have a key - * id ({@code kid}) field in order to be used. - * see DefaultJwtSigningAndValidationService(JWKSetKeyStore keyStore) - * @param jwkSetString - * @param defaultSignerKeyId - * @param defaultAlgorithm - * @throws NoSuchAlgorithmException - * @throws InvalidKeySpecException - * @throws JOSEException - */ - public DefaultJwtSigningAndValidationService(String jwkSetString, String defaultSignerKeyId,String defaultAlgorithm) throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException { - JWKSetKeyStore keyStore = new JWKSetKeyStore("{\"keys\": [" + jwkSetString + "]}"); - this.defaultSignerKeyId = defaultSignerKeyId; - this.defaultAlgorithm = JWSAlgorithm.parse(defaultAlgorithm); - _logger.trace(" signingAlg {}" , defaultAlgorithm); - - // convert all keys in the keystore to a map based on key id - if (keyStore!= null && keyStore.getJwkSet() != null) { - for (JWK key : keyStore.getKeys()) { - if (!Strings.isNullOrEmpty(key.getKeyID())) { - // use the key ID that's built into the key itself - // (#641): deal with JWK thumbprints - this.keys.put(key.getKeyID(), key); - } else { - // create a random key id - String fakeKid = UUID.randomUUID().toString(); - this.keys.put(fakeKid, key); - } - } - } - buildSignersAndVerifiers(); - } - /** - * @return the defaultSignerKeyId - */ - @Override - public String getDefaultSignerKeyId() { - return defaultSignerKeyId; - } + /** + * Build this service based on the given keystore. All keys must have a key + * id ({@code kid}) field in order to be used. + * see DefaultJwtSigningAndValidationService(JWKSetKeyStore keyStore) + * @param jwkSetString + * @param defaultSignerKeyId + * @param defaultAlgorithm + * @throws NoSuchAlgorithmException + * @throws InvalidKeySpecException + * @throws JOSEException + */ + public DefaultJwtSigningAndValidationService(String jwkSetString, String defaultSignerKeyId,String defaultAlgorithm) throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException { + JWKSetKeyStore keyStore = new JWKSetKeyStore("{\"keys\": [" + jwkSetString + "]}"); + this.defaultSignerKeyId = defaultSignerKeyId; + this.defaultAlgorithm = JWSAlgorithm.parse(defaultAlgorithm); + _logger.trace(" signingAlg {}" , defaultAlgorithm); + + // convert all keys in the keystore to a map based on key id + if (keyStore!= null && keyStore.getJwkSet() != null) { + for (JWK key : keyStore.getKeys()) { + if (!Strings.isNullOrEmpty(key.getKeyID())) { + // use the key ID that's built into the key itself + // (#641): deal with JWK thumbprints + this.keys.put(key.getKeyID(), key); + } else { + // create a random key id + String fakeKid = UUID.randomUUID().toString(); + this.keys.put(fakeKid, key); + } + } + } + buildSignersAndVerifiers(); + } + /** + * @return the defaultSignerKeyId + */ + @Override + public String getDefaultSignerKeyId() { + return defaultSignerKeyId; + } - /** - * @param defaultSignerKeyId the defaultSignerKeyId to set - */ - public void setDefaultSignerKeyId(String defaultSignerId) { - this.defaultSignerKeyId = defaultSignerId; - } + /** + * @param defaultSignerKeyId the defaultSignerKeyId to set + */ + public void setDefaultSignerKeyId(String defaultSignerId) { + this.defaultSignerKeyId = defaultSignerId; + } - /** - * @return - */ - @Override - public JWSAlgorithm getDefaultSigningAlgorithm() { - return defaultAlgorithm; - } + /** + * @return + */ + @Override + public JWSAlgorithm getDefaultSigningAlgorithm() { + return defaultAlgorithm; + } - public void setDefaultSigningAlgorithmName(String algName) { - defaultAlgorithm = JWSAlgorithm.parse(algName); - } + public void setDefaultSigningAlgorithmName(String algName) { + defaultAlgorithm = JWSAlgorithm.parse(algName); + } - public String getDefaultSigningAlgorithmName() { - if (defaultAlgorithm != null) { - return defaultAlgorithm.getName(); - } else { - return null; - } - } + public String getDefaultSigningAlgorithmName() { + if (defaultAlgorithm != null) { + return defaultAlgorithm.getName(); + } else { + return null; + } + } - /** - * Build all of the signers and verifiers for this based on the key map. - * @throws InvalidKeySpecException If the keys in the JWKs are not valid - * @throws NoSuchAlgorithmException If there is no appropriate algorithm to tie the keys to. - * @throws JOSEException - */ - private void buildSignersAndVerifiers() throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException { - for (Map.Entry jwkEntry : keys.entrySet()) { + /** + * Build all of the signers and verifiers for this based on the key map. + * @throws InvalidKeySpecException If the keys in the JWKs are not valid + * @throws NoSuchAlgorithmException If there is no appropriate algorithm to tie the keys to. + * @throws JOSEException + */ + private void buildSignersAndVerifiers() throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException { + for (Map.Entry jwkEntry : keys.entrySet()) { - String id = jwkEntry.getKey(); - JWK jwk = jwkEntry.getValue(); + String id = jwkEntry.getKey(); + JWK jwk = jwkEntry.getValue(); - if (jwk instanceof RSAKey) { - // build RSA signers & verifiers + if (jwk instanceof RSAKey) { + // build RSA signers & verifiers - if (jwk.isPrivate()) { // only add the signer if there's a private key - RSASSASigner signer = new RSASSASigner(((RSAKey) jwk).toRSAPrivateKey()); - signers.put(id, signer); - } + if (jwk.isPrivate()) { // only add the signer if there's a private key + RSASSASigner signer = new RSASSASigner(((RSAKey) jwk).toRSAPrivateKey()); + signers.put(id, signer); + } - RSASSAVerifier verifier = new RSASSAVerifier(((RSAKey) jwk).toRSAPublicKey()); - verifiers.put(id, verifier); + RSASSAVerifier verifier = new RSASSAVerifier(((RSAKey) jwk).toRSAPublicKey()); + verifiers.put(id, verifier); - } else if (jwk instanceof ECKey) { - // build EC signers & verifiers + } else if (jwk instanceof ECKey) { + // build EC signers & verifiers - // add support for EC keys - logger.warn("EC Keys are not yet supported."); + // add support for EC keys + logger.warn("EC Keys are not yet supported."); - } else if (jwk instanceof OctetSequenceKey) { - // build HMAC signers & verifiers + } else if (jwk instanceof OctetSequenceKey) { + // build HMAC signers & verifiers - if (jwk.isPrivate()) { // technically redundant check because all HMAC keys are private - MACSigner signer = new MACSigner(((OctetSequenceKey) jwk).toByteArray()); - signers.put(id, signer); - } + if (jwk.isPrivate()) { // technically redundant check because all HMAC keys are private + MACSigner signer = new MACSigner(((OctetSequenceKey) jwk).toByteArray()); + signers.put(id, signer); + } - MACVerifier verifier = new MACVerifier(((OctetSequenceKey) jwk).toByteArray()); - verifiers.put(id, verifier); + MACVerifier verifier = new MACVerifier(((OctetSequenceKey) jwk).toByteArray()); + verifiers.put(id, verifier); - } else { - logger.warn("Unknown key type: " + jwk); - } - } - - if (defaultSignerKeyId == null && keys.size() == 1) { - // if there's only one key, it's the default - setDefaultSignerKeyId(keys.keySet().iterator().next()); - } - } + } else { + logger.warn("Unknown key type: " + jwk); + } + } + + if (defaultSignerKeyId == null && keys.size() == 1) { + // if there's only one key, it's the default + setDefaultSignerKeyId(keys.keySet().iterator().next()); + } + } - /** - * Sign a jwt in place using the configured default signer. - */ - @Override - public void signJwt(SignedJWT jwt) { - if (getDefaultSignerKeyId() == null) { - throw new IllegalStateException("Tried to call default signing with no default signer ID set"); - } + /** + * Sign a jwt in place using the configured default signer. + */ + @Override + public void signJwt(SignedJWT jwt) { + if (getDefaultSignerKeyId() == null) { + throw new IllegalStateException("Tried to call default signing with no default signer ID set"); + } - JWSSigner signer = signers.get(getDefaultSignerKeyId()); + JWSSigner signer = signers.get(getDefaultSignerKeyId()); - try { - jwt.sign(signer); - } catch (JOSEException e) { + try { + jwt.sign(signer); + } catch (JOSEException e) { - logger.error("Failed to sign JWT, error was: ", e); - } + logger.error("Failed to sign JWT, error was: ", e); + } - } + } - @Override - public void signJwt(SignedJWT jwt, JWSAlgorithm alg) { + @Override + public void signJwt(SignedJWT jwt, JWSAlgorithm alg) { - JWSSigner signer = null; + JWSSigner signer = null; - for (JWSSigner s : signers.values()) { - if (s.supportedJWSAlgorithms().contains(alg)) { - signer = s; - break; - } - } + for (JWSSigner s : signers.values()) { + if (s.supportedJWSAlgorithms().contains(alg)) { + signer = s; + break; + } + } - if (signer == null) { - //If we can't find an algorithm that matches, we can't sign - logger.error("No matching algirthm found for alg=" + alg); + if (signer == null) { + //If we can't find an algorithm that matches, we can't sign + logger.error("No matching algirthm found for alg=" + alg); - } + } - try { - jwt.sign(signer); - } catch (JOSEException e) { + try { + jwt.sign(signer); + } catch (JOSEException e) { - logger.error("Failed to sign JWT, error was: ", e); - } + logger.error("Failed to sign JWT, error was: ", e); + } - } + } - @Override - public boolean validateSignature(SignedJWT jwt) { + @Override + public boolean validateSignature(SignedJWT jwt) { - for (JWSVerifier verifier : verifiers.values()) { - try { - if (jwt.verify(verifier)) { - return true; - } - } catch (JOSEException e) { + for (JWSVerifier verifier : verifiers.values()) { + try { + if (jwt.verify(verifier)) { + return true; + } + } catch (JOSEException e) { - logger.error("Failed to validate signature, error was: ", e); - } - } - return false; - } + logger.error("Failed to validate signature, error was: ", e); + } + } + return false; + } - @Override - public Map getAllPublicKeys() { - Map pubKeys = new HashMap(); + @Override + public Map getAllPublicKeys() { + Map pubKeys = new HashMap(); - // pull all keys out of the verifiers if we know how - for (String keyId : keys.keySet()) { - JWK key = keys.get(keyId); - JWK pub = key.toPublicJWK(); - if (pub != null) { - pubKeys.put(keyId, pub); - } - } + // pull all keys out of the verifiers if we know how + for (String keyId : keys.keySet()) { + JWK key = keys.get(keyId); + JWK pub = key.toPublicJWK(); + if (pub != null) { + pubKeys.put(keyId, pub); + } + } - return pubKeys; - } + return pubKeys; + } - /* (non-Javadoc) - * @see org.mitre.jwt.signer.service.JwtSigningAndValidationService#getAllSigningAlgsSupported() - */ - @Override - public Collection getAllSigningAlgsSupported() { + /* (non-Javadoc) + * @see org.mitre.jwt.signer.service.JwtSigningAndValidationService#getAllSigningAlgsSupported() + */ + @Override + public Collection getAllSigningAlgsSupported() { - Set algs = new HashSet(); + Set algs = new HashSet(); - for (JWSSigner signer : signers.values()) { - algs.addAll(signer.supportedJWSAlgorithms()); - } + for (JWSSigner signer : signers.values()) { + algs.addAll(signer.supportedJWSAlgorithms()); + } - for (JWSVerifier verifier : verifiers.values()) { - algs.addAll(verifier.supportedJWSAlgorithms()); - } + for (JWSVerifier verifier : verifiers.values()) { + algs.addAll(verifier.supportedJWSAlgorithms()); + } - return algs; + return algs; - } + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/impl/JWKSetCacheService.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/impl/JWKSetCacheService.java index c955a4a59..4348f19cc 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/impl/JWKSetCacheService.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/impl/JWKSetCacheService.java @@ -49,107 +49,107 @@ import com.nimbusds.jose.jwk.JWKSet; @Service public class JWKSetCacheService { - private static Logger logger = LoggerFactory.getLogger(JWKSetCacheService.class); + private static Logger logger = LoggerFactory.getLogger(JWKSetCacheService.class); - // map of jwk set uri -> signing/validation service built on the keys found in that jwk set - private LoadingCache validators; + // map of jwk set uri -> signing/validation service built on the keys found in that jwk set + private LoadingCache validators; - // map of jwk set uri -> encryption/decryption service built on the keys found in that jwk set - private LoadingCache encrypters; + // map of jwk set uri -> encryption/decryption service built on the keys found in that jwk set + private LoadingCache encrypters; - public JWKSetCacheService() { - this.validators = CacheBuilder.newBuilder() - .expireAfterWrite(1, TimeUnit.HOURS) // expires 1 hour after fetch - .maximumSize(100) - .build(new JWKSetVerifierFetcher()); - this.encrypters = CacheBuilder.newBuilder() - .expireAfterWrite(1, TimeUnit.HOURS) // expires 1 hour after fetch - .maximumSize(100) - .build(new JWKSetEncryptorFetcher()); - } + public JWKSetCacheService() { + this.validators = CacheBuilder.newBuilder() + .expireAfterWrite(1, TimeUnit.HOURS) // expires 1 hour after fetch + .maximumSize(100) + .build(new JWKSetVerifierFetcher()); + this.encrypters = CacheBuilder.newBuilder() + .expireAfterWrite(1, TimeUnit.HOURS) // expires 1 hour after fetch + .maximumSize(100) + .build(new JWKSetEncryptorFetcher()); + } - /** - * @param jwksUri - * @return - * @throws ExecutionException - * @see com.google.common.cache.Cache#get(java.lang.Object) - */ - public JwtSigningAndValidationService getValidator(String jwksUri) { - try { - return validators.get(jwksUri); - } catch (UncheckedExecutionException ue) { - logger.warn("Couldn't load JWK Set from " + jwksUri, ue); - return null; - } catch (ExecutionException e) { - logger.warn("Couldn't load JWK Set from " + jwksUri, e); - return null; - } - } + /** + * @param jwksUri + * @return + * @throws ExecutionException + * @see com.google.common.cache.Cache#get(java.lang.Object) + */ + public JwtSigningAndValidationService getValidator(String jwksUri) { + try { + return validators.get(jwksUri); + } catch (UncheckedExecutionException ue) { + logger.warn("Couldn't load JWK Set from " + jwksUri, ue); + return null; + } catch (ExecutionException e) { + logger.warn("Couldn't load JWK Set from " + jwksUri, e); + return null; + } + } - public JwtEncryptionAndDecryptionService getEncrypter(String jwksUri) { - try { - return encrypters.get(jwksUri); - } catch (UncheckedExecutionException ue) { - logger.warn("Couldn't load JWK Set from " + jwksUri, ue); - return null; - } catch (ExecutionException e) { - logger.warn("Couldn't load JWK Set from " + jwksUri, e); - return null; - } - } + public JwtEncryptionAndDecryptionService getEncrypter(String jwksUri) { + try { + return encrypters.get(jwksUri); + } catch (UncheckedExecutionException ue) { + logger.warn("Couldn't load JWK Set from " + jwksUri, ue); + return null; + } catch (ExecutionException e) { + logger.warn("Couldn't load JWK Set from " + jwksUri, e); + return null; + } + } - /** - * @author jricher - * - */ - private class JWKSetVerifierFetcher extends CacheLoader { - //private HttpClient httpClient = HttpClientBuilder.create().useSystemProperties().build(); - //private HttpComponentsClientHttpRequestFactory httpFactory = new HttpComponentsClientHttpRequestFactory(httpClient); - private HttpComponentsClientHttpRequestFactory httpFactory = new HttpComponentsClientHttpRequestFactory(); - private RestTemplate restTemplate = new RestTemplate(httpFactory); + /** + * @author jricher + * + */ + private class JWKSetVerifierFetcher extends CacheLoader { + //private HttpClient httpClient = HttpClientBuilder.create().useSystemProperties().build(); + //private HttpComponentsClientHttpRequestFactory httpFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + private HttpComponentsClientHttpRequestFactory httpFactory = new HttpComponentsClientHttpRequestFactory(); + private RestTemplate restTemplate = new RestTemplate(httpFactory); - /** - * Load the JWK Set and build the appropriate signing service. - */ - @Override - public JwtSigningAndValidationService load(String key) throws Exception { + /** + * Load the JWK Set and build the appropriate signing service. + */ + @Override + public JwtSigningAndValidationService load(String key) throws Exception { - String jsonString = restTemplate.getForObject(key, String.class); - JWKSet jwkSet = JWKSet.parse(jsonString); + String jsonString = restTemplate.getForObject(key, String.class); + JWKSet jwkSet = JWKSet.parse(jsonString); - JWKSetKeyStore keyStore = new JWKSetKeyStore(jwkSet); + JWKSetKeyStore keyStore = new JWKSetKeyStore(jwkSet); - JwtSigningAndValidationService service = new DefaultJwtSigningAndValidationService(keyStore); + JwtSigningAndValidationService service = new DefaultJwtSigningAndValidationService(keyStore); - return service; + return service; - } + } - } + } - /** - * @author jricher - * - */ - private class JWKSetEncryptorFetcher extends CacheLoader { - //private HttpClient httpClient = HttpClientBuilder.create().useSystemProperties().build(); - //private HttpComponentsClientHttpRequestFactory httpFactory = new HttpComponentsClientHttpRequestFactory(httpClient); - private HttpComponentsClientHttpRequestFactory httpFactory = new HttpComponentsClientHttpRequestFactory(); - private RestTemplate restTemplate = new RestTemplate(httpFactory); - /* (non-Javadoc) - * @see com.google.common.cache.CacheLoader#load(java.lang.Object) - */ - @Override - public JwtEncryptionAndDecryptionService load(String key) throws Exception { - String jsonString = restTemplate.getForObject(key, String.class); - JWKSet jwkSet = JWKSet.parse(jsonString); + /** + * @author jricher + * + */ + private class JWKSetEncryptorFetcher extends CacheLoader { + //private HttpClient httpClient = HttpClientBuilder.create().useSystemProperties().build(); + //private HttpComponentsClientHttpRequestFactory httpFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + private HttpComponentsClientHttpRequestFactory httpFactory = new HttpComponentsClientHttpRequestFactory(); + private RestTemplate restTemplate = new RestTemplate(httpFactory); + /* (non-Javadoc) + * @see com.google.common.cache.CacheLoader#load(java.lang.Object) + */ + @Override + public JwtEncryptionAndDecryptionService load(String key) throws Exception { + String jsonString = restTemplate.getForObject(key, String.class); + JWKSet jwkSet = JWKSet.parse(jsonString); - JWKSetKeyStore keyStore = new JWKSetKeyStore(jwkSet); + JWKSetKeyStore keyStore = new JWKSetKeyStore(jwkSet); - JwtEncryptionAndDecryptionService service = new DefaultJwtEncryptionAndDecryptionService(keyStore); + JwtEncryptionAndDecryptionService service = new DefaultJwtEncryptionAndDecryptionService(keyStore); - return service; - } - } + return service; + } + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/impl/SymmetricCacheService.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/impl/SymmetricCacheService.java index 52ec1e4a5..365984285 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/impl/SymmetricCacheService.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/impl/SymmetricCacheService.java @@ -44,72 +44,72 @@ import com.nimbusds.jose.jwk.JWK; @Service public class SymmetricCacheService { - private static Logger logger = LoggerFactory.getLogger(SymmetricCacheService.class); + private static Logger logger = LoggerFactory.getLogger(SymmetricCacheService.class); - private LoadingCache validators; + private LoadingCache validators; - public SymmetricCacheService() { - validators = CacheBuilder.newBuilder() - .expireAfterAccess(24, TimeUnit.HOURS) - .maximumSize(100) - .build(new SymmetricValidatorBuilder()); - } + public SymmetricCacheService() { + validators = CacheBuilder.newBuilder() + .expireAfterAccess(24, TimeUnit.HOURS) + .maximumSize(100) + .build(new SymmetricValidatorBuilder()); + } - /** - * Create a symmetric signing and validation service for the given client - * - * @param client - * @return - */ - public JwtSigningAndValidationService getSymmetricValidtor(String clientSecret) { + /** + * Create a symmetric signing and validation service for the given client + * + * @param client + * @return + */ + public JwtSigningAndValidationService getSymmetricValidtor(String clientSecret) { - if (clientSecret == null) { - logger.error("Couldn't create symmetric validator for null client"); - return null; - } + if (clientSecret == null) { + logger.error("Couldn't create symmetric validator for null client"); + return null; + } - if (Strings.isNullOrEmpty(clientSecret)) { - logger.error("Couldn't create symmetric validator for client without a client secret"); - return null; - } + if (Strings.isNullOrEmpty(clientSecret)) { + logger.error("Couldn't create symmetric validator for client without a client secret"); + return null; + } - try { - return validators.get(clientSecret); - } catch (UncheckedExecutionException ue) { - logger.error("Problem loading client validator", ue); - return null; - } catch (ExecutionException e) { - logger.error("Problem loading client validator", e); - return null; - } + try { + return validators.get(clientSecret); + } catch (UncheckedExecutionException ue) { + logger.error("Problem loading client validator", ue); + return null; + } catch (ExecutionException e) { + logger.error("Problem loading client validator", e); + return null; + } - } + } - public class SymmetricValidatorBuilder extends CacheLoader { - @Override - public JwtSigningAndValidationService load(String key) throws Exception { - try { + public class SymmetricValidatorBuilder extends CacheLoader { + @Override + public JwtSigningAndValidationService load(String key) throws Exception { + try { - String id = "SYMMETRIC-KEY"; + String id = "SYMMETRIC-KEY"; - JWK jwk =null; - //JWK jwk = new OctetSequenceKey(Base64URL.encode(key), KeyUse.SIGNATURE, null, null, id, null, null, null); - Map keys = ImmutableMap.of(id, jwk); - JwtSigningAndValidationService service = new DefaultJwtSigningAndValidationService(keys); + JWK jwk =null; + //JWK jwk = new OctetSequenceKey(Base64URL.encode(key), KeyUse.SIGNATURE, null, null, id, null, null, null); + Map keys = ImmutableMap.of(id, jwk); + JwtSigningAndValidationService service = new DefaultJwtSigningAndValidationService(keys); - return service; + return service; - } catch (NoSuchAlgorithmException e) { - logger.error("Couldn't create symmetric validator for client", e); - } catch (InvalidKeySpecException e) { - logger.error("Couldn't create symmetric validator for client", e); - } + } catch (NoSuchAlgorithmException e) { + logger.error("Couldn't create symmetric validator for client", e); + } catch (InvalidKeySpecException e) { + logger.error("Couldn't create symmetric validator for client", e); + } - throw new IllegalArgumentException("Couldn't create symmetric validator for client"); - } + throw new IllegalArgumentException("Couldn't create symmetric validator for client"); + } - } + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/impl/SymmetricSigningAndValidationServiceBuilder.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/impl/SymmetricSigningAndValidationServiceBuilder.java index 274102fc5..57642d10c 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/impl/SymmetricSigningAndValidationServiceBuilder.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/jwt/signer/service/impl/SymmetricSigningAndValidationServiceBuilder.java @@ -37,41 +37,41 @@ import com.nimbusds.jose.jwk.JWK; * Builder Symmetric Signing Service */ public class SymmetricSigningAndValidationServiceBuilder { - static final Logger _logger = LoggerFactory.getLogger(SymmetricSigningAndValidationServiceBuilder.class); - public static final String SYMMETRIC_KEY = "SYMMETRIC-KEY"; - /** - * - */ - public SymmetricSigningAndValidationServiceBuilder() { - - } - - public JwtSigningAndValidationService serviceBuilder(String sharedSecret){ - _logger.debug("shared Secret : {}" , sharedSecret); - _logger.debug("Symmetric Id : {}" , SYMMETRIC_KEY); - if (sharedSecret == null) { - _logger.error("Couldn't create symmetric SigningAndValidation"); - return null; - } + static final Logger _logger = LoggerFactory.getLogger(SymmetricSigningAndValidationServiceBuilder.class); + public static final String SYMMETRIC_KEY = "SYMMETRIC-KEY"; + /** + * + */ + public SymmetricSigningAndValidationServiceBuilder() { + + } + + public JwtSigningAndValidationService serviceBuilder(String sharedSecret){ + _logger.debug("shared Secret : {}" , sharedSecret); + _logger.debug("Symmetric Id : {}" , SYMMETRIC_KEY); + if (sharedSecret == null) { + _logger.error("Couldn't create symmetric SigningAndValidation"); + return null; + } - /** - * Builder Symmetric Signing And Validation Service - */ - JWK jwk = null; - //JWK jwk = new OctetSequenceKey(Base64URL.encode(sharedSecret), KeyUse.SIGNATURE, null, null, SYMMETRIC_KEY, null, null, null); - Map keys = ImmutableMap.of(SYMMETRIC_KEY, jwk); - try { - JwtSigningAndValidationService symmetricSigningAndValidationService = new DefaultJwtSigningAndValidationService(keys); - return symmetricSigningAndValidationService; - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } catch (InvalidKeySpecException e) { - e.printStackTrace(); - } catch (JOSEException e) { - e.printStackTrace(); - } - - return null; - } + /** + * Builder Symmetric Signing And Validation Service + */ + JWK jwk = null; + //JWK jwk = new OctetSequenceKey(Base64URL.encode(sharedSecret), KeyUse.SIGNATURE, null, null, SYMMETRIC_KEY, null, null, null); + Map keys = ImmutableMap.of(SYMMETRIC_KEY, jwk); + try { + JwtSigningAndValidationService symmetricSigningAndValidationService = new DefaultJwtSigningAndValidationService(keys); + return symmetricSigningAndValidationService; + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (InvalidKeySpecException e) { + e.printStackTrace(); + } catch (JOSEException e) { + e.printStackTrace(); + } + + return null; + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/keystore/KeyStoreType.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/keystore/KeyStoreType.java index 6c84bbea5..4dbfa8fe2 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/keystore/KeyStoreType.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/keystore/KeyStoreType.java @@ -34,121 +34,121 @@ import java.util.Set; * Standard Names */ public enum KeyStoreType { - /** JKS keystore Type */ - JKS("JKS", true, true, new String[] { "jks" }), - /** PKCS #12 keystore Type */ - PKCS12("PKCS #12", false, false, new String[] { "p12", "pfx" }), - /** JCEKS keystore Type */ - JCEKS("JCEKS", true, true, new String[] { "jceks" }), - /** Case sensitive JKS keystore Type */ - CaseExactJKS("JKS (case sensitive)", true, true, new String[] { "jks" }), - /** BKS keystore Type */ - BKS("BKS", true, true, new String[] { "bks" }), - /** UBER keystore Type */ - UBER("UBER", true, true, new String[] { "ubr" }), - /** GKR keystore Type */ - GKR("GKR", true, true, new String[] { "gkr" }), - /** PKCS #11 keystore Type */ - PKCS11("PKCS #11", false, true, new String[0]); + /** JKS keystore Type */ + JKS("JKS", true, true, new String[] { "jks" }), + /** PKCS #12 keystore Type */ + PKCS12("PKCS #12", false, false, new String[] { "p12", "pfx" }), + /** JCEKS keystore Type */ + JCEKS("JCEKS", true, true, new String[] { "jceks" }), + /** Case sensitive JKS keystore Type */ + CaseExactJKS("JKS (case sensitive)", true, true, new String[] { "jks" }), + /** BKS keystore Type */ + BKS("BKS", true, true, new String[] { "bks" }), + /** UBER keystore Type */ + UBER("UBER", true, true, new String[] { "ubr" }), + /** GKR keystore Type */ + GKR("GKR", true, true, new String[] { "gkr" }), + /** PKCS #11 keystore Type */ + PKCS11("PKCS #11", false, true, new String[0]); - /** Keystore "pretty" name */ - private final String prettyName; + /** Keystore "pretty" name */ + private final String prettyName; - /** - * Whether the keystore type provides useful values for entry creation dates - */ - private final boolean entryCreationDateUseful; + /** + * Whether the keystore type provides useful values for entry creation dates + */ + private final boolean entryCreationDateUseful; - /** Whether the keystore supports entry passwords */ - private final boolean entryPasswordSupported; + /** Whether the keystore supports entry passwords */ + private final boolean entryPasswordSupported; - /** Associated filename extensions */ - private final Set filenameExtensions; + /** Associated filename extensions */ + private final Set filenameExtensions; - /** - * Construct a KeyStoreType. Private to prevent construction from outside - * this class. - * - * @param sType - * Keystore type - * @param supportsCreationDates - * Whether the keystore supports creation dates - * @param filenameExtensions - * associated filename extensions - */ - private KeyStoreType(String prettyName, boolean entryCreationDateUseful, - boolean entryPasswordSupported, String[] filenameExtensions) { - this.prettyName = prettyName; - this.entryCreationDateUseful = entryCreationDateUseful; - this.entryPasswordSupported = entryPasswordSupported; - switch (filenameExtensions.length) { - case 0: - this.filenameExtensions = Collections.emptySet(); - break; - case 1: - this.filenameExtensions = Collections - .singleton(filenameExtensions[0]); - break; - default: - LinkedHashSet exts = new LinkedHashSet( - filenameExtensions.length); - Collections.addAll(exts, filenameExtensions); - this.filenameExtensions = Collections.unmodifiableSet(exts); - } - } + /** + * Construct a KeyStoreType. Private to prevent construction from outside + * this class. + * + * @param sType + * Keystore type + * @param supportsCreationDates + * Whether the keystore supports creation dates + * @param filenameExtensions + * associated filename extensions + */ + private KeyStoreType(String prettyName, boolean entryCreationDateUseful, + boolean entryPasswordSupported, String[] filenameExtensions) { + this.prettyName = prettyName; + this.entryCreationDateUseful = entryCreationDateUseful; + this.entryPasswordSupported = entryPasswordSupported; + switch (filenameExtensions.length) { + case 0: + this.filenameExtensions = Collections.emptySet(); + break; + case 1: + this.filenameExtensions = Collections + .singleton(filenameExtensions[0]); + break; + default: + LinkedHashSet exts = new LinkedHashSet( + filenameExtensions.length); + Collections.addAll(exts, filenameExtensions); + this.filenameExtensions = Collections.unmodifiableSet(exts); + } + } - /** - * Does the keystore type provide useful values for entry creation dates? - * Some keystores return the keystore load time as creation date for all - * entries, this is not considered useful by this class. - * - * @return true if creation dates are useful, false otherwise - */ - public boolean isEntryCreationDateUseful() { - return entryCreationDateUseful; - } + /** + * Does the keystore type provide useful values for entry creation dates? + * Some keystores return the keystore load time as creation date for all + * entries, this is not considered useful by this class. + * + * @return true if creation dates are useful, false otherwise + */ + public boolean isEntryCreationDateUseful() { + return entryCreationDateUseful; + } - /** - * Does the keystore type support passwords for entries? - * - * @return true if entry passwords are supported, false otherwise - */ - public boolean isEntryPasswordSupported() { - return entryPasswordSupported; - } + /** + * Does the keystore type support passwords for entries? + * + * @return true if entry passwords are supported, false otherwise + */ + public boolean isEntryPasswordSupported() { + return entryPasswordSupported; + } - /** - * Common filename extensions associated with this type. - * - * @return filename extensions (without leading dot, in lower case), empty - * if not applicable - */ - public Set getFilenameExtensions() { - return filenameExtensions; - } + /** + * Common filename extensions associated with this type. + * + * @return filename extensions (without leading dot, in lower case), empty + * if not applicable + */ + public Set getFilenameExtensions() { + return filenameExtensions; + } - /** - * Return string representation of keystore type. - * - * @return String representation of a keystore type - */ - @Override - public String toString() { - return prettyName; - } + /** + * Return string representation of keystore type. + * + * @return String representation of a keystore type + */ + @Override + public String toString() { + return prettyName; + } - /** - * Get set of all known keystore filename extensions. - * - * @return - */ - public static Set getKeyStoreFilenameExtensions() { - HashSet exts = new HashSet(); - for (KeyStoreType ksType : values()) { - for (String ext : ksType.getFilenameExtensions()) { - exts.add(ext); - } - } - return exts; - } + /** + * Get set of all known keystore filename extensions. + * + * @return + */ + public static Set getKeyStoreFilenameExtensions() { + HashSet exts = new HashSet(); + for (KeyStoreType ksType : values()) { + for (String ext : ksType.getFilenameExtensions()) { + exts.add(ext); + } + } + return exts; + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/password/DesedeEncoder.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/password/DesedeEncoder.java index 22b42e990..81416deca 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/password/DesedeEncoder.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/password/DesedeEncoder.java @@ -27,16 +27,16 @@ import org.springframework.security.crypto.password.PasswordEncoder; */ public class DesedeEncoder implements PasswordEncoder { - private static final String DEFAULT_SALT = "bWu3x8E5yS2h6l0J_qT7NvIzP9oRaG4kFc1QmD"; // - private static final String CRYPT = "{crypt}"; - private static final String PLAIN = "{plain}"; + private static final String DEFAULT_SALT = "bWu3x8E5yS2h6l0J_qT7NvIzP9oRaG4kFc1QmD"; // + private static final String CRYPT = "{crypt}"; + private static final String PLAIN = "{plain}"; - public static final int PREFFIX_LENGTH = 7; + public static final int PREFFIX_LENGTH = 7; private static DesedeEncoder desedePasswordEncoder; public DesedeEncoder() { - // + // } /** @@ -46,49 +46,49 @@ public class DesedeEncoder implements PasswordEncoder { public static DesedeEncoder getInstance() { if (desedePasswordEncoder == null) { - desedePasswordEncoder = new DesedeEncoder(); + desedePasswordEncoder = new DesedeEncoder(); } return desedePasswordEncoder; } public String decoder(CharSequence encodedPassword) { - if(encodedPassword == null) { - return null; - } - String encodedPasswordString = encodedPassword.toString(); - if(encodedPasswordString.startsWith(CRYPT)) { - return ReciprocalUtils.decoderHex(encodedPasswordString.substring(PREFFIX_LENGTH), DEFAULT_SALT); - }else if(encodedPasswordString.startsWith(PLAIN)) { - return encodedPasswordString.substring(PREFFIX_LENGTH); - }else { - return encodedPasswordString; - } + if(encodedPassword == null) { + return null; + } + String encodedPasswordString = encodedPassword.toString(); + if(encodedPasswordString.startsWith(CRYPT)) { + return ReciprocalUtils.decoderHex(encodedPasswordString.substring(PREFFIX_LENGTH), DEFAULT_SALT); + }else if(encodedPasswordString.startsWith(PLAIN)) { + return encodedPasswordString.substring(PREFFIX_LENGTH); + }else { + return encodedPasswordString; + } } @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { - if(encodedPassword.startsWith(PLAIN)) { - encodedPassword = encode(encodedPassword.substring(PREFFIX_LENGTH)); - } - String finalPassword = encode(rawPassword); + if(encodedPassword.startsWith(PLAIN)) { + encodedPassword = encode(encodedPassword.substring(PREFFIX_LENGTH)); + } + String finalPassword = encode(rawPassword); return finalPassword.equals(encodedPassword); } - @Override - public String encode(CharSequence plain) { - return (plain == null) ? null : (CRYPT + ReciprocalUtils.encode2Hex(plain + "", DEFAULT_SALT)); - } + @Override + public String encode(CharSequence plain) { + return (plain == null) ? null : (CRYPT + ReciprocalUtils.encode2Hex(plain + "", DEFAULT_SALT)); + } - public String encode(CharSequence plain,boolean isEncode) { - if(plain == null) { - return null; - } - if(isEncode) { - return CRYPT + ReciprocalUtils.encode2Hex(plain + "", DEFAULT_SALT); - }else { - return PLAIN + plain; - } - } + public String encode(CharSequence plain,boolean isEncode) { + if(plain == null) { + return null; + } + if(isEncode) { + return CRYPT + ReciprocalUtils.encode2Hex(plain + "", DEFAULT_SALT); + }else { + return PLAIN + plain; + } + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/password/NoOpPasswordEncoder.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/password/NoOpPasswordEncoder.java index e7b1cb6ba..9685f37a5 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/password/NoOpPasswordEncoder.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/password/NoOpPasswordEncoder.java @@ -52,12 +52,12 @@ import org.springframework.security.crypto.password.PasswordEncoder; public final class NoOpPasswordEncoder implements PasswordEncoder { - @Override + @Override public String encode(CharSequence rawPassword) { return rawPassword.toString(); } - @Override + @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { return rawPassword.toString().equals(encodedPassword); } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/password/PasswordGen.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/password/PasswordGen.java index 193160b42..ceeb36a94 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/password/PasswordGen.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/password/PasswordGen.java @@ -101,20 +101,20 @@ public class PasswordGen { } public String shuffle(final String charString) { - StringBuffer password = new StringBuffer(""); - List list = new ArrayList(); - for (int i = 0; i < charString.length(); i++) { - list.add(charString.charAt(i) + ""); - } - - for (int i = 0; i < length / 2; i++) { - Collections.shuffle(list); - } - - for(String chr : list) { - password.append(chr); - } - return password.toString(); + StringBuffer password = new StringBuffer(""); + List list = new ArrayList(); + for (int i = 0; i < charString.length(); i++) { + list.add(charString.charAt(i) + ""); + } + + for (int i = 0; i < length / 2; i++) { + Collections.shuffle(list); + } + + for(String chr : list) { + password.append(chr); + } + return password.toString(); } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/password/PasswordReciprocal.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/password/PasswordReciprocal.java index e1175fa15..41cc39a04 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/password/PasswordReciprocal.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/password/PasswordReciprocal.java @@ -28,8 +28,8 @@ import org.springframework.security.crypto.password.PasswordEncoder; */ public class PasswordReciprocal implements PasswordEncoder { - public static int PREFFIX_LENGTH = 7; - + public static int PREFFIX_LENGTH = 7; + public static PasswordReciprocal passwordReciprocal; public PasswordReciprocal() { @@ -50,16 +50,16 @@ public class PasswordReciprocal implements PasswordEncoder { } public String decoder(CharSequence encodedPassword) { - String salt = encodedPassword.subSequence(0, 29).toString(); - encodedPassword = encodedPassword.subSequence(29, encodedPassword.length()); - String plain = ReciprocalUtils.decoderHex(encodedPassword.toString(), salt.substring(PREFFIX_LENGTH)); + String salt = encodedPassword.subSequence(0, 29).toString(); + encodedPassword = encodedPassword.subSequence(29, encodedPassword.length()); + String plain = ReciprocalUtils.decoderHex(encodedPassword.toString(), salt.substring(PREFFIX_LENGTH)); return plain.substring(salt.substring(PREFFIX_LENGTH).length()); } @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { - String salt = encodedPassword.subSequence(0, 29).toString(); - String finalPassword = encode(rawPassword,salt); + String salt = encodedPassword.subSequence(0, 29).toString(); + String finalPassword = encode(rawPassword,salt); return finalPassword.equals(encodedPassword);//ReciprocalUtils.encode(rawPassword.toString()).equals(encodedPassword); } @@ -69,18 +69,18 @@ public class PasswordReciprocal implements PasswordEncoder { * @return salt */ public String gensalt() { - return BCrypt.gensalt("$2a", 10); + return BCrypt.gensalt("$2a", 10); } - @Override - public String encode(CharSequence plain) { - //$2a$10$ - String salt = gensalt(); + @Override + public String encode(CharSequence plain) { + //$2a$10$ + String salt = gensalt(); return encode(plain, salt); - } - - private String encode(CharSequence plain,String salt) { - String password = salt.substring(PREFFIX_LENGTH) + plain ; + } + + private String encode(CharSequence plain,String salt) { + String password = salt.substring(PREFFIX_LENGTH) + plain ; return salt + ReciprocalUtils.encode2Hex(password , salt.substring(PREFFIX_LENGTH)); - } + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/signature/DsaSigner.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/signature/DsaSigner.java index 524c9e478..55b360359 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/signature/DsaSigner.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/signature/DsaSigner.java @@ -39,70 +39,70 @@ import org.dromara.maxkey.crypto.KeyPairType; */ public final class DsaSigner implements ISigner { - // ����ǩ����Կ�㷨 - public static final KeyPairType KEY_ALGORITHM = KeyPairType.DSA; + // ����ǩ����Կ�㷨 + public static final KeyPairType KEY_ALGORITHM = KeyPairType.DSA; - /** - * ����ǩ�� ǩ��/��֤�㷨 - * */ - public static final String SIGNATURE_ALGORITHM = "SHA1withDSA"; + /** + * ����ǩ�� ǩ��/��֤�㷨 + * */ + public static final String SIGNATURE_ALGORITHM = "SHA1withDSA"; - @Override - public byte[] sign(byte[] dataBytes, byte[] privateKeyByte) throws Exception { - // ȡ��˽Կ - PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKeyByte); - KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM.name()); - // ���˽Կ - PrivateKey signPrivateKey = keyFactory.generatePrivate(pkcs8KeySpec); - // ʵ��Signature - Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); - // ��ʼ��Signature - signature.initSign(signPrivateKey); - // ���� - signature.update(dataBytes); + @Override + public byte[] sign(byte[] dataBytes, byte[] privateKeyByte) throws Exception { + // ȡ��˽Կ + PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKeyByte); + KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM.name()); + // ���˽Կ + PrivateKey signPrivateKey = keyFactory.generatePrivate(pkcs8KeySpec); + // ʵ��Signature + Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); + // ��ʼ��Signature + signature.initSign(signPrivateKey); + // ���� + signature.update(dataBytes); - return signature.sign(); - } - - @Override - public String signB64(String data, String privateKey) throws Exception { - - byte[] privateKeyByte = Base64Utils.decoder(privateKey); - byte[] dataBytes = data.getBytes(); - - byte[] signatureBytes=sign(dataBytes,privateKeyByte); + return signature.sign(); + } + + @Override + public String signB64(String data, String privateKey) throws Exception { + + byte[] privateKeyByte = Base64Utils.decoder(privateKey); + byte[] dataBytes = data.getBytes(); + + byte[] signatureBytes=sign(dataBytes,privateKeyByte); - return Base64Utils.encoder(signatureBytes); - } + return Base64Utils.encoder(signatureBytes); + } - @Override - public boolean verify(byte[] dataBytes, byte[] publicKeyBytes, byte[] signBytes)throws Exception { + @Override + public boolean verify(byte[] dataBytes, byte[] publicKeyBytes, byte[] signBytes)throws Exception { - KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM.name()); - // ��ʼ����Կ - // ��Կ����ת�� - X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes); - // ����Կ - PublicKey verifyPublicKey = keyFactory.generatePublic(x509KeySpec); - // ʵ��Signature - Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); - // ��ʼ��Signature - signature.initVerify(verifyPublicKey); - // ���� - signature.update(dataBytes); - // ��֤ - return signature.verify(signBytes); - } - - @Override - public boolean verifyB64(String data, String publicKey, String sign)throws Exception { + KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM.name()); + // ��ʼ����Կ + // ��Կ����ת�� + X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes); + // ����Կ + PublicKey verifyPublicKey = keyFactory.generatePublic(x509KeySpec); + // ʵ��Signature + Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); + // ��ʼ��Signature + signature.initVerify(verifyPublicKey); + // ���� + signature.update(dataBytes); + // ��֤ + return signature.verify(signBytes); + } + + @Override + public boolean verifyB64(String data, String publicKey, String sign)throws Exception { - byte[] privateKeyByte = Base64Utils.decoder(publicKey); - byte[] dataBytes = data.getBytes(); - byte[] signBytes=Base64Utils.decoder(sign); - - // ��֤ - return verify(dataBytes,privateKeyByte,signBytes); - } + byte[] privateKeyByte = Base64Utils.decoder(publicKey); + byte[] dataBytes = data.getBytes(); + byte[] signBytes=Base64Utils.decoder(sign); + + // ��֤ + return verify(dataBytes,privateKeyByte,signBytes); + } } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/signature/ISigner.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/signature/ISigner.java index ed84d7bee..1d9d2605e 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/signature/ISigner.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/signature/ISigner.java @@ -35,14 +35,14 @@ package org.dromara.maxkey.crypto.signature; * */ public interface ISigner { - - public byte[] sign(byte[] data,byte[] privateKey)throws Exception; - - public String signB64(String data,String privateKey)throws Exception; - - public boolean verify(byte[] data,byte[] publicKey,byte[] sign)throws Exception; - - public boolean verifyB64(String data,String publicKey,String sign)throws Exception; - + + public byte[] sign(byte[] data,byte[] privateKey)throws Exception; + + public String signB64(String data,String privateKey)throws Exception; + + public boolean verify(byte[] data,byte[] publicKey,byte[] sign)throws Exception; + + public boolean verifyB64(String data,String publicKey,String sign)throws Exception; + } diff --git a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/signature/RsaSigner.java b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/signature/RsaSigner.java index f734ffa82..39b18d05f 100644 --- a/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/signature/RsaSigner.java +++ b/maxkey-commons/maxkey-crypto/src/main/java/org/dromara/maxkey/crypto/signature/RsaSigner.java @@ -41,92 +41,92 @@ import org.dromara.maxkey.crypto.KeyPairType; public final class RsaSigner implements ISigner { - public static final KeyPairType KEY_ALGORTHM = KeyPairType.RSA; + public static final KeyPairType KEY_ALGORTHM = KeyPairType.RSA; - public final class RsaAlgorithm { - public static final String MD5withRSA="MD5withRSA"; - public static final String SHA1withRSA = "SHA1withRSA"; - } + public final class RsaAlgorithm { + public static final String MD5withRSA="MD5withRSA"; + public static final String SHA1withRSA = "SHA1withRSA"; + } - public static final String SIGNATURE_ALGORITHM = RsaAlgorithm.SHA1withRSA; + public static final String SIGNATURE_ALGORITHM = RsaAlgorithm.SHA1withRSA; - public byte[] sign(byte[] dataBytes, byte[] privateKeyBytes, String algorithm)throws Exception { - // ����PKCS8EncodedKeySpec���� - PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); - // ָ�������㷨 - KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM.name()); - // ȡ˽Կ�׶��� - PrivateKey signPrivateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); - // ��˽Կ����Ϣ�������ǩ�� - Signature signature = Signature.getInstance(algorithm); - signature.initSign(signPrivateKey); - signature.update(dataBytes); + public byte[] sign(byte[] dataBytes, byte[] privateKeyBytes, String algorithm)throws Exception { + // ����PKCS8EncodedKeySpec���� + PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); + // ָ�������㷨 + KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM.name()); + // ȡ˽Կ�׶��� + PrivateKey signPrivateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); + // ��˽Կ����Ϣ�������ǩ�� + Signature signature = Signature.getInstance(algorithm); + signature.initSign(signPrivateKey); + signature.update(dataBytes); - return signature.sign(); - } - - @Override - public byte[] sign(byte[] dataBytes, byte[] privateKeyBytes) throws Exception { - return sign(dataBytes,privateKeyBytes,SIGNATURE_ALGORITHM); - } + return signature.sign(); + } + + @Override + public byte[] sign(byte[] dataBytes, byte[] privateKeyBytes) throws Exception { + return sign(dataBytes,privateKeyBytes,SIGNATURE_ALGORITHM); + } - /** - * sign with BASE64 privateKey use SHA1withRSA Algorithm - */ - @Override - public String signB64(String data, String privateKey) throws Exception { - byte[] keyBytes = Base64Utils.decoder(privateKey); - byte[] dataBytes = data.getBytes(); - byte[] signature=sign(dataBytes,keyBytes); + /** + * sign with BASE64 privateKey use SHA1withRSA Algorithm + */ + @Override + public String signB64(String data, String privateKey) throws Exception { + byte[] keyBytes = Base64Utils.decoder(privateKey); + byte[] dataBytes = data.getBytes(); + byte[] signature=sign(dataBytes,keyBytes); - return Base64Utils.encoder(signature); - } + return Base64Utils.encoder(signature); + } - public boolean verify(byte[] dataBytes, byte[] publicKeyBytes , byte[] signBytes,String algorithm)throws Exception { - // ����X509EncodedKeySpec���� - X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyBytes); - // ָ�������㷨 - KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM.name()); - // ȡ��Կ�׶��� - PublicKey verifyPublicKey = keyFactory.generatePublic(x509EncodedKeySpec); + public boolean verify(byte[] dataBytes, byte[] publicKeyBytes , byte[] signBytes,String algorithm)throws Exception { + // ����X509EncodedKeySpec���� + X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyBytes); + // ָ�������㷨 + KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM.name()); + // ȡ��Կ�׶��� + PublicKey verifyPublicKey = keyFactory.generatePublic(x509EncodedKeySpec); - Signature signature = Signature.getInstance(algorithm); - signature.initVerify(verifyPublicKey); + Signature signature = Signature.getInstance(algorithm); + signature.initVerify(verifyPublicKey); - signature.update(dataBytes); - // verify - return signature.verify(signBytes); - } - - /* - * (non-Javadoc) - * - * @see com.connsec.crypto.signature.Signer#verify(java.lang.String, - * java.lang.String, java.lang.String) - */ - @Override - public boolean verify(byte[] dataBytes, byte[] publicKeyBytes , byte[] signBytes)throws Exception { - // verify - return verify(dataBytes,publicKeyBytes,signBytes,SIGNATURE_ALGORITHM); - } - /* - * (non-Javadoc) - * @param publicKey is base64 - * @param sign is base64 - * @see com.connsec.crypto.signature.Signer#verify(java.lang.String, - * java.lang.String, java.lang.String) - */ - @Override - public boolean verifyB64(String data, String publicKey, String sign)throws Exception { - // ���ܹ�Կ - byte[] keyBytes = Base64Utils.decoder(publicKey); - byte[] dataBytes = data.getBytes(); - byte[] signBytes=Base64Utils.decoder(sign); - // ��֤ǩ���Ƿ��� - return verify(dataBytes,keyBytes,signBytes); - } + signature.update(dataBytes); + // verify + return signature.verify(signBytes); + } + + /* + * (non-Javadoc) + * + * @see com.connsec.crypto.signature.Signer#verify(java.lang.String, + * java.lang.String, java.lang.String) + */ + @Override + public boolean verify(byte[] dataBytes, byte[] publicKeyBytes , byte[] signBytes)throws Exception { + // verify + return verify(dataBytes,publicKeyBytes,signBytes,SIGNATURE_ALGORITHM); + } + /* + * (non-Javadoc) + * @param publicKey is base64 + * @param sign is base64 + * @see com.connsec.crypto.signature.Signer#verify(java.lang.String, + * java.lang.String, java.lang.String) + */ + @Override + public boolean verifyB64(String data, String publicKey, String sign)throws Exception { + // ���ܹ�Կ + byte[] keyBytes = Base64Utils.decoder(publicKey); + byte[] dataBytes = data.getBytes(); + byte[] signBytes=Base64Utils.decoder(sign); + // ��֤ǩ���Ƿ��� + return verify(dataBytes,keyBytes,signBytes); + } diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/Base64UtilsTest.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/Base64UtilsTest.java index ac1840bf3..163f12669 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/Base64UtilsTest.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/Base64UtilsTest.java @@ -23,29 +23,29 @@ import org.junit.Test; public class Base64UtilsTest { - /** - * @param args - */ - @Test - public void test() { - String encode=Base64Utils.encoder("base64ToFile".getBytes()); - System.out.println(encode); - String decode=Base64Utils.decode(encode); - System.out.println(decode); - - - - String urlEncode=Base64Utils.base64UrlEncode("{\"typ\":\"JWT\",\"alg\":\"HS256\"}".getBytes()); - System.out.println(urlEncode); - String urlDecode=new String(Base64Utils.base64UrlDecode(urlEncode)); - System.out.println(urlDecode); - - System.out.println(Base64Utils.decode("AAMkADU2OWY1MGQ3LWEyNWQtNDFmOC04MWFiLTI5YTE2NGM5YTZmNABGAAAAAABPKgpqnlfYQ7BVC/BfH2XIBwCS0xhUjzMYSLVky9bw7LddAAAAjov5AACS0xhUjzMYSLVky9bw7LddAAADzoyxAAA=")); - - - String b = "UsWdAIe4opTqcrX6~SrIMhBu5Gc9oZKEnnSDFRx9JwBINK8XTgnXUs2A3b7QmxDM9nRu8~mGsikVEoISLg.JTIHYRwv-Bp5ljIADLwUHv9iJAWo1delBOlW0Hd7nIVF0"; - - System.out.println(DigestUtils.digestBase64Url(b,DigestUtils.Algorithm.SHA256)); - } + /** + * @param args + */ + @Test + public void test() { + String encode=Base64Utils.encoder("base64ToFile".getBytes()); + System.out.println(encode); + String decode=Base64Utils.decode(encode); + System.out.println(decode); + + + + String urlEncode=Base64Utils.base64UrlEncode("{\"typ\":\"JWT\",\"alg\":\"HS256\"}".getBytes()); + System.out.println(urlEncode); + String urlDecode=new String(Base64Utils.base64UrlDecode(urlEncode)); + System.out.println(urlDecode); + + System.out.println(Base64Utils.decode("AAMkADU2OWY1MGQ3LWEyNWQtNDFmOC04MWFiLTI5YTE2NGM5YTZmNABGAAAAAABPKgpqnlfYQ7BVC/BfH2XIBwCS0xhUjzMYSLVky9bw7LddAAAAjov5AACS0xhUjzMYSLVky9bw7LddAAADzoyxAAA=")); + + + String b = "UsWdAIe4opTqcrX6~SrIMhBu5Gc9oZKEnnSDFRx9JwBINK8XTgnXUs2A3b7QmxDM9nRu8~mGsikVEoISLg.JTIHYRwv-Bp5ljIADLwUHv9iJAWo1delBOlW0Hd7nIVF0"; + + System.out.println(DigestUtils.digestBase64Url(b,DigestUtils.Algorithm.SHA256)); + } } diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/DigestUtilsTest.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/DigestUtilsTest.java index b4c318b16..2e15a5e25 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/DigestUtilsTest.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/DigestUtilsTest.java @@ -24,62 +24,62 @@ import org.junit.Test; public class DigestUtilsTest { /* - @Test - public void test() { - - System.out.println(DigestUtils.shaB64("mytest")); - - System.out.println(DigestUtils.sha1B64("e707c852-29a4-bf56-f8b9-014716850d89")); - - System.out.println(DigestUtils.sha256B64("mytest")); - - System.out.println(DigestUtils.sha384B64("mytest")); - - System.out.println(DigestUtils.sha512B64("mytest")); - - System.out.println(DigestUtils.md5B64("e707c852-29a4-bf56-f8b9-014716850d89")); - } - */ - @Test - public void testHex() { - /* - System.out.println(DigestUtils.shaHex("mytest")); - - System.out.println(DigestUtils.sha1Hex("mytest")); - - System.out.println(DigestUtils.sha256Hex("mytest")); - - System.out.println(DigestUtils.sha384Hex("mytest")); - - System.out.println(DigestUtils.sha512Hex("mytest")); - - System.out.println(DigestUtils.md5Hex("seamingxy99")); - System.out.println((new Date()).getTime()); - */ - - //String zentaoLogin="http://127.0.0.1/biz/api.php?m=user&f=apilogin&account=%s&code=%s&time=%s&token=%s"; - String zentaoLogin="http://127.0.0.1/zentao/api.php?m=user&f=apilogin&account=%s&code=%s&time=%s&token=%s"; - String code = "maxkey"; - //String key = "430ba509ba95094e580b925fc4839459"; - String key = "f71792dfebf23d62bc4d65d1513087e3"; - //String time = ""+System.currentTimeMillis(); - String time = ""+Instant.now().getEpochSecond(); - //String time = "1615370929"; - //String code = "myApp"; - //String key = "427c579384224abf9570779d82969d1e"; - //String time = "1557034496"; - - String token =DigestUtils.md5Hex(code+key+time); - - System.out.println("currentTimeMillis " + System.currentTimeMillis()); - System.out.println(DigestUtils.md5Hex(code+key+time)); - String account="admin"; - - String redirec_uri=String.format(zentaoLogin,account,code,time,token); - System.out.println("redirec_uri : \n"+redirec_uri); - - + @Test + public void test() { + + System.out.println(DigestUtils.shaB64("mytest")); + + System.out.println(DigestUtils.sha1B64("e707c852-29a4-bf56-f8b9-014716850d89")); + + System.out.println(DigestUtils.sha256B64("mytest")); + + System.out.println(DigestUtils.sha384B64("mytest")); + + System.out.println(DigestUtils.sha512B64("mytest")); + + System.out.println(DigestUtils.md5B64("e707c852-29a4-bf56-f8b9-014716850d89")); + } + */ + @Test + public void testHex() { + /* + System.out.println(DigestUtils.shaHex("mytest")); + + System.out.println(DigestUtils.sha1Hex("mytest")); + + System.out.println(DigestUtils.sha256Hex("mytest")); + + System.out.println(DigestUtils.sha384Hex("mytest")); + + System.out.println(DigestUtils.sha512Hex("mytest")); + + System.out.println(DigestUtils.md5Hex("seamingxy99")); + System.out.println((new Date()).getTime()); + */ + + //String zentaoLogin="http://127.0.0.1/biz/api.php?m=user&f=apilogin&account=%s&code=%s&time=%s&token=%s"; + String zentaoLogin="http://127.0.0.1/zentao/api.php?m=user&f=apilogin&account=%s&code=%s&time=%s&token=%s"; + String code = "maxkey"; + //String key = "430ba509ba95094e580b925fc4839459"; + String key = "f71792dfebf23d62bc4d65d1513087e3"; + //String time = ""+System.currentTimeMillis(); + String time = ""+Instant.now().getEpochSecond(); + //String time = "1615370929"; + //String code = "myApp"; + //String key = "427c579384224abf9570779d82969d1e"; + //String time = "1557034496"; + + String token =DigestUtils.md5Hex(code+key+time); + + System.out.println("currentTimeMillis " + System.currentTimeMillis()); + System.out.println(DigestUtils.md5Hex(code+key+time)); + String account="admin"; + + String redirec_uri=String.format(zentaoLogin,account,code,time,token); + System.out.println("redirec_uri : \n"+redirec_uri); + + - - } + + } } diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/KeyGen.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/KeyGen.java index e2a8e57fe..404f309b1 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/KeyGen.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/KeyGen.java @@ -26,36 +26,36 @@ import java.security.SecureRandom; public class KeyGen { - public static void main(String[] args) throws Exception { - String keyInfo="ASDFSDFNUGD__TYTY"; - KeyGen kg = new KeyGen(); - kg.genKeys(keyInfo); - } + public static void main(String[] args) throws Exception { + String keyInfo="ASDFSDFNUGD__TYTY"; + KeyGen kg = new KeyGen(); + kg.genKeys(keyInfo); + } - public void genKeys(String keyInfo) throws Exception { - KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); - SecureRandom random = new SecureRandom(); - random.setSeed(keyInfo.getBytes()); - - keygen.initialize(512, random); - // ȡ����Կ�� - KeyPair kp = keygen.generateKeyPair(); - // ȡ�ù�Կ - PublicKey publicKey = kp.getPublic(); - System.out.println(publicKey); - saveFile(publicKey, "pk.dat"); - // ȡ��˽Կ - PrivateKey privateKey = kp.getPrivate(); - saveFile(privateKey, "sk.dat"); - } + public void genKeys(String keyInfo) throws Exception { + KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); + SecureRandom random = new SecureRandom(); + random.setSeed(keyInfo.getBytes()); + + keygen.initialize(512, random); + // ȡ����Կ�� + KeyPair kp = keygen.generateKeyPair(); + // ȡ�ù�Կ + PublicKey publicKey = kp.getPublic(); + System.out.println(publicKey); + saveFile(publicKey, "pk.dat"); + // ȡ��˽Կ + PrivateKey privateKey = kp.getPrivate(); + saveFile(privateKey, "sk.dat"); + } - private void saveFile(Object obj, String fileName) throws Exception { - ObjectOutputStream output=new ObjectOutputStream( - new FileOutputStream(fileName)); - output.writeObject(obj); - output.close(); - } + private void saveFile(Object obj, String fileName) throws Exception { + ObjectOutputStream output=new ObjectOutputStream( + new FileOutputStream(fileName)); + output.writeObject(obj); + output.close(); + } } //���ù�Կ���ܣ�˽Կ���ܣ� diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/Md5SumTest.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/Md5SumTest.java index 654a2daf6..d05b5656e 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/Md5SumTest.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/Md5SumTest.java @@ -24,17 +24,17 @@ import org.dromara.maxkey.crypto.Md5Sum; public class Md5SumTest { - public Md5SumTest() { - } + public Md5SumTest() { + } - public static void main(String[] args) throws FileNotFoundException { - //String md5value=Md5Sum.produce(new File("E:/transwarp-4.3.4-Final-el6/transwarp-4.3.4-Final-26854-zh.el6.x86_64.tar.gz")); - File f=new File("E:/Soft/Xmanager4_setup.1410342608.exe"); - String md5value=Md5Sum.produce(f); - - System.out.println(""+md5value); - - System.out.println(Md5Sum.check(f,md5value)); - } + public static void main(String[] args) throws FileNotFoundException { + //String md5value=Md5Sum.produce(new File("E:/transwarp-4.3.4-Final-el6/transwarp-4.3.4-Final-26854-zh.el6.x86_64.tar.gz")); + File f=new File("E:/Soft/Xmanager4_setup.1410342608.exe"); + String md5value=Md5Sum.produce(f); + + System.out.println(""+md5value); + + System.out.println(Md5Sum.check(f,md5value)); + } } diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/PasswordGenTest.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/PasswordGenTest.java index 3334b8a29..090bd5baf 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/PasswordGenTest.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/PasswordGenTest.java @@ -21,18 +21,18 @@ import org.dromara.maxkey.crypto.password.PasswordGen; public class PasswordGenTest { - public PasswordGenTest() { - } + public PasswordGenTest() { + } - public static void main(String[] args) { - PasswordGen gen=new PasswordGen(); - System.out.println(gen.gen(2,2,2,1)); - for(int i=1;i<100;i++){ - //System.out.println(gen.gen()); - //System.out.println(gen.gen(6)); - //System.out.println(gen.gen(2,2,2,0)); - } - - } + public static void main(String[] args) { + PasswordGen gen=new PasswordGen(); + System.out.println(gen.gen(2,2,2,1)); + for(int i=1;i<100;i++){ + //System.out.println(gen.gen()); + //System.out.println(gen.gen(6)); + //System.out.println(gen.gen(2,2,2,0)); + } + + } } diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/RSAUtilsTest.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/RSAUtilsTest.java index e012805f4..30362b6d4 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/RSAUtilsTest.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/RSAUtilsTest.java @@ -27,28 +27,28 @@ import org.junit.Test; public class RSAUtilsTest { - @Test - public void test() throws Exception { + @Test + public void test() throws Exception { - // RSA KeyPair - KeyPair keyPair = RSAUtils.genRSAKeyPair(); - String privateKey = HexUtils.hex2String(keyPair.getPrivate().getEncoded()); - String publicKey = HexUtils.hex2String(keyPair.getPublic().getEncoded()); - System.out.println("privateKey:" + privateKey); - System.out.println("publicKey:" + publicKey); - String signString = "my name is shiming"; - System.out.println("privateKey:"); - System.out.println( Base64Utils.base64UrlEncode(keyPair.getPublic().getEncoded())); - System.out.println("PublicKeyPEM:"); - System.out.println(RSAUtils.getPublicKeyPEM(keyPair.getPublic().getEncoded())); - - byte[] encodedData = RSAUtils.encryptByPrivateKey(signString.getBytes(), privateKey); - System.out.println("encodedData \r\n" + new String(encodedData)); - System.out.println("encodedData HexString \r\n" + HexUtils.bytes2HexString(encodedData)); - byte[] decodedData = RSAUtils.decryptByPublicKey(encodedData, publicKey); - String target = new String(decodedData); - System.out.println("target:" + target); - - } + // RSA KeyPair + KeyPair keyPair = RSAUtils.genRSAKeyPair(); + String privateKey = HexUtils.hex2String(keyPair.getPrivate().getEncoded()); + String publicKey = HexUtils.hex2String(keyPair.getPublic().getEncoded()); + System.out.println("privateKey:" + privateKey); + System.out.println("publicKey:" + publicKey); + String signString = "my name is shiming"; + System.out.println("privateKey:"); + System.out.println( Base64Utils.base64UrlEncode(keyPair.getPublic().getEncoded())); + System.out.println("PublicKeyPEM:"); + System.out.println(RSAUtils.getPublicKeyPEM(keyPair.getPublic().getEncoded())); + + byte[] encodedData = RSAUtils.encryptByPrivateKey(signString.getBytes(), privateKey); + System.out.println("encodedData \r\n" + new String(encodedData)); + System.out.println("encodedData HexString \r\n" + HexUtils.bytes2HexString(encodedData)); + byte[] decodedData = RSAUtils.decryptByPublicKey(encodedData, publicKey); + String target = new String(decodedData); + System.out.println("target:" + target); + + } } diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/ReciprocalUtilsTest.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/ReciprocalUtilsTest.java index 8acbf5837..737378037 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/ReciprocalUtilsTest.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/ReciprocalUtilsTest.java @@ -23,44 +23,44 @@ import org.dromara.maxkey.crypto.password.PasswordReciprocal; import org.junit.Test; public class ReciprocalUtilsTest { - @Test - public void test() throws UnsupportedEncodingException { - /* - //System.out.println(ReciprocalUtils.generateKey(ReciprocalUtils.Algorithm.AES)); - - System.out.println( ReciprocalUtils.aesDecoder("7f8cbcd348ea99914f077250b9d14421e32eb7335be127f4838db9ea24f59ea0be2e17e0ce63da63ff29c50150b3343703ed778f2505ea50486236d2c682fa7f49d1efd7dc37fd62b5c518c2a7285d6063dd1d5d1a5c8cd53a622fff407c6537540f0bba5957180835d928082f3901d5aedf4e6ae873f5ab17dc46b7b385a1e306abab90696aed1fbfb147308d6114f5", "846KZSzYq56M6d5o")); - - //System.out.println(ReciprocalUtils.blowfishEncode("sadf","1111")); - - // System.out.println(ReciprocalUtils.blowfishDecoder("3547433be1e3a817","1111")); - System.out.println( ReciprocalUtils.encode("0eFm6iHvTgNs")); - - System.out.println( ReciprocalUtils.decoder("76efad66eb7d10140dc2d9ef41c51df0")); - - System.out.println( ReciprocalUtils.generatorDefaultKey(ReciprocalUtils.Algorithm.DESede)); - - - - - String urlencodeString="中国"; - String urlencode = java.net.URLEncoder.encode(urlencodeString, "utf-8"); - System.out.println(urlencode); - String urldecodeString="http://exchange.maxkey.top/owa/?ae=Item&a=Open&t=IPM.Note&id=RgAAAABPKgpqnlfYQ7BVC%2fBfH2XIBwCS0xhUjzMYSLVky9bw7LddAAAAjov5AACS0xhUjzMYSLVky9bw7LddAAADzoy%2fAAAA&pspid=_1428036768398_867461813"; - String urldcode = java.net.URLDecoder.decode(urldecodeString, "utf-8"); - - - System.out.println(urldcode);*/ + @Test + public void test() throws UnsupportedEncodingException { + /* + //System.out.println(ReciprocalUtils.generateKey(ReciprocalUtils.Algorithm.AES)); + + System.out.println( ReciprocalUtils.aesDecoder("7f8cbcd348ea99914f077250b9d14421e32eb7335be127f4838db9ea24f59ea0be2e17e0ce63da63ff29c50150b3343703ed778f2505ea50486236d2c682fa7f49d1efd7dc37fd62b5c518c2a7285d6063dd1d5d1a5c8cd53a622fff407c6537540f0bba5957180835d928082f3901d5aedf4e6ae873f5ab17dc46b7b385a1e306abab90696aed1fbfb147308d6114f5", "846KZSzYq56M6d5o")); + + //System.out.println(ReciprocalUtils.blowfishEncode("sadf","1111")); + + // System.out.println(ReciprocalUtils.blowfishDecoder("3547433be1e3a817","1111")); + System.out.println( ReciprocalUtils.encode("0eFm6iHvTgNs")); + + System.out.println( ReciprocalUtils.decoder("76efad66eb7d10140dc2d9ef41c51df0")); + + System.out.println( ReciprocalUtils.generatorDefaultKey(ReciprocalUtils.Algorithm.DESede)); + + + + + String urlencodeString="中国"; + String urlencode = java.net.URLEncoder.encode(urlencodeString, "utf-8"); + System.out.println(urlencode); + String urldecodeString="http://exchange.maxkey.top/owa/?ae=Item&a=Open&t=IPM.Note&id=RgAAAABPKgpqnlfYQ7BVC%2fBfH2XIBwCS0xhUjzMYSLVky9bw7LddAAAAjov5AACS0xhUjzMYSLVky9bw7LddAAADzoy%2fAAAA&pspid=_1428036768398_867461813"; + String urldcode = java.net.URLDecoder.decode(urldecodeString, "utf-8"); + + + System.out.println(urldcode);*/ - - String encoderString="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - encoderString = PasswordReciprocal.getInstance().encode(encoderString); - System.out.println( encoderString); - System.out.println( "length " + encoderString.length()); - - encoderString=PasswordReciprocal.getInstance().decoder(encoderString); - System.out.println(encoderString ); - - - - } + + String encoderString="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + encoderString = PasswordReciprocal.getInstance().encode(encoderString); + System.out.println( encoderString); + System.out.println( "length " + encoderString.length()); + + encoderString=PasswordReciprocal.getInstance().decoder(encoderString); + System.out.println(encoderString ); + + + + } } diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/RsaMessage.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/RsaMessage.java index 058db6fe7..855f3fde8 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/RsaMessage.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/RsaMessage.java @@ -16,153 +16,153 @@ package org.maxkey.crypto; - import java.io.FileInputStream; - import java.io.ObjectInputStream; - import java.security.Key; - import java.security.PrivateKey; - import java.security.PublicKey; - import java.security.Signature; - import java.security.interfaces.RSAPrivateKey; - import java.security.interfaces.RSAPublicKey; + import java.io.FileInputStream; + import java.io.ObjectInputStream; + import java.security.Key; + import java.security.PrivateKey; + import java.security.PublicKey; + import java.security.Signature; + import java.security.interfaces.RSAPrivateKey; + import java.security.interfaces.RSAPublicKey; - import javax.crypto.Cipher; - - - /** - * RSA�ӽ���,RSAǩ��ǩ����֤�� - * - * @author Administrator - * - */ - public class RsaMessage { + import javax.crypto.Cipher; + + + /** + * RSA�ӽ���,RSAǩ��ǩ����֤�� + * + * @author Administrator + * + */ + public class RsaMessage { - public static void main(String[] args) throws Exception { - String str = "hello,�����ĵ����"; - System.out.println("ԭ�ģ�" + str); + public static void main(String[] args) throws Exception { + String str = "hello,�����ĵ����"; + System.out.println("ԭ�ģ�" + str); - RsaMessage rsa = new RsaMessage(); - RSAPrivateKey privateKey = (RSAPrivateKey) rsa.readFromFile("sk.dat"); - RSAPublicKey publickKey = (RSAPublicKey) rsa.readFromFile("pk.dat"); + RsaMessage rsa = new RsaMessage(); + RSAPrivateKey privateKey = (RSAPrivateKey) rsa.readFromFile("sk.dat"); + RSAPublicKey publickKey = (RSAPublicKey) rsa.readFromFile("pk.dat"); - byte[] encbyte = rsa.encrypt(str, privateKey); - System.out.println("˽Կ���ܺ�"); - String encStr = toHexString(encbyte); - System.out.println(encStr); + byte[] encbyte = rsa.encrypt(str, privateKey); + System.out.println("˽Կ���ܺ�"); + String encStr = toHexString(encbyte); + System.out.println(encStr); - byte[] signBytes = rsa.sign(str, privateKey); - System.out.println("ǩ��ֵ��"); - String signStr = toHexString(signBytes); - System.out.println(signStr); + byte[] signBytes = rsa.sign(str, privateKey); + System.out.println("ǩ��ֵ��"); + String signStr = toHexString(signBytes); + System.out.println(signStr); - byte[] decByte = rsa.decrypt(encStr, publickKey); - System.out.println("��Կ���ܺ�"); - String decStr = new String(decByte); - System.out.println(decStr); + byte[] decByte = rsa.decrypt(encStr, publickKey); + System.out.println("��Կ���ܺ�"); + String decStr = new String(decByte); + System.out.println(decStr); - if (rsa.verifySign(str, signStr, publickKey)) { - System.out.println("rsa sign check success"); - } else { - System.out.println("rsa sign check failure"); - } - } + if (rsa.verifySign(str, signStr, publickKey)) { + System.out.println("rsa sign check success"); + } else { + System.out.println("rsa sign check failure"); + } + } - /** - * ����,key�����ǹ�Կ��Ҳ������˽Կ - * - * @param message - * @return - * @throws Exception - */ - public byte[] encrypt(String message, Key key) throws Exception { - Cipher cipher = Cipher.getInstance("RSA"); - cipher.init(Cipher.ENCRYPT_MODE, key); - return cipher.doFinal(message.getBytes()); - } + /** + * ����,key�����ǹ�Կ��Ҳ������˽Կ + * + * @param message + * @return + * @throws Exception + */ + public byte[] encrypt(String message, Key key) throws Exception { + Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(Cipher.ENCRYPT_MODE, key); + return cipher.doFinal(message.getBytes()); + } - /** - * ���ܣ�key�����ǹ�Կ��Ҳ������˽Կ������ǹ�Կ���ܾ���˽Կ���ܣ���֮��Ȼ - * - * @param message - * @return - * @throws Exception - */ - public byte[] decrypt(String message, Key key) throws Exception { - Cipher cipher = Cipher.getInstance("RSA"); - cipher.init(Cipher.DECRYPT_MODE, key); - return cipher.doFinal(toBytes(message)); - } + /** + * ���ܣ�key�����ǹ�Կ��Ҳ������˽Կ������ǹ�Կ���ܾ���˽Կ���ܣ���֮��Ȼ + * + * @param message + * @return + * @throws Exception + */ + public byte[] decrypt(String message, Key key) throws Exception { + Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(Cipher.DECRYPT_MODE, key); + return cipher.doFinal(toBytes(message)); + } - /** - * ��˽Կǩ�� - * - * @param message - * @param key - * @return - * @throws Exception - */ - public byte[] sign(String message, PrivateKey key) throws Exception { - Signature signetcheck = Signature.getInstance("MD5withRSA"); - signetcheck.initSign(key); - signetcheck.update(message.getBytes("ISO-8859-1")); - return signetcheck.sign(); - } + /** + * ��˽Կǩ�� + * + * @param message + * @param key + * @return + * @throws Exception + */ + public byte[] sign(String message, PrivateKey key) throws Exception { + Signature signetcheck = Signature.getInstance("MD5withRSA"); + signetcheck.initSign(key); + signetcheck.update(message.getBytes("ISO-8859-1")); + return signetcheck.sign(); + } - /** - * �ù�Կ��֤ǩ�����ȷ�� - * - * @param message - * @param signStr - * @return - * @throws Exception - */ - public boolean verifySign(String message, String signStr, PublicKey key) - throws Exception { - if (message == null || signStr == null || key == null) { - return false; - } - Signature signetcheck = Signature.getInstance("MD5withRSA"); - signetcheck.initVerify(key); - signetcheck.update(message.getBytes("ISO-8859-1")); - return signetcheck.verify(toBytes(signStr)); - } + /** + * �ù�Կ��֤ǩ�����ȷ�� + * + * @param message + * @param signStr + * @return + * @throws Exception + */ + public boolean verifySign(String message, String signStr, PublicKey key) + throws Exception { + if (message == null || signStr == null || key == null) { + return false; + } + Signature signetcheck = Signature.getInstance("MD5withRSA"); + signetcheck.initVerify(key); + signetcheck.update(message.getBytes("ISO-8859-1")); + return signetcheck.verify(toBytes(signStr)); + } - /** - * ���ļ���ȡobject - * - * @param fileName - * @return - * @throws Exception - */ - private Object readFromFile(String fileName) throws Exception { - ObjectInputStream input = new ObjectInputStream(new FileInputStream( - fileName)); - Object obj = input.readObject(); - input.close(); - return obj; - } + /** + * ���ļ���ȡobject + * + * @param fileName + * @return + * @throws Exception + */ + private Object readFromFile(String fileName) throws Exception { + ObjectInputStream input = new ObjectInputStream(new FileInputStream( + fileName)); + Object obj = input.readObject(); + input.close(); + return obj; + } - public static String toHexString(byte[] b) { - StringBuilder sb = new StringBuilder(b.length * 2); - for (int i = 0; i < b.length; i++) { - sb.append(HEXCHAR[(b[i] & 0xf0) >>> 4]); - sb.append(HEXCHAR[b[i] & 0x0f]); - } - return sb.toString(); - } + public static String toHexString(byte[] b) { + StringBuilder sb = new StringBuilder(b.length * 2); + for (int i = 0; i < b.length; i++) { + sb.append(HEXCHAR[(b[i] & 0xf0) >>> 4]); + sb.append(HEXCHAR[b[i] & 0x0f]); + } + return sb.toString(); + } - public static final byte[] toBytes(String s) { - byte[] bytes; - bytes = new byte[s.length() / 2]; - for (int i = 0; i < bytes.length; i++) { - bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2), - 16); - } - return bytes; - } + public static final byte[] toBytes(String s) { + byte[] bytes; + bytes = new byte[s.length() / 2]; + for (int i = 0; i < bytes.length; i++) { + bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2), + 16); + } + return bytes; + } - private static char[] HEXCHAR = { '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; - } + private static char[] HEXCHAR = { '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + } diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/SCryptPasswordEncoderTest.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/SCryptPasswordEncoderTest.java index a099ea385..6015ed974 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/SCryptPasswordEncoderTest.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/SCryptPasswordEncoderTest.java @@ -21,16 +21,16 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; public class SCryptPasswordEncoderTest { - public SCryptPasswordEncoderTest() { - } + public SCryptPasswordEncoderTest() { + } - public static void main(String[] args) { - BCryptPasswordEncoder pe=new BCryptPasswordEncoder(); - //String c="$e0801$7Holo9EgzBeg5xf/WLZu3/5IQwOyEPDLJPgMXkF9jnekBrbQUMt4CF9O2trkz3zBCnCLpUMR437q/AjQ5TTToA==$oYB8KRSxAsxkKkt5r79W6r6P0wTUcKwGye1ivXRN0Ts=" - //; - System.out.println(pe.encode("admin")); - // System.out.println(pe.encode("shimingxy")+"_password"); - //System.out.println(pe.matches("shimingxy"+"_password", c)); - } + public static void main(String[] args) { + BCryptPasswordEncoder pe=new BCryptPasswordEncoder(); + //String c="$e0801$7Holo9EgzBeg5xf/WLZu3/5IQwOyEPDLJPgMXkF9jnekBrbQUMt4CF9O2trkz3zBCnCLpUMR437q/AjQ5TTToA==$oYB8KRSxAsxkKkt5r79W6r6P0wTUcKwGye1ivXRN0Ts=" + //; + System.out.println(pe.encode("admin")); + // System.out.println(pe.encode("shimingxy")+"_password"); + //System.out.println(pe.matches("shimingxy"+"_password", c)); + } } diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/cert/X509V3CertGenTest.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/cert/X509V3CertGenTest.java index 16aa8e953..cbefec0a3 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/cert/X509V3CertGenTest.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/cert/X509V3CertGenTest.java @@ -30,30 +30,30 @@ import org.junit.Test; public class X509V3CertGenTest { - @Test - public void generateV3() throws Exception { - Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); - KeyPair keyPair =X509V3CertGen.genRSAKeyPair(); - String issuer="CN=maxkey.top,O=maxkey,L=SH,ST=SH,C=CN"; - Date startDate=DateTime.now().toDate(); - Date endDate=DateTime.now().plusMonths(10).toDate(); - System.out.println("Private : "+ keyPair.getPrivate().toString()); - - System.out.println("Public : "+ keyPair.getPublic().toString()); - X509Certificate cert = X509V3CertGen.genV3Certificate(issuer,issuer,startDate,endDate,keyPair); - String certFileString = "D:\\MaxKey\\Workspaces\\maxkey\\Cert345.cer"; - File certFile =new File(certFileString); - if(certFile.exists()) { - certFile.deleteOnExit(); - } - - FileOutputStream out = new FileOutputStream(certFileString); - out.write(cert.getEncoded()); - out.close(); - - cert.checkValidity(new Date()); - cert.verify(cert.getPublicKey()); - - } - + @Test + public void generateV3() throws Exception { + Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); + KeyPair keyPair =X509V3CertGen.genRSAKeyPair(); + String issuer="CN=maxkey.top,O=maxkey,L=SH,ST=SH,C=CN"; + Date startDate=DateTime.now().toDate(); + Date endDate=DateTime.now().plusMonths(10).toDate(); + System.out.println("Private : "+ keyPair.getPrivate().toString()); + + System.out.println("Public : "+ keyPair.getPublic().toString()); + X509Certificate cert = X509V3CertGen.genV3Certificate(issuer,issuer,startDate,endDate,keyPair); + String certFileString = "D:\\MaxKey\\Workspaces\\maxkey\\Cert345.cer"; + File certFile =new File(certFileString); + if(certFile.exists()) { + certFile.deleteOnExit(); + } + + FileOutputStream out = new FileOutputStream(certFileString); + out.write(cert.getEncoded()); + out.close(); + + cert.checkValidity(new Date()); + cert.verify(cert.getPublicKey()); + + } + } diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/password/PasswordReciprocalTest.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/password/PasswordReciprocalTest.java index d90f65754..0a8246fd7 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/password/PasswordReciprocalTest.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/password/PasswordReciprocalTest.java @@ -22,22 +22,22 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; public class PasswordReciprocalTest { - public PasswordReciprocalTest() { - - } + public PasswordReciprocalTest() { + + } - public static void main(String[] args) { - BCryptPasswordEncoder spe= new BCryptPasswordEncoder(); - //String pass=PasswordReciprocal.getInstance().rawPassword("admin", "admin"); - String pass ="x8zPbCya"; - String epass=spe.encode(pass); - System.out.println("PasswordEncoder "+epass); - - String encode = PasswordReciprocal.getInstance().encode(pass); - System.out.println(encode); - System.out.println(PasswordReciprocal.getInstance().decoder(encode)); - - System.out.println(PasswordReciprocal.getInstance().matches(pass,encode)); - } + public static void main(String[] args) { + BCryptPasswordEncoder spe= new BCryptPasswordEncoder(); + //String pass=PasswordReciprocal.getInstance().rawPassword("admin", "admin"); + String pass ="x8zPbCya"; + String epass=spe.encode(pass); + System.out.println("PasswordEncoder "+epass); + + String encode = PasswordReciprocal.getInstance().encode(pass); + System.out.println(encode); + System.out.println(PasswordReciprocal.getInstance().decoder(encode)); + + System.out.println(PasswordReciprocal.getInstance().matches(pass,encode)); + } } diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/password/SM4PasswordEncoderTest.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/password/SM4PasswordEncoderTest.java index 71c9b5391..bd28c3f84 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/password/SM4PasswordEncoderTest.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/password/SM4PasswordEncoderTest.java @@ -22,7 +22,7 @@ import org.dromara.maxkey.crypto.password.Md4PasswordEncoder; public class SM4PasswordEncoderTest { public static void main(String[] args) { - Md4PasswordEncoder sm4 = new Md4PasswordEncoder(); + Md4PasswordEncoder sm4 = new Md4PasswordEncoder(); System.out.println(sm4.encode("maxkeypassword")); String c="{BQWoTG+C4jL8d8QNIu0jL1WkMWezxNAZtliNoJOke5k=}8cfc46546a5996e74442183bd122f370"; diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/password/StandardPasswordEncoderTest.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/password/StandardPasswordEncoderTest.java index 1fac60a19..9ca6c66aa 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/password/StandardPasswordEncoderTest.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/password/StandardPasswordEncoderTest.java @@ -22,7 +22,7 @@ import org.dromara.maxkey.crypto.password.StandardPasswordEncoder; public class StandardPasswordEncoderTest { public static void main(String[] args) { - StandardPasswordEncoder spe = new StandardPasswordEncoder(); + StandardPasswordEncoder spe = new StandardPasswordEncoder(); System.out.println(spe.encode("maxkeypassword")); String c="4b60c81ad4c31d97fbe8c87952f8de7a329ceb004261c8bd22254cfa8aa096bede6efbafcc84bade"; diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/DsaSignerTest.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/DsaSignerTest.java index 6328b1713..892891f18 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/DsaSignerTest.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/DsaSignerTest.java @@ -24,29 +24,29 @@ import org.dromara.maxkey.crypto.signature.DsaSigner; import org.junit.Test; public final class DsaSignerTest { - @Test - public void test() throws Exception { + @Test + public void test() throws Exception { - DsaSigner dsaSigner = new DsaSigner(); - // genKeyPair - Map keyMap = KeyPairUtil.genKeyPairMap(DsaSigner.KEY_ALGORITHM); - - String publicKey = KeyPairUtil.getPublicKey(keyMap); - String privateKey = KeyPairUtil.getPrivateKey(keyMap); - System.out.println("privateKey:" + privateKey); - System.out.println("privateKey:" + privateKey.length()); - System.out.println("publicKey:" + publicKey); - System.out.println("publicKey:" + publicKey.length()); - - String signStr = "my data need to sign use DSA Digital signature"; - System.out.println("signStr:" + signStr); + DsaSigner dsaSigner = new DsaSigner(); + // genKeyPair + Map keyMap = KeyPairUtil.genKeyPairMap(DsaSigner.KEY_ALGORITHM); + + String publicKey = KeyPairUtil.getPublicKey(keyMap); + String privateKey = KeyPairUtil.getPrivateKey(keyMap); + System.out.println("privateKey:" + privateKey); + System.out.println("privateKey:" + privateKey.length()); + System.out.println("publicKey:" + publicKey); + System.out.println("publicKey:" + publicKey.length()); + + String signStr = "my data need to sign use DSA Digital signature"; + System.out.println("signStr:" + signStr); - String sign = dsaSigner.signB64(signStr, privateKey); - System.out.println("sign��" + sign); - // verify - boolean status = dsaSigner.verifyB64(signStr, publicKey, sign); - System.out.println("status��" + status); + String sign = dsaSigner.signB64(signStr, privateKey); + System.out.println("sign��" + sign); + // verify + boolean status = dsaSigner.verifyB64(signStr, publicKey, sign); + System.out.println("status��" + status); - } + } } diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/HMAC512ServiceTest.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/HMAC512ServiceTest.java index 048bd3a8a..bbd8fd94f 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/HMAC512ServiceTest.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/HMAC512ServiceTest.java @@ -23,14 +23,14 @@ import com.nimbusds.jose.JOSEException; public class HMAC512ServiceTest { - public static void main(String[] args) throws JOSEException { - // TODO Auto-generated method stub + public static void main(String[] args) throws JOSEException { + // TODO Auto-generated method stub String key ="7heM-14BtxjyKPuH3ITIm7q2-ps5MuBirWCsrrdbzzSAOuSPrbQYiaJ54AeA0uH2XdkYy3hHAkTFIsieGkyqxOJZ_dQzrCbaYISH9rhUZAKYx8tUY0wkE4ArOC6LqHDJarR6UIcMsARakK9U4dhoOPO1cj74XytemI-w6ACYfzRUn_Rn4e-CQMcnD1C56oNEukwalf06xVgXl41h6K8IBEzLVod58y_VfvFn-NGWpNG0fy_Qxng6dg8Dgva2DobvzMN2eejHGLGB-x809MvC4zbG7CKNVlcrzMYDt2Gt2sOVDrt2l9YqJNfgaLFjrOEVw5cuXemGkX1MvHj6TAsbLg"; Hmac512Service HMAC512Service = new Hmac512Service(key); - String sign = HMAC512Service.sign("{\"sub\":\"hkkkk\"}"); + String sign = HMAC512Service.sign("{\"sub\":\"hkkkk\"}"); System.out.println(sign); boolean isverify = HMAC512Service.verify(sign); System.out.println(isverify); - } + } } diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/HS512SignerTest.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/HS512SignerTest.java index 700338f1b..863da3330 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/HS512SignerTest.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/HS512SignerTest.java @@ -33,34 +33,34 @@ import com.nimbusds.jose.util.Base64URL; public class HS512SignerTest { - public static void main(String[] args) throws JOSEException, ParseException { - // TODO Auto-generated method stub + public static void main(String[] args) throws JOSEException, ParseException { + // TODO Auto-generated method stub - Base64URL secret=new Base64URL( - "7heM-14BtxjyKPuH3ITIm7q2-ps5MuBirWCsrrdbzzSAOuSPrbQYiaJ54AeA0uH2XdkYy3hHAkTFIsieGkyqxOJZ_dQzrCbaYISH9rhUZAKYx8tUY0wkE4ArOC6LqHDJarR6UIcMsARakK9U4dhoOPO1cj74XytemI-w6ACYfzRUn_Rn4e-CQMcnD1C56oNEukwalf06xVgXl41h6K8IBEzLVod58y_VfvFn-NGWpNG0fy_Qxng6dg8Dgva2DobvzMN2eejHGLGB-x809MvC4zbG7CKNVlcrzMYDt2Gt2sOVDrt2l9YqJNfgaLFjrOEVw5cuXemGkX1MvHj6TAsbLg" - ); - OctetSequenceKey octKey= new OctetSequenceKey.Builder(secret) - .keyID("mxk_auth_jwk_secret") - .keyUse(KeyUse.SIGNATURE) - .algorithm(JWSAlgorithm.HS512) - .build(); - System.out.println(octKey.toJSONString()); - // Create HMAC signer - JWSSigner signer = new MACSigner(octKey); + Base64URL secret=new Base64URL( + "7heM-14BtxjyKPuH3ITIm7q2-ps5MuBirWCsrrdbzzSAOuSPrbQYiaJ54AeA0uH2XdkYy3hHAkTFIsieGkyqxOJZ_dQzrCbaYISH9rhUZAKYx8tUY0wkE4ArOC6LqHDJarR6UIcMsARakK9U4dhoOPO1cj74XytemI-w6ACYfzRUn_Rn4e-CQMcnD1C56oNEukwalf06xVgXl41h6K8IBEzLVod58y_VfvFn-NGWpNG0fy_Qxng6dg8Dgva2DobvzMN2eejHGLGB-x809MvC4zbG7CKNVlcrzMYDt2Gt2sOVDrt2l9YqJNfgaLFjrOEVw5cuXemGkX1MvHj6TAsbLg" + ); + OctetSequenceKey octKey= new OctetSequenceKey.Builder(secret) + .keyID("mxk_auth_jwk_secret") + .keyUse(KeyUse.SIGNATURE) + .algorithm(JWSAlgorithm.HS512) + .build(); + System.out.println(octKey.toJSONString()); + // Create HMAC signer + JWSSigner signer = new MACSigner(octKey); - // Prepare JWS object with "Hello, world!" payload - JWSObject jwsObject = new JWSObject(new JWSHeader(JWSAlgorithm.HS256), new Payload("Hello, world!")); + // Prepare JWS object with "Hello, world!" payload + JWSObject jwsObject = new JWSObject(new JWSHeader(JWSAlgorithm.HS256), new Payload("Hello, world!")); - // Apply the HMAC - jwsObject.sign(signer); - String s = jwsObject.serialize(); - System.out.println(s); - - JWSObject jwsObjected =JWSObject.parse(s); - MACVerifier verifier = new MACVerifier(octKey); - boolean isVerifier = verifier.verify(jwsObjected.getHeader(), jwsObjected.getSigningInput(), jwsObjected.getSignature()); - System.out.println(isVerifier); - - } + // Apply the HMAC + jwsObject.sign(signer); + String s = jwsObject.serialize(); + System.out.println(s); + + JWSObject jwsObjected =JWSObject.parse(s); + MACVerifier verifier = new MACVerifier(octKey); + boolean isVerifier = verifier.verify(jwsObjected.getHeader(), jwsObjected.getSigningInput(), jwsObjected.getSignature()); + System.out.println(isVerifier); + + } } diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/RSAKeyTest.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/RSAKeyTest.java index f19e58f2e..ce5c32f20 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/RSAKeyTest.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/RSAKeyTest.java @@ -36,43 +36,43 @@ import com.nimbusds.jose.jwk.gen.RSAKeyGenerator; public class RSAKeyTest { - public static void main(String[] args) throws JOSEException { - // RSA signatures require a public and private RSA key pair, the public key - // must be made known to the JWS recipient in order to verify the signatures - RSAKey rsaJWK = new RSAKeyGenerator(2048) - .keyID("123") - .keyUse(KeyUse.SIGNATURE) - .algorithm(JWSAlgorithm.RS256) - .generate(); - RSAKey rsaPublicJWK = rsaJWK.toPublicJWK(); - System.out.println(rsaPublicJWK.toJSONString()); - - System.out.println(rsaJWK.toJSONString()); - - byte[] sharedKey = new byte[32]; - new SecureRandom().nextBytes(sharedKey); - System.out.println(Base64Utils.encoder(sharedKey)); - - - OctetSequenceKey octKey= new OctetSequenceKeyGenerator(2048) - .keyID("123") - .keyUse(KeyUse.SIGNATURE) - .algorithm(JWSAlgorithm.HS256) - .generate(); - System.out.println(octKey.toJSONString()); - - // Create HMAC signer - JWSSigner signer = new MACSigner(octKey); + public static void main(String[] args) throws JOSEException { + // RSA signatures require a public and private RSA key pair, the public key + // must be made known to the JWS recipient in order to verify the signatures + RSAKey rsaJWK = new RSAKeyGenerator(2048) + .keyID("123") + .keyUse(KeyUse.SIGNATURE) + .algorithm(JWSAlgorithm.RS256) + .generate(); + RSAKey rsaPublicJWK = rsaJWK.toPublicJWK(); + System.out.println(rsaPublicJWK.toJSONString()); + + System.out.println(rsaJWK.toJSONString()); + + byte[] sharedKey = new byte[32]; + new SecureRandom().nextBytes(sharedKey); + System.out.println(Base64Utils.encoder(sharedKey)); + + + OctetSequenceKey octKey= new OctetSequenceKeyGenerator(2048) + .keyID("123") + .keyUse(KeyUse.SIGNATURE) + .algorithm(JWSAlgorithm.HS256) + .generate(); + System.out.println(octKey.toJSONString()); + + // Create HMAC signer + JWSSigner signer = new MACSigner(octKey); - // Prepare JWS object with "Hello, world!" payload - JWSObject jwsObject = new JWSObject(new JWSHeader(JWSAlgorithm.HS256), new Payload("Hello, world!")); + // Prepare JWS object with "Hello, world!" payload + JWSObject jwsObject = new JWSObject(new JWSHeader(JWSAlgorithm.HS256), new Payload("Hello, world!")); - // Apply the HMAC - jwsObject.sign(signer); - String s = jwsObject.serialize(); - System.out.println(s); - - System.out.print("A128KW".substring(1, 4)); - } + // Apply the HMAC + jwsObject.sign(signer); + String s = jwsObject.serialize(); + System.out.println(s); + + System.out.print("A128KW".substring(1, 4)); + } } diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/RsaSignerTest.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/RsaSignerTest.java index e38771215..8e1381674 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/RsaSignerTest.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/crypto/signature/RsaSignerTest.java @@ -29,25 +29,25 @@ import org.junit.Test; public final class RsaSignerTest { - @Test - public void test() throws Exception { + @Test + public void test() throws Exception { - RsaSigner rsaSigner = new RsaSigner(); - Map key = KeyPairUtil.genKeyPairMap(RsaSigner.KEY_ALGORTHM); - String privateKey = KeyPairUtil.getPrivateKey(key); - String publicKey = KeyPairUtil.getPublicKey(key); - System.out.println("privateKey:" + privateKey); - System.out.println("privateKey:" + privateKey.length()); - System.out.println("publicKey:" + publicKey); - System.out.println("publicKey:" + publicKey.length()); - String sdata = "MIIBSwIBADCCASwGByqGSM44BAEwggEfAoGBAP1/U4EddRIpUt9KnC7s5Of2EbdSPO9EAMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7gB00b/JmYLdrmVClpJ+f6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1VBNaFpEy9nXzrith1yrv8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUCgYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoEFgIUWEKjQXEsmz9cfPNxwhAlXl90U8c="; - String signedStringuuid = rsaSigner.signB64(sdata, privateKey); - System.out.println("signedStringuuid:" + signedStringuuid); - System.out.println("signedStringuuid:" + signedStringuuid.length()); - boolean isSigneduuid = rsaSigner.verifyB64(sdata, publicKey, - signedStringuuid); - System.out.println("isSigneduuid:" + isSigneduuid); + RsaSigner rsaSigner = new RsaSigner(); + Map key = KeyPairUtil.genKeyPairMap(RsaSigner.KEY_ALGORTHM); + String privateKey = KeyPairUtil.getPrivateKey(key); + String publicKey = KeyPairUtil.getPublicKey(key); + System.out.println("privateKey:" + privateKey); + System.out.println("privateKey:" + privateKey.length()); + System.out.println("publicKey:" + publicKey); + System.out.println("publicKey:" + publicKey.length()); + String sdata = "MIIBSwIBADCCASwGByqGSM44BAEwggEfAoGBAP1/U4EddRIpUt9KnC7s5Of2EbdSPO9EAMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7gB00b/JmYLdrmVClpJ+f6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1VBNaFpEy9nXzrith1yrv8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUCgYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoEFgIUWEKjQXEsmz9cfPNxwhAlXl90U8c="; + String signedStringuuid = rsaSigner.signB64(sdata, privateKey); + System.out.println("signedStringuuid:" + signedStringuuid); + System.out.println("signedStringuuid:" + signedStringuuid.length()); + boolean isSigneduuid = rsaSigner.verifyB64(sdata, publicKey, + signedStringuuid); + System.out.println("isSigneduuid:" + isSigneduuid); - } + } } diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/mail/MailTest.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/mail/MailTest.java index 8dd7d9cda..7428a5bdb 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/mail/MailTest.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/mail/MailTest.java @@ -19,26 +19,26 @@ package org.maxkey.mail; public class MailTest { - - //@Test - public void test() throws Exception { - String username="test@connsec.com"; - String password="3&8Ujbnm5hkjhFD"; - String smtpHost="smtp.exmail.qq.com"; - int port=465; - boolean ssl=true; - String senderMail="test@connsec.com"; - /* - Email email = new SimpleEmail(); - email.setHostName(smtpHost); - email.setSmtpPort(port); - email.setAuthenticator(new DefaultAuthenticator(username, password)); - email.setSSLOnConnect(ssl); - email.setFrom(senderMail); - email.setSubject("One Time PassWord"); - email.setMsg("You Token is "+111+" , it validity in "+5 +" minutes"); - email.addTo("shimingxy@qq.com"); - email.send(); - */ - } + + //@Test + public void test() throws Exception { + String username="test@connsec.com"; + String password="3&8Ujbnm5hkjhFD"; + String smtpHost="smtp.exmail.qq.com"; + int port=465; + boolean ssl=true; + String senderMail="test@connsec.com"; + /* + Email email = new SimpleEmail(); + email.setHostName(smtpHost); + email.setSmtpPort(port); + email.setAuthenticator(new DefaultAuthenticator(username, password)); + email.setSSLOnConnect(ssl); + email.setFrom(senderMail); + email.setSubject("One Time PassWord"); + email.setMsg("You Token is "+111+" , it validity in "+5 +" minutes"); + email.addTo("shimingxy@qq.com"); + email.send(); + */ + } } diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/word/CharacterCase.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/word/CharacterCase.java index 2462c938c..49fedceb4 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/word/CharacterCase.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/word/CharacterCase.java @@ -19,14 +19,14 @@ package org.maxkey.word; public class CharacterCase { - /** - * @param args - */ - public static void main(String[] args) { - String word="partner "; - - System.out.println(word.toUpperCase()); - System.out.println(word.toLowerCase()); - } + /** + * @param args + */ + public static void main(String[] args) { + String word="partner "; + + System.out.println(word.toUpperCase()); + System.out.println(word.toLowerCase()); + } } diff --git a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/word/SubStr.java b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/word/SubStr.java index 25cff791d..1618186ff 100644 --- a/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/word/SubStr.java +++ b/maxkey-commons/maxkey-crypto/src/test/java/org/maxkey/word/SubStr.java @@ -19,14 +19,14 @@ package org.maxkey.word; public class SubStr { - /** - * @param args - */ - public static void main(String[] args) { - String browser="Chrome/44.0.2369.0"; - System.out.println(browser.indexOf('.')); - String passwordAlgorithm = "MD5-HEX"; - System.out.println(passwordAlgorithm.substring(0,passwordAlgorithm.indexOf("-HEX"))); - } + /** + * @param args + */ + public static void main(String[] args) { + String browser="Chrome/44.0.2369.0"; + System.out.println(browser.indexOf('.')); + String passwordAlgorithm = "MD5-HEX"; + System.out.println(passwordAlgorithm.substring(0,passwordAlgorithm.indexOf("-HEX"))); + } } diff --git a/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/LdapUtils.java b/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/LdapUtils.java index a53c205ec..264d7e2a4 100644 --- a/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/LdapUtils.java +++ b/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/LdapUtils.java @@ -39,9 +39,9 @@ public class LdapUtils { private static final Logger _logger = LoggerFactory.getLogger(LdapUtils.class); public class Product{ - public static final String ActiveDirectory = "ActiveDirectory"; - public static final String OpenLDAP = "OpenLDAP"; - public static final String StandardLDAP = "StandardLDAP"; + public static final String ActiveDirectory = "ActiveDirectory"; + public static final String OpenLDAP = "OpenLDAP"; + public static final String StandardLDAP = "StandardLDAP"; } @@ -98,16 +98,16 @@ public class LdapUtils { } protected DirContext InitialDirContext(Properties properties) { - if(ctx == null) { - ctx =createDirContext(properties); - } + if(ctx == null) { + ctx =createDirContext(properties); + } return ctx; } protected DirContext createDirContext(Properties properties) { - DirContext ctx = null; + DirContext ctx = null; try { - ctx = new InitialDirContext(properties); + ctx = new InitialDirContext(properties); _logger.info("connect to ldap {} seccessful.",providerUrl); } catch (NamingException e) { _logger.error("connect to ldap {} fail.",providerUrl); @@ -117,40 +117,40 @@ public class LdapUtils { } protected void initEnvironment() { - // LDAP + // LDAP if(props == null) { - _logger.debug("PROVIDER_URL {}" , providerUrl); + _logger.debug("PROVIDER_URL {}" , providerUrl); _logger.debug("SECURITY_PRINCIPAL {}" , principal); //no log credentials //_logger.trace("SECURITY_CREDENTIALS {}" , credentials); - props = new Properties(); - props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); - props.setProperty(Context.URL_PKG_PREFIXES, "com.sun.jndi.url"); - props.setProperty(Context.REFERRAL, referral); - props.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); - - props.setProperty(Context.PROVIDER_URL, providerUrl); - props.setProperty(Context.SECURITY_PRINCIPAL, principal); - props.setProperty(Context.SECURITY_CREDENTIALS, credentials); - - if (ssl && providerUrl.toLowerCase().startsWith("ldaps")) { - System.setProperty("javax.net.ssl.trustStore", trustStore); - System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); - props.put(Context.SECURITY_PROTOCOL, "ssl"); - props.put(Context.REFERRAL, "follow"); - } + props = new Properties(); + props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); + props.setProperty(Context.URL_PKG_PREFIXES, "com.sun.jndi.url"); + props.setProperty(Context.REFERRAL, referral); + props.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); + + props.setProperty(Context.PROVIDER_URL, providerUrl); + props.setProperty(Context.SECURITY_PRINCIPAL, principal); + props.setProperty(Context.SECURITY_CREDENTIALS, credentials); + + if (ssl && providerUrl.toLowerCase().startsWith("ldaps")) { + System.setProperty("javax.net.ssl.trustStore", trustStore); + System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); + props.put(Context.SECURITY_PROTOCOL, "ssl"); + props.put(Context.REFERRAL, "follow"); + } } } // connect to ldap server public DirContext openConnection() { - initEnvironment(); + initEnvironment(); return InitialDirContext(props); } // connect to ldap server public DirContext createConnection() { - initEnvironment(); + initEnvironment(); return createDirContext(props); } @@ -298,15 +298,15 @@ public class LdapUtils { } public static String getAttrStringValue(Attributes attrs, String elem) { - StringBuffer values = new StringBuffer(""); + StringBuffer values = new StringBuffer(""); try { if (attrs.get(elem) != null) { for (int i = 0; i < attrs.get(elem).size(); i++) { - if(i == 0) { - values.append(attrs.get(elem).get(i).toString()); - }else { - values.append(" , ").append(attrs.get(elem).get(i).toString()); - } + if(i == 0) { + values.append(attrs.get(elem).get(i).toString()); + }else { + values.append(" , ").append(attrs.get(elem).get(i).toString()); + } } } } catch (NamingException e) { @@ -317,15 +317,15 @@ public class LdapUtils { } public static String getAttrStringValue(Attribute attr) { - StringBuffer values = new StringBuffer(""); + StringBuffer values = new StringBuffer(""); try { if (attr != null) { for (int i = 0; i < attr.size(); i++) { - if(i == 0) { - values.append(attr.get(i).toString()); - }else { - values.append(" , ").append(attr.get(i).toString()); - } + if(i == 0) { + values.append(attr.get(i).toString()); + }else { + values.append(" , ").append(attr.get(i).toString()); + } } } } catch (NamingException e) { @@ -336,11 +336,11 @@ public class LdapUtils { } public static String getAttributeStringValue(String attribute ,HashMap attributeMap) throws NamingException { - attribute= attribute.toLowerCase(); - if(null != attributeMap.get(attribute) && null != attributeMap.get(attribute).get()) { - return attributeMap.get(attribute).get().toString(); - }else { - return ""; - } - } + attribute= attribute.toLowerCase(); + if(null != attributeMap.get(attribute) && null != attributeMap.get(attribute).get()) { + return attributeMap.get(attribute).get().toString(); + }else { + return ""; + } + } } diff --git a/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/activedirectory/ActiveDirectoryUtils.java b/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/activedirectory/ActiveDirectoryUtils.java index c7b6b473d..41b65f3b5 100644 --- a/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/activedirectory/ActiveDirectoryUtils.java +++ b/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/activedirectory/ActiveDirectoryUtils.java @@ -68,40 +68,40 @@ public class ActiveDirectoryUtils extends LdapUtils { @Override protected void initEnvironment() { - if(props == null) { - _logger.debug("PROVIDER_URL {}" , providerUrl); + if(props == null) { + _logger.debug("PROVIDER_URL {}" , providerUrl); _logger.debug("SECURITY_PRINCIPAL {}" , principal); //no log credentials //_logger.trace("SECURITY_CREDENTIALS {}" , credentials); - // LDAP - props = new Properties(); - props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); - props.setProperty(Context.URL_PKG_PREFIXES, "com.sun.jndi.url"); - props.setProperty(Context.REFERRAL, referral); - props.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); - - props.setProperty(Context.PROVIDER_URL, providerUrl); - - if (domain.indexOf(".") > -1) { - activeDirectoryDomain = domain.substring(0, domain.indexOf(".")); - }else { - activeDirectoryDomain = domain; - } - - _logger.info("PROVIDER_DOMAIN : {} for {}" ,activeDirectoryDomain, domain); - String activeDirectoryPrincipal = activeDirectoryDomain + "\\" + principal; - _logger.debug("Active Directory SECURITY_PRINCIPAL : {}" , activeDirectoryPrincipal); - props.setProperty(Context.SECURITY_PRINCIPAL, activeDirectoryPrincipal); - props.setProperty(Context.SECURITY_CREDENTIALS, credentials); - - if (ssl && providerUrl.toLowerCase().startsWith("ldaps")) { - _logger.info("ldaps security protocol."); - System.setProperty("javax.net.ssl.trustStore", trustStore); - System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); - props.put(Context.SECURITY_PROTOCOL, "ssl"); - } - props.put(Context.REFERRAL, "follow"); - } + // LDAP + props = new Properties(); + props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); + props.setProperty(Context.URL_PKG_PREFIXES, "com.sun.jndi.url"); + props.setProperty(Context.REFERRAL, referral); + props.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); + + props.setProperty(Context.PROVIDER_URL, providerUrl); + + if (domain.indexOf(".") > -1) { + activeDirectoryDomain = domain.substring(0, domain.indexOf(".")); + }else { + activeDirectoryDomain = domain; + } + + _logger.info("PROVIDER_DOMAIN : {} for {}" ,activeDirectoryDomain, domain); + String activeDirectoryPrincipal = activeDirectoryDomain + "\\" + principal; + _logger.debug("Active Directory SECURITY_PRINCIPAL : {}" , activeDirectoryPrincipal); + props.setProperty(Context.SECURITY_PRINCIPAL, activeDirectoryPrincipal); + props.setProperty(Context.SECURITY_CREDENTIALS, credentials); + + if (ssl && providerUrl.toLowerCase().startsWith("ldaps")) { + _logger.info("ldaps security protocol."); + System.setProperty("javax.net.ssl.trustStore", trustStore); + System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); + props.put(Context.SECURITY_PROTOCOL, "ssl"); + } + props.put(Context.REFERRAL, "follow"); + } } public String getDomain() { diff --git a/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/activedirectory/constants/ActiveDirectoryUser.java b/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/activedirectory/constants/ActiveDirectoryUser.java index c116b64a8..11843a95c 100644 --- a/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/activedirectory/constants/ActiveDirectoryUser.java +++ b/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/activedirectory/constants/ActiveDirectoryUser.java @@ -30,179 +30,179 @@ import java.util.List; */ public class ActiveDirectoryUser { - public static final List OBJECTCLASS = new ArrayList<>(Arrays.asList("top", "person", "organizationalPerson", "user")); - - public static final String objectClass = "user"; + public static final List OBJECTCLASS = new ArrayList<>(Arrays.asList("top", "person", "organizationalPerson", "user")); + + public static final String objectClass = "user"; /* - *常规 - * 名 First Name givenName - * 姓 Last Name/SurName sn - * 英文缩写 Initials initials - * 描述 Description description - * 办公室 Office physicalDeliveryOfficeName - * 电话号码 Telephone Number telephoneNumber - * 电话号码 Telephone: Other otherTelephone - * 电子邮件 E-Mail mail - * 网页 Web Page wwwHomePage - * Web Page: Other url - * - * 家庭电话 Home telephoneNumber - * Home: Other otherTelephone - * 寻呼机 Pager pager - * Pager: Other pagerOther - * 移动电话 Mobile mobile - * Mobile: Other otherMobile - * 传真 Fax facsimileTelephoneNumber - * Fax: Other otherFacsimileTelephoneNumber - * IP电话 IP phone ipPhone - * IP phone: Other otherIpPhone - * 注释 Notes info - *帐号 - * 用户登录名 UserLogon Name userPrincipalName - * 用户登录名(以前版本)User logon name (pre-Windows 2000) sAMAccountname - * 登录时间 Logon Hours logonHours - * 登录到 Log On To logonWorkstation - * 用户帐户控制 Account is locked out userAccountControl (启用:512,禁用:514, 密码永不过期:66048) - * Other Account Options userAccountControl - * User must change password at next logon pwdLastSet - * User cannot change password N/A - * 帐户过期 Account Expires accountExpires - * - *地址 - * 街道 Street streetAddress - * 邮政信箱 P.O.Box postOfficeBox - * 邮政编码 Zip/Postal Code postalCode - * 市/县 City l - * 省/自治区 State/Province st - * 国家/地区 Country/Region c,co, and countryCode - * - *单位 - * 职务 Title title - * 部门 Department department - * 公司 Company company - * 经理 Manager:Name manager - * 直接汇报人 Direct Reports directReports - * + *常规 + * 名 First Name givenName + * 姓 Last Name/SurName sn + * 英文缩写 Initials initials + * 描述 Description description + * 办公室 Office physicalDeliveryOfficeName + * 电话号码 Telephone Number telephoneNumber + * 电话号码 Telephone: Other otherTelephone + * 电子邮件 E-Mail mail + * 网页 Web Page wwwHomePage + * Web Page: Other url + * + * 家庭电话 Home telephoneNumber + * Home: Other otherTelephone + * 寻呼机 Pager pager + * Pager: Other pagerOther + * 移动电话 Mobile mobile + * Mobile: Other otherMobile + * 传真 Fax facsimileTelephoneNumber + * Fax: Other otherFacsimileTelephoneNumber + * IP电话 IP phone ipPhone + * IP phone: Other otherIpPhone + * 注释 Notes info + *帐号 + * 用户登录名 UserLogon Name userPrincipalName + * 用户登录名(以前版本)User logon name (pre-Windows 2000) sAMAccountname + * 登录时间 Logon Hours logonHours + * 登录到 Log On To logonWorkstation + * 用户帐户控制 Account is locked out userAccountControl (启用:512,禁用:514, 密码永不过期:66048) + * Other Account Options userAccountControl + * User must change password at next logon pwdLastSet + * User cannot change password N/A + * 帐户过期 Account Expires accountExpires + * + *地址 + * 街道 Street streetAddress + * 邮政信箱 P.O.Box postOfficeBox + * 邮政编码 Zip/Postal Code postalCode + * 市/县 City l + * 省/自治区 State/Province st + * 国家/地区 Country/Region c,co, and countryCode + * + *单位 + * 职务 Title title + * 部门 Department department + * 公司 Company company + * 经理 Manager:Name manager + * 直接汇报人 Direct Reports directReports + * *成员 - * 成员组 Member of memberOf - * 主要组 Set Primary Group primaryGroupID - */ + * 成员组 Member of memberOf + * 主要组 Set Primary Group primaryGroupID + */ - public static final String CN = "cn"; - public static final String NAME = "name"; - public static final String UID = "uid"; - - /** - * First Name - */ - public static final String GIVENNAME = "givenName"; - /** - * Last Name/SurName - */ - public static final String SN = "sn"; - public static final String INITIALS = "initials"; - public static final String DESCRIPTION = "description"; - public static final String PHYSICALDELIVERYOFFICENAME = "physicalDeliveryOfficeName"; - public static final String MAIL = "mail"; - public static final String WWWHOMEPAGE = "wwwHomePage"; - public static final String DISPLAYNAME = "displayName"; - - public static final String TELEPHONENUMBER = "telephoneNumber"; - public static final String OTHERTELEPHONE = "otherTelephone"; - public static final String PAGER = "pager"; - public static final String PAGEROTHER = "pagerOther"; - public static final String MOBILE = "mobile"; - public static final String OTHERMOBILE = "otherMobile"; - public static final String FACSIMILETELEPHONENUMBER = "facsimileTelephoneNumber"; - public static final String OTHERFACSIMILETELEPHONENUMBER = "otherFacsimileTelephoneNumber"; - public static final String IPPHONE = "ipPhone"; - public static final String OTHERIPPHONE = "otherIpPhone"; - public static final String INFO = "info"; - public static final String HOMEPHONE = "homePhone"; - - /** - * admin@maxkey.top - */ - public static final String USERPRINCIPALNAME = "userPrincipalName"; - /** - * maxkey\admin - */ - public static final String SAMACCOUNTNAME = "sAMAccountname"; - public static final String LOGONHOURS = "logonHours"; - public static final String LOGONWORKSTATION = "logonWorkstation"; - public static final String USERACCOUNTCONTROL = "userAccountControl"; - public static final String PWDLASTSET = "pwdLastSet"; - public static final String ACCOUNTEXPIRES = "accountExpires"; - - public static final String CO = "co"; - public static final String C = "c"; - public static final String COUNTRYCODE = "countryCode"; - public static final String ST = "st"; - public static final String L = "l"; - public static final String STREETADDRESS = "streetAddress"; - public static final String POSTOFFICEBOX = "postOfficeBox"; - public static final String POSTALCODE = "postalCode"; - - public static final String TITLE = "title"; - public static final String COMPANY = "company"; - public static final String DEPARTMENT = "department"; - public static final String EMPLOYEENUMBER = "employeeNumber"; - public static final String OU = "ou"; - public static final String DEPARTMENTNUMBER = "departmentNumber"; - - public static final String MANAGER = "manager"; - public static final String DIRECTREPORTS = "directReports"; - - public static final String MEMBER = "member"; - public static final String MEMBEROF = "memberOf"; - public static final String PRIMARYGROUPID = "primaryGroupID"; - - public static final String UNICODEPWD = "unicodePwd"; - public static final String DISTINGUISHEDNAME = "distinguishedname"; - - //MaxKey EXTEND - /** - * EXTEND managerName - */ - public static final String MANAGERNAME = "managerName"; - /** - * EXTEND username - */ - public static final String USERNAME = "username"; - /** - * EXTEND userType - */ - public static final String USERTYPE = "userType"; - /** - * EXTEND gender - */ - public static final String GENDER = "gender"; - /** - * EXTEND status - */ - public static final String USERSTATUS = "status"; + public static final String CN = "cn"; + public static final String NAME = "name"; + public static final String UID = "uid"; + /** - * EXTEND firstName - */ - public static final String FIRSTNAME = "firstName"; + * First Name + */ + public static final String GIVENNAME = "givenName"; /** - * EXTEND lastName - */ - public static final String LASTNAME = "lastName"; + * Last Name/SurName + */ + public static final String SN = "sn"; + public static final String INITIALS = "initials"; + public static final String DESCRIPTION = "description"; + public static final String PHYSICALDELIVERYOFFICENAME = "physicalDeliveryOfficeName"; + public static final String MAIL = "mail"; + public static final String WWWHOMEPAGE = "wwwHomePage"; + public static final String DISPLAYNAME = "displayName"; + + public static final String TELEPHONENUMBER = "telephoneNumber"; + public static final String OTHERTELEPHONE = "otherTelephone"; + public static final String PAGER = "pager"; + public static final String PAGEROTHER = "pagerOther"; + public static final String MOBILE = "mobile"; + public static final String OTHERMOBILE = "otherMobile"; + public static final String FACSIMILETELEPHONENUMBER = "facsimileTelephoneNumber"; + public static final String OTHERFACSIMILETELEPHONENUMBER = "otherFacsimileTelephoneNumber"; + public static final String IPPHONE = "ipPhone"; + public static final String OTHERIPPHONE = "otherIpPhone"; + public static final String INFO = "info"; + public static final String HOMEPHONE = "homePhone"; + /** - * EXTEND email - */ - public static final String EMAIL = "email"; - - /** - * encodePassword for ActiveDirectory - * @param password - * @return - * @throws UnsupportedEncodingException - */ - public static byte[] encodePassword(String password) throws UnsupportedEncodingException { - return ("\"" + password + "\"").getBytes("UTF-16LE"); - } - - + * admin@maxkey.top + */ + public static final String USERPRINCIPALNAME = "userPrincipalName"; + /** + * maxkey\admin + */ + public static final String SAMACCOUNTNAME = "sAMAccountname"; + public static final String LOGONHOURS = "logonHours"; + public static final String LOGONWORKSTATION = "logonWorkstation"; + public static final String USERACCOUNTCONTROL = "userAccountControl"; + public static final String PWDLASTSET = "pwdLastSet"; + public static final String ACCOUNTEXPIRES = "accountExpires"; + + public static final String CO = "co"; + public static final String C = "c"; + public static final String COUNTRYCODE = "countryCode"; + public static final String ST = "st"; + public static final String L = "l"; + public static final String STREETADDRESS = "streetAddress"; + public static final String POSTOFFICEBOX = "postOfficeBox"; + public static final String POSTALCODE = "postalCode"; + + public static final String TITLE = "title"; + public static final String COMPANY = "company"; + public static final String DEPARTMENT = "department"; + public static final String EMPLOYEENUMBER = "employeeNumber"; + public static final String OU = "ou"; + public static final String DEPARTMENTNUMBER = "departmentNumber"; + + public static final String MANAGER = "manager"; + public static final String DIRECTREPORTS = "directReports"; + + public static final String MEMBER = "member"; + public static final String MEMBEROF = "memberOf"; + public static final String PRIMARYGROUPID = "primaryGroupID"; + + public static final String UNICODEPWD = "unicodePwd"; + public static final String DISTINGUISHEDNAME = "distinguishedname"; + + //MaxKey EXTEND + /** + * EXTEND managerName + */ + public static final String MANAGERNAME = "managerName"; + /** + * EXTEND username + */ + public static final String USERNAME = "username"; + /** + * EXTEND userType + */ + public static final String USERTYPE = "userType"; + /** + * EXTEND gender + */ + public static final String GENDER = "gender"; + /** + * EXTEND status + */ + public static final String USERSTATUS = "status"; + /** + * EXTEND firstName + */ + public static final String FIRSTNAME = "firstName"; + /** + * EXTEND lastName + */ + public static final String LASTNAME = "lastName"; + /** + * EXTEND email + */ + public static final String EMAIL = "email"; + + /** + * encodePassword for ActiveDirectory + * @param password + * @return + * @throws UnsupportedEncodingException + */ + public static byte[] encodePassword(String password) throws UnsupportedEncodingException { + return ("\"" + password + "\"").getBytes("UTF-16LE"); + } + + } diff --git a/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/activedirectory/constants/ActiveDirectoryUserAccountControl.java b/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/activedirectory/constants/ActiveDirectoryUserAccountControl.java index 954d8df1c..ec327f1cf 100644 --- a/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/activedirectory/constants/ActiveDirectoryUserAccountControl.java +++ b/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/activedirectory/constants/ActiveDirectoryUserAccountControl.java @@ -22,29 +22,29 @@ package org.dromara.maxkey.ldap.activedirectory.constants; * https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity/useraccountcontrol-manipulate-account-properties */ public class ActiveDirectoryUserAccountControl { - - //Property flag Value in hexadecimal Value in decimal - public static final int SCRIPT =0x0001 ;// 1 - public static final int ACCOUNTDISABLE =0x0002 ;// 2 - public static final int HOMEDIR_REQUIRED =0x0008 ;// 8 - public static final int LOCKOUT =0x0010 ;// 16 - public static final int PASSWD_NOTREQD =0x0020 ;// 32 - public static final int PASSWD_CANT_CHANGE =0x0040 ;// 64 You can't assign this permission by directly modifying the UserAccountControl attribute. For information about how to set the permission programmatically, see the Property flag descriptions section. - public static final int ENCRYPTED_TEXT_PWD_ALLOWED =0x0080 ;// 128 - public static final int TEMP_DUPLICATE_ACCOUNT =0x0100 ;// 256 - public static final int NORMAL_ACCOUNT =0x0200 ;// 512 - public static final int INTERDOMAIN_TRUST_ACCOUNT =0x0800 ;// 2048 - public static final int WORKSTATION_TRUST_ACCOUNT =0x1000 ;// 4096 - public static final int SERVER_TRUST_ACCOUNT =0x2000 ;// 8192 - public static final int DONT_EXPIRE_PASSWORD =0x10000 ;// 65536 - public static final int MNS_LOGON_ACCOUNT =0x20000 ;// 131072 - public static final int SMARTCARD_REQUIRED =0x40000 ;// 262144 - public static final int TRUSTED_FOR_DELEGATION =0x80000 ;// 524288 - public static final int NOT_DELEGATED =0x100000 ;// 1048576 - public static final int USE_DES_KEY_ONLY =0x200000 ;// 2097152 - public static final int DONT_REQ_PREAUTH =0x400000 ;// 4194304 - public static final int PASSWORD_EXPIRED =0x800000 ;// 8388608 - public static final int TRUSTED_TO_AUTH_FOR_DELEGATION =0x1000000 ;// 16777216 - public static final int PARTIAL_SECRETS_ACCOUNT =0x04000000 ;// 67108864 - + + //Property flag Value in hexadecimal Value in decimal + public static final int SCRIPT =0x0001 ;// 1 + public static final int ACCOUNTDISABLE =0x0002 ;// 2 + public static final int HOMEDIR_REQUIRED =0x0008 ;// 8 + public static final int LOCKOUT =0x0010 ;// 16 + public static final int PASSWD_NOTREQD =0x0020 ;// 32 + public static final int PASSWD_CANT_CHANGE =0x0040 ;// 64 You can't assign this permission by directly modifying the UserAccountControl attribute. For information about how to set the permission programmatically, see the Property flag descriptions section. + public static final int ENCRYPTED_TEXT_PWD_ALLOWED =0x0080 ;// 128 + public static final int TEMP_DUPLICATE_ACCOUNT =0x0100 ;// 256 + public static final int NORMAL_ACCOUNT =0x0200 ;// 512 + public static final int INTERDOMAIN_TRUST_ACCOUNT =0x0800 ;// 2048 + public static final int WORKSTATION_TRUST_ACCOUNT =0x1000 ;// 4096 + public static final int SERVER_TRUST_ACCOUNT =0x2000 ;// 8192 + public static final int DONT_EXPIRE_PASSWORD =0x10000 ;// 65536 + public static final int MNS_LOGON_ACCOUNT =0x20000 ;// 131072 + public static final int SMARTCARD_REQUIRED =0x40000 ;// 262144 + public static final int TRUSTED_FOR_DELEGATION =0x80000 ;// 524288 + public static final int NOT_DELEGATED =0x100000 ;// 1048576 + public static final int USE_DES_KEY_ONLY =0x200000 ;// 2097152 + public static final int DONT_REQ_PREAUTH =0x400000 ;// 4194304 + public static final int PASSWORD_EXPIRED =0x800000 ;// 8388608 + public static final int TRUSTED_TO_AUTH_FOR_DELEGATION =0x1000000 ;// 16777216 + public static final int PARTIAL_SECRETS_ACCOUNT =0x04000000 ;// 67108864 + } diff --git a/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/GroupOfNames.java b/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/GroupOfNames.java index faf1e3436..ee22e5180 100644 --- a/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/GroupOfNames.java +++ b/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/GroupOfNames.java @@ -28,16 +28,16 @@ import java.util.List; * */ public class GroupOfNames { - public static final List OBJECTCLASS = new ArrayList<>(Arrays.asList("top", "groupOfNames")); - - public static final String objectClass = "groupOfNames"; - public static final String DISTINGUISHEDNAME = "distinguishedname"; - public static final String CN = "cn"; - public static final String MEMBER = "member"; - public static final String BUSINESSCATEGORY = "businessCategory"; - public static final String SEEALSO = "seeAlso"; - public static final String OWNER = "owner"; - public static final String OU = "ou"; - public static final String O = "o"; - public static final String DESCRIPTION = "description"; + public static final List OBJECTCLASS = new ArrayList<>(Arrays.asList("top", "groupOfNames")); + + public static final String objectClass = "groupOfNames"; + public static final String DISTINGUISHEDNAME = "distinguishedname"; + public static final String CN = "cn"; + public static final String MEMBER = "member"; + public static final String BUSINESSCATEGORY = "businessCategory"; + public static final String SEEALSO = "seeAlso"; + public static final String OWNER = "owner"; + public static final String OU = "ou"; + public static final String O = "o"; + public static final String DESCRIPTION = "description"; } diff --git a/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/GroupOfUniqueNames.java b/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/GroupOfUniqueNames.java index 00a20cf18..7d60a845e 100644 --- a/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/GroupOfUniqueNames.java +++ b/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/GroupOfUniqueNames.java @@ -28,16 +28,16 @@ import java.util.List; * */ public class GroupOfUniqueNames { - public static List OBJECTCLASS = new ArrayList<>(Arrays.asList("top", "groupOfUniqueNames")); - - public static final String objectClass = "groupOfUniqueNames"; - public static final String DISTINGUISHEDNAME = "distinguishedname"; - public static final String CN = "cn"; - public static final String UNIQUEMEMBER = "uniqueMember"; - public static final String BUSINESSCATEGORY = "businessCategory"; - public static final String SEEALSO = "seeAlso"; - public static final String OWNER = "owner"; - public static final String OU = "ou"; - public static final String O = "o"; - public static final String DESCRIPTION = "description"; + public static List OBJECTCLASS = new ArrayList<>(Arrays.asList("top", "groupOfUniqueNames")); + + public static final String objectClass = "groupOfUniqueNames"; + public static final String DISTINGUISHEDNAME = "distinguishedname"; + public static final String CN = "cn"; + public static final String UNIQUEMEMBER = "uniqueMember"; + public static final String BUSINESSCATEGORY = "businessCategory"; + public static final String SEEALSO = "seeAlso"; + public static final String OWNER = "owner"; + public static final String OU = "ou"; + public static final String O = "o"; + public static final String DESCRIPTION = "description"; } diff --git a/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/InetOrgPerson.java b/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/InetOrgPerson.java index 0dd05ac89..b71181705 100644 --- a/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/InetOrgPerson.java +++ b/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/InetOrgPerson.java @@ -28,126 +28,126 @@ import java.util.List; * */ public class InetOrgPerson { - public static final List OBJECTCLASS = new ArrayList<>(Arrays.asList("top", "person","organizationalPerson","inetOrgPerson")); - - public static final String objectClass = "inetOrgPerson"; - public static final String DISTINGUISHEDNAME = "distinguishedname"; - //person sup top - /**person sn MUST*/ - public static final String SN = "sn"; - /**person cn MUST*/ - public static final String CN = "cn"; - /**person userPassword*/ - public static final String USERPASSWORD = "userPassword"; - /**person userPassword*/ - public static final String TELEPHONENUMBER = "telephoneNumber"; - /**person seeAlso*/ - public static final String SEEALSO = "seeAlso"; - /**person description*/ - public static final String DESCRIPTION = "description"; - - //organizationalPerson sup person - /**organizationalPerson title*/ - public static final String TITLE = "title"; - /**organizationalPerson x121Address*/ - public static final String X121ADDRESS = "x121Address"; - /**organizationalPerson registeredAddress*/ - public static final String REGISTEREDADDRESS = "registeredAddress"; - /**organizationalPerson destinationIndicator*/ - public static final String DESTINATIONINDICATOR = "destinationIndicator"; - /**organizationalPerson preferredDeliveryMethod*/ - public static final String PREFERREDDELIVERYMETHOD = "preferredDeliveryMethod"; - /**organizationalPerson telexNumber*/ - public static final String TELEXNUMBER = "telexNumber"; - /**organizationalPerson teletexTerminalIdentifier*/ - public static final String TELETEXTERMINALIDENTIFIER = "teletexTerminalIdentifier"; - /**organizationalPerson internationaliSDNNumber*/ - public static final String INTERNATIONALISDNNUMBER = "internationaliSDNNumber"; - /**organizationalPerson facsimileTelephoneNumber*/ - public static final String FACSIMILETELEPHONENUMBER = "facsimileTelephoneNumber"; - /**organizationalPerson street*/ - public static final String STREET = "street"; - /**organizationalPerson postOfficeBox*/ - public static final String POSTOFFICEBOX = "postOfficeBox"; - /**organizationalPerson postalCode*/ - public static final String POSTALCODE = "postalCode"; - /**organizationalPerson postalAddress*/ - public static final String POSTALADDRESS = "postalAddress"; - /**organizationalPerson physicalDeliveryOfficeName*/ - public static final String PHYSICALDELIVERYOFFICENAME = "physicalDeliveryOfficeName"; - /**organizationalPerson ou*/ - public static final String OU = "ou"; - /**organizationalPerson st*/ - public static final String ST = "st"; - /**organizationalPerson l*/ - public static final String L = "l"; - - //inetOrgPerson sup organizationalPerson - /**inetOrgPerson carLicense*/ - public static final String CARLICENSE = "carLicense"; - /**inetOrgPerson departmentNumber*/ - public static final String DEPARTMENTNUMBER = "departmentNumber"; - /**inetOrgPerson displayName*/ - public static final String DISPLAYNAME = "displayName"; - /**inetOrgPerson employeeNumber*/ - public static final String EMPLOYEENUMBER = "employeeNumber"; - /**inetOrgPerson employeeType*/ - public static final String EMPLOYEETYPE = "employeeType"; - /**inetOrgPerson jpegPhoto*/ - public static final String JPEGPHOTO = "jpegPhoto"; - /**inetOrgPerson preferredLanguage*/ - public static final String PREFERREDLANGUAGE = "preferredLanguage"; - /**inetOrgPerson userSMIMECertificate*/ - public static final String USERSMIMECERTIFICATE = "userSMIMECertificate"; - /**inetOrgPerson userPKCS12*/ - public static final String USERPKCS12 = "userPKCS12"; - /**inetOrgPerson audio*/ - public static final String AUDIO = "audio"; - /**inetOrgPerson businessCategory*/ - public static final String BUSINESSCATEGORY = "businessCategory"; - /**inetOrgPerson givenName*/ - public static final String GIVENNAME = "givenName"; - /**inetOrgPerson homePhone*/ - public static final String HOMEPHONE = "homePhone"; - /**inetOrgPerson homePostalAddress*/ - public static final String HOMEPOSTALADDRESS = "homePostalAddress"; - /**inetOrgPerson initials*/ - public static final String INITIALS = "initials"; - /**inetOrgPerson photo*/ - public static final String PHOTO = "photo"; - /**inetOrgPerson roomNumber*/ - public static final String ROOMNUMBER = "roomNumber"; - /**inetOrgPerson secretary*/ - public static final String SECRETARY = "secretary"; - /**inetOrgPerson uid*/ - public static final String UID = "uid"; - /**inetOrgPerson userCertificate*/ - public static final String USERCERTIFICATE = "userCertificate"; - /**inetOrgPerson x500uniqueIdentifier*/ - public static final String X500UNIQUEIDENTIFIER = "x500uniqueIdentifier"; - - public static final String MAIL = "mail"; - - public static final String MOBILE = "mobile"; - - public static final String MANAGER = "manager"; - - //MaxKey EXTEND - /** - * EXTEND department - */ - public static final String DEPARTMENT = "department"; + public static final List OBJECTCLASS = new ArrayList<>(Arrays.asList("top", "person","organizationalPerson","inetOrgPerson")); + + public static final String objectClass = "inetOrgPerson"; + public static final String DISTINGUISHEDNAME = "distinguishedname"; + //person sup top + /**person sn MUST*/ + public static final String SN = "sn"; + /**person cn MUST*/ + public static final String CN = "cn"; + /**person userPassword*/ + public static final String USERPASSWORD = "userPassword"; + /**person userPassword*/ + public static final String TELEPHONENUMBER = "telephoneNumber"; + /**person seeAlso*/ + public static final String SEEALSO = "seeAlso"; + /**person description*/ + public static final String DESCRIPTION = "description"; + + //organizationalPerson sup person + /**organizationalPerson title*/ + public static final String TITLE = "title"; + /**organizationalPerson x121Address*/ + public static final String X121ADDRESS = "x121Address"; + /**organizationalPerson registeredAddress*/ + public static final String REGISTEREDADDRESS = "registeredAddress"; + /**organizationalPerson destinationIndicator*/ + public static final String DESTINATIONINDICATOR = "destinationIndicator"; + /**organizationalPerson preferredDeliveryMethod*/ + public static final String PREFERREDDELIVERYMETHOD = "preferredDeliveryMethod"; + /**organizationalPerson telexNumber*/ + public static final String TELEXNUMBER = "telexNumber"; + /**organizationalPerson teletexTerminalIdentifier*/ + public static final String TELETEXTERMINALIDENTIFIER = "teletexTerminalIdentifier"; + /**organizationalPerson internationaliSDNNumber*/ + public static final String INTERNATIONALISDNNUMBER = "internationaliSDNNumber"; + /**organizationalPerson facsimileTelephoneNumber*/ + public static final String FACSIMILETELEPHONENUMBER = "facsimileTelephoneNumber"; + /**organizationalPerson street*/ + public static final String STREET = "street"; + /**organizationalPerson postOfficeBox*/ + public static final String POSTOFFICEBOX = "postOfficeBox"; + /**organizationalPerson postalCode*/ + public static final String POSTALCODE = "postalCode"; + /**organizationalPerson postalAddress*/ + public static final String POSTALADDRESS = "postalAddress"; + /**organizationalPerson physicalDeliveryOfficeName*/ + public static final String PHYSICALDELIVERYOFFICENAME = "physicalDeliveryOfficeName"; + /**organizationalPerson ou*/ + public static final String OU = "ou"; + /**organizationalPerson st*/ + public static final String ST = "st"; + /**organizationalPerson l*/ + public static final String L = "l"; + + //inetOrgPerson sup organizationalPerson + /**inetOrgPerson carLicense*/ + public static final String CARLICENSE = "carLicense"; + /**inetOrgPerson departmentNumber*/ + public static final String DEPARTMENTNUMBER = "departmentNumber"; + /**inetOrgPerson displayName*/ + public static final String DISPLAYNAME = "displayName"; + /**inetOrgPerson employeeNumber*/ + public static final String EMPLOYEENUMBER = "employeeNumber"; + /**inetOrgPerson employeeType*/ + public static final String EMPLOYEETYPE = "employeeType"; + /**inetOrgPerson jpegPhoto*/ + public static final String JPEGPHOTO = "jpegPhoto"; + /**inetOrgPerson preferredLanguage*/ + public static final String PREFERREDLANGUAGE = "preferredLanguage"; + /**inetOrgPerson userSMIMECertificate*/ + public static final String USERSMIMECERTIFICATE = "userSMIMECertificate"; + /**inetOrgPerson userPKCS12*/ + public static final String USERPKCS12 = "userPKCS12"; + /**inetOrgPerson audio*/ + public static final String AUDIO = "audio"; + /**inetOrgPerson businessCategory*/ + public static final String BUSINESSCATEGORY = "businessCategory"; + /**inetOrgPerson givenName*/ + public static final String GIVENNAME = "givenName"; + /**inetOrgPerson homePhone*/ + public static final String HOMEPHONE = "homePhone"; + /**inetOrgPerson homePostalAddress*/ + public static final String HOMEPOSTALADDRESS = "homePostalAddress"; + /**inetOrgPerson initials*/ + public static final String INITIALS = "initials"; + /**inetOrgPerson photo*/ + public static final String PHOTO = "photo"; + /**inetOrgPerson roomNumber*/ + public static final String ROOMNUMBER = "roomNumber"; + /**inetOrgPerson secretary*/ + public static final String SECRETARY = "secretary"; + /**inetOrgPerson uid*/ + public static final String UID = "uid"; + /**inetOrgPerson userCertificate*/ + public static final String USERCERTIFICATE = "userCertificate"; + /**inetOrgPerson x500uniqueIdentifier*/ + public static final String X500UNIQUEIDENTIFIER = "x500uniqueIdentifier"; + + public static final String MAIL = "mail"; + + public static final String MOBILE = "mobile"; + + public static final String MANAGER = "manager"; + + //MaxKey EXTEND /** - * EXTEND firstName - */ - public static final String FIRSTNAME = "firstName"; + * EXTEND department + */ + public static final String DEPARTMENT = "department"; /** - * EXTEND lastName - */ - public static final String LASTNAME = "lastName"; + * EXTEND firstName + */ + public static final String FIRSTNAME = "firstName"; /** - * EXTEND email - */ - public static final String EMAIL = "email"; + * EXTEND lastName + */ + public static final String LASTNAME = "lastName"; + /** + * EXTEND email + */ + public static final String EMAIL = "email"; } diff --git a/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/Organization.java b/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/Organization.java index 5e75ea0c2..09dd82bb9 100644 --- a/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/Organization.java +++ b/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/Organization.java @@ -28,57 +28,57 @@ import java.util.List; * */ public class Organization { - public static List OBJECTCLASS = new ArrayList<>(Arrays.asList("top", "organization")); - - public static final String objectClass = "organization"; - public static final String DISTINGUISHEDNAME = "distinguishedname"; - - /**Organization o*/ - public static final String O = "o"; - /**Organization userPassword*/ - public static final String USERPASSWORD = "userPassword"; - /**Organization searchGuide*/ - public static final String SEARCHGUIDE = "searchGuide"; - /**Organization seeAlso*/ - public static final String SEEALSO = "seeAlso"; - /**Organization description*/ - public static final String DESCRIPTION = "description"; - /**Organization businessCategory*/ - public static final String BUSINESSCATEGORY = "businessCategory"; - /**Organization x121Address*/ - public static final String X121ADDRESS = "x121Address"; - /**Organization registeredAddress*/ - public static final String REGISTEREDADDRESS = "registeredAddress"; - /**Organization destinationIndicator*/ - public static final String DESTINATIONINDICATOR = "destinationIndicator"; - /**Organization preferredDeliveryMethod*/ - public static final String PREFERREDDELIVERYMETHOD = "preferredDeliveryMethod"; - /**Organization telexNumber*/ - public static final String TELEXNUMBER = "telexNumber"; - /**Organization teletexTerminalIdentifier*/ - public static final String TELETEXTERMINALIDENTIFIER = "teletexTerminalIdentifier"; - /**Organization telephoneNumber*/ - public static final String TELEPHONENUMBER = "telephoneNumber"; - /**Organization internationaliSDNNumber*/ - public static final String INTERNATIONALISDNNUMBER = "internationaliSDNNumber"; - /**Organization facsimileTelephoneNumber*/ - public static final String FACSIMILETELEPHONENUMBER = "facsimileTelephoneNumber"; - /**Organization street*/ - public static final String STREET = "street"; - /**Organization postOfficeBox*/ - public static final String POSTOFFICEBOX = "postOfficeBox"; - /**Organization postalCode*/ - public static final String POSTALCODE = "postalCode"; - /**Organization postalAddress*/ - public static final String POSTALADDRESS = "postalAddress"; - /**Organization physicalDeliveryOfficeName*/ - public static final String PHYSICALDELIVERYOFFICENAME = "physicalDeliveryOfficeName"; - /**Organization st*/ - public static final String ST = "st"; - /**Organization l*/ - public static final String L = "l"; - - //for id - public static final String CN = "cn"; - + public static List OBJECTCLASS = new ArrayList<>(Arrays.asList("top", "organization")); + + public static final String objectClass = "organization"; + public static final String DISTINGUISHEDNAME = "distinguishedname"; + + /**Organization o*/ + public static final String O = "o"; + /**Organization userPassword*/ + public static final String USERPASSWORD = "userPassword"; + /**Organization searchGuide*/ + public static final String SEARCHGUIDE = "searchGuide"; + /**Organization seeAlso*/ + public static final String SEEALSO = "seeAlso"; + /**Organization description*/ + public static final String DESCRIPTION = "description"; + /**Organization businessCategory*/ + public static final String BUSINESSCATEGORY = "businessCategory"; + /**Organization x121Address*/ + public static final String X121ADDRESS = "x121Address"; + /**Organization registeredAddress*/ + public static final String REGISTEREDADDRESS = "registeredAddress"; + /**Organization destinationIndicator*/ + public static final String DESTINATIONINDICATOR = "destinationIndicator"; + /**Organization preferredDeliveryMethod*/ + public static final String PREFERREDDELIVERYMETHOD = "preferredDeliveryMethod"; + /**Organization telexNumber*/ + public static final String TELEXNUMBER = "telexNumber"; + /**Organization teletexTerminalIdentifier*/ + public static final String TELETEXTERMINALIDENTIFIER = "teletexTerminalIdentifier"; + /**Organization telephoneNumber*/ + public static final String TELEPHONENUMBER = "telephoneNumber"; + /**Organization internationaliSDNNumber*/ + public static final String INTERNATIONALISDNNUMBER = "internationaliSDNNumber"; + /**Organization facsimileTelephoneNumber*/ + public static final String FACSIMILETELEPHONENUMBER = "facsimileTelephoneNumber"; + /**Organization street*/ + public static final String STREET = "street"; + /**Organization postOfficeBox*/ + public static final String POSTOFFICEBOX = "postOfficeBox"; + /**Organization postalCode*/ + public static final String POSTALCODE = "postalCode"; + /**Organization postalAddress*/ + public static final String POSTALADDRESS = "postalAddress"; + /**Organization physicalDeliveryOfficeName*/ + public static final String PHYSICALDELIVERYOFFICENAME = "physicalDeliveryOfficeName"; + /**Organization st*/ + public static final String ST = "st"; + /**Organization l*/ + public static final String L = "l"; + + //for id + public static final String CN = "cn"; + } diff --git a/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/OrganizationalUnit.java b/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/OrganizationalUnit.java index 1c64d923b..939bf2b0b 100644 --- a/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/OrganizationalUnit.java +++ b/maxkey-commons/maxkey-ldap/src/main/java/org/dromara/maxkey/ldap/constants/OrganizationalUnit.java @@ -28,60 +28,60 @@ import java.util.List; * */ public class OrganizationalUnit { - public static final List OBJECTCLASS = new ArrayList<>(Arrays.asList("top", "OrganizationalUnit")); - public static final String objectClass = "OrganizationalUnit"; - public static final String DISTINGUISHEDNAME = "distinguishedname"; - /**OrganizationalUnit ou*/ - public static final String OU = "ou"; - /**OrganizationalUnit userPassword*/ - public static final String USERPASSWORD = "userPassword"; - /**OrganizationalUnit searchGuide*/ - public static final String SEARCHGUIDE = "searchGuide"; - /**OrganizationalUnit seeAlso*/ - public static final String SEEALSO = "seeAlso"; - /**OrganizationalUnit description*/ - public static final String DESCRIPTION = "description"; - /**OrganizationalUnit businessCategory*/ - public static final String BUSINESSCATEGORY = "businessCategory"; - /**OrganizationalUnit x121Address*/ - public static final String X121ADDRESS = "x121Address"; - /**OrganizationalUnit registeredAddress*/ - public static final String REGISTEREDADDRESS = "registeredAddress"; - /**OrganizationalUnit destinationIndicator*/ - public static final String DESTINATIONINDICATOR = "destinationIndicator"; - /**OrganizationalUnit preferredDeliveryMethod*/ - public static final String PREFERREDDELIVERYMETHOD = "preferredDeliveryMethod"; - /**OrganizationalUnit telexNumber*/ - public static final String TELEXNUMBER = "telexNumber"; - /**OrganizationalUnit teletexTerminalIdentifier*/ - public static final String TELETEXTERMINALIDENTIFIER = "teletexTerminalIdentifier"; - /**OrganizationalUnit telephoneNumber*/ - public static final String TELEPHONENUMBER = "telephoneNumber"; - /**OrganizationalUnit internationaliSDNNumber*/ - public static final String INTERNATIONALISDNNUMBER = "internationaliSDNNumber"; - /**OrganizationalUnit facsimileTelephoneNumber*/ - public static final String FACSIMILETELEPHONENUMBER = "facsimileTelephoneNumber"; - /**OrganizationalUnit street*/ - public static final String STREET = "street"; - /**OrganizationalUnit postOfficeBox*/ - public static final String POSTOFFICEBOX = "postOfficeBox"; - /**OrganizationalUnit postalCode*/ - public static final String POSTALCODE = "postalCode"; - /**OrganizationalUnit postalAddress*/ - public static final String POSTALADDRESS = "postalAddress"; - /**OrganizationalUnit physicalDeliveryOfficeName*/ - public static final String PHYSICALDELIVERYOFFICENAME = "physicalDeliveryOfficeName"; - /**OrganizationalUnit st*/ - public static final String ST = "st";//省/州 - /**OrganizationalUnit l*/ - public static final String L = "l";//县市 + public static final List OBJECTCLASS = new ArrayList<>(Arrays.asList("top", "OrganizationalUnit")); + public static final String objectClass = "OrganizationalUnit"; + public static final String DISTINGUISHEDNAME = "distinguishedname"; + /**OrganizationalUnit ou*/ + public static final String OU = "ou"; + /**OrganizationalUnit userPassword*/ + public static final String USERPASSWORD = "userPassword"; + /**OrganizationalUnit searchGuide*/ + public static final String SEARCHGUIDE = "searchGuide"; + /**OrganizationalUnit seeAlso*/ + public static final String SEEALSO = "seeAlso"; + /**OrganizationalUnit description*/ + public static final String DESCRIPTION = "description"; + /**OrganizationalUnit businessCategory*/ + public static final String BUSINESSCATEGORY = "businessCategory"; + /**OrganizationalUnit x121Address*/ + public static final String X121ADDRESS = "x121Address"; + /**OrganizationalUnit registeredAddress*/ + public static final String REGISTEREDADDRESS = "registeredAddress"; + /**OrganizationalUnit destinationIndicator*/ + public static final String DESTINATIONINDICATOR = "destinationIndicator"; + /**OrganizationalUnit preferredDeliveryMethod*/ + public static final String PREFERREDDELIVERYMETHOD = "preferredDeliveryMethod"; + /**OrganizationalUnit telexNumber*/ + public static final String TELEXNUMBER = "telexNumber"; + /**OrganizationalUnit teletexTerminalIdentifier*/ + public static final String TELETEXTERMINALIDENTIFIER = "teletexTerminalIdentifier"; + /**OrganizationalUnit telephoneNumber*/ + public static final String TELEPHONENUMBER = "telephoneNumber"; + /**OrganizationalUnit internationaliSDNNumber*/ + public static final String INTERNATIONALISDNNUMBER = "internationaliSDNNumber"; + /**OrganizationalUnit facsimileTelephoneNumber*/ + public static final String FACSIMILETELEPHONENUMBER = "facsimileTelephoneNumber"; + /**OrganizationalUnit street*/ + public static final String STREET = "street"; + /**OrganizationalUnit postOfficeBox*/ + public static final String POSTOFFICEBOX = "postOfficeBox"; + /**OrganizationalUnit postalCode*/ + public static final String POSTALCODE = "postalCode"; + /**OrganizationalUnit postalAddress*/ + public static final String POSTALADDRESS = "postalAddress"; + /**OrganizationalUnit physicalDeliveryOfficeName*/ + public static final String PHYSICALDELIVERYOFFICENAME = "physicalDeliveryOfficeName"; + /**OrganizationalUnit st*/ + public static final String ST = "st";//省/州 + /**OrganizationalUnit l*/ + public static final String L = "l";//县市 - public static final String CO = "co"; //中国 - public static final String C = "c"; //CN - public static final String COUNTRYCODE = "countryCode";//156 - public static final String NAME = "name"; - - //for id - public static final String CN = "cn"; - + public static final String CO = "co"; //中国 + public static final String C = "c"; //CN + public static final String COUNTRYCODE = "countryCode";//156 + public static final String NAME = "name"; + + //for id + public static final String CN = "cn"; + } diff --git a/maxkey-commons/maxkey-ldap/src/test/java/org/dromara/maxkey/persistence/ldap/ActiveDirectoryUtilsTest.java b/maxkey-commons/maxkey-ldap/src/test/java/org/dromara/maxkey/persistence/ldap/ActiveDirectoryUtilsTest.java index e47d11fc7..c166ef6b6 100644 --- a/maxkey-commons/maxkey-ldap/src/test/java/org/dromara/maxkey/persistence/ldap/ActiveDirectoryUtilsTest.java +++ b/maxkey-commons/maxkey-ldap/src/test/java/org/dromara/maxkey/persistence/ldap/ActiveDirectoryUtilsTest.java @@ -23,21 +23,21 @@ import javax.naming.directory.DirContext; import org.dromara.maxkey.ldap.activedirectory.ActiveDirectoryUtils; public class ActiveDirectoryUtilsTest { - public static void main(String[] args) throws Exception { - String trustStore="D:/JavaIDE/jdk1.6.0_30/jre/lib/security/cacerts"; - String trustStorePassword="changeit"; - //ActiveDirectoryUtils activeDirectoryUtils=new ActiveDirectoryUtils("ldap://192.168.0.171:389","administrator","p@ssw0rdp@ssw0rd","DC=kygfcrmtest,DC=com","kygfcrmtest"); - ActiveDirectoryUtils activeDirectoryUtils=new ActiveDirectoryUtils("ldaps://msad.connsec.com:636","administrator","1qaz@WSX","DC=CONNSEC,DC=com","CONNSEC"); - //ActiveDirectoryUtils activeDirectoryUtils=new ActiveDirectoryUtils("ldap://msad.connsec.com:389","administrator","1qaz@WSX","DC=CONNSEC,DC=com","CONNSEC"); - activeDirectoryUtils.setTrustStore(trustStore); - activeDirectoryUtils.setTrustStorePassword(trustStorePassword); - activeDirectoryUtils.setSsl(true); - //activeDirectoryUtils.setSsl(false); - DirContext dirContext=activeDirectoryUtils.openConnection(); - try { - dirContext.close(); - } catch (NamingException e) { - e.printStackTrace(); - } - } + public static void main(String[] args) throws Exception { + String trustStore="D:/JavaIDE/jdk1.6.0_30/jre/lib/security/cacerts"; + String trustStorePassword="changeit"; + //ActiveDirectoryUtils activeDirectoryUtils=new ActiveDirectoryUtils("ldap://192.168.0.171:389","administrator","p@ssw0rdp@ssw0rd","DC=kygfcrmtest,DC=com","kygfcrmtest"); + ActiveDirectoryUtils activeDirectoryUtils=new ActiveDirectoryUtils("ldaps://msad.connsec.com:636","administrator","1qaz@WSX","DC=CONNSEC,DC=com","CONNSEC"); + //ActiveDirectoryUtils activeDirectoryUtils=new ActiveDirectoryUtils("ldap://msad.connsec.com:389","administrator","1qaz@WSX","DC=CONNSEC,DC=com","CONNSEC"); + activeDirectoryUtils.setTrustStore(trustStore); + activeDirectoryUtils.setTrustStorePassword(trustStorePassword); + activeDirectoryUtils.setSsl(true); + //activeDirectoryUtils.setSsl(false); + DirContext dirContext=activeDirectoryUtils.openConnection(); + try { + dirContext.close(); + } catch (NamingException e) { + e.printStackTrace(); + } + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Access.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Access.java index de1c7777c..f0f2ac0a6 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Access.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Access.java @@ -31,142 +31,142 @@ import org.dromara.maxkey.entity.apps.Apps; @Table(name = "mxk_access") public class Access extends Apps implements Serializable{ - /** - * - */ - private static final long serialVersionUID = 8634166407201007340L; - @Id - @Column - @GeneratedValue - String id; - @Column - private String groupId; - - private String groupName; - - @Column - private String appId; - - private String appName; - - @Column - private String instId; + /** + * + */ + private static final long serialVersionUID = 8634166407201007340L; + @Id + @Column + @GeneratedValue + String id; + @Column + private String groupId; + + private String groupName; + + @Column + private String appId; + + private String appName; + + @Column + private String instId; - private String instName; - - public Access(){ - super(); - } - - - /** - * @param groupId - * @param appId - */ - public Access(String groupId, String appId, String instId) { - super(); - this.groupId = groupId; - this.appId = appId; - this.instId = instId; - } + private String instName; + + public Access(){ + super(); + } + + + /** + * @param groupId + * @param appId + */ + public Access(String groupId, String appId, String instId) { + super(); + this.groupId = groupId; + this.appId = appId; + this.instId = instId; + } - public String getGroupId() { - return groupId; - } + public String getGroupId() { + return groupId; + } - public void setGroupId(String groupId) { - this.groupId = groupId; - } + public void setGroupId(String groupId) { + this.groupId = groupId; + } - public String getGroupName() { - return groupName; - } + public String getGroupName() { + return groupName; + } - public void setGroupName(String groupName) { - this.groupName = groupName; - } + public void setGroupName(String groupName) { + this.groupName = groupName; + } - /** - * @return the appId - */ - public String getAppId() { - return appId; - } - /** - * @param appId the appId to set - */ - public void setAppId(String appId) { - this.appId = appId; - } + /** + * @return the appId + */ + public String getAppId() { + return appId; + } + /** + * @param appId the appId to set + */ + public void setAppId(String appId) { + this.appId = appId; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - public String getAppName() { - return appName; - } + public String getAppName() { + return appName; + } - public void setAppName(String appName) { - this.appName = appName; - } + public void setAppName(String appName) { + this.appName = appName; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Access [id="); - builder.append(id); - builder.append(", groupId="); - builder.append(groupId); - builder.append(", groupName="); - builder.append(groupName); - builder.append(", appId="); - builder.append(appId); - builder.append(", appName="); - builder.append(appName); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append("]"); - return builder.toString(); - } - + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Access [id="); + builder.append(id); + builder.append(", groupId="); + builder.append(groupId); + builder.append(", groupName="); + builder.append(groupName); + builder.append(", appId="); + builder.append(appId); + builder.append(", appName="); + builder.append(appName); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append("]"); + return builder.toString(); + } + } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Accounts.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Accounts.java index 766d6fd25..14635cb89 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Accounts.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Accounts.java @@ -212,30 +212,30 @@ public class Accounts extends JpaEntity implements Serializable { } public String getStrategyName() { - return strategyName; - } + return strategyName; + } - public void setStrategyName(String strategyName) { - this.strategyName = strategyName; - } + public void setStrategyName(String strategyName) { + this.strategyName = strategyName; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override + @Override public String toString() { return "AppAccounts [uid=" + userId + ", username=" + username + ", displayName=" + displayName + ", appId=" + appId + ", appName=" + appName + ", relatedUsername=" + relatedUsername + ", relatedPassword=" diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/AccountsStrategy.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/AccountsStrategy.java index 2df313a5a..efa868547 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/AccountsStrategy.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/AccountsStrategy.java @@ -131,22 +131,22 @@ public class AccountsStrategy extends JpaEntity implements Serializable { } public Date getCreatedDate() { - return createdDate; - } + return createdDate; + } - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } - public Date getModifiedDate() { - return modifiedDate; - } + public Date getModifiedDate() { + return modifiedDate; + } - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } - public String getFilters() { + public String getFilters() { return filters; } @@ -187,63 +187,63 @@ public class AccountsStrategy extends JpaEntity implements Serializable { } public byte[] getAppIcon() { - return appIcon; - } + return appIcon; + } - public String getAppIconBase64() { - return appIconBase64; - } + public String getAppIconBase64() { + return appIconBase64; + } - public void setAppIconBase64(String appIconBase64) { - this.appIconBase64 = appIconBase64; - } + public void setAppIconBase64(String appIconBase64) { + this.appIconBase64 = appIconBase64; + } - public void setAppIcon(byte[] appIcon) { - this.appIcon = appIcon; - } + public void setAppIcon(byte[] appIcon) { + this.appIcon = appIcon; + } - public String getCreateType() { - return createType; - } + public String getCreateType() { + return createType; + } - public void setCreateType(String createType) { - this.createType = createType; - } + public void setCreateType(String createType) { + this.createType = createType; + } - public String getSuffixes() { - return suffixes; - } + public String getSuffixes() { + return suffixes; + } - public void setSuffixes(String suffixes) { - this.suffixes = suffixes; - } + public void setSuffixes(String suffixes) { + this.suffixes = suffixes; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - - public void transIconBase64() { - if(this.appIcon !=null) { - this.appIconBase64 = "data:image/png;base64," + - Base64.getEncoder().encodeToString(appIcon); - } - } - - - @Override + + public void transIconBase64() { + if(this.appIcon !=null) { + this.appIconBase64 = "data:image/png;base64," + + Base64.getEncoder().encodeToString(appIcon); + } + } + + + @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("AccountsStrategy [id="); diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/ChangePassword.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/ChangePassword.java index e149b396c..cecb0b7e2 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/ChangePassword.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/ChangePassword.java @@ -24,237 +24,237 @@ import org.dromara.mybatis.jpa.entity.JpaEntity; public class ChangePassword extends JpaEntity{ - /** - * - */ - private static final long serialVersionUID = -2362608803392892403L; + /** + * + */ + private static final long serialVersionUID = -2362608803392892403L; - private String id; - private String userId; - private String username; - private String email; - private String mobile; - private String windowsAccount; - private String employeeNumber; - private String displayName; - private String oldPassword; - private String password; - private String confirmPassword; - private String decipherable; - private String instId; - private int passwordSetType; - private Date passwordLastSetTime; - - /** - * - */ - public ChangePassword() { + private String id; + private String userId; + private String username; + private String email; + private String mobile; + private String windowsAccount; + private String employeeNumber; + private String displayName; + private String oldPassword; + private String password; + private String confirmPassword; + private String decipherable; + private String instId; + private int passwordSetType; + private Date passwordLastSetTime; + + /** + * + */ + 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()); - } - - public void clearPassword() { - this.password =""; - this.decipherable = ""; - } - - /** - * @return the id - */ - public String getId() { - return id; - } + } + + 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()); + } + + public void clearPassword() { + this.password =""; + this.decipherable = ""; + } + + /** + * @return the id + */ + public String getId() { + return id; + } - /** - * @param id the id to set - */ - public void setId(String id) { - this.id = id; - } + /** + * @param id the id to set + */ + public void setId(String id) { + this.id = id; + } - /** - * @return the uid - */ - public String getUserId() { - return userId; - } + /** + * @return the uid + */ + public String getUserId() { + return userId; + } - /** - * @param uid the uid to set - */ - public void setUserId(String uid) { - this.userId = uid; - } + /** + * @param uid the uid to set + */ + public void setUserId(String uid) { + this.userId = uid; + } - /** - * @return the username - */ - public String getUsername() { - return username; - } + /** + * @return the username + */ + public String getUsername() { + return username; + } - /** - * @param username the username to set - */ - public void setUsername(String username) { - this.username = username; - } + /** + * @param username the username to set + */ + public void setUsername(String username) { + this.username = username; + } - /** - * @return the oldPassword - */ - public String getOldPassword() { - return oldPassword; - } + /** + * @return the oldPassword + */ + public String getOldPassword() { + return oldPassword; + } - /** - * @param oldPassword the oldPassword to set - */ - public void setOldPassword(String oldPassword) { - this.oldPassword = oldPassword; - } + /** + * @param oldPassword the oldPassword to set + */ + public void setOldPassword(String oldPassword) { + this.oldPassword = oldPassword; + } - /** - * @return the password - */ - public String getPassword() { - return password; - } + /** + * @return the password + */ + public String getPassword() { + return password; + } - /** - * @param password the password to set - */ - public void setPassword(String password) { - this.password = password; - } + /** + * @param password the password to set + */ + public void setPassword(String password) { + this.password = password; + } - public String getConfirmPassword() { - return confirmPassword; - } + public String getConfirmPassword() { + return confirmPassword; + } - public void setConfirmPassword(String confirmPassword) { - this.confirmPassword = confirmPassword; - } + public void setConfirmPassword(String confirmPassword) { + this.confirmPassword = confirmPassword; + } - /** - * @return the decipherable - */ - public String getDecipherable() { - return decipherable; - } + /** + * @return the decipherable + */ + public String getDecipherable() { + return decipherable; + } - /** - * @param decipherable the decipherable to set - */ - public void setDecipherable(String decipherable) { - this.decipherable = decipherable; - } + /** + * @param decipherable the decipherable to set + */ + public void setDecipherable(String decipherable) { + this.decipherable = decipherable; + } - public String getMobile() { - return mobile; - } + public String getMobile() { + return mobile; + } - public void setMobile(String mobile) { - this.mobile = mobile; - } + public void setMobile(String mobile) { + this.mobile = mobile; + } - public String getDisplayName() { - return displayName; - } + public String getDisplayName() { + return displayName; + } - public void setDisplayName(String displayName) { - this.displayName = displayName; - } + public void setDisplayName(String displayName) { + this.displayName = displayName; + } - public String getEmail() { - return email; - } + public String getEmail() { + return email; + } - public void setEmail(String email) { - this.email = email; - } + public void setEmail(String email) { + this.email = email; + } - public String getWindowsAccount() { - return windowsAccount; - } + public String getWindowsAccount() { + return windowsAccount; + } - public void setWindowsAccount(String windowsAccount) { - this.windowsAccount = windowsAccount; - } + public void setWindowsAccount(String windowsAccount) { + this.windowsAccount = windowsAccount; + } - public String getEmployeeNumber() { - return employeeNumber; - } + public String getEmployeeNumber() { + return employeeNumber; + } - public void setEmployeeNumber(String employeeNumber) { - this.employeeNumber = employeeNumber; - } + public void setEmployeeNumber(String employeeNumber) { + this.employeeNumber = employeeNumber; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - - public int getPasswordSetType() { - return passwordSetType; - } + + public int getPasswordSetType() { + return passwordSetType; + } - public void setPasswordSetType(int passwordSetType) { - this.passwordSetType = passwordSetType; - } + public void setPasswordSetType(int passwordSetType) { + this.passwordSetType = passwordSetType; + } - public Date getPasswordLastSetTime() { - return passwordLastSetTime; - } + public Date getPasswordLastSetTime() { + return passwordLastSetTime; + } - public void setPasswordLastSetTime(Date passwordLastSetTime) { - this.passwordLastSetTime = passwordLastSetTime; - } + public void setPasswordLastSetTime(Date passwordLastSetTime) { + this.passwordLastSetTime = passwordLastSetTime; + } - @Override + @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ChangePassword [id="); @@ -276,5 +276,5 @@ public class ChangePassword extends JpaEntity{ builder.append("]"); return builder.toString(); } - + } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Connectors.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Connectors.java index e7d6d3f7f..f005ad589 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Connectors.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Connectors.java @@ -32,182 +32,182 @@ import jakarta.persistence.Table; @Table(name = "MXK_CONNECTORS") public class Connectors extends JpaEntity implements Serializable { - private static final long serialVersionUID = 4660258495864814777L; - @Id - @Column - @GeneratedValue - String id; - @Column - String connName; - @Column - String scheduler; - @Column - int justInTime; - @Column - String providerUrl; - @Column - String principal; - @Column - String credentials; - @Column - String filters; - @Column - String description; - @Column - String createdBy; - @Column - Date createdDate; - @Column - String modifiedBy; - @Column - Date modifiedDate; - @Column - String status; + private static final long serialVersionUID = 4660258495864814777L; + @Id + @Column + @GeneratedValue + String id; + @Column + String connName; + @Column + String scheduler; + @Column + int justInTime; + @Column + String providerUrl; + @Column + String principal; + @Column + String credentials; + @Column + String filters; + @Column + String description; + @Column + String createdBy; + @Column + Date createdDate; + @Column + String modifiedBy; + @Column + Date modifiedDate; + @Column + String status; - @Column - private String instId; + @Column + private String instId; - private String instName; + private String instName; - public Connectors() { - } + public Connectors() { + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getConnName() { - return connName; - } + public String getConnName() { + return connName; + } - public void setConnName(String connName) { - this.connName = connName; - } + public void setConnName(String connName) { + this.connName = connName; + } - public int getJustInTime() { - return justInTime; - } + public int getJustInTime() { + return justInTime; + } - public void setJustInTime(int justInTime) { - this.justInTime = justInTime; - } + public void setJustInTime(int justInTime) { + this.justInTime = justInTime; + } - public String getScheduler() { - return scheduler; - } + public String getScheduler() { + return scheduler; + } - public void setScheduler(String scheduler) { - this.scheduler = scheduler; - } + public void setScheduler(String scheduler) { + this.scheduler = scheduler; + } - public String getProviderUrl() { - return providerUrl; - } + public String getProviderUrl() { + return providerUrl; + } - public void setProviderUrl(String providerUrl) { - this.providerUrl = providerUrl; - } + public void setProviderUrl(String providerUrl) { + this.providerUrl = providerUrl; + } - public String getPrincipal() { - return principal; - } + public String getPrincipal() { + return principal; + } - public void setPrincipal(String principal) { - this.principal = principal; - } + public void setPrincipal(String principal) { + this.principal = principal; + } - public String getCredentials() { - return credentials; - } + public String getCredentials() { + return credentials; + } - public void setCredentials(String credentials) { - this.credentials = credentials; - } + public void setCredentials(String credentials) { + this.credentials = credentials; + } - public String getFilters() { - return filters; - } + public String getFilters() { + return filters; + } - public void setFilters(String filters) { - this.filters = filters; - } + public void setFilters(String filters) { + this.filters = filters; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public String getCreatedBy() { - return createdBy; - } + public String getCreatedBy() { + return createdBy; + } - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } - public String getModifiedBy() { - return modifiedBy; - } + public String getModifiedBy() { + return modifiedBy; + } - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } - public Date getCreatedDate() { - return createdDate; - } + public Date getCreatedDate() { + return createdDate; + } - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } - public Date getModifiedDate() { - return modifiedDate; - } + public Date getModifiedDate() { + return modifiedDate; + } - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } - public String getStatus() { - return status; - } + public String getStatus() { + return status; + } - public void setStatus(String status) { - this.status = status; - } + public void setStatus(String status) { + this.status = status; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - public Connectors(String id) { - this.id = id; - } + public Connectors(String id) { + this.id = id; + } - @Override - public String toString() { - return new JsonPretty().format(this); - } + @Override + public String toString() { + return new JsonPretty().format(this); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/ExcelImport.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/ExcelImport.java index 982a13f89..315b3007f 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/ExcelImport.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/ExcelImport.java @@ -57,7 +57,7 @@ public class ExcelImport extends JpaEntity { InputStream inputStream = null; - Workbook workbook = null; + Workbook workbook = null; public ExcelImport() { super(); @@ -88,34 +88,34 @@ public class ExcelImport extends JpaEntity { } public boolean isExcelNotEmpty() { - return excelFile != null && !excelFile.isEmpty() ; + return excelFile != null && !excelFile.isEmpty() ; } public Workbook biuldWorkbook() throws IOException { - workbook = null; - inputStream = excelFile.getInputStream(); - if (excelFile.getOriginalFilename().toLowerCase().endsWith(".xls")) { - workbook = new HSSFWorkbook(inputStream); + workbook = null; + inputStream = excelFile.getInputStream(); + if (excelFile.getOriginalFilename().toLowerCase().endsWith(".xls")) { + workbook = new HSSFWorkbook(inputStream); } else if (excelFile.getOriginalFilename().toLowerCase().endsWith(".xlsx")) { - workbook = new XSSFWorkbook(inputStream); + workbook = new XSSFWorkbook(inputStream); } else { throw new RuntimeException("Excel suffix error."); } - return workbook; + return workbook; } public void closeWorkbook() { - if (inputStream != null) { + if (inputStream != null) { try { - inputStream.close(); + inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if(workbook != null) { try { - workbook.close(); + workbook.close(); } catch (IOException e) { e.printStackTrace(); } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/ExtraAttr.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/ExtraAttr.java index 012171d52..e8ff73dc5 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/ExtraAttr.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/ExtraAttr.java @@ -25,52 +25,52 @@ package org.dromara.maxkey.entity; * */ public class ExtraAttr { - - String attr; - String type; - String value; - - public ExtraAttr() { - super(); - } - - public ExtraAttr(String attr, String value) { - super(); - this.attr = attr; - this.value = value; - } - - /** - * @param attr - * @param value - */ - public ExtraAttr(String attr, String type,String value) { - super(); - this.attr = attr; - this.type=type; - this.value = value; - } - public String getAttr() { - return attr; - } - public void setAttr(String attr) { - this.attr = attr; - } - public String getValue() { - return value; - } - public void setValue(String value) { - this.value = value; - } - - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - - @Override + + String attr; + String type; + String value; + + public ExtraAttr() { + super(); + } + + public ExtraAttr(String attr, String value) { + super(); + this.attr = attr; + this.value = value; + } + + /** + * @param attr + * @param value + */ + public ExtraAttr(String attr, String type,String value) { + super(); + this.attr = attr; + this.type=type; + this.value = value; + } + public String getAttr() { + return attr; + } + public void setAttr(String attr) { + this.attr = attr; + } + public String getValue() { + return value; + } + public void setValue(String value) { + this.value = value; + } + + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ExtraAttr [attr="); @@ -82,5 +82,5 @@ public class ExtraAttr { builder.append("]"); return builder.toString(); } - + } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/ExtraAttrs.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/ExtraAttrs.java index caf73986a..105cc9a8f 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/ExtraAttrs.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/ExtraAttrs.java @@ -26,89 +26,89 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ExtraAttrs { - static final Logger _logger = LoggerFactory.getLogger(ExtraAttrs.class); - - ArrayList extraAttrs ; + static final Logger _logger = LoggerFactory.getLogger(ExtraAttrs.class); + + ArrayList extraAttrs ; - - /** - * - */ - public ExtraAttrs() { - super(); - } - - /** - * - */ - public ExtraAttrs(String arrayJsonString) { - String extraAttrsJsonString= "{\"extraAttrs\":"+arrayJsonString+"}"; - _logger.debug("Extra Attrs Json String {}" ,extraAttrsJsonString); - ExtraAttrs extraAttrs=JsonUtils.gsonStringToObject(extraAttrsJsonString, ExtraAttrs.class); - this.extraAttrs=extraAttrs.getExtraAttrs(); - } - - + + /** + * + */ + public ExtraAttrs() { + super(); + } + + /** + * + */ + public ExtraAttrs(String arrayJsonString) { + String extraAttrsJsonString= "{\"extraAttrs\":"+arrayJsonString+"}"; + _logger.debug("Extra Attrs Json String {}" ,extraAttrsJsonString); + ExtraAttrs extraAttrs=JsonUtils.gsonStringToObject(extraAttrsJsonString, ExtraAttrs.class); + this.extraAttrs=extraAttrs.getExtraAttrs(); + } + + - public void put(String attr,String value) { - if(extraAttrs==null){ - extraAttrs=new ArrayList<>(); - } - this.extraAttrs.add(new ExtraAttr(attr,value)); - } - - public void put(String attr,String type,String value) { - if(extraAttrs==null){ - extraAttrs=new ArrayList<>(); - } - this.extraAttrs.add(new ExtraAttr(attr,type,value)); - } - - public String get(String attr) { - String value=null; - if(extraAttrs!=null&& !extraAttrs.isEmpty()){ - for(ExtraAttr extraAttr :extraAttrs){ - if(extraAttr.getAttr().equals(attr)){ - value=extraAttr.getValue(); - } - } - } - return value; - } - - public String toJsonString(){ - String jsonString =JsonUtils.gsonToString(extraAttrs); - _logger.debug("jsonString {}" ,jsonString); - return jsonString; - } - - public HashMap toJsonHashMap(){ - HashMap extraAttrsHashMap=new HashMap(); - for(ExtraAttr extraAttr :extraAttrs){ - extraAttrsHashMap.put(extraAttr.getAttr(), extraAttr.getValue()); - } - _logger.debug("extraAttrs HashMap {}" , extraAttrsHashMap); - return extraAttrsHashMap; - } - - public Properties toProperties(){ - Properties properties=new Properties(); - for(ExtraAttr extraAttr :extraAttrs){ - properties.put(extraAttr.getAttr(), extraAttr.getValue()); - } - _logger.debug("extraAttrs HashMap {}" , properties); - return properties; - } - - public ArrayList getExtraAttrs() { - return extraAttrs; - } + public void put(String attr,String value) { + if(extraAttrs==null){ + extraAttrs=new ArrayList<>(); + } + this.extraAttrs.add(new ExtraAttr(attr,value)); + } + + public void put(String attr,String type,String value) { + if(extraAttrs==null){ + extraAttrs=new ArrayList<>(); + } + this.extraAttrs.add(new ExtraAttr(attr,type,value)); + } + + public String get(String attr) { + String value=null; + if(extraAttrs!=null&& !extraAttrs.isEmpty()){ + for(ExtraAttr extraAttr :extraAttrs){ + if(extraAttr.getAttr().equals(attr)){ + value=extraAttr.getValue(); + } + } + } + return value; + } + + public String toJsonString(){ + String jsonString =JsonUtils.gsonToString(extraAttrs); + _logger.debug("jsonString {}" ,jsonString); + return jsonString; + } + + public HashMap toJsonHashMap(){ + HashMap extraAttrsHashMap=new HashMap(); + for(ExtraAttr extraAttr :extraAttrs){ + extraAttrsHashMap.put(extraAttr.getAttr(), extraAttr.getValue()); + } + _logger.debug("extraAttrs HashMap {}" , extraAttrsHashMap); + return extraAttrsHashMap; + } + + public Properties toProperties(){ + Properties properties=new Properties(); + for(ExtraAttr extraAttr :extraAttrs){ + properties.put(extraAttr.getAttr(), extraAttr.getValue()); + } + _logger.debug("extraAttrs HashMap {}" , properties); + return properties; + } + + public ArrayList getExtraAttrs() { + return extraAttrs; + } - public void setExtraAttrs(ArrayList extraAttrs) { - this.extraAttrs = extraAttrs; - } - - @Override + public void setExtraAttrs(ArrayList extraAttrs) { + this.extraAttrs = extraAttrs; + } + + @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ExtraAttrs [extraAttrs="); @@ -116,6 +116,6 @@ public class ExtraAttrs { builder.append("]"); return builder.toString(); } - - + + } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/FileUpload.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/FileUpload.java index a91aabd1c..f35b4e13c 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/FileUpload.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/FileUpload.java @@ -34,13 +34,13 @@ import jakarta.persistence.Table; @Entity @Table(name = "MXK_FILE_UPLOAD") public class FileUpload extends JpaEntity { - - @Id + + @Id @Column @GeneratedValue String id; - - @Column + + @Column byte[] uploaded; @JsonIgnore @@ -60,81 +60,81 @@ public class FileUpload extends JpaEntity { Date createdDate; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public byte[] getUploaded() { - return uploaded; - } + public byte[] getUploaded() { + return uploaded; + } - public void setUploaded(byte[] uploaded) { - this.uploaded = uploaded; - } + public void setUploaded(byte[] uploaded) { + this.uploaded = uploaded; + } - public MultipartFile getUploadFile() { - return uploadFile; - } + public MultipartFile getUploadFile() { + return uploadFile; + } - public void setUploadFile(MultipartFile uploadFile) { - this.uploadFile = uploadFile; - } + public void setUploadFile(MultipartFile uploadFile) { + this.uploadFile = uploadFile; + } - public String getFileName() { - return fileName; - } + public String getFileName() { + return fileName; + } - public void setFileName(String fileName) { - this.fileName = fileName; - } + public void setFileName(String fileName) { + this.fileName = fileName; + } - public String getContentType() { - return contentType; - } + public String getContentType() { + return contentType; + } - public void setContentType(String contentType) { - this.contentType = contentType; - } + public void setContentType(String contentType) { + this.contentType = contentType; + } - public long getContentSize() { - return contentSize; - } + public long getContentSize() { + return contentSize; + } - public void setContentSize(long contentSize) { - this.contentSize = contentSize; - } + public void setContentSize(long contentSize) { + this.contentSize = contentSize; + } - public String getCreatedBy() { - return createdBy; - } + public String getCreatedBy() { + return createdBy; + } - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } - public Date getCreatedDate() { - return createdDate; - } + public Date getCreatedDate() { + return createdDate; + } - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("FileUpload [id="); - builder.append(id); - builder.append(", uploadFile="); - builder.append(uploadFile); - builder.append(", createdBy="); - builder.append(this.createdBy); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("FileUpload [id="); + builder.append(id); + builder.append(", uploadFile="); + builder.append(uploadFile); + builder.append(", createdBy="); + builder.append(this.createdBy); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Institutions.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Institutions.java index 69d97f185..57eed0f5b 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Institutions.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Institutions.java @@ -29,278 +29,278 @@ import jakarta.persistence.Table; @Entity @Table(name = "MXK_INSTITUTIONS") public class Institutions extends JpaEntity implements Serializable { - private static final long serialVersionUID = -2375872012431214098L; + private static final long serialVersionUID = -2375872012431214098L; - @Id - @Column - @GeneratedValue - private String id; - @Column - private String name; - @Column - private String fullName; - @Column - private String division; - @Column - private String country; - @Column - private String region; - @Column - private String locality; - @Column - private String street; - @Column - private String address; - @Column - private String contact; - @Column - private String postalCode; - @Column - private String phone; - @Column - private String fax; - @Column - private String email; + @Id + @Column + @GeneratedValue + private String id; + @Column + private String name; + @Column + private String fullName; + @Column + private String division; + @Column + private String country; + @Column + private String region; + @Column + private String locality; + @Column + private String street; + @Column + private String address; + @Column + private String contact; + @Column + private String postalCode; + @Column + private String phone; + @Column + private String fax; + @Column + private String email; - @Column - private String description; + @Column + private String description; - @Column - private String logo; - @Column - private String domain; - @Column - private String frontTitle; - @Column - private String consoleDomain; - @Column - private String consoleTitle; - - @Column - private String defaultUri; + @Column + private String logo; + @Column + private String domain; + @Column + private String frontTitle; + @Column + private String consoleDomain; + @Column + private String consoleTitle; + + @Column + private String defaultUri; - public Institutions() { - super(); - } + public Institutions() { + super(); + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getFullName() { - return fullName; - } + public String getFullName() { + return fullName; + } - public void setFullName(String fullName) { - this.fullName = fullName; - } + public void setFullName(String fullName) { + this.fullName = fullName; + } - public String getLogo() { - return logo; - } + public String getLogo() { + return logo; + } - public void setLogo(String logo) { - this.logo = logo; - } + public void setLogo(String logo) { + this.logo = logo; + } - public String getFrontTitle() { - return frontTitle; - } + public String getFrontTitle() { + return frontTitle; + } - public void setFrontTitle(String frontTitle) { - this.frontTitle = frontTitle; - } + public void setFrontTitle(String frontTitle) { + this.frontTitle = frontTitle; + } - public String getConsoleDomain() { - return consoleDomain; - } + public String getConsoleDomain() { + return consoleDomain; + } - public void setConsoleDomain(String consoleDomain) { - this.consoleDomain = consoleDomain; - } + public void setConsoleDomain(String consoleDomain) { + this.consoleDomain = consoleDomain; + } - public String getConsoleTitle() { - return consoleTitle; - } + public String getConsoleTitle() { + return consoleTitle; + } - public void setConsoleTitle(String consoleTitle) { - this.consoleTitle = consoleTitle; - } + public void setConsoleTitle(String consoleTitle) { + this.consoleTitle = consoleTitle; + } - public String getDomain() { - return domain; - } + public String getDomain() { + return domain; + } - public void setDomain(String domain) { - this.domain = domain; - } + public void setDomain(String domain) { + this.domain = domain; + } - public String getDivision() { - return division; - } + public String getDivision() { + return division; + } - public void setDivision(String division) { - this.division = division; - } + public void setDivision(String division) { + this.division = division; + } - public String getCountry() { - return country; - } + public String getCountry() { + return country; + } - public void setCountry(String country) { - this.country = country; - } + public void setCountry(String country) { + this.country = country; + } - public String getRegion() { - return region; - } + public String getRegion() { + return region; + } - public void setRegion(String region) { - this.region = region; - } + public void setRegion(String region) { + this.region = region; + } - public String getLocality() { - return locality; - } + public String getLocality() { + return locality; + } - public void setLocality(String locality) { - this.locality = locality; - } + public void setLocality(String locality) { + this.locality = locality; + } - public String getStreet() { - return street; - } + public String getStreet() { + return street; + } - public void setStreet(String street) { - this.street = street; - } + public void setStreet(String street) { + this.street = street; + } - public String getAddress() { - return address; - } + public String getAddress() { + return address; + } - public void setAddress(String address) { - this.address = address; - } + public void setAddress(String address) { + this.address = address; + } - public String getContact() { - return contact; - } + public String getContact() { + return contact; + } - public void setContact(String contact) { - this.contact = contact; - } + public void setContact(String contact) { + this.contact = contact; + } - public String getPostalCode() { - return postalCode; - } + public String getPostalCode() { + return postalCode; + } - public void setPostalCode(String postalCode) { - this.postalCode = postalCode; - } + public void setPostalCode(String postalCode) { + this.postalCode = postalCode; + } - public String getPhone() { - return phone; - } + public String getPhone() { + return phone; + } - public void setPhone(String phone) { - this.phone = phone; - } + public void setPhone(String phone) { + this.phone = phone; + } - public String getFax() { - return fax; - } + public String getFax() { + return fax; + } - public void setFax(String fax) { - this.fax = fax; - } + public void setFax(String fax) { + this.fax = fax; + } - public String getEmail() { - return email; - } + public String getEmail() { + return email; + } - public void setEmail(String email) { - this.email = email; - } + public void setEmail(String email) { + this.email = email; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public String getDefaultUri() { - return defaultUri; - } + public String getDefaultUri() { + return defaultUri; + } - public void setDefaultUri(String defaultUri) { - this.defaultUri = defaultUri; - } + public void setDefaultUri(String defaultUri) { + this.defaultUri = defaultUri; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Institutions [id="); - builder.append(id); - builder.append(", name="); - builder.append(name); - builder.append(", fullName="); - builder.append(fullName); - builder.append(", division="); - builder.append(division); - builder.append(", country="); - builder.append(country); - builder.append(", region="); - builder.append(region); - builder.append(", locality="); - builder.append(locality); - builder.append(", street="); - builder.append(street); - builder.append(", address="); - builder.append(address); - builder.append(", contact="); - builder.append(contact); - builder.append(", postalCode="); - builder.append(postalCode); - builder.append(", phone="); - builder.append(phone); - builder.append(", fax="); - builder.append(fax); - builder.append(", email="); - builder.append(email); - builder.append(", description="); - builder.append(description); - builder.append(", logo="); - builder.append(logo); - builder.append(", domain="); - builder.append(domain); - builder.append(", frontTitle="); - builder.append(frontTitle); - builder.append(", consoleDomain="); - builder.append(consoleDomain); - builder.append(", consoleTitle="); - builder.append(consoleTitle); - builder.append(", defaultUri="); - builder.append(defaultUri); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Institutions [id="); + builder.append(id); + builder.append(", name="); + builder.append(name); + builder.append(", fullName="); + builder.append(fullName); + builder.append(", division="); + builder.append(division); + builder.append(", country="); + builder.append(country); + builder.append(", region="); + builder.append(region); + builder.append(", locality="); + builder.append(locality); + builder.append(", street="); + builder.append(street); + builder.append(", address="); + builder.append(address); + builder.append(", contact="); + builder.append(contact); + builder.append(", postalCode="); + builder.append(postalCode); + builder.append(", phone="); + builder.append(phone); + builder.append(", fax="); + builder.append(fax); + builder.append(", email="); + builder.append(email); + builder.append(", description="); + builder.append(description); + builder.append(", logo="); + builder.append(logo); + builder.append(", domain="); + builder.append(domain); + builder.append(", frontTitle="); + builder.append(frontTitle); + builder.append(", consoleDomain="); + builder.append(consoleDomain); + builder.append(", consoleTitle="); + builder.append(consoleTitle); + builder.append(", defaultUri="); + builder.append(defaultUri); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/OrganizationsCast.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/OrganizationsCast.java index 3a9c16849..18c1c1d23 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/OrganizationsCast.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/OrganizationsCast.java @@ -32,10 +32,10 @@ public class OrganizationsCast extends JpaEntity implements Serializable { /** - * - */ - private static final long serialVersionUID = 5166920258761620856L; - @Id + * + */ + private static final long serialVersionUID = 5166920258761620856L; + @Id @Column @GeneratedValue private String id; @@ -71,10 +71,10 @@ public class OrganizationsCast extends JpaEntity implements Serializable { @Column private String appName; - @Column - private String instId; + @Column + private String instId; - private String instName; + private String instName; //重组标志 boolean reorgNamePath; @@ -84,161 +84,161 @@ public class OrganizationsCast extends JpaEntity implements Serializable { } public String getId() { - return id; - } + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getCode() { - return code; - } + public String getCode() { + return code; + } - public void setCode(String code) { - this.code = code; - } + public void setCode(String code) { + this.code = code; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getFullName() { - return fullName; - } + public String getFullName() { + return fullName; + } - public void setFullName(String fullName) { - this.fullName = fullName; - } + public void setFullName(String fullName) { + this.fullName = fullName; + } - public String getParentId() { - return parentId; - } + public String getParentId() { + return parentId; + } - public void setParentId(String parentId) { - this.parentId = parentId; - } + public void setParentId(String parentId) { + this.parentId = parentId; + } - public String getParentName() { - return parentName; - } + public String getParentName() { + return parentName; + } - public void setParentName(String parentName) { - this.parentName = parentName; - } + public void setParentName(String parentName) { + this.parentName = parentName; + } - public String getCodePath() { - return codePath; - } + public String getCodePath() { + return codePath; + } - public void setCodePath(String codePath) { - this.codePath = codePath; - } + public void setCodePath(String codePath) { + this.codePath = codePath; + } - public String getNamePath() { - return namePath; - } + public String getNamePath() { + return namePath; + } - public void setNamePath(String namePath) { - this.namePath = namePath; - } + public void setNamePath(String namePath) { + this.namePath = namePath; + } - public int getStatus() { - return status; - } + public int getStatus() { + return status; + } - public void setStatus(int status) { - this.status = status; - } + public void setStatus(int status) { + this.status = status; + } - public String getOrgId() { - return orgId; - } + public String getOrgId() { + return orgId; + } - public void setOrgId(String orgId) { - this.orgId = orgId; - } + public void setOrgId(String orgId) { + this.orgId = orgId; + } - public String getOrgParentId() { - return orgParentId; - } + public String getOrgParentId() { + return orgParentId; + } - public void setOrgParentId(String orgParentId) { - this.orgParentId = orgParentId; - } + public void setOrgParentId(String orgParentId) { + this.orgParentId = orgParentId; + } - public long getSortIndex() { - return sortIndex; - } + public long getSortIndex() { + return sortIndex; + } - public void setSortIndex(long sortIndex) { - this.sortIndex = sortIndex; - } + public void setSortIndex(long sortIndex) { + this.sortIndex = sortIndex; + } - public String getProvider() { - return provider; - } + public String getProvider() { + return provider; + } - public void setProvider(String provider) { - this.provider = provider; - } + public void setProvider(String provider) { + this.provider = provider; + } - public boolean isReorgNamePath() { - return reorgNamePath; - } + public boolean isReorgNamePath() { + return reorgNamePath; + } - public void setReorgNamePath(boolean reorgNamePath) { - this.reorgNamePath = reorgNamePath; - } + public void setReorgNamePath(boolean reorgNamePath) { + this.reorgNamePath = reorgNamePath; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("OrganizationsMapper [id="); - builder.append(id); - builder.append(", code="); - builder.append(code); - builder.append(", name="); - builder.append(name); - builder.append(", fullName="); - builder.append(fullName); - builder.append(", parentId="); - builder.append(parentId); - builder.append(", parentName="); - builder.append(parentName); - builder.append(", codePath="); - builder.append(codePath); - builder.append(", namePath="); - builder.append(namePath); - builder.append(", status="); - builder.append(status); - builder.append(", orgId="); - builder.append(orgId); - builder.append(", orgParentId="); - builder.append(orgParentId); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("OrganizationsMapper [id="); + builder.append(id); + builder.append(", code="); + builder.append(code); + builder.append(", name="); + builder.append(name); + builder.append(", fullName="); + builder.append(fullName); + builder.append(", parentId="); + builder.append(parentId); + builder.append(", parentName="); + builder.append(parentName); + builder.append(", codePath="); + builder.append(codePath); + builder.append(", namePath="); + builder.append(namePath); + builder.append(", status="); + builder.append(status); + builder.append(", orgId="); + builder.append(orgId); + builder.append(", orgParentId="); + builder.append(orgParentId); + builder.append("]"); + return builder.toString(); + } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Register.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Register.java index 875b00f74..efb2a063e 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Register.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Register.java @@ -31,30 +31,30 @@ import jakarta.persistence.Table; @Entity @Table(name = "MXK_REGISTER") public class Register extends JpaEntity implements Serializable { - - /** - * - */ - private static final long serialVersionUID = -4021412077583763378L; - @Id + + /** + * + */ + private static final long serialVersionUID = -4021412077583763378L; + @Id @Column @GeneratedValue - private String id; - @Column - private String displayName; - @Column - private String workEmail; - @Column - private String workPhone; - @Column - private Integer employees; - - //机构 - private String instId; - @Column - private String instName; - - @Column + private String id; + @Column + private String displayName; + @Column + private String workEmail; + @Column + private String workPhone; + @Column + private Integer employees; + + //机构 + private String instId; + @Column + private String instName; + + @Column int status; @Column String createdBy; @@ -65,141 +65,141 @@ public class Register extends JpaEntity implements Serializable { @Column Date modifiedDate; - - /** - * - */ - public Register() { - super(); - } + + /** + * + */ + public Register() { + super(); + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getDisplayName() { - return displayName; - } + public String getDisplayName() { + return displayName; + } - public void setDisplayName(String displayName) { - this.displayName = displayName; - } + public void setDisplayName(String displayName) { + this.displayName = displayName; + } - public String getWorkEmail() { - return workEmail; - } + public String getWorkEmail() { + return workEmail; + } - public void setWorkEmail(String workEmail) { - this.workEmail = workEmail; - } + public void setWorkEmail(String workEmail) { + this.workEmail = workEmail; + } - public String getWorkPhone() { - return workPhone; - } + public String getWorkPhone() { + return workPhone; + } - public void setWorkPhone(String workPhone) { - this.workPhone = workPhone; - } + public void setWorkPhone(String workPhone) { + this.workPhone = workPhone; + } - public Integer getEmployees() { - return employees; - } + public Integer getEmployees() { + return employees; + } - public void setEmployees(Integer employees) { - this.employees = employees; - } + public void setEmployees(Integer employees) { + this.employees = employees; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - public int getStatus() { - return status; - } + public int getStatus() { + return status; + } - public void setStatus(int status) { - this.status = status; - } + public void setStatus(int status) { + this.status = status; + } - public String getCreatedBy() { - return createdBy; - } + public String getCreatedBy() { + return createdBy; + } - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } - public String getModifiedBy() { - return modifiedBy; - } + public String getModifiedBy() { + return modifiedBy; + } - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - public Date getCreatedDate() { - return createdDate; - } + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + public Date getCreatedDate() { + return createdDate; + } - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } - public Date getModifiedDate() { - return modifiedDate; - } + public Date getModifiedDate() { + return modifiedDate; + } - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Register [id="); - builder.append(id); - builder.append(", displayName="); - builder.append(displayName); - builder.append(", workEmail="); - builder.append(workEmail); - builder.append(", workPhone="); - builder.append(workPhone); - builder.append(", employees="); - builder.append(employees); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append(", status="); - builder.append(status); - builder.append(", createdBy="); - builder.append(createdBy); - builder.append(", createdDate="); - builder.append(createdDate); - builder.append(", modifiedBy="); - builder.append(modifiedBy); - builder.append(", modifiedDate="); - builder.append(modifiedDate); - builder.append("]"); - return builder.toString(); - } - + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Register [id="); + builder.append(id); + builder.append(", displayName="); + builder.append(displayName); + builder.append(", workEmail="); + builder.append(workEmail); + builder.append(", workPhone="); + builder.append(workPhone); + builder.append(", employees="); + builder.append(employees); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append(", status="); + builder.append(status); + builder.append(", createdBy="); + builder.append(createdBy); + builder.append(", createdDate="); + builder.append(createdDate); + builder.append(", modifiedBy="); + builder.append(modifiedBy); + builder.append(", modifiedDate="); + builder.append(modifiedDate); + builder.append("]"); + return builder.toString(); + } + } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SocialsAssociate.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SocialsAssociate.java index c37a0e30b..e742ab588 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SocialsAssociate.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SocialsAssociate.java @@ -35,151 +35,151 @@ import jakarta.persistence.Table; @Entity @Table(name = "MXK_SOCIALS_ASSOCIATE") public class SocialsAssociate extends JpaEntity implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 2151179554190800162L; - @Id + + /** + * + */ + private static final long serialVersionUID = 2151179554190800162L; + @Id @Column @GeneratedValue - private String id; - @Column - private String provider; - private String providerName; - private String icon; - - @Column - private String userId; - @Column - private String username; - @Column - private String socialUserId; - @Column - private String socialUserInfo; - private String accessToken; - private String exAttribute; - @Column + private String id; + @Column + private String provider; + private String providerName; + private String icon; + + @Column + private String userId; + @Column + private String username; + @Column + private String socialUserId; + @Column + private String socialUserInfo; + private String accessToken; + private String exAttribute; + @Column private Date createdDate; @Column private Date updatedDate; @Column private String instId; - - public SocialsAssociate() {} + + public SocialsAssociate() {} - /** - * @return the id - */ - public String getId() { - return id; - } + /** + * @return the id + */ + public String getId() { + return id; + } - /** - * @param id the id to set - */ - public void setId(String id) { - this.id = id; - } + /** + * @param id the id to set + */ + public void setId(String id) { + this.id = id; + } - public String getProvider() { - return provider; - } + public String getProvider() { + return provider; + } - public void setProvider(String provider) { - this.provider = provider; - } + public void setProvider(String provider) { + this.provider = provider; + } - public String getUserId() { - return userId; - } + public String getUserId() { + return userId; + } - public void setUserId(String uid) { - this.userId = uid; - } + public void setUserId(String uid) { + this.userId = uid; + } - public String getSocialUserId() { - return socialUserId; - } + public String getSocialUserId() { + return socialUserId; + } - public String getUsername() { - return username; - } + public String getUsername() { + return username; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } - public void setSocialUserId(String socialUserId) { - this.socialUserId = socialUserId; - } + public void setSocialUserId(String socialUserId) { + this.socialUserId = socialUserId; + } - public String getSocialUserInfo() { - return socialUserInfo; - } + public String getSocialUserInfo() { + return socialUserInfo; + } - public void setSocialUserInfo(String socialUserInfo) { - this.socialUserInfo = socialUserInfo; - } + public void setSocialUserInfo(String socialUserInfo) { + this.socialUserInfo = socialUserInfo; + } - public String getAccessToken() { - return accessToken; - } + public String getAccessToken() { + return accessToken; + } - public void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } - public String getExAttribute() { - return exAttribute; - } + public String getExAttribute() { + return exAttribute; + } - public void setExAttribute(String exAttribute) { - this.exAttribute = exAttribute; - } + public void setExAttribute(String exAttribute) { + this.exAttribute = exAttribute; + } public Date getCreatedDate() { - return createdDate; - } + return createdDate; + } - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } - public Date getUpdatedDate() { - return updatedDate; - } + public Date getUpdatedDate() { + return updatedDate; + } - public void setUpdatedDate(Date updatedDate) { - this.updatedDate = updatedDate; - } + public void setUpdatedDate(Date updatedDate) { + this.updatedDate = updatedDate; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - - public String getProviderName() { - return providerName; - } + + public String getProviderName() { + return providerName; + } - public void setProviderName(String providerName) { - this.providerName = providerName; - } + public void setProviderName(String providerName) { + this.providerName = providerName; + } - public String getIcon() { - return icon; - } + public String getIcon() { + return icon; + } - public void setIcon(String icon) { - this.icon = icon; - } + public void setIcon(String icon) { + this.icon = icon; + } - @Override + @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("SocialsAssociate [id="); diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SocialsProvider.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SocialsProvider.java index af9cc7a64..a612fe06d 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SocialsProvider.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SocialsProvider.java @@ -44,15 +44,15 @@ public class SocialsProvider extends JpaEntity implements Serializable { @GeneratedValue private String id; @Column - private String provider; + private String provider; @Column - private String providerName; + private String providerName; @Column - private String icon; + private String icon; @Column - private String clientId; + private String clientId; @Column - private String clientSecret; + private String clientSecret; @Column private String agentId; @Column @@ -64,7 +64,7 @@ public class SocialsProvider extends JpaEntity implements Serializable { @Column private int status; @Column - private String instId; + private String instId; @Column String createdBy; @Column @@ -74,91 +74,91 @@ public class SocialsProvider extends JpaEntity implements Serializable { @Column Date modifiedDate; - private String redirectUri; - - private String accountId; - private String bindTime; - private String unBindTime; - private String lastLoginTime; - private String state; - - - private boolean userBind; - - /** - * - */ - public SocialsProvider() { + private String redirectUri; + + private String accountId; + private String bindTime; + private String unBindTime; + private String lastLoginTime; + private String state; + + + private boolean userBind; + + /** + * + */ + public SocialsProvider() { - } - - public SocialsProvider(SocialsProvider copy) { - this.clientId = copy.getClientId(); - this.id = copy.getId(); - this.provider = copy.getProvider(); - this.providerName = copy.getProviderName(); - this.agentId = copy.getAgentId(); - this.icon = copy.getIcon(); - this.scanCode = copy.getScanCode(); - } + } + + public SocialsProvider(SocialsProvider copy) { + this.clientId = copy.getClientId(); + this.id = copy.getId(); + this.provider = copy.getProvider(); + this.providerName = copy.getProviderName(); + this.agentId = copy.getAgentId(); + this.icon = copy.getIcon(); + this.scanCode = copy.getScanCode(); + } - public String getProvider() { - return provider; - } + public String getProvider() { + return provider; + } - public void setProvider(String provider) { - this.provider = provider; - } + public void setProvider(String provider) { + this.provider = provider; + } - public String getProviderName() { - return providerName; - } + public String getProviderName() { + return providerName; + } - public void setProviderName(String providerName) { - this.providerName = providerName; - } + public void setProviderName(String providerName) { + this.providerName = providerName; + } - public String getIcon() { - return icon; - } + public String getIcon() { + return icon; + } - public void setIcon(String icon) { - this.icon = icon; - } + public void setIcon(String icon) { + this.icon = icon; + } - public String getClientId() { - return clientId; - } + public String getClientId() { + return clientId; + } - public void setClientId(String clientId) { - this.clientId = clientId; - } + public void setClientId(String clientId) { + this.clientId = clientId; + } - public String getClientSecret() { - return clientSecret; - } + public String getClientSecret() { + return clientSecret; + } - public void setClientSecret(String clientSecret) { - this.clientSecret = clientSecret; - } + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } - public String getAccountId() { - return accountId; - } + public String getAccountId() { + return accountId; + } - public void setAccountId(String accountId) { - this.accountId = accountId; - } + public void setAccountId(String accountId) { + this.accountId = accountId; + } - public boolean isUserBind() { - return userBind; - } + public boolean isUserBind() { + return userBind; + } - public void setUserBind(boolean userBind) { - this.userBind = userBind; - } + public void setUserBind(boolean userBind) { + this.userBind = userBind; + } - + public String getBindTime() { return bindTime; } @@ -184,28 +184,28 @@ public class SocialsProvider extends JpaEntity implements Serializable { } public String getRedirectUri() { - return redirectUri; - } + return redirectUri; + } - public void setRedirectUri(String redirectUri) { - this.redirectUri = redirectUri; - } + public void setRedirectUri(String redirectUri) { + this.redirectUri = redirectUri; + } - public String getAgentId() { - return agentId; - } + public String getAgentId() { + return agentId; + } - public void setAgentId(String agentId) { - this.agentId = agentId; - } + public void setAgentId(String agentId) { + this.agentId = agentId; + } - public String getState() { - return state; - } + public String getState() { + return state; + } - public void setState(String state) { - this.state = state; - } + public void setState(String state) { + this.state = state; + } @@ -218,14 +218,14 @@ public class SocialsProvider extends JpaEntity implements Serializable { } public String getDisplay() { - return display; - } + return display; + } - public void setDisplay(String display) { - this.display = display; - } + public void setDisplay(String display) { + this.display = display; + } - public int getStatus() { + public int getStatus() { return status; } @@ -250,22 +250,22 @@ public class SocialsProvider extends JpaEntity implements Serializable { } public Date getCreatedDate() { - return createdDate; - } + return createdDate; + } - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } - public Date getModifiedDate() { - return modifiedDate; - } + public Date getModifiedDate() { + return modifiedDate; + } - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } - public long getSortIndex() { + public long getSortIndex() { return sortIndex; } @@ -274,74 +274,74 @@ public class SocialsProvider extends JpaEntity implements Serializable { } public String getScanCode() { - return scanCode; - } + return scanCode; + } - public void setScanCode(String scanCode) { - this.scanCode = scanCode; - } + public void setScanCode(String scanCode) { + this.scanCode = scanCode; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("SocialsProvider [id="); - builder.append(id); - builder.append(", provider="); - builder.append(provider); - builder.append(", providerName="); - builder.append(providerName); - builder.append(", icon="); - builder.append(icon); - builder.append(", clientId="); - builder.append(clientId); - builder.append(", clientSecret="); - builder.append(clientSecret); - builder.append(", agentId="); - builder.append(agentId); - builder.append(", display="); - builder.append(display); - builder.append(", sortIndex="); - builder.append(sortIndex); - builder.append(", scanCode="); - builder.append(scanCode); - builder.append(", status="); - builder.append(status); - builder.append(", instId="); - builder.append(instId); - builder.append(", createdBy="); - builder.append(createdBy); - builder.append(", createdDate="); - builder.append(createdDate); - builder.append(", modifiedBy="); - builder.append(modifiedBy); - builder.append(", modifiedDate="); - builder.append(modifiedDate); - builder.append(", redirectUri="); - builder.append(redirectUri); - builder.append(", accountId="); - builder.append(accountId); - builder.append(", bindTime="); - builder.append(bindTime); - builder.append(", unBindTime="); - builder.append(unBindTime); - builder.append(", lastLoginTime="); - builder.append(lastLoginTime); - builder.append(", state="); - builder.append(state); - builder.append(", userBind="); - builder.append(userBind); - builder.append("]"); - return builder.toString(); - } - - + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("SocialsProvider [id="); + builder.append(id); + builder.append(", provider="); + builder.append(provider); + builder.append(", providerName="); + builder.append(providerName); + builder.append(", icon="); + builder.append(icon); + builder.append(", clientId="); + builder.append(clientId); + builder.append(", clientSecret="); + builder.append(clientSecret); + builder.append(", agentId="); + builder.append(agentId); + builder.append(", display="); + builder.append(display); + builder.append(", sortIndex="); + builder.append(sortIndex); + builder.append(", scanCode="); + builder.append(scanCode); + builder.append(", status="); + builder.append(status); + builder.append(", instId="); + builder.append(instId); + builder.append(", createdBy="); + builder.append(createdBy); + builder.append(", createdDate="); + builder.append(createdDate); + builder.append(", modifiedBy="); + builder.append(modifiedBy); + builder.append(", modifiedDate="); + builder.append(modifiedDate); + builder.append(", redirectUri="); + builder.append(redirectUri); + builder.append(", accountId="); + builder.append(accountId); + builder.append(", bindTime="); + builder.append(bindTime); + builder.append(", unBindTime="); + builder.append(unBindTime); + builder.append(", lastLoginTime="); + builder.append(lastLoginTime); + builder.append(", state="); + builder.append(state); + builder.append(", userBind="); + builder.append(userBind); + builder.append("]"); + return builder.toString(); + } + + } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SocialsProviderLogin.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SocialsProviderLogin.java index 64629d70d..7d2aa06aa 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SocialsProviderLogin.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SocialsProviderLogin.java @@ -29,32 +29,32 @@ import java.util.List; public class SocialsProviderLogin implements Serializable { /** - * - */ - private static final long serialVersionUID = -2672107566766342357L; - - List providers = new ArrayList(); - - String qrScan = null; + * + */ + private static final long serialVersionUID = -2672107566766342357L; + + List providers = new ArrayList(); + + String qrScan = null; - public SocialsProviderLogin(List socialSignOnProviders) { - super(); - this.providers = socialSignOnProviders; - } + public SocialsProviderLogin(List socialSignOnProviders) { + super(); + this.providers = socialSignOnProviders; + } - public String getQrScan() { - return qrScan; - } + public String getQrScan() { + return qrScan; + } - public void setQrScan(String qrScan) { - this.qrScan = qrScan; - } + public void setQrScan(String qrScan) { + this.qrScan = qrScan; + } - public List getProviders() { - return providers; - } + public List getProviders() { + return providers; + } - public void setProviders(List providers) { - this.providers = providers; - } + public void setProviders(List providers) { + this.providers = providers; + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SyncJobConfigField.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SyncJobConfigField.java index 885e7fb28..de4960189 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SyncJobConfigField.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SyncJobConfigField.java @@ -36,190 +36,190 @@ import java.util.Date; @Table(name = "SYNC_JOB_CONFIG_FIELD") public class SyncJobConfigField extends JpaEntity implements Serializable { - private static final long serialVersionUID = 6784822536779144306L; + private static final long serialVersionUID = 6784822536779144306L; - /** - * - * ID - */ - @Id - @Column - private Long id; + /** + * + * ID + */ + @Id + @Column + private Long id; - /** - * 同步任务ID - */ - @Column - private Long jobId; + /** + * 同步任务ID + */ + @Column + private Long jobId; - /** - * 规则名 - */ - @Column - private String name; + /** + * 规则名 + */ + @Column + private String name; - /** - * 类型 - */ - @Column - private String objectType; + /** + * 类型 + */ + @Column + private String objectType; - /** - * 目标字段 - */ - @Column - private String targetField; + /** + * 目标字段 + */ + @Column + private String targetField; - /** - * 目标字段描述 - */ - @Column - private String targetFieldName; + /** + * 目标字段描述 + */ + @Column + private String targetFieldName; - /** - * 来源字段 - */ - @Column - private String sourceField; + /** + * 来源字段 + */ + @Column + private String sourceField; - /** - * 来源字段描述 - */ - @Column - private String sourceFieldName; + /** + * 来源字段描述 + */ + @Column + private String sourceFieldName; - /** - * 描述 - */ - @Column - private String description; + /** + * 描述 + */ + @Column + private String description; - /** - * 创建人 - */ - @Column - private Long createUser; + /** + * 创建人 + */ + @Column + private Long createUser; - /** - * 创建时间 - */ - @Column - private Date createTime; + /** + * 创建时间 + */ + @Column + private Date createTime; - /** - * 修改人 - */ - @Column - private Long updateUser; + /** + * 修改人 + */ + @Column + private Long updateUser; - /** - * 修改时间 - */ - @Column - private Date updateTime; + /** + * 修改时间 + */ + @Column + private Date updateTime; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public Long getJobId() { - return jobId; - } + public Long getJobId() { + return jobId; + } - public void setJobId(Long jobId) { - this.jobId = jobId; - } + public void setJobId(Long jobId) { + this.jobId = jobId; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getObjectType() { - return objectType; - } + public String getObjectType() { + return objectType; + } - public void setObjectType(String objectType) { - this.objectType = objectType; - } + public void setObjectType(String objectType) { + this.objectType = objectType; + } - public String getTargetField() { - return targetField; - } + public String getTargetField() { + return targetField; + } - public void setTargetField(String targetField) { - this.targetField = targetField; - } + public void setTargetField(String targetField) { + this.targetField = targetField; + } - public String getTargetFieldName() { - return targetFieldName; - } + public String getTargetFieldName() { + return targetFieldName; + } - public void setTargetFieldName(String targetFieldName) { - this.targetFieldName = targetFieldName; - } + public void setTargetFieldName(String targetFieldName) { + this.targetFieldName = targetFieldName; + } - public String getSourceField() { - return sourceField; - } + public String getSourceField() { + return sourceField; + } - public void setSourceField(String sourceField) { - this.sourceField = sourceField; - } + public void setSourceField(String sourceField) { + this.sourceField = sourceField; + } - public String getSourceFieldName() { - return sourceFieldName; - } + public String getSourceFieldName() { + return sourceFieldName; + } - public void setSourceFieldName(String sourceFieldName) { - this.sourceFieldName = sourceFieldName; - } + public void setSourceFieldName(String sourceFieldName) { + this.sourceFieldName = sourceFieldName; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public Long getCreateUser() { - return createUser; - } + public Long getCreateUser() { + return createUser; + } - public void setCreateUser(Long createUser) { - this.createUser = createUser; - } + public void setCreateUser(Long createUser) { + this.createUser = createUser; + } - public Date getCreateTime() { - return createTime; - } + public Date getCreateTime() { + return createTime; + } - public void setCreateTime(Date createTime) { - this.createTime = createTime; - } + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } - public Long getUpdateUser() { - return updateUser; - } + public Long getUpdateUser() { + return updateUser; + } - public void setUpdateUser(Long updateUser) { - this.updateUser = updateUser; - } + public void setUpdateUser(Long updateUser) { + this.updateUser = updateUser; + } - public Date getUpdateTime() { - return updateTime; - } + public Date getUpdateTime() { + return updateTime; + } - public void setUpdateTime(Date updateTime) { - this.updateTime = updateTime; - } + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SynchroRelated.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SynchroRelated.java index 5a676cef1..126c54eae 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SynchroRelated.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/SynchroRelated.java @@ -38,202 +38,202 @@ import org.dromara.maxkey.util.DateUtils; @Entity @Table(name = "MXK_SYNCHRO_RELATED") public class SynchroRelated extends JpaEntity implements Serializable { - private static final long serialVersionUID = 6993697309055585706L; + private static final long serialVersionUID = 6993697309055585706L; - @Id - @Column - @GeneratedValue - String id; - @Column - protected String objectId; - @Column - protected String objectName; - @Column - protected String objectDisplayName; - @Column - protected String objectType; - @Column - protected String syncId; - @Column - protected String syncName; - @Column - protected String originId; - @Column - protected String originId2; - @Column - protected String originId3; - @Column - protected String originName; - @Column - protected String instId; + @Id + @Column + @GeneratedValue + String id; + @Column + protected String objectId; + @Column + protected String objectName; + @Column + protected String objectDisplayName; + @Column + protected String objectType; + @Column + protected String syncId; + @Column + protected String syncName; + @Column + protected String originId; + @Column + protected String originId2; + @Column + protected String originId3; + @Column + protected String originName; + @Column + protected String instId; - protected String instName; - @Column - protected String syncTime; + protected String instName; + @Column + protected String syncTime; - public SynchroRelated() { - super(); - } + public SynchroRelated() { + super(); + } - public SynchroRelated(String objectId, String objectName,String objectDisplayName, String objectType, String syncId, String syncName, - String originId, String originName, String originId2, String originId3, String instId) { - super(); - this.objectId = objectId; - this.objectName = objectName; - this.objectDisplayName = objectDisplayName; - this.objectType = objectType; - this.syncId = syncId; - this.syncName = syncName; - this.originId = originId; - this.originName = originName; - this.originId2 = originId2; - this.originId3 = originId3; - this.instId = instId; - this.syncTime = DateUtils.formatDateTime(new Date()); - } + public SynchroRelated(String objectId, String objectName,String objectDisplayName, String objectType, String syncId, String syncName, + String originId, String originName, String originId2, String originId3, String instId) { + super(); + this.objectId = objectId; + this.objectName = objectName; + this.objectDisplayName = objectDisplayName; + this.objectType = objectType; + this.syncId = syncId; + this.syncName = syncName; + this.originId = originId; + this.originName = originName; + this.originId2 = originId2; + this.originId3 = originId3; + this.instId = instId; + this.syncTime = DateUtils.formatDateTime(new Date()); + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getObjectId() { - return objectId; - } + public String getObjectId() { + return objectId; + } - public void setObjectId(String objectId) { - this.objectId = objectId; - } + public void setObjectId(String objectId) { + this.objectId = objectId; + } - public String getObjectName() { - return objectName; - } + public String getObjectName() { + return objectName; + } - public void setObjectName(String objectName) { - this.objectName = objectName; - } + public void setObjectName(String objectName) { + this.objectName = objectName; + } - public String getObjectDisplayName() { - return objectDisplayName; - } + public String getObjectDisplayName() { + return objectDisplayName; + } - public void setObjectDisplayName(String objectDisplayName) { - this.objectDisplayName = objectDisplayName; - } + public void setObjectDisplayName(String objectDisplayName) { + this.objectDisplayName = objectDisplayName; + } - public String getObjectType() { - return objectType; - } + public String getObjectType() { + return objectType; + } - public void setObjectType(String objectType) { - this.objectType = objectType; - } + public void setObjectType(String objectType) { + this.objectType = objectType; + } - public String getSyncId() { - return syncId; - } + public String getSyncId() { + return syncId; + } - public void setSyncId(String syncId) { - this.syncId = syncId; - } + public void setSyncId(String syncId) { + this.syncId = syncId; + } - public String getSyncName() { - return syncName; - } + public String getSyncName() { + return syncName; + } - public void setSyncName(String syncName) { - this.syncName = syncName; - } + public void setSyncName(String syncName) { + this.syncName = syncName; + } - public String getOriginId() { - return originId; - } + public String getOriginId() { + return originId; + } - public void setOriginId(String originId) { - this.originId = originId; - } + public void setOriginId(String originId) { + this.originId = originId; + } - public String getOriginName() { - return originName; - } + public String getOriginName() { + return originName; + } - public void setOriginName(String originName) { - this.originName = originName; - } + public void setOriginName(String originName) { + this.originName = originName; + } - public String getOriginId2() { - return originId2; - } + public String getOriginId2() { + return originId2; + } - public void setOriginId2(String originId2) { - this.originId2 = originId2; - } + public void setOriginId2(String originId2) { + this.originId2 = originId2; + } - public String getOriginId3() { - return originId3; - } + public String getOriginId3() { + return originId3; + } - public void setOriginId3(String originId3) { - this.originId3 = originId3; - } + public void setOriginId3(String originId3) { + this.originId3 = originId3; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - public String getSyncTime() { - return syncTime; - } + public String getSyncTime() { + return syncTime; + } - public void setSyncTime(String syncTime) { - this.syncTime = syncTime; - } + public void setSyncTime(String syncTime) { + this.syncTime = syncTime; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("SynchroRelated [id="); - builder.append(id); - builder.append(", objectId="); - builder.append(objectId); - builder.append(", objectName="); - builder.append(objectName); - builder.append(", objectType="); - builder.append(objectType); - builder.append(", syncId="); - builder.append(syncId); - builder.append(", syncName="); - builder.append(syncName); - builder.append(", originId="); - builder.append(originId); - builder.append(", originId2="); - builder.append(originId2); - builder.append(", originId3="); - builder.append(originId3); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append(", syncTime="); - builder.append(syncTime); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("SynchroRelated [id="); + builder.append(id); + builder.append(", objectId="); + builder.append(objectId); + builder.append(", objectName="); + builder.append(objectName); + builder.append(", objectType="); + builder.append(objectType); + builder.append(", syncId="); + builder.append(syncId); + builder.append(", syncName="); + builder.append(syncName); + builder.append(", originId="); + builder.append(originId); + builder.append(", originId2="); + builder.append(originId2); + builder.append(", originId3="); + builder.append(originId3); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append(", syncTime="); + builder.append(syncTime); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Synchronizers.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Synchronizers.java index 6e2e45723..af659a4b1 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Synchronizers.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/Synchronizers.java @@ -33,365 +33,365 @@ import org.hibernate.validator.constraints.Length; @Table(name = "MXK_SYNCHRONIZERS") public class Synchronizers extends JpaEntity implements Serializable { - private static final long serialVersionUID = 4660258495864814777L; - - @Id - @Column - @GeneratedValue - String id; + private static final long serialVersionUID = 4660258495864814777L; + + @Id + @Column + @GeneratedValue + String id; - @Length(max = 60) - @Column - String name; - @Column - String sourceType; - @Column - String resumeTime; - @Column - String suspendTime; - @Column - String scheduler; + @Length(max = 60) + @Column + String name; + @Column + String sourceType; + @Column + String resumeTime; + @Column + String suspendTime; + @Column + String scheduler; - // 同步时间范围(单位天) - @Column - Integer syncStartTime; + // 同步时间范围(单位天) + @Column + Integer syncStartTime; - @Column - String providerUrl; - @Column - String driverClass; - @Column - String principal; - @Column - String credentials; - @Column - String userBasedn; - @Column - String userFilters; - @Column - String orgBasedn; - @Column - String orgFilters; - @Column - String msadDomain; - @Column - String sslSwitch; - @Column - String trustStore; - @Column - String trustStorePassword; - @Column - String description; - @Column - String createdBy; - @Column - Date createdDate; - @Column - String modifiedBy; - @Column - Date modifiedDate; - @Column - String status; - @Column - String service; + @Column + String providerUrl; + @Column + String driverClass; + @Column + String principal; + @Column + String credentials; + @Column + String userBasedn; + @Column + String userFilters; + @Column + String orgBasedn; + @Column + String orgFilters; + @Column + String msadDomain; + @Column + String sslSwitch; + @Column + String trustStore; + @Column + String trustStorePassword; + @Column + String description; + @Column + String createdBy; + @Column + Date createdDate; + @Column + String modifiedBy; + @Column + Date modifiedDate; + @Column + String status; + @Column + String service; - @Column - private String instId; + @Column + private String instId; - private String instName; + private String instName; - public Synchronizers() { - } + public Synchronizers() { + } - public Synchronizers(String id) { - this.id = id; - } + public Synchronizers(String id) { + this.id = id; + } - public Integer getSyncStartTime() { - return syncStartTime; - } + public Integer getSyncStartTime() { + return syncStartTime; + } - public void setSyncStartTime(Integer syncStartTime) { - this.syncStartTime = syncStartTime; - } + public void setSyncStartTime(Integer syncStartTime) { + this.syncStartTime = syncStartTime; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getSourceType() { - return sourceType; - } + public String getSourceType() { + return sourceType; + } - public void setSourceType(String sourceType) { - this.sourceType = sourceType; - } + public void setSourceType(String sourceType) { + this.sourceType = sourceType; + } - public String getResumeTime() { - return resumeTime; - } + public String getResumeTime() { + return resumeTime; + } - public void setResumeTime(String resumeTime) { - this.resumeTime = resumeTime; - } + public void setResumeTime(String resumeTime) { + this.resumeTime = resumeTime; + } - public String getSuspendTime() { - return suspendTime; - } + public String getSuspendTime() { + return suspendTime; + } - public void setSuspendTime(String suspendTime) { - this.suspendTime = suspendTime; - } + public void setSuspendTime(String suspendTime) { + this.suspendTime = suspendTime; + } - public String getScheduler() { - return scheduler; - } + public String getScheduler() { + return scheduler; + } - public void setScheduler(String scheduler) { - this.scheduler = scheduler; - } + public void setScheduler(String scheduler) { + this.scheduler = scheduler; + } - public String getProviderUrl() { - return providerUrl; - } + public String getProviderUrl() { + return providerUrl; + } - public void setProviderUrl(String providerUrl) { - this.providerUrl = providerUrl; - } + public void setProviderUrl(String providerUrl) { + this.providerUrl = providerUrl; + } - public String getDriverClass() { - return driverClass; - } + public String getDriverClass() { + return driverClass; + } - public void setDriverClass(String driverClass) { - this.driverClass = driverClass; - } + public void setDriverClass(String driverClass) { + this.driverClass = driverClass; + } - public String getPrincipal() { - return principal; - } + public String getPrincipal() { + return principal; + } - public void setPrincipal(String principal) { - this.principal = principal; - } + public void setPrincipal(String principal) { + this.principal = principal; + } - public String getCredentials() { - return credentials; - } + public String getCredentials() { + return credentials; + } - public void setCredentials(String credentials) { - this.credentials = credentials; - } + public void setCredentials(String credentials) { + this.credentials = credentials; + } - public String getUserBasedn() { - return userBasedn; - } + public String getUserBasedn() { + return userBasedn; + } - public void setUserBasedn(String userBasedn) { - this.userBasedn = userBasedn; - } + public void setUserBasedn(String userBasedn) { + this.userBasedn = userBasedn; + } - public String getUserFilters() { - return userFilters; - } + public String getUserFilters() { + return userFilters; + } - public void setUserFilters(String userFilters) { - this.userFilters = userFilters; - } + public void setUserFilters(String userFilters) { + this.userFilters = userFilters; + } - public String getOrgBasedn() { - return orgBasedn; - } + public String getOrgBasedn() { + return orgBasedn; + } - public void setOrgBasedn(String orgBasedn) { - this.orgBasedn = orgBasedn; - } + public void setOrgBasedn(String orgBasedn) { + this.orgBasedn = orgBasedn; + } - public String getOrgFilters() { - return orgFilters; - } + public String getOrgFilters() { + return orgFilters; + } - public void setOrgFilters(String orgFilters) { - this.orgFilters = orgFilters; - } + public void setOrgFilters(String orgFilters) { + this.orgFilters = orgFilters; + } - public String getMsadDomain() { - return msadDomain; - } + public String getMsadDomain() { + return msadDomain; + } - public void setMsadDomain(String msadDomain) { - this.msadDomain = msadDomain; - } + public void setMsadDomain(String msadDomain) { + this.msadDomain = msadDomain; + } - public String getSslSwitch() { - return sslSwitch; - } + public String getSslSwitch() { + return sslSwitch; + } - public void setSslSwitch(String sslSwitch) { - this.sslSwitch = sslSwitch; - } + public void setSslSwitch(String sslSwitch) { + this.sslSwitch = sslSwitch; + } - public String getTrustStore() { - return trustStore; - } + public String getTrustStore() { + return trustStore; + } - public void setTrustStore(String trustStore) { - this.trustStore = trustStore; - } + public void setTrustStore(String trustStore) { + this.trustStore = trustStore; + } - public String getTrustStorePassword() { - return trustStorePassword; - } + public String getTrustStorePassword() { + return trustStorePassword; + } - public void setTrustStorePassword(String trustStorePassword) { - this.trustStorePassword = trustStorePassword; - } + public void setTrustStorePassword(String trustStorePassword) { + this.trustStorePassword = trustStorePassword; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public String getCreatedBy() { - return createdBy; - } + public String getCreatedBy() { + return createdBy; + } - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } - public String getModifiedBy() { - return modifiedBy; - } + public String getModifiedBy() { + return modifiedBy; + } - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } - public Date getCreatedDate() { - return createdDate; - } + public Date getCreatedDate() { + return createdDate; + } - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } - public Date getModifiedDate() { - return modifiedDate; - } + public Date getModifiedDate() { + return modifiedDate; + } - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } - public String getStatus() { - return status; - } + public String getStatus() { + return status; + } - public void setStatus(String status) { - this.status = status; - } + public void setStatus(String status) { + this.status = status; + } - public String getService() { - return service; - } + public String getService() { + return service; + } - public void setService(String service) { - this.service = service; - } + public void setService(String service) { + this.service = service; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Synchronizers [id="); - builder.append(id); - builder.append(", name="); - builder.append(name); - builder.append(", sourceType="); - builder.append(sourceType); - builder.append(", resumeTime="); - builder.append(resumeTime); - builder.append(", suspendTime="); - builder.append(suspendTime); - builder.append(", scheduler="); - builder.append(scheduler); - builder.append(", syncStartTime="); - builder.append(syncStartTime); - builder.append(", providerUrl="); - builder.append(providerUrl); - builder.append(", driverClass="); - builder.append(driverClass); - builder.append(", principal="); - builder.append(principal); - builder.append(", credentials="); - builder.append(credentials); - builder.append(", userBasedn="); - builder.append(userBasedn); - builder.append(", userFilters="); - builder.append(userFilters); - builder.append(", orgBasedn="); - builder.append(orgBasedn); - builder.append(", orgFilters="); - builder.append(orgFilters); - builder.append(", msadDomain="); - builder.append(msadDomain); - builder.append(", sslSwitch="); - builder.append(sslSwitch); - builder.append(", trustStore="); - builder.append(trustStore); - builder.append(", trustStorePassword="); - builder.append(trustStorePassword); - builder.append(", description="); - builder.append(description); - builder.append(", createdBy="); - builder.append(createdBy); - builder.append(", createdDate="); - builder.append(createdDate); - builder.append(", modifiedBy="); - builder.append(modifiedBy); - builder.append(", modifiedDate="); - builder.append(modifiedDate); - builder.append(", status="); - builder.append(status); - builder.append(", service="); - builder.append(service); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Synchronizers [id="); + builder.append(id); + builder.append(", name="); + builder.append(name); + builder.append(", sourceType="); + builder.append(sourceType); + builder.append(", resumeTime="); + builder.append(resumeTime); + builder.append(", suspendTime="); + builder.append(suspendTime); + builder.append(", scheduler="); + builder.append(scheduler); + builder.append(", syncStartTime="); + builder.append(syncStartTime); + builder.append(", providerUrl="); + builder.append(providerUrl); + builder.append(", driverClass="); + builder.append(driverClass); + builder.append(", principal="); + builder.append(principal); + builder.append(", credentials="); + builder.append(credentials); + builder.append(", userBasedn="); + builder.append(userBasedn); + builder.append(", userFilters="); + builder.append(userFilters); + builder.append(", orgBasedn="); + builder.append(orgBasedn); + builder.append(", orgFilters="); + builder.append(orgFilters); + builder.append(", msadDomain="); + builder.append(msadDomain); + builder.append(", sslSwitch="); + builder.append(sslSwitch); + builder.append(", trustStore="); + builder.append(trustStore); + builder.append(", trustStorePassword="); + builder.append(trustStorePassword); + builder.append(", description="); + builder.append(description); + builder.append(", createdBy="); + builder.append(createdBy); + builder.append(", createdDate="); + builder.append(createdDate); + builder.append(", modifiedBy="); + builder.append(modifiedBy); + builder.append(", modifiedDate="); + builder.append(modifiedDate); + builder.append(", status="); + builder.append(status); + builder.append(", service="); + builder.append(service); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/Apps.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/Apps.java index ba7802e78..28852925a 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/Apps.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/Apps.java @@ -43,9 +43,9 @@ public class Apps extends JpaEntity implements Serializable { public static final class CREDENTIALS { public static final String USER_DEFINED = "user_defined"; - public static final String SHARED = "shared"; - public static final String SYSTEM = "system"; - public static final String NONE = "none"; + public static final String SHARED = "shared"; + public static final String SYSTEM = "system"; + public static final String NONE = "none"; } public static final class VISIBLE { @@ -147,9 +147,9 @@ public class Apps extends JpaEntity implements Serializable { @Column private String adapter; - @Column - private String frequently; - + @Column + private String frequently; + @Column protected int sortIndex; @Column @@ -164,10 +164,10 @@ public class Apps extends JpaEntity implements Serializable { protected Date modifiedDate; @Column protected String description; - @Column - private String instId; - - private String instName; + @Column + private String instId; + + private String instName; protected String loginDateTime; @@ -187,18 +187,18 @@ public class Apps extends JpaEntity implements Serializable { } public String getAppName() { - return appName; - } + return appName; + } - public void setAppName(String appName) { - this.appName = appName; - } + public void setAppName(String appName) { + this.appName = appName; + } - /** + /** * @return the loginUrl */ public String getLoginUrl() { @@ -256,14 +256,14 @@ public class Apps extends JpaEntity implements Serializable { public String getFrequently() { - return frequently; - } + return frequently; + } - public void setFrequently(String frequently) { - this.frequently = frequently; - } + public void setFrequently(String frequently) { + this.frequently = frequently; + } - /** + /** * @return the icon */ public byte[] getIcon() { @@ -286,28 +286,28 @@ public class Apps extends JpaEntity implements Serializable { } public String getIconBase64() { - return iconBase64; - } + return iconBase64; + } - public void setIconBase64(String iconBase64) { - this.iconBase64 = iconBase64; - } - - public void transIconBase64() { - if(icon !=null) { - this.iconBase64 = Base64Utils.encodeImage(icon); - } - } + public void setIconBase64(String iconBase64) { + this.iconBase64 = iconBase64; + } + + public void transIconBase64() { + if(icon !=null) { + this.iconBase64 = Base64Utils.encodeImage(icon); + } + } public String getIconId() { - return iconId; - } + return iconId; + } - public void setIconId(String iconId) { - this.iconId = iconId; - } + public void setIconId(String iconId) { + this.iconId = iconId; + } - /** + /** * @return the description */ public String getDescription() { @@ -521,42 +521,42 @@ public class Apps extends JpaEntity implements Serializable { /** - * @return the createdDate - */ - public Date getCreatedDate() { - return createdDate; - } + * @return the createdDate + */ + public Date getCreatedDate() { + return createdDate; + } - /** - * @param createdDate the createdDate to set - */ - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } + /** + * @param createdDate the createdDate to set + */ + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } - /** - * @return the modifiedDate - */ - public Date getModifiedDate() { - return modifiedDate; - } + /** + * @return the modifiedDate + */ + public Date getModifiedDate() { + return modifiedDate; + } - /** - * @param modifiedDate the modifiedDate to set - */ - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } + /** + * @param modifiedDate the modifiedDate to set + */ + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } - public int getStatus() { + public int getStatus() { return status; } @@ -599,112 +599,112 @@ public class Apps extends JpaEntity implements Serializable { } public String getAdapterId() { - return adapterId; - } + return adapterId; + } - public void setAdapterId(String adapterId) { - this.adapterId = adapterId; - } + public void setAdapterId(String adapterId) { + this.adapterId = adapterId; + } - public String getAdapterName() { - return adapterName; - } + public String getAdapterName() { + return adapterName; + } - public void setAdapterName(String adapterName) { - this.adapterName = adapterName; - } + public void setAdapterName(String adapterName) { + this.adapterName = adapterName; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Apps [id="); - builder.append(id); - builder.append(", appName="); - builder.append(appName); - builder.append(", loginUrl="); - builder.append(loginUrl); - builder.append(", category="); - builder.append(category); - builder.append(", protocol="); - builder.append(protocol); - builder.append(", secret="); - builder.append(secret); - builder.append(", iconId="); - builder.append(iconId); - builder.append(", visible="); - builder.append(visible); - builder.append(", inducer="); - builder.append(inducer); - builder.append(", vendor="); - builder.append(vendor); - builder.append(", vendorUrl="); - builder.append(vendorUrl); - builder.append(", credential="); - builder.append(credential); - builder.append(", sharedUsername="); - builder.append(sharedUsername); - builder.append(", sharedPassword="); - builder.append(sharedPassword); - builder.append(", systemUserAttr="); - builder.append(systemUserAttr); - builder.append(", principal="); - builder.append(principal); - builder.append(", credentials="); - builder.append(credentials); - builder.append(", logoutUrl="); - builder.append(logoutUrl); - builder.append(", logoutType="); - builder.append(logoutType); - builder.append(", isExtendAttr="); - builder.append(isExtendAttr); - builder.append(", extendAttr="); - builder.append(extendAttr); - builder.append(", userPropertys="); - builder.append(userPropertys); - builder.append(", isSignature="); - builder.append(isSignature); - builder.append(", isAdapter="); - builder.append(isAdapter); - builder.append(", adapterId="); - builder.append(adapterId); - builder.append(", adapterName="); - builder.append(adapterName); - builder.append(", adapter="); - builder.append(adapter); - builder.append(", sortIndex="); - builder.append(sortIndex); - builder.append(", status="); - builder.append(status); - builder.append(", createdBy="); - builder.append(createdBy); - builder.append(", createdDate="); - builder.append(createdDate); - builder.append(", modifiedBy="); - builder.append(modifiedBy); - builder.append(", modifiedDate="); - builder.append(modifiedDate); - builder.append(", description="); - builder.append(description); - builder.append(", loginDateTime="); - builder.append(loginDateTime); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Apps [id="); + builder.append(id); + builder.append(", appName="); + builder.append(appName); + builder.append(", loginUrl="); + builder.append(loginUrl); + builder.append(", category="); + builder.append(category); + builder.append(", protocol="); + builder.append(protocol); + builder.append(", secret="); + builder.append(secret); + builder.append(", iconId="); + builder.append(iconId); + builder.append(", visible="); + builder.append(visible); + builder.append(", inducer="); + builder.append(inducer); + builder.append(", vendor="); + builder.append(vendor); + builder.append(", vendorUrl="); + builder.append(vendorUrl); + builder.append(", credential="); + builder.append(credential); + builder.append(", sharedUsername="); + builder.append(sharedUsername); + builder.append(", sharedPassword="); + builder.append(sharedPassword); + builder.append(", systemUserAttr="); + builder.append(systemUserAttr); + builder.append(", principal="); + builder.append(principal); + builder.append(", credentials="); + builder.append(credentials); + builder.append(", logoutUrl="); + builder.append(logoutUrl); + builder.append(", logoutType="); + builder.append(logoutType); + builder.append(", isExtendAttr="); + builder.append(isExtendAttr); + builder.append(", extendAttr="); + builder.append(extendAttr); + builder.append(", userPropertys="); + builder.append(userPropertys); + builder.append(", isSignature="); + builder.append(isSignature); + builder.append(", isAdapter="); + builder.append(isAdapter); + builder.append(", adapterId="); + builder.append(adapterId); + builder.append(", adapterName="); + builder.append(adapterName); + builder.append(", adapter="); + builder.append(adapter); + builder.append(", sortIndex="); + builder.append(sortIndex); + builder.append(", status="); + builder.append(status); + builder.append(", createdBy="); + builder.append(createdBy); + builder.append(", createdDate="); + builder.append(createdDate); + builder.append(", modifiedBy="); + builder.append(modifiedBy); + builder.append(", modifiedDate="); + builder.append(modifiedDate); + builder.append(", description="); + builder.append(description); + builder.append(", loginDateTime="); + builder.append(loginDateTime); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsAdapters.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsAdapters.java index 7e58b83ce..86f22b62b 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsAdapters.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsAdapters.java @@ -70,131 +70,131 @@ public class AppsAdapters extends JpaEntity implements Serializable { } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getProtocol() { - return protocol; - } + public String getProtocol() { + return protocol; + } - public void setProtocol(String protocol) { - this.protocol = protocol; - } + public void setProtocol(String protocol) { + this.protocol = protocol; + } - public String getAdapter() { - return adapter; - } + public String getAdapter() { + return adapter; + } - public void setAdapter(String adapter) { - this.adapter = adapter; - } + public void setAdapter(String adapter) { + this.adapter = adapter; + } - public int getSortIndex() { - return sortIndex; - } + public int getSortIndex() { + return sortIndex; + } - public void setSortIndex(int sortIndex) { - this.sortIndex = sortIndex; - } + public void setSortIndex(int sortIndex) { + this.sortIndex = sortIndex; + } - public String getCreatedBy() { - return createdBy; - } + public String getCreatedBy() { + return createdBy; + } - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } - public String getCreatedDate() { - return createdDate; - } + public String getCreatedDate() { + return createdDate; + } - public void setCreatedDate(String createdDate) { - this.createdDate = createdDate; - } + public void setCreatedDate(String createdDate) { + this.createdDate = createdDate; + } - public String getModifiedBy() { - return modifiedBy; - } + public String getModifiedBy() { + return modifiedBy; + } - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } - public String getModifiedDate() { - return modifiedDate; - } + public String getModifiedDate() { + return modifiedDate; + } - public void setModifiedDate(String modifiedDate) { - this.modifiedDate = modifiedDate; - } + public void setModifiedDate(String modifiedDate) { + this.modifiedDate = modifiedDate; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("AppsAdapters [id="); - builder.append(id); - builder.append(", name="); - builder.append(name); - builder.append(", protocol="); - builder.append(protocol); - builder.append(", adapter="); - builder.append(adapter); - builder.append(", sortIndex="); - builder.append(sortIndex); - builder.append(", createdBy="); - builder.append(createdBy); - builder.append(", createdDate="); - builder.append(createdDate); - builder.append(", modifiedBy="); - builder.append(modifiedBy); - builder.append(", modifiedDate="); - builder.append(modifiedDate); - builder.append(", description="); - builder.append(description); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("AppsAdapters [id="); + builder.append(id); + builder.append(", name="); + builder.append(name); + builder.append(", protocol="); + builder.append(protocol); + builder.append(", adapter="); + builder.append(adapter); + builder.append(", sortIndex="); + builder.append(sortIndex); + builder.append(", createdBy="); + builder.append(createdBy); + builder.append(", createdDate="); + builder.append(createdDate); + builder.append(", modifiedBy="); + builder.append(modifiedBy); + builder.append(", modifiedDate="); + builder.append(modifiedDate); + builder.append(", description="); + builder.append(description); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsCasDetails.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsCasDetails.java index 0f6a91d79..ac7908312 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsCasDetails.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsCasDetails.java @@ -44,12 +44,12 @@ public class AppsCasDetails extends Apps implements Serializable { private Integer expires; @Column private String callbackUrl; - @Column - private String instId; - @Column - private String casUser; + @Column + private String instId; + @Column + private String casUser; - private String instName; + private String instName; /** * @return the service @@ -75,55 +75,55 @@ public class AppsCasDetails extends Apps implements Serializable { - public Integer getExpires() { - return expires; - } + public Integer getExpires() { + return expires; + } - public void setExpires(Integer expires) { - this.expires = expires; - } + public void setExpires(Integer expires) { + this.expires = expires; + } - public String getCasUser() { - return casUser; - } + public String getCasUser() { + return casUser; + } - public void setCasUser(String casUser) { - this.casUser = casUser; - } + public void setCasUser(String casUser) { + this.casUser = casUser; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("AppsCasDetails [id="); - builder.append(id); - builder.append(", service="); - builder.append(service); - builder.append(", expires="); - builder.append(expires); - builder.append(", callbackUrl="); - builder.append(callbackUrl); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("AppsCasDetails [id="); + builder.append(id); + builder.append(", service="); + builder.append(service); + builder.append(", expires="); + builder.append(expires); + builder.append(", callbackUrl="); + builder.append(callbackUrl); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsExtendApiDetails.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsExtendApiDetails.java index 5ccb35c45..b7cbbe87f 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsExtendApiDetails.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsExtendApiDetails.java @@ -26,10 +26,10 @@ import jakarta.persistence.Table; @Table(name = "MXK_APPS_EXTENDAPI_DETAILS") public class AppsExtendApiDetails extends Apps implements Serializable { - /** - * - */ - private static final long serialVersionUID = -4272290765948322084L; + /** + * + */ + private static final long serialVersionUID = -4272290765948322084L; - + } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsFormBasedDetails.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsFormBasedDetails.java index e25fb8d9b..0097202c7 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsFormBasedDetails.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsFormBasedDetails.java @@ -32,104 +32,104 @@ import jakarta.persistence.Table; @Entity @Table(name = "MXK_APPS_FORM_BASED_DETAILS") public class AppsFormBasedDetails extends Apps implements Serializable { - /** - * - */ - private static final long serialVersionUID = 563313247706861431L; - @Id - @Column - @GeneratedValue - protected String id; - - @Column - private String redirectUri; - @Column - private String usernameMapping; - @Column - private String passwordMapping; - @Column - private String passwordAlgorithm; - @Column - private String authorizeView; - @Column - private String instId; + /** + * + */ + private static final long serialVersionUID = 563313247706861431L; + @Id + @Column + @GeneratedValue + protected String id; + + @Column + private String redirectUri; + @Column + private String usernameMapping; + @Column + private String passwordMapping; + @Column + private String passwordAlgorithm; + @Column + private String authorizeView; + @Column + private String instId; - private String instName; + private String instName; - /** - * - */ - public AppsFormBasedDetails() { - - } + /** + * + */ + public AppsFormBasedDetails() { + + } - /** - * @return the redirectUri - */ - public String getRedirectUri() { - return redirectUri; - } + /** + * @return the redirectUri + */ + public String getRedirectUri() { + return redirectUri; + } - /** - * @param redirectUri the redirectUri to set - */ - public void setRedirectUri(String redirectUri) { - this.redirectUri = redirectUri; - } + /** + * @param redirectUri the redirectUri to set + */ + public void setRedirectUri(String redirectUri) { + this.redirectUri = redirectUri; + } - /** - * @return the usernameMapping - */ - public String getUsernameMapping() { - return usernameMapping; - } + /** + * @return the usernameMapping + */ + public String getUsernameMapping() { + return usernameMapping; + } - /** - * @param usernameMapping the usernameMapping to set - */ - public void setUsernameMapping(String usernameMapping) { - this.usernameMapping = usernameMapping; - } + /** + * @param usernameMapping the usernameMapping to set + */ + public void setUsernameMapping(String usernameMapping) { + this.usernameMapping = usernameMapping; + } - /** - * @return the passwordMapping - */ - public String getPasswordMapping() { - return passwordMapping; - } + /** + * @return the passwordMapping + */ + public String getPasswordMapping() { + return passwordMapping; + } - /** - * @param passwordMapping the passwordMapping to set - */ - public void setPasswordMapping(String passwordMapping) { - this.passwordMapping = passwordMapping; - } + /** + * @param passwordMapping the passwordMapping to set + */ + public void setPasswordMapping(String passwordMapping) { + this.passwordMapping = passwordMapping; + } - public String getAuthorizeView() { - return authorizeView; - } + public String getAuthorizeView() { + return authorizeView; + } - public void setAuthorizeView(String authorizeView) { - this.authorizeView = authorizeView; - } + public void setAuthorizeView(String authorizeView) { + this.authorizeView = authorizeView; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getPasswordAlgorithm() { + public String getPasswordAlgorithm() { return passwordAlgorithm; } @@ -140,46 +140,46 @@ public class AppsFormBasedDetails extends Apps implements Serializable { public String getInstId() { - return instId; - } + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("AppsFormBasedDetails [id="); - builder.append(id); - builder.append(", redirectUri="); - builder.append(redirectUri); - builder.append(", usernameMapping="); - builder.append(usernameMapping); - builder.append(", passwordMapping="); - builder.append(passwordMapping); - builder.append(", passwordAlgorithm="); - builder.append(passwordAlgorithm); - builder.append(", authorizeView="); - builder.append(authorizeView); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("AppsFormBasedDetails [id="); + builder.append(id); + builder.append(", redirectUri="); + builder.append(redirectUri); + builder.append(", usernameMapping="); + builder.append(usernameMapping); + builder.append(", passwordMapping="); + builder.append(passwordMapping); + builder.append(", passwordAlgorithm="); + builder.append(passwordAlgorithm); + builder.append(", authorizeView="); + builder.append(authorizeView); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsJwtDetails.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsJwtDetails.java index e7b9eefad..dcb9bd091 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsJwtDetails.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsJwtDetails.java @@ -36,54 +36,54 @@ import jakarta.persistence.Table; @Table(name = "MXK_APPS_JWT_DETAILS") public class AppsJwtDetails extends Apps implements Serializable { - /** - * - */ - private static final long serialVersionUID = -1717427271305620545L; + /** + * + */ + private static final long serialVersionUID = -1717427271305620545L; - @Id - @Column - @GeneratedValue - protected String id; - - @Column - private String subject; - - @Column - private String issuer; - - @Column - private String audience; - /** - * - */ - @Column - private String redirectUri; - // - @Column - private String tokenType; - @Column - private String jwtName; - @Column - private String algorithm; - @Column - private String algorithmKey; - @Column - private String encryptionMethod; - @Column - private String signature; - @Column - private String signatureKey; - @Column - private Integer expires; - @Column - private String instId; + @Id + @Column + @GeneratedValue + protected String id; + + @Column + private String subject; + + @Column + private String issuer; + + @Column + private String audience; + /** + * + */ + @Column + private String redirectUri; + // + @Column + private String tokenType; + @Column + private String jwtName; + @Column + private String algorithm; + @Column + private String algorithmKey; + @Column + private String encryptionMethod; + @Column + private String signature; + @Column + private String signatureKey; + @Column + private Integer expires; + @Column + private String instId; - private String instName; - - public AppsJwtDetails() { - super(); - } + private String instName; + + public AppsJwtDetails() { + super(); + } public String getId() { @@ -97,36 +97,36 @@ public class AppsJwtDetails extends Apps implements Serializable { public String getSubject() { - return subject; - } + return subject; + } - public void setSubject(String subject) { - this.subject = subject; - } + public void setSubject(String subject) { + this.subject = subject; + } - public String getIssuer() { - return issuer; - } + public String getIssuer() { + return issuer; + } - public void setIssuer(String issuer) { - this.issuer = issuer; - } + public void setIssuer(String issuer) { + this.issuer = issuer; + } - public String getAudience() { - return audience; - } + public String getAudience() { + return audience; + } - public void setAudience(String audience) { - this.audience = audience; - } + public void setAudience(String audience) { + this.audience = audience; + } - public String getRedirectUri() { + public String getRedirectUri() { return redirectUri; } @@ -149,16 +149,16 @@ public class AppsJwtDetails extends Apps implements Serializable { public String getJwtName() { - return jwtName; - } + return jwtName; + } - public void setJwtName(String jwtName) { - this.jwtName = jwtName; - } + public void setJwtName(String jwtName) { + this.jwtName = jwtName; + } - public String getAlgorithm() { + public String getAlgorithm() { return algorithm; } @@ -179,36 +179,36 @@ public class AppsJwtDetails extends Apps implements Serializable { public String getEncryptionMethod() { - return encryptionMethod; - } + return encryptionMethod; + } - public void setEncryptionMethod(String encryptionMethod) { - this.encryptionMethod = encryptionMethod; - } + public void setEncryptionMethod(String encryptionMethod) { + this.encryptionMethod = encryptionMethod; + } - public String getSignature() { - return signature; - } + public String getSignature() { + return signature; + } - public void setSignature(String signature) { - this.signature = signature; - } + public void setSignature(String signature) { + this.signature = signature; + } - public String getSignatureKey() { - return signatureKey; - } + public String getSignatureKey() { + return signatureKey; + } - public void setSignatureKey(String signatureKey) { - this.signatureKey = signatureKey; - } + public void setSignatureKey(String signatureKey) { + this.signatureKey = signatureKey; + } - public Integer getExpires() { + public Integer getExpires() { return expires; } @@ -219,48 +219,48 @@ public class AppsJwtDetails extends Apps implements Serializable { public String getInstId() { - return instId; - } + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("AppsJwtDetails [id="); - builder.append(id); - builder.append(", redirectUri="); - builder.append(redirectUri); - builder.append(", tokenType="); - builder.append(tokenType); - builder.append(", jwtName="); - builder.append(jwtName); - builder.append(", algorithm="); - builder.append(algorithm); - builder.append(", algorithmKey="); - builder.append(algorithmKey); - builder.append(", expires="); - builder.append(expires); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("AppsJwtDetails [id="); + builder.append(id); + builder.append(", redirectUri="); + builder.append(redirectUri); + builder.append(", tokenType="); + builder.append(tokenType); + builder.append(", jwtName="); + builder.append(jwtName); + builder.append(", algorithm="); + builder.append(algorithm); + builder.append(", algorithmKey="); + builder.append(algorithmKey); + builder.append(", expires="); + builder.append(expires); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsOAuth20Details.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsOAuth20Details.java index 2114aa861..bb751f1db 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsOAuth20Details.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsOAuth20Details.java @@ -56,29 +56,29 @@ public class AppsOAuth20Details extends Apps implements Serializable { // for OpenID Connect - private String issuer; - - private String audience; - - private String algorithm; - - private String algorithmKey; - - private String encryptionMethod; - - private String signature; - - private String signatureKey; - - private String subject; - - private String userInfoResponse; + private String issuer; + + private String audience; + + private String algorithm; + + private String algorithmKey; + + private String encryptionMethod; + + private String signature; + + private String signatureKey; + + private String subject; + + private String userInfoResponse; private String pkce; - private String instId; + private String instId; - private String instName; + private String instName; /** * */ @@ -182,22 +182,22 @@ public class AppsOAuth20Details extends Apps implements Serializable { } public String getSubject() { - return subject; - } + return subject; + } - public void setSubject(String subject) { - this.subject = subject; - } + public void setSubject(String subject) { + this.subject = subject; + } - public String getUserInfoResponse() { - return userInfoResponse; - } + public String getUserInfoResponse() { + return userInfoResponse; + } - public void setUserInfoResponse(String userInfoResponse) { - this.userInfoResponse = userInfoResponse; - } + public void setUserInfoResponse(String userInfoResponse) { + this.userInfoResponse = userInfoResponse; + } - /** + /** * @param clientId the clientId to set */ public void setClientId(String clientId) { @@ -318,80 +318,80 @@ public class AppsOAuth20Details extends Apps implements Serializable { public String getIssuer() { - return issuer; - } + return issuer; + } - public void setIssuer(String issuer) { - this.issuer = issuer; - } + public void setIssuer(String issuer) { + this.issuer = issuer; + } - public String getAudience() { - return audience; - } + public String getAudience() { + return audience; + } - public void setAudience(String audience) { - this.audience = audience; - } + public void setAudience(String audience) { + this.audience = audience; + } - public String getAlgorithm() { - return algorithm; - } + public String getAlgorithm() { + return algorithm; + } - public void setAlgorithm(String algorithm) { - this.algorithm = algorithm; - } + public void setAlgorithm(String algorithm) { + this.algorithm = algorithm; + } - public String getAlgorithmKey() { - return algorithmKey; - } + public String getAlgorithmKey() { + return algorithmKey; + } - public void setAlgorithmKey(String algorithmKey) { - this.algorithmKey = algorithmKey; - } + public void setAlgorithmKey(String algorithmKey) { + this.algorithmKey = algorithmKey; + } - public String getEncryptionMethod() { - return encryptionMethod; - } + public String getEncryptionMethod() { + return encryptionMethod; + } - public void setEncryptionMethod(String encryptionMethod) { - this.encryptionMethod = encryptionMethod; - } + public void setEncryptionMethod(String encryptionMethod) { + this.encryptionMethod = encryptionMethod; + } - public String getSignature() { - return signature; - } + public String getSignature() { + return signature; + } - public void setSignature(String signature) { - this.signature = signature; - } + public void setSignature(String signature) { + this.signature = signature; + } - public String getSignatureKey() { - return signatureKey; - } + public String getSignatureKey() { + return signatureKey; + } - public void setSignatureKey(String signatureKey) { - this.signatureKey = signatureKey; - } + public void setSignatureKey(String signatureKey) { + this.signatureKey = signatureKey; + } public String getInstId() { - return instId; - } + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - public BaseClientDetails clientDetailsRowMapper() { + public BaseClientDetails clientDetailsRowMapper() { BaseClientDetails baseClientDetails = new BaseClientDetails(this.getId(), this.getId(), this.getScope(), this.getAuthorizedGrantTypes(), "ROLE_CLIENT, ROLE_TRUSTED_CLIENT", this.getRegisteredRedirectUris()); baseClientDetails.setAccessTokenValiditySeconds(this.getAccessTokenValiditySeconds()); @@ -420,50 +420,50 @@ public class AppsOAuth20Details extends Apps implements Serializable { } @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("AppsOAuth20Details [clientId="); - builder.append(clientId); - builder.append(", clientSecret="); - builder.append(clientSecret); - builder.append(", scope="); - builder.append(scope); - builder.append(", resourceIds="); - builder.append(resourceIds); - builder.append(", authorizedGrantTypes="); - builder.append(authorizedGrantTypes); - builder.append(", registeredRedirectUris="); - builder.append(registeredRedirectUris); - builder.append(", authorities="); - builder.append(authorities); - builder.append(", accessTokenValiditySeconds="); - builder.append(accessTokenValiditySeconds); - builder.append(", refreshTokenValiditySeconds="); - builder.append(refreshTokenValiditySeconds); - builder.append(", approvalPrompt="); - builder.append(approvalPrompt); - builder.append(", issuer="); - builder.append(issuer); - builder.append(", audience="); - builder.append(audience); - builder.append(", algorithm="); - builder.append(algorithm); - builder.append(", algorithmKey="); - builder.append(algorithmKey); - builder.append(", encryptionMethod="); - builder.append(encryptionMethod); - builder.append(", signature="); - builder.append(signature); - builder.append(", signatureKey="); - builder.append(signatureKey); - builder.append(", pkce="); - builder.append(pkce); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append("]"); - return builder.toString(); - } + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("AppsOAuth20Details [clientId="); + builder.append(clientId); + builder.append(", clientSecret="); + builder.append(clientSecret); + builder.append(", scope="); + builder.append(scope); + builder.append(", resourceIds="); + builder.append(resourceIds); + builder.append(", authorizedGrantTypes="); + builder.append(authorizedGrantTypes); + builder.append(", registeredRedirectUris="); + builder.append(registeredRedirectUris); + builder.append(", authorities="); + builder.append(authorities); + builder.append(", accessTokenValiditySeconds="); + builder.append(accessTokenValiditySeconds); + builder.append(", refreshTokenValiditySeconds="); + builder.append(refreshTokenValiditySeconds); + builder.append(", approvalPrompt="); + builder.append(approvalPrompt); + builder.append(", issuer="); + builder.append(issuer); + builder.append(", audience="); + builder.append(audience); + builder.append(", algorithm="); + builder.append(algorithm); + builder.append(", algorithmKey="); + builder.append(algorithmKey); + builder.append(", encryptionMethod="); + builder.append(encryptionMethod); + builder.append(", signature="); + builder.append(signature); + builder.append(", signatureKey="); + builder.append(signatureKey); + builder.append(", pkce="); + builder.append(pkce); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsSAML20Details.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsSAML20Details.java index c94ef985d..2bfa1dc38 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsSAML20Details.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsSAML20Details.java @@ -100,11 +100,11 @@ public class AppsSAML20Details extends Apps implements Serializable { @Column private String nameIdSuffix; - @Column - private String instId; + @Column + private String instId; - private String instName; - + private String instName; + public static final class BindingType { public static final String Redirect_Post = "Redirect-Post"; public static final String Post_Post = "Post-Post"; @@ -295,14 +295,14 @@ public class AppsSAML20Details extends Apps implements Serializable { } public String getMetaFileId() { - return metaFileId; - } + return metaFileId; + } - public void setMetaFileId(String metaFileId) { - this.metaFileId = metaFileId; - } + public void setMetaFileId(String metaFileId) { + this.metaFileId = metaFileId; + } - public String getBinding() { + public String getBinding() { return binding; } @@ -359,22 +359,22 @@ public class AppsSAML20Details extends Apps implements Serializable { } public String getInstId() { - return instId; - } + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override + @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("AppsSAML20Details [id="); diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsTokenBasedDetails.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsTokenBasedDetails.java index f1cda3f33..ec1debcf7 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsTokenBasedDetails.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/AppsTokenBasedDetails.java @@ -35,39 +35,39 @@ import jakarta.persistence.Table; @Table(name = "MXK_APPS_TOKEN_BASED_DETAILS") public class AppsTokenBasedDetails extends Apps implements Serializable { - /** - * - */ - private static final long serialVersionUID = -1717427271305620545L; + /** + * + */ + private static final long serialVersionUID = -1717427271305620545L; - @Id - @Column - @GeneratedValue - protected String id; - /** - * - */ - @Column - private String redirectUri; - // - @Column - private String tokenType; - @Column - private String cookieName; - @Column - private String algorithm; - @Column - private String algorithmKey; - @Column - private Integer expires; - @Column - private String instId; + @Id + @Column + @GeneratedValue + protected String id; + /** + * + */ + @Column + private String redirectUri; + // + @Column + private String tokenType; + @Column + private String cookieName; + @Column + private String algorithm; + @Column + private String algorithmKey; + @Column + private Integer expires; + @Column + private String instId; - private String instName; - - public AppsTokenBasedDetails() { - super(); - } + private String instName; + + public AppsTokenBasedDetails() { + super(); + } public String getId() { @@ -141,26 +141,26 @@ public class AppsTokenBasedDetails extends Apps implements Serializable { public String getInstId() { - return instId; - } + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override + @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("AppsTokenBasedDetails [id="); diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/oauth2/provider/ClientDetails.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/oauth2/provider/ClientDetails.java index 0fa6719c4..e4eecba95 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/oauth2/provider/ClientDetails.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/oauth2/provider/ClientDetails.java @@ -31,132 +31,132 @@ import org.springframework.security.core.GrantedAuthority; */ public interface ClientDetails extends Serializable { - /** - * The client id. - * - * @return The client id. - */ - String getClientId(); + /** + * The client id. + * + * @return The client id. + */ + String getClientId(); - /** - * The resources that this client can access. Can be ignored by callers if empty. - * - * @return The resources of this client. - */ - Set getResourceIds(); + /** + * The resources that this client can access. Can be ignored by callers if empty. + * + * @return The resources of this client. + */ + Set getResourceIds(); - /** - * Whether a secret is required to authenticate this client. - * - * @return Whether a secret is required to authenticate this client. - */ - boolean isSecretRequired(); + /** + * Whether a secret is required to authenticate this client. + * + * @return Whether a secret is required to authenticate this client. + */ + boolean isSecretRequired(); - /** - * The client secret. Ignored if the {@link #isSecretRequired() secret isn't required}. - * - * @return The client secret. - */ - String getClientSecret(); + /** + * The client secret. Ignored if the {@link #isSecretRequired() secret isn't required}. + * + * @return The client secret. + */ + String getClientSecret(); - /** - * Whether this client is limited to a specific scope. If false, the scope of the authentication request will be - * ignored. - * - * @return Whether this client is limited to a specific scope. - */ - boolean isScoped(); + /** + * Whether this client is limited to a specific scope. If false, the scope of the authentication request will be + * ignored. + * + * @return Whether this client is limited to a specific scope. + */ + boolean isScoped(); - /** - * The scope of this client. Empty if the client isn't scoped. - * - * @return The scope of this client. - */ - Set getScope(); + /** + * The scope of this client. Empty if the client isn't scoped. + * + * @return The scope of this client. + */ + Set getScope(); - /** - * The grant types for which this client is authorized. - * - * @return The grant types for which this client is authorized. - */ - Set getAuthorizedGrantTypes(); + /** + * The grant types for which this client is authorized. + * + * @return The grant types for which this client is authorized. + */ + Set getAuthorizedGrantTypes(); - /** - * The pre-defined redirect URI for this client to use during the "authorization_code" access grant. See OAuth spec, - * section 4.1.1. - * - * @return The pre-defined redirect URI for this client. - */ - Set getRegisteredRedirectUri(); + /** + * The pre-defined redirect URI for this client to use during the "authorization_code" access grant. See OAuth spec, + * section 4.1.1. + * + * @return The pre-defined redirect URI for this client. + */ + Set getRegisteredRedirectUri(); - /** - * Get the authorities that are granted to the OAuth client. Note that these are NOT the authorities that are - * granted to the user with an authorized access token. Instead, these authorities are inherent to the client - * itself. - * - * @return The authorities. - */ - Collection getAuthorities(); + /** + * Get the authorities that are granted to the OAuth client. Note that these are NOT the authorities that are + * granted to the user with an authorized access token. Instead, these authorities are inherent to the client + * itself. + * + * @return The authorities. + */ + Collection getAuthorities(); - /** - * The access token validity period for this client. Null if not set explicitly (implementations might use that fact - * to provide a default value for instance). - * - * @return the access token validity period - */ - Integer getAccessTokenValiditySeconds(); + /** + * The access token validity period for this client. Null if not set explicitly (implementations might use that fact + * to provide a default value for instance). + * + * @return the access token validity period + */ + Integer getAccessTokenValiditySeconds(); - /** - * The refresh token validity period for this client. Zero or negative for default value set by token service. - * - * @return the refresh token validity period - */ - Integer getRefreshTokenValiditySeconds(); - - /** - * Test whether client needs user approval for a particular scope. - * - * @param scope the scope to consider - * @return true if this client does not need user approval - */ - boolean isAutoApprove(String scope); + /** + * The refresh token validity period for this client. Zero or negative for default value set by token service. + * + * @return the refresh token validity period + */ + Integer getRefreshTokenValiditySeconds(); + + /** + * Test whether client needs user approval for a particular scope. + * + * @param scope the scope to consider + * @return true if this client does not need user approval + */ + boolean isAutoApprove(String scope); - /** - * Additional information for this client, not needed by the vanilla OAuth protocol but might be useful, for example, - * for storing descriptive information. - * - * @return a map of additional information - */ - Map getAdditionalInformation(); - - /* - * for OpenID Connect - */ - public String getIssuer() ; - - public String getAudience() ; - - public String getAlgorithm(); - - public String getAlgorithmKey(); - - public String getEncryptionMethod(); - - public String getSignature(); - - public String getSignatureKey(); - - public String getApprovalPrompt(); - - public String getSubject(); - - public String getUserInfoResponse(); - - public String getPkce(); - - public String getProtocol(); - - public String getInstId(); - + /** + * Additional information for this client, not needed by the vanilla OAuth protocol but might be useful, for example, + * for storing descriptive information. + * + * @return a map of additional information + */ + Map getAdditionalInformation(); + + /* + * for OpenID Connect + */ + public String getIssuer() ; + + public String getAudience() ; + + public String getAlgorithm(); + + public String getAlgorithmKey(); + + public String getEncryptionMethod(); + + public String getSignature(); + + public String getSignatureKey(); + + public String getApprovalPrompt(); + + public String getSubject(); + + public String getUserInfoResponse(); + + public String getPkce(); + + public String getProtocol(); + + public String getInstId(); + } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/oauth2/provider/client/BaseClientDetails.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/oauth2/provider/client/BaseClientDetails.java index 20ae0973c..ee341620c 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/oauth2/provider/client/BaseClientDetails.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/oauth2/provider/client/BaseClientDetails.java @@ -45,354 +45,354 @@ import org.springframework.util.StringUtils; @com.fasterxml.jackson.annotation.JsonIgnoreProperties(ignoreUnknown = true) public class BaseClientDetails implements ClientDetails { - @com.fasterxml.jackson.annotation.JsonProperty("client_id") - private String clientId; - - @com.fasterxml.jackson.annotation.JsonProperty("client_secret") - private String clientSecret; - - @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = Jackson2ArrayOrStringDeserializer.class) - private Set scope = Collections.emptySet(); - - @com.fasterxml.jackson.annotation.JsonProperty("resource_ids") - @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = Jackson2ArrayOrStringDeserializer.class) - private Set resourceIds = Collections.emptySet(); - - @com.fasterxml.jackson.annotation.JsonProperty("authorized_grant_types") - @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = Jackson2ArrayOrStringDeserializer.class) - private Set authorizedGrantTypes = Collections.emptySet(); - - @com.fasterxml.jackson.annotation.JsonProperty("redirect_uri") - @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = Jackson2ArrayOrStringDeserializer.class) - private Set registeredRedirectUris; - - @com.fasterxml.jackson.annotation.JsonProperty("autoapprove") - @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = Jackson2ArrayOrStringDeserializer.class) - private Set autoApproveScopes; - - private List authorities = Collections.emptyList(); - - @com.fasterxml.jackson.annotation.JsonProperty("access_token_validity") - private Integer accessTokenValiditySeconds; - - @com.fasterxml.jackson.annotation.JsonProperty("refresh_token_validity") - private Integer refreshTokenValiditySeconds; - - @com.fasterxml.jackson.annotation.JsonIgnore - private Map additionalInformation = new LinkedHashMap(); - - //for OpenID Connect - - private String issuer; - - private String audience; - - private String algorithm; - - private String algorithmKey; - - private String encryptionMethod; - - private String signature; - - private String signatureKey; - - private String subject; - - private String userInfoResponse; - - private String approvalPrompt; - - private String pkce; - - private String protocol; - - private String instId; - - - public BaseClientDetails() { - } - - public BaseClientDetails(ClientDetails prototype) { - this(); - setAccessTokenValiditySeconds(prototype.getAccessTokenValiditySeconds()); - setRefreshTokenValiditySeconds(prototype - .getRefreshTokenValiditySeconds()); - setAuthorities(prototype.getAuthorities()); - setAuthorizedGrantTypes(prototype.getAuthorizedGrantTypes()); - setClientId(prototype.getClientId()); - setClientSecret(prototype.getClientSecret()); - setRegisteredRedirectUri(prototype.getRegisteredRedirectUri()); - setScope(prototype.getScope()); - setResourceIds(prototype.getResourceIds()); - } - - public BaseClientDetails(String clientId, String resourceIds, - String scopes, String grantTypes, String authorities) { - this(clientId, resourceIds, scopes, grantTypes, authorities, null); - } - - public BaseClientDetails(String clientId, String resourceIds, - String scopes, String grantTypes, String authorities, - String redirectUris) { - - this.clientId = clientId; - - if (StringUtils.hasText(resourceIds)) { - Set resources = StringUtils - .commaDelimitedListToSet(resourceIds); - if (!resources.isEmpty()) { - this.resourceIds = resources; - } - } - - if (StringUtils.hasText(scopes)) { - Set scopeList = StringUtils.commaDelimitedListToSet(scopes); - if (!scopeList.isEmpty()) { - this.scope = scopeList; - } - } - - if (StringUtils.hasText(grantTypes)) { - this.authorizedGrantTypes = StringUtils - .commaDelimitedListToSet(grantTypes); - } else { - this.authorizedGrantTypes = new HashSet(Arrays.asList( - "authorization_code", "refresh_token")); - } - - if (StringUtils.hasText(authorities)) { - this.authorities = AuthorityUtils - .commaSeparatedStringToAuthorityList(authorities); - } - - if (StringUtils.hasText(redirectUris)) { - this.registeredRedirectUris = StringUtils - .commaDelimitedListToSet(redirectUris); - } - } - - @com.fasterxml.jackson.annotation.JsonIgnore - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - - public void setAutoApproveScopes(Collection autoApproveScopes) { - this.autoApproveScopes = new HashSet(autoApproveScopes); - } - - @Override - public boolean isAutoApprove(String scope) { - if (autoApproveScopes == null) { - return false; - } - for (String auto : autoApproveScopes) { - if (auto.equals("true") || scope.matches(auto)) { - return true; - } - } - return false; - } - - @com.fasterxml.jackson.annotation.JsonIgnore - public Set getAutoApproveScopes() { - return autoApproveScopes; - } - - @com.fasterxml.jackson.annotation.JsonIgnore - public boolean isSecretRequired() { - return this.clientSecret != null; - } - - @com.fasterxml.jackson.annotation.JsonIgnore - public String getClientSecret() { - return clientSecret; - } - - public void setClientSecret(String clientSecret) { - this.clientSecret = clientSecret; - } - - @com.fasterxml.jackson.annotation.JsonIgnore - public boolean isScoped() { - return this.scope != null && !this.scope.isEmpty(); - } - - public Set getScope() { - return scope; - } - - public void setScope(Collection scope) { - this.scope = scope == null ? Collections. emptySet() - : new LinkedHashSet(scope); - } - - @com.fasterxml.jackson.annotation.JsonIgnore - public Set getResourceIds() { - return resourceIds; - } - - public void setResourceIds(Collection resourceIds) { - this.resourceIds = resourceIds == null ? Collections - . emptySet() : new LinkedHashSet(resourceIds); - } - - @com.fasterxml.jackson.annotation.JsonIgnore - public Set getAuthorizedGrantTypes() { - return authorizedGrantTypes; - } - - public void setAuthorizedGrantTypes(Collection authorizedGrantTypes) { - this.authorizedGrantTypes = new LinkedHashSet( - authorizedGrantTypes); - } - - @com.fasterxml.jackson.annotation.JsonIgnore - public Set getRegisteredRedirectUri() { - return registeredRedirectUris; - } - - public void setRegisteredRedirectUri(Set registeredRedirectUris) { - this.registeredRedirectUris = registeredRedirectUris == null ? null - : new LinkedHashSet(registeredRedirectUris); - } - - @com.fasterxml.jackson.annotation.JsonProperty("authorities") - private List getAuthoritiesAsStrings() { - return new ArrayList( - AuthorityUtils.authorityListToSet(authorities)); - } - - @com.fasterxml.jackson.annotation.JsonProperty("authorities") - @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = Jackson2ArrayOrStringDeserializer.class) - private void setAuthoritiesAsStrings(Set values) { - setAuthorities(AuthorityUtils.createAuthorityList(values - .toArray(new String[values.size()]))); - } - - @com.fasterxml.jackson.annotation.JsonIgnore - public Collection getAuthorities() { - return authorities; - } - - @com.fasterxml.jackson.annotation.JsonIgnore - public void setAuthorities( - Collection authorities) { - this.authorities = new ArrayList(authorities); - } - - @com.fasterxml.jackson.annotation.JsonIgnore - public Integer getAccessTokenValiditySeconds() { - return accessTokenValiditySeconds; - } - - public void setAccessTokenValiditySeconds(Integer accessTokenValiditySeconds) { - this.accessTokenValiditySeconds = accessTokenValiditySeconds; - } - - @com.fasterxml.jackson.annotation.JsonIgnore - public Integer getRefreshTokenValiditySeconds() { - return refreshTokenValiditySeconds; - } - - public void setRefreshTokenValiditySeconds( - Integer refreshTokenValiditySeconds) { - this.refreshTokenValiditySeconds = refreshTokenValiditySeconds; - } - - public void setAdditionalInformation(Map additionalInformation) { - this.additionalInformation = new LinkedHashMap( - additionalInformation); - } - - @com.fasterxml.jackson.annotation.JsonAnyGetter - public Map getAdditionalInformation() { - return Collections.unmodifiableMap(this.additionalInformation); - } - - @com.fasterxml.jackson.annotation.JsonAnySetter - public void addAdditionalInformation(String key, Object value) { - this.additionalInformation.put(key, value); - } - - public String getIssuer() { - return issuer; - } - - public void setIssuer(String issuer) { - this.issuer = issuer; - } - - public String getAudience() { - return audience; - } - - public void setAudience(String audience) { - this.audience = audience; - } - - public String getAlgorithm() { - return algorithm; - } - - public void setAlgorithm(String algorithm) { - this.algorithm = algorithm; - } - - public String getAlgorithmKey() { - return algorithmKey; - } - - public void setAlgorithmKey(String algorithmKey) { - this.algorithmKey = algorithmKey; - } - - public String getEncryptionMethod() { - return encryptionMethod; - } - - public void setEncryptionMethod(String encryptionMethod) { - this.encryptionMethod = encryptionMethod; - } - - public String getSignature() { - return signature; - } - - public void setSignature(String signature) { - this.signature = signature; - } - - public String getSignatureKey() { - return signatureKey; - } - - public void setSignatureKey(String signatureKey) { - this.signatureKey = signatureKey; - } - - - public String getSubject() { - return subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - public String getUserInfoResponse() { - return userInfoResponse; - } - - public void setUserInfoResponse(String userInfoResponse) { - this.userInfoResponse = userInfoResponse; - } - - public String getApprovalPrompt() { + @com.fasterxml.jackson.annotation.JsonProperty("client_id") + private String clientId; + + @com.fasterxml.jackson.annotation.JsonProperty("client_secret") + private String clientSecret; + + @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = Jackson2ArrayOrStringDeserializer.class) + private Set scope = Collections.emptySet(); + + @com.fasterxml.jackson.annotation.JsonProperty("resource_ids") + @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = Jackson2ArrayOrStringDeserializer.class) + private Set resourceIds = Collections.emptySet(); + + @com.fasterxml.jackson.annotation.JsonProperty("authorized_grant_types") + @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = Jackson2ArrayOrStringDeserializer.class) + private Set authorizedGrantTypes = Collections.emptySet(); + + @com.fasterxml.jackson.annotation.JsonProperty("redirect_uri") + @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = Jackson2ArrayOrStringDeserializer.class) + private Set registeredRedirectUris; + + @com.fasterxml.jackson.annotation.JsonProperty("autoapprove") + @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = Jackson2ArrayOrStringDeserializer.class) + private Set autoApproveScopes; + + private List authorities = Collections.emptyList(); + + @com.fasterxml.jackson.annotation.JsonProperty("access_token_validity") + private Integer accessTokenValiditySeconds; + + @com.fasterxml.jackson.annotation.JsonProperty("refresh_token_validity") + private Integer refreshTokenValiditySeconds; + + @com.fasterxml.jackson.annotation.JsonIgnore + private Map additionalInformation = new LinkedHashMap(); + + //for OpenID Connect + + private String issuer; + + private String audience; + + private String algorithm; + + private String algorithmKey; + + private String encryptionMethod; + + private String signature; + + private String signatureKey; + + private String subject; + + private String userInfoResponse; + + private String approvalPrompt; + + private String pkce; + + private String protocol; + + private String instId; + + + public BaseClientDetails() { + } + + public BaseClientDetails(ClientDetails prototype) { + this(); + setAccessTokenValiditySeconds(prototype.getAccessTokenValiditySeconds()); + setRefreshTokenValiditySeconds(prototype + .getRefreshTokenValiditySeconds()); + setAuthorities(prototype.getAuthorities()); + setAuthorizedGrantTypes(prototype.getAuthorizedGrantTypes()); + setClientId(prototype.getClientId()); + setClientSecret(prototype.getClientSecret()); + setRegisteredRedirectUri(prototype.getRegisteredRedirectUri()); + setScope(prototype.getScope()); + setResourceIds(prototype.getResourceIds()); + } + + public BaseClientDetails(String clientId, String resourceIds, + String scopes, String grantTypes, String authorities) { + this(clientId, resourceIds, scopes, grantTypes, authorities, null); + } + + public BaseClientDetails(String clientId, String resourceIds, + String scopes, String grantTypes, String authorities, + String redirectUris) { + + this.clientId = clientId; + + if (StringUtils.hasText(resourceIds)) { + Set resources = StringUtils + .commaDelimitedListToSet(resourceIds); + if (!resources.isEmpty()) { + this.resourceIds = resources; + } + } + + if (StringUtils.hasText(scopes)) { + Set scopeList = StringUtils.commaDelimitedListToSet(scopes); + if (!scopeList.isEmpty()) { + this.scope = scopeList; + } + } + + if (StringUtils.hasText(grantTypes)) { + this.authorizedGrantTypes = StringUtils + .commaDelimitedListToSet(grantTypes); + } else { + this.authorizedGrantTypes = new HashSet(Arrays.asList( + "authorization_code", "refresh_token")); + } + + if (StringUtils.hasText(authorities)) { + this.authorities = AuthorityUtils + .commaSeparatedStringToAuthorityList(authorities); + } + + if (StringUtils.hasText(redirectUris)) { + this.registeredRedirectUris = StringUtils + .commaDelimitedListToSet(redirectUris); + } + } + + @com.fasterxml.jackson.annotation.JsonIgnore + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public void setAutoApproveScopes(Collection autoApproveScopes) { + this.autoApproveScopes = new HashSet(autoApproveScopes); + } + + @Override + public boolean isAutoApprove(String scope) { + if (autoApproveScopes == null) { + return false; + } + for (String auto : autoApproveScopes) { + if (auto.equals("true") || scope.matches(auto)) { + return true; + } + } + return false; + } + + @com.fasterxml.jackson.annotation.JsonIgnore + public Set getAutoApproveScopes() { + return autoApproveScopes; + } + + @com.fasterxml.jackson.annotation.JsonIgnore + public boolean isSecretRequired() { + return this.clientSecret != null; + } + + @com.fasterxml.jackson.annotation.JsonIgnore + public String getClientSecret() { + return clientSecret; + } + + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } + + @com.fasterxml.jackson.annotation.JsonIgnore + public boolean isScoped() { + return this.scope != null && !this.scope.isEmpty(); + } + + public Set getScope() { + return scope; + } + + public void setScope(Collection scope) { + this.scope = scope == null ? Collections. emptySet() + : new LinkedHashSet(scope); + } + + @com.fasterxml.jackson.annotation.JsonIgnore + public Set getResourceIds() { + return resourceIds; + } + + public void setResourceIds(Collection resourceIds) { + this.resourceIds = resourceIds == null ? Collections + . emptySet() : new LinkedHashSet(resourceIds); + } + + @com.fasterxml.jackson.annotation.JsonIgnore + public Set getAuthorizedGrantTypes() { + return authorizedGrantTypes; + } + + public void setAuthorizedGrantTypes(Collection authorizedGrantTypes) { + this.authorizedGrantTypes = new LinkedHashSet( + authorizedGrantTypes); + } + + @com.fasterxml.jackson.annotation.JsonIgnore + public Set getRegisteredRedirectUri() { + return registeredRedirectUris; + } + + public void setRegisteredRedirectUri(Set registeredRedirectUris) { + this.registeredRedirectUris = registeredRedirectUris == null ? null + : new LinkedHashSet(registeredRedirectUris); + } + + @com.fasterxml.jackson.annotation.JsonProperty("authorities") + private List getAuthoritiesAsStrings() { + return new ArrayList( + AuthorityUtils.authorityListToSet(authorities)); + } + + @com.fasterxml.jackson.annotation.JsonProperty("authorities") + @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = Jackson2ArrayOrStringDeserializer.class) + private void setAuthoritiesAsStrings(Set values) { + setAuthorities(AuthorityUtils.createAuthorityList(values + .toArray(new String[values.size()]))); + } + + @com.fasterxml.jackson.annotation.JsonIgnore + public Collection getAuthorities() { + return authorities; + } + + @com.fasterxml.jackson.annotation.JsonIgnore + public void setAuthorities( + Collection authorities) { + this.authorities = new ArrayList(authorities); + } + + @com.fasterxml.jackson.annotation.JsonIgnore + public Integer getAccessTokenValiditySeconds() { + return accessTokenValiditySeconds; + } + + public void setAccessTokenValiditySeconds(Integer accessTokenValiditySeconds) { + this.accessTokenValiditySeconds = accessTokenValiditySeconds; + } + + @com.fasterxml.jackson.annotation.JsonIgnore + public Integer getRefreshTokenValiditySeconds() { + return refreshTokenValiditySeconds; + } + + public void setRefreshTokenValiditySeconds( + Integer refreshTokenValiditySeconds) { + this.refreshTokenValiditySeconds = refreshTokenValiditySeconds; + } + + public void setAdditionalInformation(Map additionalInformation) { + this.additionalInformation = new LinkedHashMap( + additionalInformation); + } + + @com.fasterxml.jackson.annotation.JsonAnyGetter + public Map getAdditionalInformation() { + return Collections.unmodifiableMap(this.additionalInformation); + } + + @com.fasterxml.jackson.annotation.JsonAnySetter + public void addAdditionalInformation(String key, Object value) { + this.additionalInformation.put(key, value); + } + + public String getIssuer() { + return issuer; + } + + public void setIssuer(String issuer) { + this.issuer = issuer; + } + + public String getAudience() { + return audience; + } + + public void setAudience(String audience) { + this.audience = audience; + } + + public String getAlgorithm() { + return algorithm; + } + + public void setAlgorithm(String algorithm) { + this.algorithm = algorithm; + } + + public String getAlgorithmKey() { + return algorithmKey; + } + + public void setAlgorithmKey(String algorithmKey) { + this.algorithmKey = algorithmKey; + } + + public String getEncryptionMethod() { + return encryptionMethod; + } + + public void setEncryptionMethod(String encryptionMethod) { + this.encryptionMethod = encryptionMethod; + } + + public String getSignature() { + return signature; + } + + public void setSignature(String signature) { + this.signature = signature; + } + + public String getSignatureKey() { + return signatureKey; + } + + public void setSignatureKey(String signatureKey) { + this.signatureKey = signatureKey; + } + + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getUserInfoResponse() { + return userInfoResponse; + } + + public void setUserInfoResponse(String userInfoResponse) { + this.userInfoResponse = userInfoResponse; + } + + public String getApprovalPrompt() { return approvalPrompt; } @@ -416,154 +416,154 @@ public class BaseClientDetails implements ClientDetails { this.protocol = protocol; } - @Override - public String getInstId() { - return this.instId; - } - + @Override + public String getInstId() { + return this.instId; + } + public void setInstId(String instId) { - this.instId = instId; - } + this.instId = instId; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime - * result - + ((accessTokenValiditySeconds == null) ? 0 - : accessTokenValiditySeconds); - result = prime - * result - + ((refreshTokenValiditySeconds == null) ? 0 - : refreshTokenValiditySeconds); - result = prime * result - + ((authorities == null) ? 0 : authorities.hashCode()); - result = prime - * result - + ((authorizedGrantTypes == null) ? 0 : authorizedGrantTypes - .hashCode()); - result = prime * result - + ((clientId == null) ? 0 : clientId.hashCode()); - result = prime * result - + ((clientSecret == null) ? 0 : clientSecret.hashCode()); - result = prime - * result - + ((registeredRedirectUris == null) ? 0 - : registeredRedirectUris.hashCode()); - result = prime * result - + ((resourceIds == null) ? 0 : resourceIds.hashCode()); - result = prime * result + ((scope == null) ? 0 : scope.hashCode()); - result = prime * result + additionalInformation.hashCode(); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime + * result + + ((accessTokenValiditySeconds == null) ? 0 + : accessTokenValiditySeconds); + result = prime + * result + + ((refreshTokenValiditySeconds == null) ? 0 + : refreshTokenValiditySeconds); + result = prime * result + + ((authorities == null) ? 0 : authorities.hashCode()); + result = prime + * result + + ((authorizedGrantTypes == null) ? 0 : authorizedGrantTypes + .hashCode()); + result = prime * result + + ((clientId == null) ? 0 : clientId.hashCode()); + result = prime * result + + ((clientSecret == null) ? 0 : clientSecret.hashCode()); + result = prime + * result + + ((registeredRedirectUris == null) ? 0 + : registeredRedirectUris.hashCode()); + result = prime * result + + ((resourceIds == null) ? 0 : resourceIds.hashCode()); + result = prime * result + ((scope == null) ? 0 : scope.hashCode()); + result = prime * result + additionalInformation.hashCode(); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - BaseClientDetails other = (BaseClientDetails) obj; - if (accessTokenValiditySeconds != other.accessTokenValiditySeconds) - return false; - if (refreshTokenValiditySeconds != other.refreshTokenValiditySeconds) - return false; - if (authorities == null) { - if (other.authorities != null) - return false; - } else if (!authorities.equals(other.authorities)) - return false; - if (authorizedGrantTypes == null) { - if (other.authorizedGrantTypes != null) - return false; - } else if (!authorizedGrantTypes.equals(other.authorizedGrantTypes)) - return false; - if (clientId == null) { - if (other.clientId != null) - return false; - } else if (!clientId.equals(other.clientId)) - return false; - if (clientSecret == null) { - if (other.clientSecret != null) - return false; - } else if (!clientSecret.equals(other.clientSecret)) - return false; - if (registeredRedirectUris == null) { - if (other.registeredRedirectUris != null) - return false; - } else if (!registeredRedirectUris.equals(other.registeredRedirectUris)) - return false; - if (resourceIds == null) { - if (other.resourceIds != null) - return false; - } else if (!resourceIds.equals(other.resourceIds)) - return false; - if (scope == null) { - if (other.scope != null) - return false; - } else if (!scope.equals(other.scope)) - return false; - if (additionalInformation == null) { - if (other.additionalInformation != null) - return false; - } else if (!additionalInformation.equals(other.additionalInformation)) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + BaseClientDetails other = (BaseClientDetails) obj; + if (accessTokenValiditySeconds != other.accessTokenValiditySeconds) + return false; + if (refreshTokenValiditySeconds != other.refreshTokenValiditySeconds) + return false; + if (authorities == null) { + if (other.authorities != null) + return false; + } else if (!authorities.equals(other.authorities)) + return false; + if (authorizedGrantTypes == null) { + if (other.authorizedGrantTypes != null) + return false; + } else if (!authorizedGrantTypes.equals(other.authorizedGrantTypes)) + return false; + if (clientId == null) { + if (other.clientId != null) + return false; + } else if (!clientId.equals(other.clientId)) + return false; + if (clientSecret == null) { + if (other.clientSecret != null) + return false; + } else if (!clientSecret.equals(other.clientSecret)) + return false; + if (registeredRedirectUris == null) { + if (other.registeredRedirectUris != null) + return false; + } else if (!registeredRedirectUris.equals(other.registeredRedirectUris)) + return false; + if (resourceIds == null) { + if (other.resourceIds != null) + return false; + } else if (!resourceIds.equals(other.resourceIds)) + return false; + if (scope == null) { + if (other.scope != null) + return false; + } else if (!scope.equals(other.scope)) + return false; + if (additionalInformation == null) { + if (other.additionalInformation != null) + return false; + } else if (!additionalInformation.equals(other.additionalInformation)) + return false; + return true; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("BaseClientDetails [clientId="); - builder.append(clientId); - builder.append(", clientSecret="); - builder.append(clientSecret); - builder.append(", scope="); - builder.append(scope); - builder.append(", resourceIds="); - builder.append(resourceIds); - builder.append(", authorizedGrantTypes="); - builder.append(authorizedGrantTypes); - builder.append(", registeredRedirectUris="); - builder.append(registeredRedirectUris); - builder.append(", autoApproveScopes="); - builder.append(autoApproveScopes); - builder.append(", authorities="); - builder.append(authorities); - builder.append(", accessTokenValiditySeconds="); - builder.append(accessTokenValiditySeconds); - builder.append(", refreshTokenValiditySeconds="); - builder.append(refreshTokenValiditySeconds); - builder.append(", additionalInformation="); - builder.append(additionalInformation); - builder.append(", issuer="); - builder.append(issuer); - builder.append(", audience="); - builder.append(audience); - builder.append(", algorithm="); - builder.append(algorithm); - builder.append(", algorithmKey="); - builder.append(algorithmKey); - builder.append(", encryptionMethod="); - builder.append(encryptionMethod); - builder.append(", signature="); - builder.append(signature); - builder.append(", signatureKey="); - builder.append(signatureKey); - builder.append(", approvalPrompt="); - builder.append(approvalPrompt); - builder.append(", pkce="); - builder.append(pkce); - builder.append(", protocol="); - builder.append(protocol); - builder.append(", instId="); - builder.append(instId); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("BaseClientDetails [clientId="); + builder.append(clientId); + builder.append(", clientSecret="); + builder.append(clientSecret); + builder.append(", scope="); + builder.append(scope); + builder.append(", resourceIds="); + builder.append(resourceIds); + builder.append(", authorizedGrantTypes="); + builder.append(authorizedGrantTypes); + builder.append(", registeredRedirectUris="); + builder.append(registeredRedirectUris); + builder.append(", autoApproveScopes="); + builder.append(autoApproveScopes); + builder.append(", authorities="); + builder.append(authorities); + builder.append(", accessTokenValiditySeconds="); + builder.append(accessTokenValiditySeconds); + builder.append(", refreshTokenValiditySeconds="); + builder.append(refreshTokenValiditySeconds); + builder.append(", additionalInformation="); + builder.append(additionalInformation); + builder.append(", issuer="); + builder.append(issuer); + builder.append(", audience="); + builder.append(audience); + builder.append(", algorithm="); + builder.append(algorithm); + builder.append(", algorithmKey="); + builder.append(algorithmKey); + builder.append(", encryptionMethod="); + builder.append(encryptionMethod); + builder.append(", signature="); + builder.append(signature); + builder.append(", signatureKey="); + builder.append(signatureKey); + builder.append(", approvalPrompt="); + builder.append(approvalPrompt); + builder.append(", pkce="); + builder.append(pkce); + builder.append(", protocol="); + builder.append(protocol); + builder.append(", instId="); + builder.append(instId); + builder.append("]"); + return builder.toString(); + } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/oauth2/provider/client/Jackson2ArrayOrStringDeserializer.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/oauth2/provider/client/Jackson2ArrayOrStringDeserializer.java index 84224152b..2607ce603 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/oauth2/provider/client/Jackson2ArrayOrStringDeserializer.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/apps/oauth2/provider/client/Jackson2ArrayOrStringDeserializer.java @@ -36,26 +36,26 @@ import com.fasterxml.jackson.databind.type.TypeFactory; @SuppressWarnings("serial") public class Jackson2ArrayOrStringDeserializer extends StdDeserializer> { - public Jackson2ArrayOrStringDeserializer() { - super(Set.class); - } + public Jackson2ArrayOrStringDeserializer() { + super(Set.class); + } - @Override - public JavaType getValueType() { - //return SimpleType.construct(String.class); - return TypeFactory.defaultInstance().constructType(String.class); - } + @Override + public JavaType getValueType() { + //return SimpleType.construct(String.class); + return TypeFactory.defaultInstance().constructType(String.class); + } - @Override - public Set deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, - JsonProcessingException { - JsonToken token = jp.getCurrentToken(); - if (token.isScalarValue()) { - String list = jp.getText(); - list = list.replaceAll("\\s+", ","); - return new LinkedHashSet(Arrays.asList(StringUtils.commaDelimitedListToStringArray(list))); - } - return jp.readValueAs(new TypeReference>() { - }); - } + @Override + public Set deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, + JsonProcessingException { + JsonToken token = jp.getCurrentToken(); + if (token.isScalarValue()) { + String list = jp.getText(); + list = list.replaceAll("\\s+", ","); + return new LinkedHashSet(Arrays.asList(StringUtils.commaDelimitedListToStringArray(list))); + } + return jp.readValueAs(new TypeReference>() { + }); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/authz/QueryAppResourceDto.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/authz/QueryAppResourceDto.java index bc91b620f..69ad4696b 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/authz/QueryAppResourceDto.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/authz/QueryAppResourceDto.java @@ -23,53 +23,53 @@ import java.util.ArrayList; import java.util.List; public class QueryAppResourceDto { - - String appId; - - String userId; - - List groupIds; - - List roleIds; + + String appId; + + String userId; + + List groupIds; + + List roleIds; - public QueryAppResourceDto(String userId,String appId) { - super(); - this.appId = appId; - this.userId = userId; - groupIds = new ArrayList<>(); - roleIds = new ArrayList<>(); - } + public QueryAppResourceDto(String userId,String appId) { + super(); + this.appId = appId; + this.userId = userId; + groupIds = new ArrayList<>(); + roleIds = new ArrayList<>(); + } - public String getAppId() { - return appId; - } + public String getAppId() { + return appId; + } - public void setAppId(String appId) { - this.appId = appId; - } + public void setAppId(String appId) { + this.appId = appId; + } - public String getUserId() { - return userId; - } + public String getUserId() { + return userId; + } - public void setUserId(String userId) { - this.userId = userId; - } + public void setUserId(String userId) { + this.userId = userId; + } - public List getGroupIds() { - return groupIds; - } + public List getGroupIds() { + return groupIds; + } - public void setGroupIds(List groupIds) { - this.groupIds = groupIds; - } + public void setGroupIds(List groupIds) { + this.groupIds = groupIds; + } - public List getRoleIds() { - return roleIds; - } + public List getRoleIds() { + return roleIds; + } - public void setRoleIds(List roleIds) { - this.roleIds = roleIds; - } + public void setRoleIds(List roleIds) { + this.roleIds = roleIds; + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/authz/QueryGroupMembersDto.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/authz/QueryGroupMembersDto.java index 72df0baac..01cbcf331 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/authz/QueryGroupMembersDto.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/authz/QueryGroupMembersDto.java @@ -23,27 +23,27 @@ import java.util.ArrayList; import java.util.List; public class QueryGroupMembersDto { - - List members; + + List members; - public QueryGroupMembersDto() { - members = new ArrayList<>(); - } + public QueryGroupMembersDto() { + members = new ArrayList<>(); + } - public QueryGroupMembersDto(List members) { - this.members = members; - } - - public void add(String memberId) { - this.members.add(memberId); - } + public QueryGroupMembersDto(List members) { + this.members = members; + } + + public void add(String memberId) { + this.members.add(memberId); + } - public List getMembers() { - return members; - } + public List getMembers() { + return members; + } - public void setMembers(List members) { - this.members = members; - } - + public void setMembers(List members) { + this.members = members; + } + } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/authz/QueryRoleMembersDto.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/authz/QueryRoleMembersDto.java index 478db0af9..521fb4c41 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/authz/QueryRoleMembersDto.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/authz/QueryRoleMembersDto.java @@ -22,36 +22,36 @@ import java.util.ArrayList; import java.util.List; public class QueryRoleMembersDto { - String appId; - - List members; + String appId; + + List members; - public QueryRoleMembersDto() { - members = new ArrayList<>(); - } + public QueryRoleMembersDto() { + members = new ArrayList<>(); + } - public QueryRoleMembersDto(List members) { - this.members = members; - } - - public String getAppId() { - return appId; - } + public QueryRoleMembersDto(List members) { + this.members = members; + } + + public String getAppId() { + return appId; + } - public void setAppId(String appId) { - this.appId = appId; - } - - public void add(String memberId) { - this.members.add(memberId); - } + public void setAppId(String appId) { + this.appId = appId; + } + + public void add(String memberId) { + this.members.add(memberId); + } - public List getMembers() { - return members; - } + public List getMembers() { + return members; + } - public void setMembers(List members) { - this.members = members; - } - + public void setMembers(List members) { + this.members = members; + } + } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/cnf/CnfEmailSenders.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/cnf/CnfEmailSenders.java index f5eeaee59..fb92bd77c 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/cnf/CnfEmailSenders.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/cnf/CnfEmailSenders.java @@ -34,40 +34,40 @@ import jakarta.persistence.Table; @Table(name = "MXK_CNF_EMAIL_SENDERS") public class CnfEmailSenders extends JpaEntity implements Serializable { - /** - * - */ - private static final long serialVersionUID = 3689854324601731505L; - - @Id + /** + * + */ + private static final long serialVersionUID = 3689854324601731505L; + + @Id @Column @GeneratedValue private String id; - - @Column + + @Column private String account; - @Column + @Column private String credentials; - @Column + @Column private String smtpHost; - @Column + @Column private Integer port; - @Column + @Column private int sslSwitch; - @Column + @Column private String sender; - - @Column + + @Column private String encoding; - - @Column + + @Column private String protocol; - + @Column private int status; @@ -91,182 +91,182 @@ public class CnfEmailSenders extends JpaEntity implements Serializable { @Column private Date modifiedDate; - public CnfEmailSenders() { - super(); - } + public CnfEmailSenders() { + super(); + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getAccount() { - return account; - } + public String getAccount() { + return account; + } - public void setAccount(String account) { - this.account = account; - } + public void setAccount(String account) { + this.account = account; + } - public String getCredentials() { - return credentials; - } + public String getCredentials() { + return credentials; + } - public void setCredentials(String credentials) { - this.credentials = credentials; - } + public void setCredentials(String credentials) { + this.credentials = credentials; + } - public String getSmtpHost() { - return smtpHost; - } + public String getSmtpHost() { + return smtpHost; + } - public void setSmtpHost(String smtpHost) { - this.smtpHost = smtpHost; - } + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; + } - public Integer getPort() { - return port; - } + public Integer getPort() { + return port; + } - public void setPort(Integer port) { - this.port = port; - } + public void setPort(Integer port) { + this.port = port; + } - public int getSslSwitch() { - return sslSwitch; - } + public int getSslSwitch() { + return sslSwitch; + } - public void setSslSwitch(int sslSwitch) { - this.sslSwitch = sslSwitch; - } + public void setSslSwitch(int sslSwitch) { + this.sslSwitch = sslSwitch; + } - public String getEncoding() { - return encoding; - } + public String getEncoding() { + return encoding; + } - public void setEncoding(String encoding) { - this.encoding = encoding; - } + public void setEncoding(String encoding) { + this.encoding = encoding; + } - public String getProtocol() { - return protocol; - } + public String getProtocol() { + return protocol; + } - public void setProtocol(String protocol) { - this.protocol = protocol; - } + public void setProtocol(String protocol) { + this.protocol = protocol; + } - public String getSender() { - return sender; - } + public String getSender() { + return sender; + } - public void setSender(String sender) { - this.sender = sender; - } + public void setSender(String sender) { + this.sender = sender; + } - public int getStatus() { - return status; - } + public int getStatus() { + return status; + } - public void setStatus(int status) { - this.status = status; - } + public void setStatus(int status) { + this.status = status; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public String getCreatedBy() { - return createdBy; - } + public String getCreatedBy() { + return createdBy; + } - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } - public String getModifiedBy() { - return modifiedBy; - } + public String getModifiedBy() { + return modifiedBy; + } - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } - public Date getCreatedDate() { - return createdDate; - } + public Date getCreatedDate() { + return createdDate; + } - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } - public Date getModifiedDate() { - return modifiedDate; - } + public Date getModifiedDate() { + return modifiedDate; + } - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("EmailSenders [id="); - builder.append(id); - builder.append(", account="); - builder.append(account); - builder.append(", credentials="); - builder.append(credentials); - builder.append(", smtpHost="); - builder.append(smtpHost); - builder.append(", port="); - builder.append(port); - builder.append(", sslSwitch="); - builder.append(sslSwitch); - builder.append(", sender="); - builder.append(sender); - builder.append(", status="); - builder.append(status); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append(", description="); - builder.append(description); - builder.append(", createdBy="); - builder.append(createdBy); - builder.append(", createdDate="); - builder.append(createdDate); - builder.append(", modifiedBy="); - builder.append(modifiedBy); - builder.append(", modifiedDate="); - builder.append(modifiedDate); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("EmailSenders [id="); + builder.append(id); + builder.append(", account="); + builder.append(account); + builder.append(", credentials="); + builder.append(credentials); + builder.append(", smtpHost="); + builder.append(smtpHost); + builder.append(", port="); + builder.append(port); + builder.append(", sslSwitch="); + builder.append(sslSwitch); + builder.append(", sender="); + builder.append(sender); + builder.append(", status="); + builder.append(status); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append(", description="); + builder.append(description); + builder.append(", createdBy="); + builder.append(createdBy); + builder.append(", createdDate="); + builder.append(createdDate); + builder.append(", modifiedBy="); + builder.append(modifiedBy); + builder.append(", modifiedDate="); + builder.append(modifiedDate); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/cnf/CnfLdapContext.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/cnf/CnfLdapContext.java index ddf2dac05..3decf7932 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/cnf/CnfLdapContext.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/cnf/CnfLdapContext.java @@ -33,11 +33,11 @@ import jakarta.persistence.Table; public class CnfLdapContext extends JpaEntity implements Serializable { - /** - * - */ - private static final long serialVersionUID = -4595539647817265938L; - @Id + /** + * + */ + private static final long serialVersionUID = -4595539647817265938L; + @Id @Column @GeneratedValue String id; @@ -76,218 +76,218 @@ public class CnfLdapContext extends JpaEntity implements Serializable { @Column int status; - @Column - private String instId; + @Column + private String instId; - private String instName; + private String instName; public CnfLdapContext() { } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getProduct() { - return product; - } + public String getProduct() { + return product; + } - public void setProduct(String product) { - this.product = product; - } + public void setProduct(String product) { + this.product = product; + } - public String getProviderUrl() { - return providerUrl; - } + public String getProviderUrl() { + return providerUrl; + } - public void setProviderUrl(String providerUrl) { - this.providerUrl = providerUrl; - } + public void setProviderUrl(String providerUrl) { + this.providerUrl = providerUrl; + } - public String getPrincipal() { - return principal; - } + public String getPrincipal() { + return principal; + } - public void setPrincipal(String principal) { - this.principal = principal; - } + public void setPrincipal(String principal) { + this.principal = principal; + } - public String getCredentials() { - return credentials; - } + public String getCredentials() { + return credentials; + } - public void setCredentials(String credentials) { - this.credentials = credentials; - } + public void setCredentials(String credentials) { + this.credentials = credentials; + } - public String getFilters() { - return filters; - } + public String getFilters() { + return filters; + } - public void setFilters(String filters) { - this.filters = filters; - } + public void setFilters(String filters) { + this.filters = filters; + } - public String getBasedn() { - return basedn; - } + public String getBasedn() { + return basedn; + } - public void setBasedn(String basedn) { - this.basedn = basedn; - } + public void setBasedn(String basedn) { + this.basedn = basedn; + } - public String getMsadDomain() { - return msadDomain; - } + public String getMsadDomain() { + return msadDomain; + } - public void setMsadDomain(String msadDomain) { - this.msadDomain = msadDomain; - } + public void setMsadDomain(String msadDomain) { + this.msadDomain = msadDomain; + } - public String getSslSwitch() { - return sslSwitch; - } + public String getSslSwitch() { + return sslSwitch; + } - public void setSslSwitch(String sslSwitch) { - this.sslSwitch = sslSwitch; - } + public void setSslSwitch(String sslSwitch) { + this.sslSwitch = sslSwitch; + } - public String getAccountMapping() { - return accountMapping; - } + public String getAccountMapping() { + return accountMapping; + } - public void setAccountMapping(String accountMapping) { - this.accountMapping = accountMapping; - } + public void setAccountMapping(String accountMapping) { + this.accountMapping = accountMapping; + } - public String getTrustStore() { - return trustStore; - } + public String getTrustStore() { + return trustStore; + } - public void setTrustStore(String trustStore) { - this.trustStore = trustStore; - } + public void setTrustStore(String trustStore) { + this.trustStore = trustStore; + } - public String getTrustStorePassword() { - return trustStorePassword; - } + public String getTrustStorePassword() { + return trustStorePassword; + } - public void setTrustStorePassword(String trustStorePassword) { - this.trustStorePassword = trustStorePassword; - } + public void setTrustStorePassword(String trustStorePassword) { + this.trustStorePassword = trustStorePassword; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public String getCreatedBy() { - return createdBy; - } + public String getCreatedBy() { + return createdBy; + } - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } - public String getModifiedBy() { - return modifiedBy; - } + public String getModifiedBy() { + return modifiedBy; + } - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } - public Date getCreatedDate() { - return createdDate; - } + public Date getCreatedDate() { + return createdDate; + } - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } - public Date getModifiedDate() { - return modifiedDate; - } + public Date getModifiedDate() { + return modifiedDate; + } - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } - public int getStatus() { - return status; - } + public int getStatus() { + return status; + } - public void setStatus(int status) { - this.status = status; - } + public void setStatus(int status) { + this.status = status; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("LdapContext [id="); - builder.append(id); - builder.append(", product="); - builder.append(product); - builder.append(", providerUrl="); - builder.append(providerUrl); - builder.append(", principal="); - builder.append(principal); - builder.append(", credentials="); - builder.append(credentials); - builder.append(", filters="); - builder.append(filters); - builder.append(", basedn="); - builder.append(basedn); - builder.append(", msadDomain="); - builder.append(msadDomain); - builder.append(", sslSwitch="); - builder.append(sslSwitch); - builder.append(", trustStore="); - builder.append(trustStore); - builder.append(", trustStorePassword="); - builder.append(trustStorePassword); - builder.append(", description="); - builder.append(description); - builder.append(", createdBy="); - builder.append(createdBy); - builder.append(", createdDate="); - builder.append(createdDate); - builder.append(", modifiedBy="); - builder.append(modifiedBy); - builder.append(", modifiedDate="); - builder.append(modifiedDate); - builder.append(", status="); - builder.append(status); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("LdapContext [id="); + builder.append(id); + builder.append(", product="); + builder.append(product); + builder.append(", providerUrl="); + builder.append(providerUrl); + builder.append(", principal="); + builder.append(principal); + builder.append(", credentials="); + builder.append(credentials); + builder.append(", filters="); + builder.append(filters); + builder.append(", basedn="); + builder.append(basedn); + builder.append(", msadDomain="); + builder.append(msadDomain); + builder.append(", sslSwitch="); + builder.append(sslSwitch); + builder.append(", trustStore="); + builder.append(trustStore); + builder.append(", trustStorePassword="); + builder.append(trustStorePassword); + builder.append(", description="); + builder.append(description); + builder.append(", createdBy="); + builder.append(createdBy); + builder.append(", createdDate="); + builder.append(createdDate); + builder.append(", modifiedBy="); + builder.append(modifiedBy); + builder.append(", modifiedDate="); + builder.append(modifiedDate); + builder.append(", status="); + builder.append(status); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/cnf/CnfSmsProvider.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/cnf/CnfSmsProvider.java index 6b252d9ca..a63949172 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/cnf/CnfSmsProvider.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/cnf/CnfSmsProvider.java @@ -33,11 +33,11 @@ import jakarta.persistence.Table; public class CnfSmsProvider extends JpaEntity implements Serializable { - /** - * - */ - private static final long serialVersionUID = -4595539647817265938L; - @Id + /** + * + */ + private static final long serialVersionUID = -4595539647817265938L; + @Id @Column @GeneratedValue String id; @@ -70,189 +70,189 @@ public class CnfSmsProvider extends JpaEntity implements Serializable { @Column int status; - @Column - private String instId; + @Column + private String instId; - private String instName; + private String instName; public CnfSmsProvider() { } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getProvider() { - return provider; - } + public String getProvider() { + return provider; + } - public void setProvider(String provider) { - this.provider = provider; - } + public void setProvider(String provider) { + this.provider = provider; + } - public String getProviderName() { - return providerName; - } + public String getProviderName() { + return providerName; + } - public void setProviderName(String providerName) { - this.providerName = providerName; - } + public void setProviderName(String providerName) { + this.providerName = providerName; + } - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } - public void setMessage(String message) { - this.message = message; - } + public void setMessage(String message) { + this.message = message; + } - public String getAppKey() { - return appKey; - } + public String getAppKey() { + return appKey; + } - public void setAppKey(String appKey) { - this.appKey = appKey; - } + public void setAppKey(String appKey) { + this.appKey = appKey; + } - public String getAppSecret() { - return appSecret; - } + public String getAppSecret() { + return appSecret; + } - public void setAppSecret(String appSecret) { - this.appSecret = appSecret; - } + public void setAppSecret(String appSecret) { + this.appSecret = appSecret; + } - public String getTemplateId() { - return templateId; - } + public String getTemplateId() { + return templateId; + } - public void setTemplateId(String templateId) { - this.templateId = templateId; - } + public void setTemplateId(String templateId) { + this.templateId = templateId; + } - public String getSignName() { - return signName; - } + public String getSignName() { + return signName; + } - public void setSignName(String signName) { - this.signName = signName; - } + public void setSignName(String signName) { + this.signName = signName; + } - public String getSmsSdkAppId() { - return smsSdkAppId; - } + public String getSmsSdkAppId() { + return smsSdkAppId; + } - public void setSmsSdkAppId(String smsSdkAppId) { - this.smsSdkAppId = smsSdkAppId; - } + public void setSmsSdkAppId(String smsSdkAppId) { + this.smsSdkAppId = smsSdkAppId; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public String getCreatedBy() { - return createdBy; - } + public String getCreatedBy() { + return createdBy; + } - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } - public String getModifiedBy() { - return modifiedBy; - } + public String getModifiedBy() { + return modifiedBy; + } - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } - public Date getCreatedDate() { - return createdDate; - } + public Date getCreatedDate() { + return createdDate; + } - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } - public Date getModifiedDate() { - return modifiedDate; - } + public Date getModifiedDate() { + return modifiedDate; + } - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } - public int getStatus() { - return status; - } + public int getStatus() { + return status; + } - public void setStatus(int status) { - this.status = status; - } + public void setStatus(int status) { + this.status = status; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("SmsProvider [id="); - builder.append(id); - builder.append(", provider="); - builder.append(provider); - builder.append(", providerName="); - builder.append(providerName); - builder.append(", message="); - builder.append(message); - builder.append(", appKey="); - builder.append(appKey); - builder.append(", appSecret="); - builder.append(appSecret); - builder.append(", templateId="); - builder.append(templateId); - builder.append(", signName="); - builder.append(signName); - builder.append(", smsSdkAppId="); - builder.append(smsSdkAppId); - builder.append(", description="); - builder.append(description); - builder.append(", createdBy="); - builder.append(createdBy); - builder.append(", createdDate="); - builder.append(createdDate); - builder.append(", modifiedBy="); - builder.append(modifiedBy); - builder.append(", modifiedDate="); - builder.append(modifiedDate); - builder.append(", status="); - builder.append(status); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("SmsProvider [id="); + builder.append(id); + builder.append(", provider="); + builder.append(provider); + builder.append(", providerName="); + builder.append(providerName); + builder.append(", message="); + builder.append(message); + builder.append(", appKey="); + builder.append(appKey); + builder.append(", appSecret="); + builder.append(appSecret); + builder.append(", templateId="); + builder.append(templateId); + builder.append(", signName="); + builder.append(signName); + builder.append(", smsSdkAppId="); + builder.append(smsSdkAppId); + builder.append(", description="); + builder.append(description); + builder.append(", createdBy="); + builder.append(createdBy); + builder.append(", createdDate="); + builder.append(createdDate); + builder.append(", modifiedBy="); + builder.append(modifiedBy); + builder.append(", modifiedDate="); + builder.append(modifiedDate); + builder.append(", status="); + builder.append(status); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistoryConnector.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistoryConnector.java index 4f61c0f2b..912e76224 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistoryConnector.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistoryConnector.java @@ -32,209 +32,209 @@ import jakarta.persistence.Table; @Table(name = "MXK_HISTORY_CONNECTOR") public class HistoryConnector extends JpaEntity implements Serializable { - /** - * - */ - private static final long serialVersionUID = 3465459057253994386L; + /** + * + */ + private static final long serialVersionUID = 3465459057253994386L; - @Id - @Column - @GeneratedValue - String id; + @Id + @Column + @GeneratedValue + String id; - @Column - String conName; + @Column + String conName; - @Column - String topic; + @Column + String topic; - @Column - String actionType; + @Column + String actionType; - @Column - String sourceId; + @Column + String sourceId; - @Column - String sourceName; + @Column + String sourceName; - @Column - String objectId; + @Column + String objectId; - @Column - String objectName; + @Column + String objectName; - @Column - String description; + @Column + String description; - Date syncTime; + Date syncTime; - @Column - String result; + @Column + String result; - String startDate; + String startDate; - String endDate; + String endDate; - @Column - private String instId; + @Column + private String instId; - private String instName; + private String instName; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getConName() { - return conName; - } + public String getConName() { + return conName; + } - public void setConName(String conName) { - this.conName = conName; - } + public void setConName(String conName) { + this.conName = conName; + } - public String getSourceId() { - return sourceId; - } + public String getSourceId() { + return sourceId; + } - public void setSourceId(String sourceId) { - this.sourceId = sourceId; - } + public void setSourceId(String sourceId) { + this.sourceId = sourceId; + } - public String getSourceName() { - return sourceName; - } + public String getSourceName() { + return sourceName; + } - public void setSourceName(String sourceName) { - this.sourceName = sourceName; - } + public void setSourceName(String sourceName) { + this.sourceName = sourceName; + } - public String getObjectId() { - return objectId; - } + public String getObjectId() { + return objectId; + } - public void setObjectId(String objectId) { - this.objectId = objectId; - } + public void setObjectId(String objectId) { + this.objectId = objectId; + } - public String getObjectName() { - return objectName; - } + public String getObjectName() { + return objectName; + } - public void setObjectName(String objectName) { - this.objectName = objectName; - } + public void setObjectName(String objectName) { + this.objectName = objectName; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public Date getSyncTime() { - return syncTime; - } + public Date getSyncTime() { + return syncTime; + } - public void setSyncTime(Date syncTime) { - this.syncTime = syncTime; - } + public void setSyncTime(Date syncTime) { + this.syncTime = syncTime; + } - public String getResult() { - return result; - } + public String getResult() { + return result; + } - public String getTopic() { - return topic; - } + public String getTopic() { + return topic; + } - public void setTopic(String topic) { - this.topic = topic; - } + public void setTopic(String topic) { + this.topic = topic; + } - public String getActionType() { - return actionType; - } + public String getActionType() { + return actionType; + } - public void setActionType(String actionType) { - this.actionType = actionType; - } + public void setActionType(String actionType) { + this.actionType = actionType; + } - public void setResult(String result) { - this.result = result; - } + public void setResult(String result) { + this.result = result; + } - public String getStartDate() { - return startDate; - } + public String getStartDate() { + return startDate; + } - public void setStartDate(String startDate) { - this.startDate = startDate; - } + public void setStartDate(String startDate) { + this.startDate = startDate; + } - public String getEndDate() { - return endDate; - } + public String getEndDate() { + return endDate; + } - public void setEndDate(String endDate) { - this.endDate = endDate; - } + public void setEndDate(String endDate) { + this.endDate = endDate; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("HistoryConnector [id="); - builder.append(id); - builder.append(", conName="); - builder.append(conName); - builder.append(", topic="); - builder.append(topic); - builder.append(", actionType="); - builder.append(actionType); - builder.append(", sourceId="); - builder.append(sourceId); - builder.append(", sourceName="); - builder.append(sourceName); - builder.append(", objectId="); - builder.append(objectId); - builder.append(", objectName="); - builder.append(objectName); - builder.append(", description="); - builder.append(description); - builder.append(", syncTime="); - builder.append(syncTime); - builder.append(", result="); - builder.append(result); - builder.append(", startDate="); - builder.append(startDate); - builder.append(", endDate="); - builder.append(endDate); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("HistoryConnector [id="); + builder.append(id); + builder.append(", conName="); + builder.append(conName); + builder.append(", topic="); + builder.append(topic); + builder.append(", actionType="); + builder.append(actionType); + builder.append(", sourceId="); + builder.append(sourceId); + builder.append(", sourceName="); + builder.append(sourceName); + builder.append(", objectId="); + builder.append(objectId); + builder.append(", objectName="); + builder.append(objectName); + builder.append(", description="); + builder.append(description); + builder.append(", syncTime="); + builder.append(syncTime); + builder.append(", result="); + builder.append(result); + builder.append(", startDate="); + builder.append(startDate); + builder.append(", endDate="); + builder.append(endDate); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistoryLogin.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistoryLogin.java index b03474c02..c644bcdac 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistoryLogin.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistoryLogin.java @@ -37,244 +37,244 @@ import jakarta.persistence.Table; @Entity @Table(name = "MXK_HISTORY_LOGIN") public class HistoryLogin extends JpaEntity implements Serializable{ - - /** - * - */ - private static final long serialVersionUID = -1321470643357719383L; - @Id - @Column - @GeneratedValue - String id; - @Column - String sessionId; - @Column - int category; - @Column - String userId; - @Column - String username; - @Column - String displayName; - @Column - String loginType; - @Column - String message; - @Column - String code; - @Column - String provider; - @Column - String sourceIp; - @Column - String country; - @Column - String province; - @Column - String city; - @Column - String location; - @Column - String browser; - @Column - String platform; - @Column - String application; - @Column - Date loginTime; - @Column - Date logoutTime; - @Column - int sessionStatus; - @Column - private String instId; + + /** + * + */ + private static final long serialVersionUID = -1321470643357719383L; + @Id + @Column + @GeneratedValue + String id; + @Column + String sessionId; + @Column + int category; + @Column + String userId; + @Column + String username; + @Column + String displayName; + @Column + String loginType; + @Column + String message; + @Column + String code; + @Column + String provider; + @Column + String sourceIp; + @Column + String country; + @Column + String province; + @Column + String city; + @Column + String location; + @Column + String browser; + @Column + String platform; + @Column + String application; + @Column + Date loginTime; + @Column + Date logoutTime; + @Column + int sessionStatus; + @Column + private String instId; - private String instName; - - String startDate; - String endDate; - - public HistoryLogin() { - super(); - } + private String instName; + + String startDate; + String endDate; + + public HistoryLogin() { + super(); + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getSessionId() { - return sessionId; - } + public String getSessionId() { + return sessionId; + } - public void setSessionId(String sessionId) { - this.sessionId = sessionId; - } + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } - public int getCategory() { - return category; - } + public int getCategory() { + return category; + } - public void setCategory(int category) { - this.category = category; - } + public void setCategory(int category) { + this.category = category; + } - public String getUserId() { - return userId; - } + public String getUserId() { + return userId; + } - public void setUserId(String userId) { - this.userId = userId; - } + public void setUserId(String userId) { + this.userId = userId; + } - public String getUsername() { - return username; - } + public String getUsername() { + return username; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } - public String getDisplayName() { - return displayName; - } + public String getDisplayName() { + return displayName; + } - public void setDisplayName(String displayName) { - this.displayName = displayName; - } + public void setDisplayName(String displayName) { + this.displayName = displayName; + } - public String getLoginType() { - return loginType; - } + public String getLoginType() { + return loginType; + } - public void setLoginType(String loginType) { - this.loginType = loginType; - } + public void setLoginType(String loginType) { + this.loginType = loginType; + } - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } - public void setMessage(String message) { - this.message = message; - } + public void setMessage(String message) { + this.message = message; + } - public String getCode() { - return code; - } + public String getCode() { + return code; + } - public void setCode(String code) { - this.code = code; - } + public void setCode(String code) { + this.code = code; + } - public String getProvider() { - return provider; - } + public String getProvider() { + return provider; + } - public void setProvider(String provider) { - this.provider = provider; - } + public void setProvider(String provider) { + this.provider = provider; + } - public String getSourceIp() { - return sourceIp; - } + public String getSourceIp() { + return sourceIp; + } - public void setSourceIp(String sourceIp) { - this.sourceIp = sourceIp; - } + public void setSourceIp(String sourceIp) { + this.sourceIp = sourceIp; + } - public String getCountry() { - return country; - } + public String getCountry() { + return country; + } - public void setCountry(String country) { - this.country = country; - } + public void setCountry(String country) { + this.country = country; + } - public String getProvince() { - return province; - } + public String getProvince() { + return province; + } - public void setProvince(String province) { - this.province = province; - } + public void setProvince(String province) { + this.province = province; + } - public String getCity() { - return city; - } + public String getCity() { + return city; + } - public void setCity(String city) { - this.city = city; - } + public void setCity(String city) { + this.city = city; + } - public String getLocation() { - return location; - } + public String getLocation() { + return location; + } - public void setLocation(String location) { - this.location = location; - } + public void setLocation(String location) { + this.location = location; + } - public String getBrowser() { - return browser; - } + public String getBrowser() { + return browser; + } - public void setBrowser(String browser) { - this.browser = browser; - } + public void setBrowser(String browser) { + this.browser = browser; + } - public String getPlatform() { - return platform; - } + public String getPlatform() { + return platform; + } - public void setPlatform(String platform) { - this.platform = platform; - } + public void setPlatform(String platform) { + this.platform = platform; + } - public String getApplication() { - return application; - } + public String getApplication() { + return application; + } - public void setApplication(String application) { - this.application = application; - } + public void setApplication(String application) { + this.application = application; + } - public Date getLoginTime() { - return loginTime; - } + public Date getLoginTime() { + return loginTime; + } - public void setLoginTime(Date loginTime) { - this.loginTime = loginTime; - } + public void setLoginTime(Date loginTime) { + this.loginTime = loginTime; + } - public Date getLogoutTime() { - return logoutTime; - } + public Date getLogoutTime() { + return logoutTime; + } - public void setLogoutTime(Date logoutTime) { - this.logoutTime = logoutTime; - } + public void setLogoutTime(Date logoutTime) { + this.logoutTime = logoutTime; + } - public String getStartDate() { - return startDate; - } + public String getStartDate() { + return startDate; + } - public void setStartDate(String startDate) { - this.startDate = startDate; - } + public void setStartDate(String startDate) { + this.startDate = startDate; + } - public String getEndDate() { - return endDate; - } + public String getEndDate() { + return endDate; + } - public void setEndDate(String endDate) { - this.endDate = endDate; - } + public void setEndDate(String endDate) { + this.endDate = endDate; + } - public int getSessionStatus() { + public int getSessionStatus() { return sessionStatus; } @@ -283,73 +283,73 @@ public class HistoryLogin extends JpaEntity implements Serializable{ } public String getInstId() { - return instId; - } + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("HistoryLogin [id="); - builder.append(id); - builder.append(", sessionId="); - builder.append(sessionId); - builder.append(", userId="); - builder.append(userId); - builder.append(", username="); - builder.append(username); - builder.append(", displayName="); - builder.append(displayName); - builder.append(", loginType="); - builder.append(loginType); - builder.append(", message="); - builder.append(message); - builder.append(", code="); - builder.append(code); - builder.append(", provider="); - builder.append(provider); - builder.append(", sourceIp="); - builder.append(sourceIp); - builder.append(", country="); - builder.append(country); - builder.append(", province="); - builder.append(province); - builder.append(", city="); - builder.append(city); - builder.append(", location="); - builder.append(location); - builder.append(", browser="); - builder.append(browser); - builder.append(", platform="); - builder.append(platform); - builder.append(", application="); - builder.append(application); - builder.append(", loginTime="); - builder.append(loginTime); - builder.append(", logoutTime="); - builder.append(logoutTime); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append(", sessionStatus="); - builder.append(sessionStatus); - builder.append(", startDate="); - builder.append(startDate); - builder.append(", endDate="); - builder.append(endDate); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("HistoryLogin [id="); + builder.append(id); + builder.append(", sessionId="); + builder.append(sessionId); + builder.append(", userId="); + builder.append(userId); + builder.append(", username="); + builder.append(username); + builder.append(", displayName="); + builder.append(displayName); + builder.append(", loginType="); + builder.append(loginType); + builder.append(", message="); + builder.append(message); + builder.append(", code="); + builder.append(code); + builder.append(", provider="); + builder.append(provider); + builder.append(", sourceIp="); + builder.append(sourceIp); + builder.append(", country="); + builder.append(country); + builder.append(", province="); + builder.append(province); + builder.append(", city="); + builder.append(city); + builder.append(", location="); + builder.append(location); + builder.append(", browser="); + builder.append(browser); + builder.append(", platform="); + builder.append(platform); + builder.append(", application="); + builder.append(application); + builder.append(", loginTime="); + builder.append(loginTime); + builder.append(", logoutTime="); + builder.append(logoutTime); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append(", sessionStatus="); + builder.append(sessionStatus); + builder.append(", startDate="); + builder.append(startDate); + builder.append(", endDate="); + builder.append(endDate); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistoryLoginApps.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistoryLoginApps.java index c89df876c..6f09205c6 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistoryLoginApps.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistoryLoginApps.java @@ -35,207 +35,207 @@ import jakarta.persistence.Table; @Entity @Table(name = "MXK_HISTORY_LOGIN_APPS") public class HistoryLoginApps extends JpaEntity implements Serializable { - - private static final long serialVersionUID = 5085201575292304749L; - @Id - @Column - @GeneratedValue - String id; - @Column - private String sessionId; - @Column - private String appId; - @Column - private String appName; - @Column - private String userId; - @Column - private String username; - @Column - private String displayName; - @Column - private Date loginTime; - @Column - private String instId; + + private static final long serialVersionUID = 5085201575292304749L; + @Id + @Column + @GeneratedValue + String id; + @Column + private String sessionId; + @Column + private String appId; + @Column + private String appName; + @Column + private String userId; + @Column + private String username; + @Column + private String displayName; + @Column + private Date loginTime; + @Column + private String instId; - private String instName; - String startDate; - String endDate; - - /** - * - */ - public HistoryLoginApps() { - super(); - } - - - /** - * @return the id - */ - public String getId() { - return id; - } + private String instName; + String startDate; + String endDate; + + /** + * + */ + public HistoryLoginApps() { + super(); + } + + + /** + * @return the id + */ + public String getId() { + return id; + } - /** - * @param id the id to set - */ - public void setId(String id) { - this.id = id; - } + /** + * @param id the id to set + */ + public void setId(String id) { + this.id = id; + } - /** - * @param sessionId - * @param appId - */ - public HistoryLoginApps(String sessionId, String appId) { - super(); - this.sessionId = sessionId; - this.appId = appId; - } + /** + * @param sessionId + * @param appId + */ + public HistoryLoginApps(String sessionId, String appId) { + super(); + this.sessionId = sessionId; + this.appId = appId; + } - /** - * @return the sessionId - */ - public String getSessionId() { - return sessionId; - } - /** - * @param sessionId the sessionId to set - */ - public void setSessionId(String sessionId) { - this.sessionId = sessionId; - } - /** - * @return the appId - */ - public String getAppId() { - return appId; - } - /** - * @param appId the appId to set - */ - public void setAppId(String appId) { - this.appId = appId; - } - /** - * @return the appName - */ - public String getAppName() { - return appName; - } - /** - * @param appName the appName to set - */ - public void setAppName(String appName) { - this.appName = appName; - } - /** - * @return the loginTime - */ - public Date getLoginTime() { - return loginTime; - } - /** - * @param loginTime the loginTime to set - */ - public void setLoginTime(Date loginTime) { - this.loginTime = loginTime; - } + /** + * @return the sessionId + */ + public String getSessionId() { + return sessionId; + } + /** + * @param sessionId the sessionId to set + */ + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + /** + * @return the appId + */ + public String getAppId() { + return appId; + } + /** + * @param appId the appId to set + */ + public void setAppId(String appId) { + this.appId = appId; + } + /** + * @return the appName + */ + public String getAppName() { + return appName; + } + /** + * @param appName the appName to set + */ + public void setAppName(String appName) { + this.appName = appName; + } + /** + * @return the loginTime + */ + public Date getLoginTime() { + return loginTime; + } + /** + * @param loginTime the loginTime to set + */ + public void setLoginTime(Date loginTime) { + this.loginTime = loginTime; + } - /** - * @return the userId - */ - public String getUserId() { - return userId; - } + /** + * @return the userId + */ + public String getUserId() { + return userId; + } - /** - * @param uid the uid to set - */ - public void setUserId(String uid) { - this.userId = uid; - } + /** + * @param uid the uid to set + */ + public void setUserId(String uid) { + this.userId = uid; + } - /** - * @return the username - */ - public String getUsername() { - return username; - } + /** + * @return the username + */ + public String getUsername() { + return username; + } - /** - * @param username the username to set - */ - public void setUsername(String username) { - this.username = username; - } + /** + * @param username the username to set + */ + public void setUsername(String username) { + this.username = username; + } - /** - * @return the displayName - */ - public String getDisplayName() { - return displayName; - } + /** + * @return the displayName + */ + public String getDisplayName() { + return displayName; + } - /** - * @param displayName the displayName to set - */ - public void setDisplayName(String displayName) { - this.displayName = displayName; - } + /** + * @param displayName the displayName to set + */ + public void setDisplayName(String displayName) { + this.displayName = displayName; + } - public String getStartDate() { - return startDate; - } + public String getStartDate() { + return startDate; + } - public void setStartDate(String startDate) { - this.startDate = startDate; - } + public void setStartDate(String startDate) { + this.startDate = startDate; + } - public String getEndDate() { - return endDate; - } + public String getEndDate() { + return endDate; + } - public void setEndDate(String endDate) { - this.endDate = endDate; - } + public void setEndDate(String endDate) { + this.endDate = endDate; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override + @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("HistoryLoginApps [id="); diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistorySynchronizer.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistorySynchronizer.java index 4ff8da5b9..0998f7a4b 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistorySynchronizer.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistorySynchronizer.java @@ -58,45 +58,45 @@ public class HistorySynchronizer extends JpaEntity implements Serializable{ Date syncTime; @Column String result; - @Column - private String instId; + @Column + private String instId; - private String instName; + private String instName; String startDate; String endDate; public HistorySynchronizer(String id, String syncId, String syncName, String objectId, - String objectType, String objectName, String result,String instId) { - super(); - this.id = id; - this.syncId = syncId; - this.syncName = syncName; - this.objectId = objectId; - this.objectType = objectType; - this.objectName = objectName; - this.syncTime = new Date(); - this.result = result; - this.instId = instId; - } + String objectType, String objectName, String result,String instId) { + super(); + this.id = id; + this.syncId = syncId; + this.syncName = syncName; + this.objectId = objectId; + this.objectType = objectType; + this.objectName = objectName; + this.syncTime = new Date(); + this.result = result; + this.instId = instId; + } - public HistorySynchronizer(String id, String syncId, String sessionId, String syncName, String objectId, - String objectType, String objectName, String result, String instId) { - super(); - this.id = id; - this.syncId = syncId; - this.sessionId = sessionId; - this.syncName = syncName; - this.objectId = objectId; - this.objectType = objectType; - this.objectName = objectName; - this.syncTime = new Date(); - this.result = result; - this.instId = instId; - } + public HistorySynchronizer(String id, String syncId, String sessionId, String syncName, String objectId, + String objectType, String objectName, String result, String instId) { + super(); + this.id = id; + this.syncId = syncId; + this.sessionId = sessionId; + this.syncName = syncName; + this.objectId = objectId; + this.objectType = objectType; + this.objectName = objectName; + this.syncTime = new Date(); + this.result = result; + this.instId = instId; + } - public String getId() { + public String getId() { return id; } public void setId(String id) { @@ -168,18 +168,18 @@ public class HistorySynchronizer extends JpaEntity implements Serializable{ } public String getInstId() { - return instId; - } - public void setInstId(String instId) { - this.instId = instId; - } - public String getInstName() { - return instName; - } - public void setInstName(String instName) { - this.instName = instName; - } - @Override + return instId; + } + public void setInstId(String instId) { + this.instId = instId; + } + public String getInstName() { + return instName; + } + public void setInstName(String instName) { + this.instName = instName; + } + @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("HistorySynchronizer [id="); diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistorySystemLogs.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistorySystemLogs.java index a8b8de4d5..b856f1fa3 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistorySystemLogs.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/history/HistorySystemLogs.java @@ -57,12 +57,12 @@ public class HistorySystemLogs extends JpaEntity implements Serializable { String displayName; @Column Date executeTime; - @Column - private String instId; + @Column + private String instId; - String jsonCotent; - - private String instName; + String jsonCotent; + + private String instName; String startDate; String endDate; @@ -70,143 +70,143 @@ public class HistorySystemLogs extends JpaEntity implements Serializable { super(); } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getTopic() { - return topic; - } + public String getTopic() { + return topic; + } - public void setTopic(String topic) { - this.topic = topic; - } + public void setTopic(String topic) { + this.topic = topic; + } - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } - public void setMessage(String message) { - this.message = message; - } + public void setMessage(String message) { + this.message = message; + } - public String getMessageAction() { - return messageAction; - } + public String getMessageAction() { + return messageAction; + } - public void setMessageAction(String messageAction) { - this.messageAction = messageAction; - } + public void setMessageAction(String messageAction) { + this.messageAction = messageAction; + } - public String getMessageResult() { - return messageResult; - } + public String getMessageResult() { + return messageResult; + } - public void setMessageResult(String messageResult) { - this.messageResult = messageResult; - } + public void setMessageResult(String messageResult) { + this.messageResult = messageResult; + } - public String getUserId() { - return userId; - } + public String getUserId() { + return userId; + } - public void setUserId(String userId) { - this.userId = userId; - } + public void setUserId(String userId) { + this.userId = userId; + } - public String getUsername() { - return username; - } + public String getUsername() { + return username; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } - public String getDisplayName() { - return displayName; - } + public String getDisplayName() { + return displayName; + } - public void setDisplayName(String displayName) { - this.displayName = displayName; - } + public void setDisplayName(String displayName) { + this.displayName = displayName; + } - public Date getExecuteTime() { - return executeTime; - } + public Date getExecuteTime() { + return executeTime; + } - public void setExecuteTime(Date executeTime) { - this.executeTime = executeTime; - } + public void setExecuteTime(Date executeTime) { + this.executeTime = executeTime; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - public String getStartDate() { - return startDate; - } + public String getStartDate() { + return startDate; + } - public void setStartDate(String startDate) { - this.startDate = startDate; - } + public void setStartDate(String startDate) { + this.startDate = startDate; + } - public String getEndDate() { - return endDate; - } + public String getEndDate() { + return endDate; + } - public void setEndDate(String endDate) { - this.endDate = endDate; - } + public void setEndDate(String endDate) { + this.endDate = endDate; + } - public String getJsonCotent() { - return jsonCotent; - } + public String getJsonCotent() { + return jsonCotent; + } - public void setJsonCotent(String jsonCotent) { - this.jsonCotent = jsonCotent; - } + public void setJsonCotent(String jsonCotent) { + this.jsonCotent = jsonCotent; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("HistorySystemLogs [id="); - builder.append(id); - builder.append(", topic="); - builder.append(topic); - builder.append(", message="); - builder.append(message); - builder.append(", messageAction="); - builder.append(messageAction); - builder.append(", messageResult="); - builder.append(messageResult); - builder.append(", userId="); - builder.append(userId); - builder.append(", username="); - builder.append(username); - builder.append(", displayName="); - builder.append(displayName); - builder.append(", executeTime="); - builder.append(executeTime); - builder.append(", jsonCotent="); - builder.append(jsonCotent); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("HistorySystemLogs [id="); + builder.append(id); + builder.append(", topic="); + builder.append(topic); + builder.append(", message="); + builder.append(message); + builder.append(", messageAction="); + builder.append(messageAction); + builder.append(", messageResult="); + builder.append(messageResult); + builder.append(", userId="); + builder.append(userId); + builder.append(", username="); + builder.append(username); + builder.append(", displayName="); + builder.append(displayName); + builder.append(", executeTime="); + builder.append(executeTime); + builder.append(", jsonCotent="); + builder.append(jsonCotent); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/idm/GroupMember.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/idm/GroupMember.java index 63a5c6baf..75e0f4ab8 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/idm/GroupMember.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/idm/GroupMember.java @@ -29,183 +29,183 @@ import jakarta.persistence.Table; @Table(name = "mxk_group_member") public class GroupMember extends UserInfo implements Serializable{ - /** - * - */ - private static final long serialVersionUID = -8059639972590554760L; - @Id - @Column - @GeneratedValue - String id; - @Column - private String groupId; - private String groupName; - private String category; - @Column - private String memberId; - private String memberName; - @Column - private String type;//User or Group + /** + * + */ + private static final long serialVersionUID = -8059639972590554760L; + @Id + @Column + @GeneratedValue + String id; + @Column + private String groupId; + private String groupName; + private String category; + @Column + private String memberId; + private String memberName; + @Column + private String type;//User or Group - @Column - private String instId; + @Column + private String instId; - private String instName; - - public GroupMember(){ - super(); - } + private String instName; + + public GroupMember(){ + super(); + } - - /** - * @param groupId - * @param memberId - * @param type - */ - public GroupMember(String groupId, String memberId, String type , String instId) { - super(); - this.groupId = groupId; - this.memberId = memberId; - this.type = type; - this.instId = instId; - } + + /** + * @param groupId + * @param memberId + * @param type + */ + public GroupMember(String groupId, String memberId, String type , String instId) { + super(); + this.groupId = groupId; + this.memberId = memberId; + this.type = type; + this.instId = instId; + } - public GroupMember(String groupId, String groupName, String memberId, - String memberName, String type , String instId) { - super(); - this.groupId = groupId; - this.groupName = groupName; - this.memberId = memberId; - this.memberName = memberName; - this.type = type; - this.instId = instId; - } + public GroupMember(String groupId, String groupName, String memberId, + String memberName, String type , String instId) { + super(); + this.groupId = groupId; + this.groupName = groupName; + this.memberId = memberId; + this.memberName = memberName; + this.type = type; + this.instId = instId; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getGroupId() { - return groupId; - } + public String getGroupId() { + return groupId; + } - public void setGroupId(String groupId) { - this.groupId = groupId; - } + public void setGroupId(String groupId) { + this.groupId = groupId; + } - public String getGroupName() { - return groupName; - } + public String getGroupName() { + return groupName; + } - public void setGroupName(String groupName) { - this.groupName = groupName; - } + public void setGroupName(String groupName) { + this.groupName = groupName; + } - /** - * @return the memberId - */ - public String getMemberId() { - return memberId; - } + /** + * @return the memberId + */ + public String getMemberId() { + return memberId; + } - /** - * @param memberId the memberId to set - */ - public void setMemberId(String memberId) { - this.memberId = memberId; - } + /** + * @param memberId the memberId to set + */ + public void setMemberId(String memberId) { + this.memberId = memberId; + } - /** - * @return the type - */ - public String getType() { - return type; - } + /** + * @return the type + */ + public String getType() { + return type; + } - /** - * @param type the type to set - */ - public void setType(String type) { - this.type = type; - } + /** + * @param type the type to set + */ + public void setType(String type) { + this.type = type; + } - public String getMemberName() { - return memberName; - } + public String getMemberName() { + return memberName; + } - public void setMemberName(String memberName) { - this.memberName = memberName; - } + public void setMemberName(String memberName) { + this.memberName = memberName; + } - public String getCategory() { - return category; - } + public String getCategory() { + return category; + } - public void setCategory(String category) { - this.category = category; - } + public void setCategory(String category) { + this.category = category; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("GroupMember [id="); - builder.append(id); - builder.append(", groupId="); - builder.append(groupId); - builder.append(", groupName="); - builder.append(groupName); - builder.append(", category="); - builder.append(category); - builder.append(", memberId="); - builder.append(memberId); - builder.append(", memberName="); - builder.append(memberName); - builder.append(", type="); - builder.append(type); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("GroupMember [id="); + builder.append(id); + builder.append(", groupId="); + builder.append(groupId); + builder.append(", groupName="); + builder.append(groupName); + builder.append(", category="); + builder.append(category); + builder.append(", memberId="); + builder.append(memberId); + builder.append(", memberName="); + builder.append(memberName); + builder.append(", type="); + builder.append(type); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/idm/Groups.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/idm/Groups.java index 895d1869c..ca96200a2 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/idm/Groups.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/idm/Groups.java @@ -36,11 +36,11 @@ public class Groups extends JpaEntity implements Serializable { private static final long serialVersionUID = 4660258495864814777L; public class Category{ - public static final String DYNAMIC = "dynamic"; - - public static final String STATIC = "static"; - - public static final String APP = "app"; + public static final String DYNAMIC = "dynamic"; + + public static final String STATIC = "static"; + + public static final String APP = "app"; } @@ -81,10 +81,10 @@ public class Groups extends JpaEntity implements Serializable { @Column int status; - @Column - private String instId; + @Column + private String instId; - private String instName; + private String instName; public Groups() { } @@ -107,7 +107,7 @@ public class Groups extends JpaEntity implements Serializable { this.isdefault = isdefault; } - public String getId() { + public String getId() { return id; } @@ -115,24 +115,24 @@ public class Groups extends JpaEntity implements Serializable { this.id = id; } - + public String getGroupCode() { - return groupCode; - } + return groupCode; + } - public void setGroupCode(String groupCode) { - this.groupCode = groupCode; - } + public void setGroupCode(String groupCode) { + this.groupCode = groupCode; + } - public String getGroupName() { - return groupName; - } + public String getGroupName() { + return groupName; + } - public void setGroupName(String groupName) { - this.groupName = groupName; - } + public void setGroupName(String groupName) { + this.groupName = groupName; + } - public int getIsdefault() { + public int getIsdefault() { return isdefault; } @@ -165,22 +165,22 @@ public class Groups extends JpaEntity implements Serializable { } public Date getCreatedDate() { - return createdDate; - } + return createdDate; + } - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } - public Date getModifiedDate() { - return modifiedDate; - } + public Date getModifiedDate() { + return modifiedDate; + } - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } - public int getStatus() { + public int getStatus() { return status; } @@ -190,25 +190,25 @@ public class Groups extends JpaEntity implements Serializable { /** * ROLE_ALL_USER must be - * 1, dynamic - * 2, all orgIdsList - * 3, not filters + * 1, dynamic + * 2, all orgIdsList + * 3, not filters */ public void setDefaultAllUser() { - this.category = "dynamic"; - this.orgIdsList =""; - this.filters =""; + this.category = "dynamic"; + this.orgIdsList =""; + this.filters =""; } public String getCategory() { - return category; - } + return category; + } - public void setCategory(String category) { - this.category = category; - } + public void setCategory(String category) { + this.category = category; + } - public String getFilters() { + public String getFilters() { return filters; } @@ -225,56 +225,56 @@ public class Groups extends JpaEntity implements Serializable { } public String getInstId() { - return instId; - } + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Groups [id="); - builder.append(id); - builder.append(", groupCode="); - builder.append(groupCode); - builder.append(", groupName="); - builder.append(groupName); - builder.append(", category="); - builder.append(category); - builder.append(", filters="); - builder.append(filters); - builder.append(", orgIdsList="); - builder.append(orgIdsList); - builder.append(", isdefault="); - builder.append(isdefault); - builder.append(", description="); - builder.append(description); - builder.append(", createdBy="); - builder.append(createdBy); - builder.append(", createdDate="); - builder.append(createdDate); - builder.append(", modifiedBy="); - builder.append(modifiedBy); - builder.append(", modifiedDate="); - builder.append(modifiedDate); - builder.append(", status="); - builder.append(status); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Groups [id="); + builder.append(id); + builder.append(", groupCode="); + builder.append(groupCode); + builder.append(", groupName="); + builder.append(groupName); + builder.append(", category="); + builder.append(category); + builder.append(", filters="); + builder.append(filters); + builder.append(", orgIdsList="); + builder.append(orgIdsList); + builder.append(", isdefault="); + builder.append(isdefault); + builder.append(", description="); + builder.append(description); + builder.append(", createdBy="); + builder.append(createdBy); + builder.append(", createdDate="); + builder.append(createdDate); + builder.append(", modifiedBy="); + builder.append(modifiedBy); + builder.append(", modifiedDate="); + builder.append(modifiedDate); + builder.append(", status="); + builder.append(status); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/idm/Organizations.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/idm/Organizations.java index 3a2234bf9..51f82b081 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/idm/Organizations.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/idm/Organizations.java @@ -111,11 +111,11 @@ public class Organizations extends JpaEntity implements Serializable { @Column Date modifiedDate; - @Column - private String instId; + @Column + private String instId; - private String instName; - + private String instName; + String syncId; String syncName; @@ -141,22 +141,22 @@ public class Organizations extends JpaEntity implements Serializable { } public String getOrgCode() { - return orgCode; - } + return orgCode; + } - public void setOrgCode(String orgCode) { - this.orgCode = orgCode; - } + public void setOrgCode(String orgCode) { + this.orgCode = orgCode; + } - public String getOrgName() { - return orgName; - } + public String getOrgName() { + return orgName; + } - public void setOrgName(String orgName) { - this.orgName = orgName; - } + public void setOrgName(String orgName) { + this.orgName = orgName; + } - public String getFullName() { + public String getFullName() { return fullName; } @@ -175,14 +175,14 @@ public class Organizations extends JpaEntity implements Serializable { } public String getParentCode() { - return parentCode; - } + return parentCode; + } - public void setParentCode(String parentCode) { - this.parentCode = parentCode; - } + public void setParentCode(String parentCode) { + this.parentCode = parentCode; + } - public String getParentName() { + public String getParentName() { return parentName; } @@ -337,14 +337,14 @@ public class Organizations extends JpaEntity implements Serializable { public String getLdapDn() { - return ldapDn; - } + return ldapDn; + } - public void setLdapDn(String ldapDn) { - this.ldapDn = ldapDn; - } + public void setLdapDn(String ldapDn) { + this.ldapDn = ldapDn; + } - public int getStatus() { + public int getStatus() { return status; } @@ -352,7 +352,7 @@ public class Organizations extends JpaEntity implements Serializable { this.status = status; } - public int getIsPrimary() { + public int getIsPrimary() { return isPrimary; } @@ -369,87 +369,87 @@ public class Organizations extends JpaEntity implements Serializable { } public String getCreatedBy() { - return createdBy; - } + return createdBy; + } - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } - public String getModifiedBy() { - return modifiedBy; - } + public String getModifiedBy() { + return modifiedBy; + } - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } - public Date getCreatedDate() { - return createdDate; - } + public Date getCreatedDate() { + return createdDate; + } - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } - public Date getModifiedDate() { - return modifiedDate; - } + public Date getModifiedDate() { + return modifiedDate; + } - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - - public String getSyncId() { - return syncId; - } + + public String getSyncId() { + return syncId; + } - public void setSyncId(String syncId) { - this.syncId = syncId; - } + public void setSyncId(String syncId) { + this.syncId = syncId; + } - public String getSyncName() { - return syncName; - } + public String getSyncName() { + return syncName; + } - public void setSyncName(String syncName) { - this.syncName = syncName; - } + public void setSyncName(String syncName) { + this.syncName = syncName; + } - public String getOriginId() { - return originId; - } + public String getOriginId() { + return originId; + } - public void setOriginId(String originId) { - this.originId = originId; - } + public void setOriginId(String originId) { + this.originId = originId; + } - public String getOriginId2() { - return originId2; - } + public String getOriginId2() { + return originId2; + } - public void setOriginId2(String originId2) { - this.originId2 = originId2; - } + public void setOriginId2(String originId2) { + this.originId2 = originId2; + } - @Override + @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Organizations [id="); diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/idm/UserInfo.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/idm/UserInfo.java index c25c18070..e004fc61c 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/idm/UserInfo.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/idm/UserInfo.java @@ -283,11 +283,11 @@ public class UserInfo extends JpaEntity implements Serializable { @Column String description; - @Column - private String instId; + @Column + private String instId; - private String instName; - + private String instName; + String syncId; String syncName; @@ -295,85 +295,85 @@ public class UserInfo extends JpaEntity implements Serializable { String originId; String originId2; - + List depts; public static class ONLINE { // 在线 - public static final int ONLINE = 1; + public static final int ONLINE = 1; // 下线 - public static final int OFFLINE = 0; + public static final int OFFLINE = 0; } public static class MARRIED { // 未知 - public static final int UNKNOWN = 0; + public static final int UNKNOWN = 0; // 单身 - public static final int SINGLE = 1; + public static final int SINGLE = 1; // 结婚 - public static final int MARRIED = 2; + public static final int MARRIED = 2; // 离异 - public static final int DIVORCE = 3; + public static final int DIVORCE = 3; // 丧偶 - public static final int WIDOWED = 4; + public static final int WIDOWED = 4; } public static class GENDER { // 未知 - public static final int UNKNOWN = 0; + public static final int UNKNOWN = 0; // 女性 - public static final int FEMALE = 1; + public static final int FEMALE = 1; // 男性 - public static final int MALE = 2; + public static final int MALE = 2; } public static class IDTYPE { // 未知 - public static final int UNKNOWN = 0; + public static final int UNKNOWN = 0; // 身份证 - public static final int IDCARD = 1; + public static final int IDCARD = 1; // 护照 - public static final int PASSPORT = 2; + public static final int PASSPORT = 2; // 学生证 - public static final int STUDENTCARD = 3; + public static final int STUDENTCARD = 3; // 军人证 - public static final int MILITARYCARD = 4; + public static final int MILITARYCARD = 4; } public static class AUTHNTYPE { // 用户名密码 - public static final int NORMAL = 1; + public static final int NORMAL = 1; // 手机 - public static final int MOBILE = 2; + public static final int MOBILE = 2; // 短信 - public static final int SMS = 3; + public static final int SMS = 3; // 邮箱 - public static final int EMAIL = 4; + public static final int EMAIL = 4; - public static final int TIMEBASED_OPT = 5; + public static final int TIMEBASED_OPT = 5; - public static final int COUNTERBASED_OPT = 6; + public static final int COUNTERBASED_OPT = 6; - public static final int HOTP_OPT = 7; + public static final int HOTP_OPT = 7; - public static final int RSA_OPT = 8; + public static final int RSA_OPT = 8; // 证书 - public static final int CERTIFICATE = 9; + public static final int CERTIFICATE = 9; // usb证书 - public static final int USBKEY = 10; + public static final int USBKEY = 10; } public static class EMPLOYMENTSTATUS { // 在册人员 - public static final int ACTIVE = 1; + public static final int ACTIVE = 1; // 离职人员 - public static final int WITHDRAWN = 2; + public static final int WITHDRAWN = 2; // 停薪留职人员 - public static final int INACTIVE = 3; + public static final int INACTIVE = 3; // 退休人员 - public static final int RETIREE = 4; + public static final int RETIREE = 4; } @@ -398,15 +398,15 @@ public class UserInfo extends JpaEntity implements Serializable { this.id = id; } - public String getSessionId() { - return sessionId; - } + public String getSessionId() { + return sessionId; + } - public void setSessionId(String sessionId) { - this.sessionId = sessionId; - } + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } - /** + /** * @param username */ public UserInfo(String username) { @@ -426,24 +426,24 @@ public class UserInfo extends JpaEntity implements Serializable { public String getPictureBase64() { - return pictureBase64; - } + return pictureBase64; + } - public void setPictureBase64(String pictureBase64) { - this.pictureBase64 = pictureBase64; - } + public void setPictureBase64(String pictureBase64) { + this.pictureBase64 = pictureBase64; + } - public void transPictureBase64() { - if(picture != null) { - this.pictureBase64 = Base64Utils.encodeImage(picture); - } - } - - public byte[] getPicture() { - return picture; - } + public void transPictureBase64() { + if(picture != null) { + this.pictureBase64 = Base64Utils.encodeImage(picture); + } + } + + public byte[] getPicture() { + return picture; + } - /** + /** * @return the protectedAppsMap */ public HashMap getProtectedAppsMap() { @@ -479,14 +479,14 @@ public class UserInfo extends JpaEntity implements Serializable { } public String getWorkOfficeName() { - return workOfficeName; - } + return workOfficeName; + } - public void setWorkOfficeName(String workOfficeName) { - this.workOfficeName = workOfficeName; - } + public void setWorkOfficeName(String workOfficeName) { + this.workOfficeName = workOfficeName; + } - public String getDecipherable() { + public String getDecipherable() { return decipherable; } @@ -543,30 +543,30 @@ public class UserInfo extends JpaEntity implements Serializable { } public String getEducation() { - return education; - } + return education; + } - public void setEducation(String education) { - this.education = education; - } + public void setEducation(String education) { + this.education = education; + } - public String getGraduateFrom() { - return graduateFrom; - } + public String getGraduateFrom() { + return graduateFrom; + } - public void setGraduateFrom(String graduateFrom) { - this.graduateFrom = graduateFrom; - } + public void setGraduateFrom(String graduateFrom) { + this.graduateFrom = graduateFrom; + } - public String getGraduateDate() { - return graduateDate; - } + public String getGraduateDate() { + return graduateDate; + } - public void setGraduateDate(String graduateDate) { - this.graduateDate = graduateDate; - } + public void setGraduateDate(String graduateDate) { + this.graduateDate = graduateDate; + } - public String getNameZhSpell() { + public String getNameZhSpell() { return nameZhSpell; } @@ -654,15 +654,15 @@ public class UserInfo extends JpaEntity implements Serializable { this.birthDate = birthDate; } - public String getPictureId() { - return pictureId; - } + public String getPictureId() { + return pictureId; + } - public void setPictureId(String pictureId) { - this.pictureId = pictureId; - } + public void setPictureId(String pictureId) { + this.pictureId = pictureId; + } - public int getIdType() { + public int getIdType() { return idType; } @@ -1237,104 +1237,104 @@ public class UserInfo extends JpaEntity implements Serializable { } /** - * @return the passwordLastSetTime - */ - public Date getPasswordLastSetTime() { - return passwordLastSetTime; - } + * @return the passwordLastSetTime + */ + public Date getPasswordLastSetTime() { + return passwordLastSetTime; + } - /** - * @param passwordLastSetTime the passwordLastSetTime to set - */ - public void setPasswordLastSetTime(Date passwordLastSetTime) { - this.passwordLastSetTime = passwordLastSetTime; - } + /** + * @param passwordLastSetTime the passwordLastSetTime to set + */ + public void setPasswordLastSetTime(Date passwordLastSetTime) { + this.passwordLastSetTime = passwordLastSetTime; + } - /** - * @return the badPasswordTime - */ - public Date getBadPasswordTime() { - return badPasswordTime; - } + /** + * @return the badPasswordTime + */ + public Date getBadPasswordTime() { + return badPasswordTime; + } - /** - * @param badPasswordTime the badPasswordTime to set - */ - public void setBadPasswordTime(Date badPasswordTime) { - this.badPasswordTime = badPasswordTime; - } + /** + * @param badPasswordTime the badPasswordTime to set + */ + public void setBadPasswordTime(Date badPasswordTime) { + this.badPasswordTime = badPasswordTime; + } - /** - * @return the unLockTime - */ - public Date getUnLockTime() { - return unLockTime; - } + /** + * @return the unLockTime + */ + public Date getUnLockTime() { + return unLockTime; + } - /** - * @param unLockTime the unLockTime to set - */ - public void setUnLockTime(Date unLockTime) { - this.unLockTime = unLockTime; - } + /** + * @param unLockTime the unLockTime to set + */ + public void setUnLockTime(Date unLockTime) { + this.unLockTime = unLockTime; + } - /** - * @return the lastLoginTime - */ - public Date getLastLoginTime() { - return lastLoginTime; - } + /** + * @return the lastLoginTime + */ + public Date getLastLoginTime() { + return lastLoginTime; + } - /** - * @param lastLoginTime the lastLoginTime to set - */ - public void setLastLoginTime(Date lastLoginTime) { - this.lastLoginTime = lastLoginTime; - } + /** + * @param lastLoginTime the lastLoginTime to set + */ + public void setLastLoginTime(Date lastLoginTime) { + this.lastLoginTime = lastLoginTime; + } - /** - * @return the lastLogoffTime - */ - public Date getLastLogoffTime() { - return lastLogoffTime; - } + /** + * @return the lastLogoffTime + */ + public Date getLastLogoffTime() { + return lastLogoffTime; + } - /** - * @param lastLogoffTime the lastLogoffTime to set - */ - public void setLastLogoffTime(Date lastLogoffTime) { - this.lastLogoffTime = lastLogoffTime; - } + /** + * @param lastLogoffTime the lastLogoffTime to set + */ + public void setLastLogoffTime(Date lastLogoffTime) { + this.lastLogoffTime = lastLogoffTime; + } - /** - * @return the createdDate - */ - public Date getCreatedDate() { - return createdDate; - } + /** + * @return the createdDate + */ + public Date getCreatedDate() { + return createdDate; + } - /** - * @param createdDate the createdDate to set - */ - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } + /** + * @param createdDate the createdDate to set + */ + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } - /** - * @return the modifiedDate - */ - public Date getModifiedDate() { - return modifiedDate; - } + /** + * @return the modifiedDate + */ + public Date getModifiedDate() { + return modifiedDate; + } - /** - * @param modifiedDate the modifiedDate to set - */ - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } + /** + * @param modifiedDate the modifiedDate to set + */ + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } - public String getTheme() { + public String getTheme() { return theme; } @@ -1344,12 +1344,12 @@ public class UserInfo extends JpaEntity implements Serializable { public String getUserState() { - return userState; - } + return userState; + } - public void setUserState(String userState) { - this.userState = userState; - } + public void setUserState(String userState) { + this.userState = userState; + } public List getDepts() { return depts; @@ -1360,279 +1360,279 @@ public class UserInfo extends JpaEntity implements Serializable { } public String getInstId() { - return instId; - } + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - public String getRegionHistory() { - return regionHistory; - } + public String getRegionHistory() { + return regionHistory; + } - public void setRegionHistory(String regionHistory) { - this.regionHistory = regionHistory; - } + public void setRegionHistory(String regionHistory) { + this.regionHistory = regionHistory; + } - public String getPasswordHistory() { - return passwordHistory; - } + public String getPasswordHistory() { + return passwordHistory; + } - public void setPasswordHistory(String passwordHistory) { - this.passwordHistory = passwordHistory; - } + public void setPasswordHistory(String passwordHistory) { + this.passwordHistory = passwordHistory; + } - public String getSyncId() { - return syncId; - } + public String getSyncId() { + return syncId; + } - public void setSyncId(String syncId) { - this.syncId = syncId; - } + public void setSyncId(String syncId) { + this.syncId = syncId; + } - public String getSyncName() { - return syncName; - } + public String getSyncName() { + return syncName; + } - public void setSyncName(String syncName) { - this.syncName = syncName; - } + public void setSyncName(String syncName) { + this.syncName = syncName; + } - public String getOriginId() { - return originId; - } + public String getOriginId() { + return originId; + } - public void setOriginId(String originId) { - this.originId = originId; - } + public void setOriginId(String originId) { + this.originId = originId; + } - public String getOriginId2() { - return originId2; - } + public String getOriginId2() { + return originId2; + } - public void setOriginId2(String originId2) { - this.originId2 = originId2; - } - - public void trans() { - this.setPassword(""); - this.setDecipherable(""); - this.transPictureBase64(); - } - - public void clearPassword() { - this.setPassword(null); - this.setDecipherable(null); - } + public void setOriginId2(String originId2) { + this.originId2 = originId2; + } + + public void trans() { + this.setPassword(""); + this.setDecipherable(""); + this.transPictureBase64(); + } + + public void clearPassword() { + this.setPassword(null); + this.setDecipherable(null); + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("UserInfo [id="); - builder.append(id); - builder.append(", username="); - builder.append(username); - builder.append(", sharedSecret="); - builder.append(sharedSecret); - builder.append(", sharedCounter="); - builder.append(sharedCounter); - builder.append(", userType="); - builder.append(userType); - builder.append(", userState="); - builder.append(userState); - builder.append(", windowsAccount="); - builder.append(windowsAccount); - builder.append(", displayName="); - builder.append(displayName); - builder.append(", nickName="); - builder.append(nickName); - builder.append(", nameZhSpell="); - builder.append(nameZhSpell); - builder.append(", nameZhShortSpell="); - builder.append(nameZhShortSpell); - builder.append(", givenName="); - builder.append(givenName); - builder.append(", middleName="); - builder.append(middleName); - builder.append(", familyName="); - builder.append(familyName); - builder.append(", honorificPrefix="); - builder.append(honorificPrefix); - builder.append(", honorificSuffix="); - builder.append(honorificSuffix); - builder.append(", formattedName="); - builder.append(formattedName); - builder.append(", married="); - builder.append(married); - builder.append(", gender="); - builder.append(gender); - builder.append(", birthDate="); - builder.append(birthDate); - builder.append(", idType="); - builder.append(idType); - builder.append(", idCardNo="); - builder.append(idCardNo); - builder.append(", webSite="); - builder.append(webSite); - builder.append(", startWorkDate="); - builder.append(startWorkDate); - builder.append(", authnType="); - builder.append(authnType); - builder.append(", email="); - builder.append(email); - builder.append(", emailVerified="); - builder.append(emailVerified); - builder.append(", mobile="); - builder.append(mobile); - builder.append(", mobileVerified="); - builder.append(mobileVerified); - builder.append(", passwordQuestion="); - builder.append(passwordQuestion); - builder.append(", passwordAnswer="); - builder.append(passwordAnswer); - builder.append(", appLoginAuthnType="); - builder.append(appLoginAuthnType); - builder.append(", appLoginPassword="); - builder.append(appLoginPassword); - builder.append(", protectedApps="); - builder.append(protectedApps); - builder.append(", protectedAppsMap="); - builder.append(protectedAppsMap); - builder.append(", passwordLastSetTime="); - builder.append(passwordLastSetTime); - builder.append(", badPasswordCount="); - builder.append(badPasswordCount); - builder.append(", badPasswordTime="); - builder.append(badPasswordTime); - builder.append(", unLockTime="); - builder.append(unLockTime); - builder.append(", isLocked="); - builder.append(isLocked); - builder.append(", lastLoginTime="); - builder.append(lastLoginTime); - builder.append(", lastLoginIp="); - builder.append(lastLoginIp); - builder.append(", lastLogoffTime="); - builder.append(lastLogoffTime); - builder.append(", passwordSetType="); - builder.append(passwordSetType); - builder.append(", loginCount="); - builder.append(loginCount); - builder.append(", locale="); - builder.append(locale); - builder.append(", timeZone="); - builder.append(timeZone); - builder.append(", preferredLanguage="); - builder.append(preferredLanguage); - builder.append(", workCountry="); - builder.append(workCountry); - builder.append(", workRegion="); - builder.append(workRegion); - builder.append(", workLocality="); - builder.append(workLocality); - builder.append(", workStreetAddress="); - builder.append(workStreetAddress); - builder.append(", workAddressFormatted="); - builder.append(workAddressFormatted); - builder.append(", workEmail="); - builder.append(workEmail); - builder.append(", workPhoneNumber="); - builder.append(workPhoneNumber); - builder.append(", workPostalCode="); - builder.append(workPostalCode); - builder.append(", workFax="); - builder.append(workFax); - builder.append(", workOfficeName="); - builder.append(workOfficeName); - builder.append(", homeCountry="); - builder.append(homeCountry); - builder.append(", homeRegion="); - builder.append(homeRegion); - builder.append(", homeLocality="); - builder.append(homeLocality); - builder.append(", homeStreetAddress="); - builder.append(homeStreetAddress); - builder.append(", homeAddressFormatted="); - builder.append(homeAddressFormatted); - builder.append(", homeEmail="); - builder.append(homeEmail); - builder.append(", homePhoneNumber="); - builder.append(homePhoneNumber); - builder.append(", homePostalCode="); - builder.append(homePostalCode); - builder.append(", homeFax="); - builder.append(homeFax); - builder.append(", employeeNumber="); - builder.append(employeeNumber); - builder.append(", costCenter="); - builder.append(costCenter); - builder.append(", organization="); - builder.append(organization); - builder.append(", division="); - builder.append(division); - builder.append(", departmentId="); - builder.append(departmentId); - builder.append(", department="); - builder.append(department); - builder.append(", jobTitle="); - builder.append(jobTitle); - builder.append(", jobLevel="); - builder.append(jobLevel); - builder.append(", managerId="); - builder.append(managerId); - builder.append(", manager="); - builder.append(manager); - builder.append(", assistantId="); - builder.append(assistantId); - builder.append(", assistant="); - builder.append(assistant); - builder.append(", entryDate="); - builder.append(entryDate); - builder.append(", quitDate="); - builder.append(quitDate); - builder.append(", defineIm="); - builder.append(defineIm); - builder.append(", weixinFollow="); - builder.append(weixinFollow); - builder.append(", theme="); - builder.append(theme); - builder.append(", extraAttribute="); - builder.append(extraAttribute); - builder.append(", extraAttributeName="); - builder.append(extraAttributeName); - builder.append(", extraAttributeValue="); - builder.append(extraAttributeValue); - builder.append(", extraAttributeMap="); - builder.append(extraAttributeMap); - builder.append(", online="); - builder.append(online); - builder.append(", ldapDn="); - builder.append(ldapDn); - builder.append(", gridList="); - builder.append(gridList); - builder.append(", createdBy="); - builder.append(createdBy); - builder.append(", createdDate="); - builder.append(createdDate); - builder.append(", modifiedBy="); - builder.append(modifiedBy); - builder.append(", modifiedDate="); - builder.append(modifiedDate); - builder.append(", status="); - builder.append(status); - builder.append(", description="); - builder.append(description); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("UserInfo [id="); + builder.append(id); + builder.append(", username="); + builder.append(username); + builder.append(", sharedSecret="); + builder.append(sharedSecret); + builder.append(", sharedCounter="); + builder.append(sharedCounter); + builder.append(", userType="); + builder.append(userType); + builder.append(", userState="); + builder.append(userState); + builder.append(", windowsAccount="); + builder.append(windowsAccount); + builder.append(", displayName="); + builder.append(displayName); + builder.append(", nickName="); + builder.append(nickName); + builder.append(", nameZhSpell="); + builder.append(nameZhSpell); + builder.append(", nameZhShortSpell="); + builder.append(nameZhShortSpell); + builder.append(", givenName="); + builder.append(givenName); + builder.append(", middleName="); + builder.append(middleName); + builder.append(", familyName="); + builder.append(familyName); + builder.append(", honorificPrefix="); + builder.append(honorificPrefix); + builder.append(", honorificSuffix="); + builder.append(honorificSuffix); + builder.append(", formattedName="); + builder.append(formattedName); + builder.append(", married="); + builder.append(married); + builder.append(", gender="); + builder.append(gender); + builder.append(", birthDate="); + builder.append(birthDate); + builder.append(", idType="); + builder.append(idType); + builder.append(", idCardNo="); + builder.append(idCardNo); + builder.append(", webSite="); + builder.append(webSite); + builder.append(", startWorkDate="); + builder.append(startWorkDate); + builder.append(", authnType="); + builder.append(authnType); + builder.append(", email="); + builder.append(email); + builder.append(", emailVerified="); + builder.append(emailVerified); + builder.append(", mobile="); + builder.append(mobile); + builder.append(", mobileVerified="); + builder.append(mobileVerified); + builder.append(", passwordQuestion="); + builder.append(passwordQuestion); + builder.append(", passwordAnswer="); + builder.append(passwordAnswer); + builder.append(", appLoginAuthnType="); + builder.append(appLoginAuthnType); + builder.append(", appLoginPassword="); + builder.append(appLoginPassword); + builder.append(", protectedApps="); + builder.append(protectedApps); + builder.append(", protectedAppsMap="); + builder.append(protectedAppsMap); + builder.append(", passwordLastSetTime="); + builder.append(passwordLastSetTime); + builder.append(", badPasswordCount="); + builder.append(badPasswordCount); + builder.append(", badPasswordTime="); + builder.append(badPasswordTime); + builder.append(", unLockTime="); + builder.append(unLockTime); + builder.append(", isLocked="); + builder.append(isLocked); + builder.append(", lastLoginTime="); + builder.append(lastLoginTime); + builder.append(", lastLoginIp="); + builder.append(lastLoginIp); + builder.append(", lastLogoffTime="); + builder.append(lastLogoffTime); + builder.append(", passwordSetType="); + builder.append(passwordSetType); + builder.append(", loginCount="); + builder.append(loginCount); + builder.append(", locale="); + builder.append(locale); + builder.append(", timeZone="); + builder.append(timeZone); + builder.append(", preferredLanguage="); + builder.append(preferredLanguage); + builder.append(", workCountry="); + builder.append(workCountry); + builder.append(", workRegion="); + builder.append(workRegion); + builder.append(", workLocality="); + builder.append(workLocality); + builder.append(", workStreetAddress="); + builder.append(workStreetAddress); + builder.append(", workAddressFormatted="); + builder.append(workAddressFormatted); + builder.append(", workEmail="); + builder.append(workEmail); + builder.append(", workPhoneNumber="); + builder.append(workPhoneNumber); + builder.append(", workPostalCode="); + builder.append(workPostalCode); + builder.append(", workFax="); + builder.append(workFax); + builder.append(", workOfficeName="); + builder.append(workOfficeName); + builder.append(", homeCountry="); + builder.append(homeCountry); + builder.append(", homeRegion="); + builder.append(homeRegion); + builder.append(", homeLocality="); + builder.append(homeLocality); + builder.append(", homeStreetAddress="); + builder.append(homeStreetAddress); + builder.append(", homeAddressFormatted="); + builder.append(homeAddressFormatted); + builder.append(", homeEmail="); + builder.append(homeEmail); + builder.append(", homePhoneNumber="); + builder.append(homePhoneNumber); + builder.append(", homePostalCode="); + builder.append(homePostalCode); + builder.append(", homeFax="); + builder.append(homeFax); + builder.append(", employeeNumber="); + builder.append(employeeNumber); + builder.append(", costCenter="); + builder.append(costCenter); + builder.append(", organization="); + builder.append(organization); + builder.append(", division="); + builder.append(division); + builder.append(", departmentId="); + builder.append(departmentId); + builder.append(", department="); + builder.append(department); + builder.append(", jobTitle="); + builder.append(jobTitle); + builder.append(", jobLevel="); + builder.append(jobLevel); + builder.append(", managerId="); + builder.append(managerId); + builder.append(", manager="); + builder.append(manager); + builder.append(", assistantId="); + builder.append(assistantId); + builder.append(", assistant="); + builder.append(assistant); + builder.append(", entryDate="); + builder.append(entryDate); + builder.append(", quitDate="); + builder.append(quitDate); + builder.append(", defineIm="); + builder.append(defineIm); + builder.append(", weixinFollow="); + builder.append(weixinFollow); + builder.append(", theme="); + builder.append(theme); + builder.append(", extraAttribute="); + builder.append(extraAttribute); + builder.append(", extraAttributeName="); + builder.append(extraAttributeName); + builder.append(", extraAttributeValue="); + builder.append(extraAttributeValue); + builder.append(", extraAttributeMap="); + builder.append(extraAttributeMap); + builder.append(", online="); + builder.append(online); + builder.append(", ldapDn="); + builder.append(ldapDn); + builder.append(", gridList="); + builder.append(gridList); + builder.append(", createdBy="); + builder.append(createdBy); + builder.append(", createdDate="); + builder.append(createdDate); + builder.append(", modifiedBy="); + builder.append(modifiedBy); + builder.append(", modifiedDate="); + builder.append(modifiedDate); + builder.append(", status="); + builder.append(status); + builder.append(", description="); + builder.append(description); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/Permission.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/Permission.java index 8129d4dbc..648ae4ff3 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/Permission.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/Permission.java @@ -44,11 +44,11 @@ public class Permission extends JpaEntity implements Serializable { String resourceId; int status = ConstsStatus.ACTIVE; - @Column - private String instId; + @Column + private String instId; - private String instName; - + private String instName; + public Permission() { } @@ -89,14 +89,14 @@ public class Permission extends JpaEntity implements Serializable { } public String getGroupId() { - return groupId; - } + return groupId; + } - public void setGroupId(String groupId) { - this.groupId = groupId; - } + public void setGroupId(String groupId) { + this.groupId = groupId; + } - public String getResourceId() { + public String getResourceId() { return resourceId; } @@ -117,22 +117,22 @@ public class Permission extends JpaEntity implements Serializable { } public String getInstId() { - return instId; - } + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override + @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("RolePrivileges [id="); diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/PermissionRole.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/PermissionRole.java index fbbb6eebb..fa64d29d4 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/PermissionRole.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/PermissionRole.java @@ -50,11 +50,11 @@ public class PermissionRole extends JpaEntity implements Serializable { String createdDate; int status = ConstsStatus.ACTIVE; - @Column - private String instId; + @Column + private String instId; - private String instName; - + private String instName; + public PermissionRole() { } @@ -124,61 +124,61 @@ public class PermissionRole extends JpaEntity implements Serializable { } public String getCreatedBy() { - return createdBy; - } + return createdBy; + } - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } - public String getCreatedDate() { - return createdDate; - } + public String getCreatedDate() { + return createdDate; + } - public void setCreatedDate(String createdDate) { - this.createdDate = createdDate; - } + public void setCreatedDate(String createdDate) { + this.createdDate = createdDate; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("PermissionRole [id="); - builder.append(id); - builder.append(", appId="); - builder.append(appId); - builder.append(", roleId="); - builder.append(roleId); - builder.append(", resourceId="); - builder.append(resourceId); - builder.append(", createdBy="); - builder.append(createdBy); - builder.append(", createdDate="); - builder.append(createdDate); - builder.append(", status="); - builder.append(status); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("PermissionRole [id="); + builder.append(id); + builder.append(", appId="); + builder.append(appId); + builder.append(", roleId="); + builder.append(roleId); + builder.append(", resourceId="); + builder.append(resourceId); + builder.append(", createdBy="); + builder.append(createdBy); + builder.append(", createdDate="); + builder.append(createdDate); + builder.append(", status="); + builder.append(status); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/Resources.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/Resources.java index ba28d2852..cd24ed7e7 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/Resources.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/Resources.java @@ -71,11 +71,11 @@ public class Resources extends JpaEntity implements Serializable { String modifiedBy; @Column Date modifiedDate; - @Column - private String instId; + @Column + private String instId; - private String instName; - + private String instName; + public Resources() { super(); } @@ -89,14 +89,14 @@ public class Resources extends JpaEntity implements Serializable { } public String getResourceName() { - return resourceName; - } + return resourceName; + } - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } - public String getAppId() { + public String getAppId() { return appId; } @@ -113,14 +113,14 @@ public class Resources extends JpaEntity implements Serializable { } public String getPermission() { - return permission; - } + return permission; + } - public void setPermission(String permission) { - this.permission = permission; - } + public void setPermission(String permission) { + this.permission = permission; + } - public String getParentId() { + public String getParentId() { return parentId; } @@ -209,22 +209,22 @@ public class Resources extends JpaEntity implements Serializable { } public Date getCreatedDate() { - return createdDate; - } + return createdDate; + } - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } - public Date getModifiedDate() { - return modifiedDate; - } + public Date getModifiedDate() { + return modifiedDate; + } - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } - public int getSortIndex() { + public int getSortIndex() { return sortIndex; } @@ -233,22 +233,22 @@ public class Resources extends JpaEntity implements Serializable { } public String getInstId() { - return instId; - } + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override + @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Resources [id="); diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/RoleMember.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/RoleMember.java index 3f0bc067b..68d2f2421 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/RoleMember.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/RoleMember.java @@ -31,193 +31,193 @@ import jakarta.persistence.Table; @Table(name = "MXK_ROLE_MEMBER") public class RoleMember extends UserInfo implements Serializable{ - /** - * - */ - private static final long serialVersionUID = -8059639972590554760L; - @Id - @Column - @GeneratedValue - String id; - @Column - private String roleId; - private String roleName; - private String category; - @Column - private String memberId; - private String memberName; - @Column - private String type;//User or Group - - private String createdBy; + /** + * + */ + private static final long serialVersionUID = -8059639972590554760L; + @Id + @Column + @GeneratedValue + String id; + @Column + private String roleId; + private String roleName; + private String category; + @Column + private String memberId; + private String memberName; + @Column + private String type;//User or Group + + private String createdBy; - @Column - private String instId; + @Column + private String instId; - private String instName; - - public RoleMember(){ - super(); - } + private String instName; + + public RoleMember(){ + super(); + } - - /** - * @param groupId - * @param memberId - * @param type - */ - public RoleMember(String roleId, String memberId, String type , String instId) { - super(); - this.roleId = roleId; - this.memberId = memberId; - this.type = type; - this.instId = instId; - } + + /** + * @param groupId + * @param memberId + * @param type + */ + public RoleMember(String roleId, String memberId, String type , String instId) { + super(); + this.roleId = roleId; + this.memberId = memberId; + this.type = type; + this.instId = instId; + } - public RoleMember(String roleId, String roleName, String memberId,String memberName, String type , String createdBy, String instId) { - super(); - this.roleId = roleId; - this.roleName = roleName; - this.memberId = memberId; - this.memberName = memberName; - this.type = type; - this.createdBy = createdBy; - this.instId = instId; - } + public RoleMember(String roleId, String roleName, String memberId,String memberName, String type , String createdBy, String instId) { + super(); + this.roleId = roleId; + this.roleName = roleName; + this.memberId = memberId; + this.memberName = memberName; + this.type = type; + this.createdBy = createdBy; + this.instId = instId; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getRoleId() { - return roleId; - } + public String getRoleId() { + return roleId; + } - public void setRoleId(String roleId) { - this.roleId = roleId; - } + public void setRoleId(String roleId) { + this.roleId = roleId; + } - public String getRoleName() { - return roleName; - } + public String getRoleName() { + return roleName; + } - public void setRoleName(String roleName) { - this.roleName = roleName; - } + public void setRoleName(String roleName) { + this.roleName = roleName; + } - /** - * @return the memberId - */ - public String getMemberId() { - return memberId; - } + /** + * @return the memberId + */ + public String getMemberId() { + return memberId; + } - /** - * @param memberId the memberId to set - */ - public void setMemberId(String memberId) { - this.memberId = memberId; - } + /** + * @param memberId the memberId to set + */ + public void setMemberId(String memberId) { + this.memberId = memberId; + } - /** - * @return the type - */ - public String getType() { - return type; - } + /** + * @return the type + */ + public String getType() { + return type; + } - /** - * @param type the type to set - */ - public void setType(String type) { - this.type = type; - } + /** + * @param type the type to set + */ + public void setType(String type) { + this.type = type; + } - public String getMemberName() { - return memberName; - } + public String getMemberName() { + return memberName; + } - public void setMemberName(String memberName) { - this.memberName = memberName; - } + public void setMemberName(String memberName) { + this.memberName = memberName; + } - public String getCategory() { - return category; - } + public String getCategory() { + return category; + } - public void setCategory(String category) { - this.category = category; - } + public void setCategory(String category) { + this.category = category; + } - public String getCreatedBy() { - return createdBy; - } + public String getCreatedBy() { + return createdBy; + } - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("RoleMember [id="); - builder.append(id); - builder.append(", roleId="); - builder.append(roleId); - builder.append(", roleName="); - builder.append(roleName); - builder.append(", category="); - builder.append(category); - builder.append(", memberId="); - builder.append(memberId); - builder.append(", memberName="); - builder.append(memberName); - builder.append(", type="); - builder.append(type); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("RoleMember [id="); + builder.append(id); + builder.append(", roleId="); + builder.append(roleId); + builder.append(", roleName="); + builder.append(roleName); + builder.append(", category="); + builder.append(category); + builder.append(", memberId="); + builder.append(memberId); + builder.append(", memberName="); + builder.append(memberName); + builder.append(", type="); + builder.append(type); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/Roles.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/Roles.java index 85175ba25..d8203351b 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/Roles.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/permissions/Roles.java @@ -36,11 +36,11 @@ public class Roles extends JpaEntity implements Serializable { private static final long serialVersionUID = 4660258495864814777L; public class Category{ - public static final String DYNAMIC = "dynamic"; - - public static final String STATIC = "static"; - - public static final String APP = "app"; + public static final String DYNAMIC = "dynamic"; + + public static final String STATIC = "static"; + + public static final String APP = "app"; } @Id @@ -83,10 +83,10 @@ public class Roles extends JpaEntity implements Serializable { @Column String appId; - @Column - private String instId; + @Column + private String instId; - private String instName; + private String instName; public Roles() { } @@ -110,7 +110,7 @@ public class Roles extends JpaEntity implements Serializable { this.appId = appId; } - public String getId() { + public String getId() { return id; } @@ -119,21 +119,21 @@ public class Roles extends JpaEntity implements Serializable { } public String getRoleCode() { - return roleCode; - } + return roleCode; + } - public void setRoleCode(String roleCode) { - this.roleCode = roleCode; - } + public void setRoleCode(String roleCode) { + this.roleCode = roleCode; + } - public String getRoleName() { - return roleName; - } + public String getRoleName() { + return roleName; + } - public void setRoleName(String roleName) { - this.roleName = roleName; - } - + public void setRoleName(String roleName) { + this.roleName = roleName; + } + public int getIsdefault() { return isdefault; } @@ -167,22 +167,22 @@ public class Roles extends JpaEntity implements Serializable { } public Date getCreatedDate() { - return createdDate; - } + return createdDate; + } - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } - public Date getModifiedDate() { - return modifiedDate; - } + public Date getModifiedDate() { + return modifiedDate; + } - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } - public int getStatus() { + public int getStatus() { return status; } @@ -192,25 +192,25 @@ public class Roles extends JpaEntity implements Serializable { /** * ROLE_ALL_USER must be - * 1, dynamic - * 2, all orgIdsList - * 3, not filters + * 1, dynamic + * 2, all orgIdsList + * 3, not filters */ public void setDefaultAllUser() { - this.category = Category.DYNAMIC; - this.orgIdsList =""; - this.filters =""; + this.category = Category.DYNAMIC; + this.orgIdsList =""; + this.filters =""; } public String getCategory() { - return category; - } + return category; + } - public void setCategory(String category) { - this.category = category; - } + public void setCategory(String category) { + this.category = category; + } - public String getFilters() { + public String getFilters() { return filters; } @@ -227,64 +227,64 @@ public class Roles extends JpaEntity implements Serializable { } public String getAppId() { - return appId; - } + return appId; + } - public void setAppId(String appId) { - this.appId = appId; - } + public void setAppId(String appId) { + this.appId = appId; + } - public String getInstId() { - return instId; - } + public String getInstId() { + return instId; + } - public void setInstId(String instId) { - this.instId = instId; - } + public void setInstId(String instId) { + this.instId = instId; + } - public String getInstName() { - return instName; - } + public String getInstName() { + return instName; + } - public void setInstName(String instName) { - this.instName = instName; - } + public void setInstName(String instName) { + this.instName = instName; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Roles [id="); - builder.append(id); - builder.append(", roleCode="); - builder.append(roleCode); - builder.append(", roleName="); - builder.append(roleName); - builder.append(", category="); - builder.append(category); - builder.append(", filters="); - builder.append(filters); - builder.append(", orgIdsList="); - builder.append(orgIdsList); - builder.append(", isdefault="); - builder.append(isdefault); - builder.append(", description="); - builder.append(description); - builder.append(", createdBy="); - builder.append(createdBy); - builder.append(", createdDate="); - builder.append(createdDate); - builder.append(", modifiedBy="); - builder.append(modifiedBy); - builder.append(", modifiedDate="); - builder.append(modifiedDate); - builder.append(", status="); - builder.append(status); - builder.append(", instId="); - builder.append(instId); - builder.append(", instName="); - builder.append(instName); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Roles [id="); + builder.append(id); + builder.append(", roleCode="); + builder.append(roleCode); + builder.append(", roleName="); + builder.append(roleName); + builder.append(", category="); + builder.append(category); + builder.append(", filters="); + builder.append(filters); + builder.append(", orgIdsList="); + builder.append(orgIdsList); + builder.append(", isdefault="); + builder.append(isdefault); + builder.append(", description="); + builder.append(description); + builder.append(", createdBy="); + builder.append(createdBy); + builder.append(", createdDate="); + builder.append(createdDate); + builder.append(", modifiedBy="); + builder.append(modifiedBy); + builder.append(", modifiedDate="); + builder.append(modifiedDate); + builder.append(", status="); + builder.append(status); + builder.append(", instId="); + builder.append(instId); + builder.append(", instName="); + builder.append(instName); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/userinfo/ContactEntity.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/userinfo/ContactEntity.java index 80d509c03..03c1892f2 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/userinfo/ContactEntity.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/userinfo/ContactEntity.java @@ -18,83 +18,83 @@ package org.dromara.maxkey.entity.userinfo; public class ContactEntity { - private String country; - private String region; - private String locality; - private String streetAddress; - private String addressFormatted; - private String email; - private String phoneNumber; - private String postalCode; - private String fax; - /** - * - */ - public ContactEntity() { - - } - public String getCountry() { - return country; - } - public void setCountry(String country) { - this.country = country; - } - public String getRegion() { - return region; - } - public void setRegion(String region) { - this.region = region; - } - public String getLocality() { - return locality; - } - public void setLocality(String locality) { - this.locality = locality; - } - public String getStreetAddress() { - return streetAddress; - } - public void setStreetAddress(String streetAddress) { - this.streetAddress = streetAddress; - } - public String getAddressFormatted() { - return addressFormatted; - } - public void setAddressFormatted(String addressFormatted) { - this.addressFormatted = addressFormatted; - } - public String getEmail() { - return email; - } - public void setEmail(String email) { - this.email = email; - } - public String getPhoneNumber() { - return phoneNumber; - } - public void setPhoneNumber(String phoneNumber) { - this.phoneNumber = phoneNumber; - } - public String getPostalCode() { - return postalCode; - } - public void setPostalCode(String postalCode) { - this.postalCode = postalCode; - } - public String getFax() { - return fax; - } - public void setFax(String fax) { - this.fax = fax; - } - @Override - public String toString() { - return "Contact [country=" + country + ", region=" + region - + ", locality=" + locality + ", streetAddress=" - + streetAddress + ", addressFormatted=" + addressFormatted - + ", email=" + email + ", phoneNumber=" + phoneNumber - + ", postalCode=" + postalCode + ", fax=" + fax + "]"; - } - - - } + private String country; + private String region; + private String locality; + private String streetAddress; + private String addressFormatted; + private String email; + private String phoneNumber; + private String postalCode; + private String fax; + /** + * + */ + public ContactEntity() { + + } + public String getCountry() { + return country; + } + public void setCountry(String country) { + this.country = country; + } + public String getRegion() { + return region; + } + public void setRegion(String region) { + this.region = region; + } + public String getLocality() { + return locality; + } + public void setLocality(String locality) { + this.locality = locality; + } + public String getStreetAddress() { + return streetAddress; + } + public void setStreetAddress(String streetAddress) { + this.streetAddress = streetAddress; + } + public String getAddressFormatted() { + return addressFormatted; + } + public void setAddressFormatted(String addressFormatted) { + this.addressFormatted = addressFormatted; + } + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + public String getPhoneNumber() { + return phoneNumber; + } + public void setPhoneNumber(String phoneNumber) { + this.phoneNumber = phoneNumber; + } + public String getPostalCode() { + return postalCode; + } + public void setPostalCode(String postalCode) { + this.postalCode = postalCode; + } + public String getFax() { + return fax; + } + public void setFax(String fax) { + this.fax = fax; + } + @Override + public String toString() { + return "Contact [country=" + country + ", region=" + region + + ", locality=" + locality + ", streetAddress=" + + streetAddress + ", addressFormatted=" + addressFormatted + + ", email=" + email + ", phoneNumber=" + phoneNumber + + ", postalCode=" + postalCode + ", fax=" + fax + "]"; + } + + + } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/userinfo/EnterpriseEntity.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/userinfo/EnterpriseEntity.java index 443b837c0..4678371ab 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/userinfo/EnterpriseEntity.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/userinfo/EnterpriseEntity.java @@ -18,97 +18,97 @@ package org.dromara.maxkey.entity.userinfo; public class EnterpriseEntity { - private String employeeNumber; - private String costCenter; - private String organization; - private String division; - private String departmentId; - private String department; - private String title; - private String managerId; - private String manager; - private String assistantId; - private String assistant; - /** - * - */ - public EnterpriseEntity() { - - } - public String getEmployeeNumber() { - return employeeNumber; - } - public void setEmployeeNumber(String employeeNumber) { - this.employeeNumber = employeeNumber; - } - public String getCostCenter() { - return costCenter; - } - public void setCostCenter(String costCenter) { - this.costCenter = costCenter; - } - public String getOrganization() { - return organization; - } - public void setOrganization(String organization) { - this.organization = organization; - } - public String getDivision() { - return division; - } - public void setDivision(String division) { - this.division = division; - } - public String getDepartmentId() { - return departmentId; - } - public void setDepartmentId(String departmentId) { - this.departmentId = departmentId; - } - public String getDepartment() { - return department; - } - public void setDepartment(String department) { - this.department = department; - } - public String getTitle() { - return title; - } - public void setTitle(String title) { - this.title = title; - } - public String getManagerId() { - return managerId; - } - public void setManagerId(String managerId) { - this.managerId = managerId; - } - public String getManager() { - return manager; - } - public void setManager(String manager) { - this.manager = manager; - } - public String getAssistantId() { - return assistantId; - } - public void setAssistantId(String assistantId) { - this.assistantId = assistantId; - } - public String getAssistant() { - return assistant; - } - public void setAssistant(String assistant) { - this.assistant = assistant; - } - @Override - public String toString() { - return "EnterpriseEntity [employeeNumber=" + employeeNumber - + ", costCenter=" + costCenter + ", organization=" - + organization + ", division=" + division - + ", departmentId=" + departmentId + ", department=" - + department + ", title=" + title + ", managerId=" - + managerId + ", manager=" + manager + ", assistantId=" - + assistantId + ", assistant=" + assistant + "]"; - } + private String employeeNumber; + private String costCenter; + private String organization; + private String division; + private String departmentId; + private String department; + private String title; + private String managerId; + private String manager; + private String assistantId; + private String assistant; + /** + * + */ + public EnterpriseEntity() { + + } + public String getEmployeeNumber() { + return employeeNumber; + } + public void setEmployeeNumber(String employeeNumber) { + this.employeeNumber = employeeNumber; + } + public String getCostCenter() { + return costCenter; + } + public void setCostCenter(String costCenter) { + this.costCenter = costCenter; + } + public String getOrganization() { + return organization; + } + public void setOrganization(String organization) { + this.organization = organization; + } + public String getDivision() { + return division; + } + public void setDivision(String division) { + this.division = division; + } + public String getDepartmentId() { + return departmentId; + } + public void setDepartmentId(String departmentId) { + this.departmentId = departmentId; + } + public String getDepartment() { + return department; + } + public void setDepartment(String department) { + this.department = department; + } + public String getTitle() { + return title; + } + public void setTitle(String title) { + this.title = title; + } + public String getManagerId() { + return managerId; + } + public void setManagerId(String managerId) { + this.managerId = managerId; + } + public String getManager() { + return manager; + } + public void setManager(String manager) { + this.manager = manager; + } + public String getAssistantId() { + return assistantId; + } + public void setAssistantId(String assistantId) { + this.assistantId = assistantId; + } + public String getAssistant() { + return assistant; + } + public void setAssistant(String assistant) { + this.assistant = assistant; + } + @Override + public String toString() { + return "EnterpriseEntity [employeeNumber=" + employeeNumber + + ", costCenter=" + costCenter + ", organization=" + + organization + ", division=" + division + + ", departmentId=" + departmentId + ", department=" + + department + ", title=" + title + ", managerId=" + + managerId + ", manager=" + manager + ", assistantId=" + + assistantId + ", assistant=" + assistant + "]"; + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/userinfo/ImsEntity.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/userinfo/ImsEntity.java index db657965f..57f8ce83e 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/userinfo/ImsEntity.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/userinfo/ImsEntity.java @@ -18,81 +18,81 @@ package org.dromara.maxkey.entity.userinfo; public class ImsEntity{ - private String aim; - private String gtalk; - private String icq; - private String xmpp; - private String skype; - private String qq; - private String yahoo; - private String sinaweibo; - private String weixin; - - /** - * - */ - public ImsEntity() { - - } - public String getAim() { - return aim; - } - public void setAim(String aim) { - this.aim = aim; - } - public String getGtalk() { - return gtalk; - } - public void setGtalk(String gtalk) { - this.gtalk = gtalk; - } - public String getIcq() { - return icq; - } - public void setIcq(String icq) { - this.icq = icq; - } - public String getXmpp() { - return xmpp; - } - public void setXmpp(String xmpp) { - this.xmpp = xmpp; - } - public String getSkype() { - return skype; - } - public void setSkype(String skype) { - this.skype = skype; - } - public String getQq() { - return qq; - } - public void setQq(String qq) { - this.qq = qq; - } - public String getYahoo() { - return yahoo; - } - public void setYahoo(String yahoo) { - this.yahoo = yahoo; - } - public String getSinaweibo() { - return sinaweibo; - } - public void setSinaweibo(String sinaweibo) { - this.sinaweibo = sinaweibo; - } - public String getWeixin() { - return weixin; - } - public void setWeixin(String weixin) { - this.weixin = weixin; - } - @Override - public String toString() { - return "Ims [aim=" + aim + ", gtalk=" + gtalk + ", icq=" + icq - + ", xmpp=" + xmpp + ", skype=" + skype + ", qq=" + qq - + ", yahoo=" + yahoo + ", sinaweibo=" + sinaweibo - + ", weixin=" + weixin + "]"; - } + private String aim; + private String gtalk; + private String icq; + private String xmpp; + private String skype; + private String qq; + private String yahoo; + private String sinaweibo; + private String weixin; + + /** + * + */ + public ImsEntity() { + + } + public String getAim() { + return aim; + } + public void setAim(String aim) { + this.aim = aim; + } + public String getGtalk() { + return gtalk; + } + public void setGtalk(String gtalk) { + this.gtalk = gtalk; + } + public String getIcq() { + return icq; + } + public void setIcq(String icq) { + this.icq = icq; + } + public String getXmpp() { + return xmpp; + } + public void setXmpp(String xmpp) { + this.xmpp = xmpp; + } + public String getSkype() { + return skype; + } + public void setSkype(String skype) { + this.skype = skype; + } + public String getQq() { + return qq; + } + public void setQq(String qq) { + this.qq = qq; + } + public String getYahoo() { + return yahoo; + } + public void setYahoo(String yahoo) { + this.yahoo = yahoo; + } + public String getSinaweibo() { + return sinaweibo; + } + public void setSinaweibo(String sinaweibo) { + this.sinaweibo = sinaweibo; + } + public String getWeixin() { + return weixin; + } + public void setWeixin(String weixin) { + this.weixin = weixin; + } + @Override + public String toString() { + return "Ims [aim=" + aim + ", gtalk=" + gtalk + ", icq=" + icq + + ", xmpp=" + xmpp + ", skype=" + skype + ", qq=" + qq + + ", yahoo=" + yahoo + ", sinaweibo=" + sinaweibo + + ", weixin=" + weixin + "]"; + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/userinfo/NameEntity.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/userinfo/NameEntity.java index cada72e9c..0dabfeec6 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/userinfo/NameEntity.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/userinfo/NameEntity.java @@ -18,60 +18,60 @@ package org.dromara.maxkey.entity.userinfo; public class NameEntity{ - private String givenName; - private String middleName; - private String familyName; - private String honorificPrefix; - private String honorificSuffix; - private String formattedName; - /** - * - */ - public NameEntity() { - - } - public String getGivenName() { - return givenName; - } - public void setGivenName(String givenName) { - this.givenName = givenName; - } - public String getMiddleName() { - return middleName; - } - public void setMiddleName(String middleName) { - this.middleName = middleName; - } - public String getFamilyName() { - return familyName; - } - public void setFamilyName(String familyName) { - this.familyName = familyName; - } - public String getHonorificPrefix() { - return honorificPrefix; - } - public void setHonorificPrefix(String honorificPrefix) { - this.honorificPrefix = honorificPrefix; - } - public String getHonorificSuffix() { - return honorificSuffix; - } - public void setHonorificSuffix(String honorificSuffix) { - this.honorificSuffix = honorificSuffix; - } - public String getFormattedName() { - return formattedName; - } - public void setFormattedName(String formattedName) { - this.formattedName = formattedName; - } - @Override - public String toString() { - return "NameEntity [givenName=" + givenName + ", middleName=" - + middleName + ", familyName=" + familyName - + ", honorificPrefix=" + honorificPrefix - + ", honorificSuffix=" + honorificSuffix - + ", formattedName=" + formattedName + "]"; - } + private String givenName; + private String middleName; + private String familyName; + private String honorificPrefix; + private String honorificSuffix; + private String formattedName; + /** + * + */ + public NameEntity() { + + } + public String getGivenName() { + return givenName; + } + public void setGivenName(String givenName) { + this.givenName = givenName; + } + public String getMiddleName() { + return middleName; + } + public void setMiddleName(String middleName) { + this.middleName = middleName; + } + public String getFamilyName() { + return familyName; + } + public void setFamilyName(String familyName) { + this.familyName = familyName; + } + public String getHonorificPrefix() { + return honorificPrefix; + } + public void setHonorificPrefix(String honorificPrefix) { + this.honorificPrefix = honorificPrefix; + } + public String getHonorificSuffix() { + return honorificSuffix; + } + public void setHonorificSuffix(String honorificSuffix) { + this.honorificSuffix = honorificSuffix; + } + public String getFormattedName() { + return formattedName; + } + public void setFormattedName(String formattedName) { + this.formattedName = formattedName; + } + @Override + public String toString() { + return "NameEntity [givenName=" + givenName + ", middleName=" + + middleName + ", familyName=" + familyName + + ", honorificPrefix=" + honorificPrefix + + ", honorificSuffix=" + honorificSuffix + + ", formattedName=" + formattedName + "]"; + } } diff --git a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/xml/UserInfoXML.java b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/xml/UserInfoXML.java index 66280ab1a..890bdf51b 100644 --- a/maxkey-entity/src/main/java/org/dromara/maxkey/entity/xml/UserInfoXML.java +++ b/maxkey-entity/src/main/java/org/dromara/maxkey/entity/xml/UserInfoXML.java @@ -29,17 +29,17 @@ import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement public class UserInfoXML extends JpaEntity { - /** - * - */ - private static final long serialVersionUID = 6942731467730249291L; + /** + * + */ + private static final long serialVersionUID = 6942731467730249291L; - /** - * - */ - public UserInfoXML() { - super(); - } + /** + * + */ + public UserInfoXML() { + super(); + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AccessMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AccessMapper.java index 4ccce53dc..72e1269e2 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AccessMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AccessMapper.java @@ -31,11 +31,11 @@ import org.dromara.mybatis.jpa.IJpaMapper; */ public interface AccessMapper extends IJpaMapper { - - public ListappsInGroup(Access entity); - - - public List appsNotInGroup(Access entity); - + + public ListappsInGroup(Access entity); + + + public List appsNotInGroup(Access entity); + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AccountsMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AccountsMapper.java index 887b81bb1..e7416ab0a 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AccountsMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AccountsMapper.java @@ -35,7 +35,7 @@ import org.dromara.mybatis.jpa.IJpaMapper; * */ public interface AccountsMapper extends IJpaMapper { - + public List queryUserNotInStrategy(AccountsStrategy strategy); @@ -43,7 +43,7 @@ public interface AccountsMapper extends IJpaMapper { public List queryByAppIdAndDate(Accounts account); - @Select("select * from mxk_accounts where appid=#{appId} and relatedusername=#{relatedUsername}") + @Select("select * from mxk_accounts where appid=#{appId} and relatedusername=#{relatedUsername}") public List queryByAppIdAndAccount(@Param ("appId") String appId,@Param ("relatedUsername") String relatedUsername); @Update("update mxk_accounts set status = #{status} where id= #{id}") diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsAdaptersMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsAdaptersMapper.java index 9ef377fea..2d2888f05 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsAdaptersMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsAdaptersMapper.java @@ -28,6 +28,6 @@ import org.dromara.mybatis.jpa.IJpaMapper; * */ public interface AppsAdaptersMapper extends IJpaMapper { - + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsCasDetailsMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsCasDetailsMapper.java index baaa06763..4da25e0b7 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsCasDetailsMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsCasDetailsMapper.java @@ -28,6 +28,6 @@ import org.dromara.mybatis.jpa.IJpaMapper; * */ public interface AppsCasDetailsMapper extends IJpaMapper { - - public AppsCasDetails getAppDetails(String id) ; + + public AppsCasDetails getAppDetails(String id) ; } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsFormBasedDetailsMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsFormBasedDetailsMapper.java index 0a3d7ec2d..e51f69a5e 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsFormBasedDetailsMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsFormBasedDetailsMapper.java @@ -28,6 +28,6 @@ import org.dromara.mybatis.jpa.IJpaMapper; * */ public interface AppsFormBasedDetailsMapper extends IJpaMapper { - - public AppsFormBasedDetails getAppDetails(String id) ; + + public AppsFormBasedDetails getAppDetails(String id) ; } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsJwtDetailsMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsJwtDetailsMapper.java index 1d667d8d4..c943f95d4 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsJwtDetailsMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsJwtDetailsMapper.java @@ -28,6 +28,6 @@ import org.dromara.mybatis.jpa.IJpaMapper; * */ public interface AppsJwtDetailsMapper extends IJpaMapper { - - public AppsJwtDetails getAppDetails(String id); + + public AppsJwtDetails getAppDetails(String id); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsMapper.java index f2550a819..c9de81371 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsMapper.java @@ -32,14 +32,14 @@ import org.dromara.mybatis.jpa.IJpaMapper; * */ public interface AppsMapper extends IJpaMapper { - - public int insertApp(Apps app); - - public int updateApp(Apps app); - - @Update("update mxk_apps set extendattr=#{extendAttr} where id = #{id}") - public int updateExtendAttr(Apps app); - + + public int insertApp(Apps app); + + public int updateApp(Apps app); + + @Update("update mxk_apps set extendattr=#{extendAttr} where id = #{id}") + public int updateExtendAttr(Apps app); + public List queryMyApps(UserApps userApplications); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsSaml20DetailsMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsSaml20DetailsMapper.java index d1931b164..c72bc2a8c 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsSaml20DetailsMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsSaml20DetailsMapper.java @@ -28,6 +28,6 @@ import org.dromara.mybatis.jpa.IJpaMapper; * */ public interface AppsSaml20DetailsMapper extends IJpaMapper { - - public AppsSAML20Details getAppDetails(String id); + + public AppsSAML20Details getAppDetails(String id); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsTokenBasedDetailsMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsTokenBasedDetailsMapper.java index ab5d4a644..8f15f190a 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsTokenBasedDetailsMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AppsTokenBasedDetailsMapper.java @@ -28,6 +28,6 @@ import org.dromara.mybatis.jpa.IJpaMapper; * */ public interface AppsTokenBasedDetailsMapper extends IJpaMapper { - - public AppsTokenBasedDetails getAppDetails(String id); + + public AppsTokenBasedDetails getAppDetails(String id); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AuthzResourceMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AuthzResourceMapper.java index a2bd1e2b8..281a584da 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AuthzResourceMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/AuthzResourceMapper.java @@ -31,15 +31,15 @@ import org.dromara.maxkey.entity.permissions.Roles; import org.dromara.mybatis.jpa.IJpaMapper; public interface AuthzResourceMapper extends IJpaMapper { - - public List queryResourcesByGroupId(QueryAppResourceDto dto) ; - - public List queryResourcesByRoleId(QueryAppResourceDto dto) ; - - - public List queryGroupsByMembers(QueryGroupMembersDto dto) ; - - public List queryRolesByMembers(QueryRoleMembersDto dto) ; - - + + public List queryResourcesByGroupId(QueryAppResourceDto dto) ; + + public List queryResourcesByRoleId(QueryAppResourceDto dto) ; + + + public List queryGroupsByMembers(QueryGroupMembersDto dto) ; + + public List queryRolesByMembers(QueryRoleMembersDto dto) ; + + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/CnfPasswordPolicyMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/CnfPasswordPolicyMapper.java index 99922288c..b5849c859 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/CnfPasswordPolicyMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/CnfPasswordPolicyMapper.java @@ -28,6 +28,6 @@ import org.dromara.mybatis.jpa.IJpaMapper; * */ public interface CnfPasswordPolicyMapper extends IJpaMapper { - + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/ConnectorsMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/ConnectorsMapper.java index 946f4fa01..2f929498d 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/ConnectorsMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/ConnectorsMapper.java @@ -29,5 +29,5 @@ import org.dromara.mybatis.jpa.IJpaMapper; */ public interface ConnectorsMapper extends IJpaMapper { - + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/GroupMemberMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/GroupMemberMapper.java index 094fea5c1..68132c1f6 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/GroupMemberMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/GroupMemberMapper.java @@ -33,20 +33,20 @@ import org.dromara.mybatis.jpa.IJpaMapper; */ public interface GroupMemberMapper extends IJpaMapper { - - public List memberIn(GroupMember entity); - public List memberNotIn(GroupMember entity); - - public List noMember(GroupMember entity); - - public int addDynamicMember(Groups dynamicRole); - - public int deleteDynamicMember(Groups dynamicRole); - - public int deleteByGroupId(String groupId); - - public List queryMemberByGroupId(String groupId); - - - + + public List memberIn(GroupMember entity); + public List memberNotIn(GroupMember entity); + + public List noMember(GroupMember entity); + + public int addDynamicMember(Groups dynamicRole); + + public int deleteDynamicMember(Groups dynamicRole); + + public int deleteByGroupId(String groupId); + + public List queryMemberByGroupId(String groupId); + + + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/HistorySystemLogsMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/HistorySystemLogsMapper.java index c3be5adda..95382e810 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/HistorySystemLogsMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/HistorySystemLogsMapper.java @@ -28,6 +28,6 @@ import org.dromara.mybatis.jpa.IJpaMapper; * */ public interface HistorySystemLogsMapper extends IJpaMapper { - + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/InstitutionsMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/InstitutionsMapper.java index 75fa4ace3..74583e4df 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/InstitutionsMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/InstitutionsMapper.java @@ -23,6 +23,6 @@ import org.dromara.mybatis.jpa.IJpaMapper; public interface InstitutionsMapper extends IJpaMapper { - @Select("select * from mxk_institutions where (id = #{value} or domain = #{value} or consoledomain = #{value} ) and status = " + ConstsStatus.ACTIVE) - public Institutions findByDomain(String domain); + @Select("select * from mxk_institutions where (id = #{value} or domain = #{value} or consoledomain = #{value} ) and status = " + ConstsStatus.ACTIVE) + public Institutions findByDomain(String domain); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/OrganizationsCastMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/OrganizationsCastMapper.java index daf854e5c..7bd10a800 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/OrganizationsCastMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/OrganizationsCastMapper.java @@ -24,8 +24,8 @@ import org.dromara.mybatis.jpa.IJpaMapper; public interface OrganizationsCastMapper extends IJpaMapper { - public List queryOrgs(Organizations organization); - - - public long updateCast(OrganizationsCast organizationsCast); + public List queryOrgs(Organizations organization); + + + public long updateCast(OrganizationsCast organizationsCast); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/OrganizationsMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/OrganizationsMapper.java index 695b24379..b47d7f12d 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/OrganizationsMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/OrganizationsMapper.java @@ -24,8 +24,8 @@ import org.dromara.mybatis.jpa.IJpaMapper; public interface OrganizationsMapper extends IJpaMapper { - public List queryOrgs(Organizations organization); - - @Update("update mxk_organizations set codepath = #{codePath} , namepath = #{namePath} where id = #{id}") - boolean updateNamePath(Organizations organization); + public List queryOrgs(Organizations organization); + + @Update("update mxk_organizations set codepath = #{codePath} , namepath = #{namePath} where id = #{id}") + boolean updateNamePath(Organizations organization); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/RegisterMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/RegisterMapper.java index cedae04a1..4d9ba5a20 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/RegisterMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/RegisterMapper.java @@ -32,8 +32,8 @@ import org.dromara.mybatis.jpa.IJpaMapper; */ public interface RegisterMapper extends IJpaMapper { - + - public List findByEmail(String email); + public List findByEmail(String email); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/ReportMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/ReportMapper.java index 357ea508d..b17306ca2 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/ReportMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/ReportMapper.java @@ -33,31 +33,31 @@ import org.dromara.mybatis.jpa.entity.JpaEntity; * */ public interface ReportMapper extends IJpaMapper { - - public Integer analysisDay(HashMap reportParameter); - - public Integer analysisNewUsers(HashMap reportParameter); - - public Integer analysisOnlineUsers(HashMap reportParameter); - - public Integer analysisActiveUsers(HashMap reportParameter); - - public Integer totalUsers(HashMap reportParameter); - - public Integer totalDepts(HashMap reportParameter); - - public Integer totalApps(HashMap reportParameter); - - public List> analysisDayHour(HashMap reportParameter); - - public List> analysisMonth(HashMap reportParameter); - - public List> analysisBrowser(HashMap reportParameter); - - public List> analysisApp(HashMap reportParameter ); - - public List> analysisProvince(HashMap reportParameter); - - public List> analysisCountry(HashMap reportParameter); - + + public Integer analysisDay(HashMap reportParameter); + + public Integer analysisNewUsers(HashMap reportParameter); + + public Integer analysisOnlineUsers(HashMap reportParameter); + + public Integer analysisActiveUsers(HashMap reportParameter); + + public Integer totalUsers(HashMap reportParameter); + + public Integer totalDepts(HashMap reportParameter); + + public Integer totalApps(HashMap reportParameter); + + public List> analysisDayHour(HashMap reportParameter); + + public List> analysisMonth(HashMap reportParameter); + + public List> analysisBrowser(HashMap reportParameter); + + public List> analysisApp(HashMap reportParameter ); + + public List> analysisProvince(HashMap reportParameter); + + public List> analysisCountry(HashMap reportParameter); + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/RoleMemberMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/RoleMemberMapper.java index b06fc789e..5199844d1 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/RoleMemberMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/RoleMemberMapper.java @@ -30,23 +30,23 @@ import org.dromara.mybatis.jpa.IJpaMapper; */ public interface RoleMemberMapper extends IJpaMapper { - - public List memberInRole(RoleMember entity); - - public List memberNotInRole(RoleMember entity); - - public List memberPostNotInRole(RoleMember entity); - - public List rolesNoMember(RoleMember entity); - - public int addDynamicRoleMember(Roles dynamicRole); - - public int deleteDynamicRoleMember(Roles dynamicRole); - - public int deleteByRoleId(String roleId); - - public List queryMemberByRoleId(String roleId); - - - + + public List memberInRole(RoleMember entity); + + public List memberNotInRole(RoleMember entity); + + public List memberPostNotInRole(RoleMember entity); + + public List rolesNoMember(RoleMember entity); + + public int addDynamicRoleMember(Roles dynamicRole); + + public int deleteDynamicRoleMember(Roles dynamicRole); + + public int deleteByRoleId(String roleId); + + public List queryMemberByRoleId(String roleId); + + + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/SocialsAssociateMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/SocialsAssociateMapper.java index 390a9e357..a5b2cad4e 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/SocialsAssociateMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/SocialsAssociateMapper.java @@ -24,5 +24,5 @@ import org.dromara.mybatis.jpa.IJpaMapper; public interface SocialsAssociateMapper extends IJpaMapper { - public List queryByUser(UserInfo user); + public List queryByUser(UserInfo user); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/SocialsProviderMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/SocialsProviderMapper.java index 80d7a0eb2..bfb021432 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/SocialsProviderMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/SocialsProviderMapper.java @@ -27,5 +27,5 @@ import org.dromara.mybatis.jpa.IJpaMapper; */ public interface SocialsProviderMapper extends IJpaMapper{ - + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/SynchroRelatedMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/SynchroRelatedMapper.java index a8a188e41..2ec87a91c 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/SynchroRelatedMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/SynchroRelatedMapper.java @@ -29,6 +29,6 @@ import org.dromara.mybatis.jpa.IJpaMapper; * */ public interface SynchroRelatedMapper extends IJpaMapper { - @Update("update mxk_synchro_related set synctime = #{syncTime} where id= #{id} ") - public int updateSyncTime(SynchroRelated synchroRelated); + @Update("update mxk_synchro_related set synctime = #{syncTime} where id= #{id} ") + public int updateSyncTime(SynchroRelated synchroRelated); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/SynchronizersMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/SynchronizersMapper.java index 796fa4257..9125bff20 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/SynchronizersMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/SynchronizersMapper.java @@ -29,5 +29,5 @@ import org.dromara.mybatis.jpa.IJpaMapper; */ public interface SynchronizersMapper extends IJpaMapper { - + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/UserInfoMapper.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/UserInfoMapper.java index 6fbef06d5..508d2f296 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/UserInfoMapper.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/mapper/UserInfoMapper.java @@ -33,47 +33,47 @@ import org.dromara.mybatis.jpa.IJpaMapper; * */ public interface UserInfoMapper extends IJpaMapper{ - - //login query - public UserInfo findByAppIdAndUsername(UserInfo userInfo); - - @Select("select * from mxk_userinfo where username = #{value} and status = " + ConstsStatus.ACTIVE) - public UserInfo findByUsername(String username); - - @Select("select * from mxk_userinfo where ( email = #{value} or mobile= #{value} ) and status = " + ConstsStatus.ACTIVE) - public UserInfo findByEmailMobile(String emailMobile); - - public List findDeptsByUserId(String userId); - - public void updateLocked(UserInfo userInfo); + + //login query + public UserInfo findByAppIdAndUsername(UserInfo userInfo); + + @Select("select * from mxk_userinfo where username = #{value} and status = " + ConstsStatus.ACTIVE) + public UserInfo findByUsername(String username); + + @Select("select * from mxk_userinfo where ( email = #{value} or mobile= #{value} ) and status = " + ConstsStatus.ACTIVE) + public UserInfo findByEmailMobile(String emailMobile); + + public List findDeptsByUserId(String userId); + + public void updateLocked(UserInfo userInfo); - public void updateLockout(UserInfo userInfo); + public void updateLockout(UserInfo userInfo); - public void badPasswordCount(UserInfo userInfo); - - public void badPasswordCountReset(UserInfo userInfo); - - public int changePassword(ChangePassword changePassword); - - public int updateAppLoginPassword(UserInfo userInfo); - - public int updateProtectedApps(UserInfo userInfo); - - public int updateSharedSecret(UserInfo userInfo); - - public int updatePasswordQuestion(UserInfo userInfo); - - public int updateAuthnType(UserInfo userInfo); - - public int updateEmail(UserInfo userInfo); - - public int updateMobile(UserInfo userInfo); - - public int updateProfile(UserInfo userInfo); - + public void badPasswordCount(UserInfo userInfo); + + public void badPasswordCountReset(UserInfo userInfo); + + public int changePassword(ChangePassword changePassword); + + public int updateAppLoginPassword(UserInfo userInfo); + + public int updateProtectedApps(UserInfo userInfo); + + public int updateSharedSecret(UserInfo userInfo); + + public int updatePasswordQuestion(UserInfo userInfo); + + public int updateAuthnType(UserInfo userInfo); + + public int updateEmail(UserInfo userInfo); + + public int updateMobile(UserInfo userInfo); + + public int updateProfile(UserInfo userInfo); + @Update("update mxk_userinfo set gridlist = #{gridList} where id = #{id}") - public int updateGridList(UserInfo userInfo) ; + public int updateGridList(UserInfo userInfo) ; @Update("update mxk_userinfo set status = #{status} where id = #{id}") - public int updateStatus(UserInfo userInfo) ; + public int updateStatus(UserInfo userInfo) ; } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AccountsService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AccountsService.java index bcd96a9ec..a6dfe1035 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AccountsService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AccountsService.java @@ -37,12 +37,12 @@ public interface AccountsService extends IJpaService{ public List queryUserNotInStrategy(AccountsStrategy strategy); public long deleteByStrategy(AccountsStrategy strategy) ; - + public List queryByAppIdAndDate(Accounts account) ; public List queryByAppIdAndAccount(String appId,String relatedUsername); public String generateAccount(UserInfo userInfo,AccountsStrategy accountsStrategy) ; - + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AccountsStrategyService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AccountsStrategyService.java index dac34ab98..49be9be77 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AccountsStrategyService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AccountsStrategyService.java @@ -25,8 +25,8 @@ import org.dromara.mybatis.jpa.service.IJpaService; public interface AccountsStrategyService extends IJpaService { - public List queryDynamicGroups(Roles groups); - - public boolean deleteById(String groupId) ; - + public List queryDynamicGroups(Roles groups); + + public boolean deleteById(String groupId) ; + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsCasDetailsService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsCasDetailsService.java index 3dddfb7ae..c7db2ffbd 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsCasDetailsService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsCasDetailsService.java @@ -22,5 +22,5 @@ import org.dromara.mybatis.jpa.service.IJpaService; public interface AppsCasDetailsService extends IJpaService{ - public AppsCasDetails getAppDetails(String id , boolean cached) ; + public AppsCasDetails getAppDetails(String id , boolean cached) ; } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsFormBasedDetailsService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsFormBasedDetailsService.java index a70bbe140..7d4586129 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsFormBasedDetailsService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsFormBasedDetailsService.java @@ -22,5 +22,5 @@ import org.dromara.mybatis.jpa.service.IJpaService; public interface AppsFormBasedDetailsService extends IJpaService{ - public AppsFormBasedDetails getAppDetails(String id,boolean cached) ; + public AppsFormBasedDetails getAppDetails(String id,boolean cached) ; } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsJwtDetailsService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsJwtDetailsService.java index 3587324d8..91b86b8ef 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsJwtDetailsService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsJwtDetailsService.java @@ -22,5 +22,5 @@ import org.dromara.mybatis.jpa.service.IJpaService; public interface AppsJwtDetailsService extends IJpaService{ - public AppsJwtDetails getAppDetails(String id , boolean cached) ; + public AppsJwtDetails getAppDetails(String id , boolean cached) ; } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsSaml20DetailsService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsSaml20DetailsService.java index 69209f044..c2acf1d90 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsSaml20DetailsService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsSaml20DetailsService.java @@ -22,5 +22,5 @@ import org.dromara.mybatis.jpa.service.IJpaService; public interface AppsSaml20DetailsService extends IJpaService{ - public AppsSAML20Details getAppDetails(String id , boolean cached); + public AppsSAML20Details getAppDetails(String id , boolean cached); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsService.java index 9a8ae6efe..ca210c157 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsService.java @@ -23,18 +23,18 @@ import org.dromara.maxkey.entity.apps.UserApps; import org.dromara.mybatis.jpa.service.IJpaService; public interface AppsService extends IJpaService{ - - public boolean insertApp(Apps app) ; - - public boolean updateApp(Apps app) ; - - public boolean updateExtendAttr(Apps app) ; - + + public boolean insertApp(Apps app) ; + + public boolean updateApp(Apps app) ; + + public boolean updateExtendAttr(Apps app) ; + public List queryMyApps(UserApps userApplications); //cache for running public void put(String appId, Apps appDetails) ; - + public Apps get(String appId, boolean cached); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsTokenBasedDetailsService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsTokenBasedDetailsService.java index c45e62dce..7ddc7f5f3 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsTokenBasedDetailsService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AppsTokenBasedDetailsService.java @@ -22,5 +22,5 @@ import org.dromara.mybatis.jpa.service.IJpaService; public interface AppsTokenBasedDetailsService extends IJpaService{ - public AppsTokenBasedDetails getAppDetails(String id , boolean cached) ; + public AppsTokenBasedDetails getAppDetails(String id , boolean cached) ; } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AuthzResourceService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AuthzResourceService.java index 479f3dff7..719d783a6 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AuthzResourceService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/AuthzResourceService.java @@ -29,26 +29,26 @@ import org.dromara.maxkey.entity.permissions.Resources; import org.dromara.mybatis.jpa.service.IJpaService; public interface AuthzResourceService extends IJpaService{ - - /** - * 根据主体获取用户对应得应用资源清单 - * @param user - * @param app - * @return 资源清单列表 - */ + + /** + * 根据主体获取用户对应得应用资源清单 + * @param user + * @param app + * @return 资源清单列表 + */ public Set getResourcesBySubject(UserInfo user,Apps app); - /** - * 根据组列表获取资源清单 - * @param dto - * @return - */ - public List queryResourcesByGroupId(QueryAppResourceDto dto) ; + /** + * 根据组列表获取资源清单 + * @param dto + * @return + */ + public List queryResourcesByGroupId(QueryAppResourceDto dto) ; - /** - * 根据角色列表获取资源清单 - * @param dto - * @return - */ - public List queryResourcesByRoleId(QueryAppResourceDto dto) ; + /** + * 根据角色列表获取资源清单 + * @param dto + * @return + */ + public List queryResourcesByRoleId(QueryAppResourceDto dto) ; } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/CnfEmailSendersService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/CnfEmailSendersService.java index aabe78df4..bcadafa19 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/CnfEmailSendersService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/CnfEmailSendersService.java @@ -23,5 +23,5 @@ import org.dromara.mybatis.jpa.service.IJpaService; public interface CnfEmailSendersService extends IJpaService{ - + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/CnfPasswordPolicyService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/CnfPasswordPolicyService.java index 4be8677c8..6a22f7d05 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/CnfPasswordPolicyService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/CnfPasswordPolicyService.java @@ -24,10 +24,10 @@ import org.dromara.mybatis.jpa.service.IJpaService; import org.passay.Rule; public interface CnfPasswordPolicyService extends IJpaService{ - - public CnfPasswordPolicy getPasswordPolicy(); - - public List getPasswordPolicyRuleList(); - - public void buildTipMessage(CnfPasswordPolicy passwordPolicy); + + public CnfPasswordPolicy getPasswordPolicy(); + + public List getPasswordPolicyRuleList(); + + public void buildTipMessage(CnfPasswordPolicy passwordPolicy); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/CnfSmsProviderService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/CnfSmsProviderService.java index af42cf6f4..cb013a1c5 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/CnfSmsProviderService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/CnfSmsProviderService.java @@ -22,5 +22,5 @@ import org.dromara.mybatis.jpa.service.IJpaService; public interface CnfSmsProviderService extends IJpaService{ - + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/GroupMemberService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/GroupMemberService.java index ded0a6b1f..535d3e664 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/GroupMemberService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/GroupMemberService.java @@ -27,14 +27,14 @@ import org.dromara.mybatis.jpa.entity.JpaPageResults; public interface GroupMemberService extends IJpaService{ - public int addDynamicMember(Groups dynamicGroup) ; - - public int deleteDynamicMember(Groups dynamicGroup) ; - - public int deleteByGroupId(String groupId); - - public List queryMemberByGroupId(String groupId); - - public JpaPageResults noMember(GroupMember entity) ; - + public int addDynamicMember(Groups dynamicGroup) ; + + public int deleteDynamicMember(Groups dynamicGroup) ; + + public int deleteByGroupId(String groupId); + + public List queryMemberByGroupId(String groupId); + + public JpaPageResults noMember(GroupMember entity) ; + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/GroupsService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/GroupsService.java index d434b9c75..da48b8555 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/GroupsService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/GroupsService.java @@ -24,14 +24,14 @@ import org.dromara.mybatis.jpa.service.IJpaService; public interface GroupsService extends IJpaService{ - public List queryDynamicGroups(Groups groups); - - public boolean deleteById(String groupId) ; - - public List queryByUserId(String userId); - - public void refreshDynamicGroups(Groups dynamicGroup); - - public void refreshAllDynamicGroups(); + public List queryDynamicGroups(Groups groups); + + public boolean deleteById(String groupId) ; + + public List queryByUserId(String userId); + + public void refreshDynamicGroups(Groups dynamicGroup); + + public void refreshAllDynamicGroups(); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/HistoryLoginService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/HistoryLoginService.java index e492975e9..20c0ef44d 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/HistoryLoginService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/HistoryLoginService.java @@ -23,7 +23,7 @@ import org.dromara.mybatis.jpa.entity.JpaPageResults; public interface HistoryLoginService extends IJpaService{ - public JpaPageResults queryOnlineSession(HistoryLogin historyLogin); - - public void login(HistoryLogin historyLogin); + public JpaPageResults queryOnlineSession(HistoryLogin historyLogin); + + public void login(HistoryLogin historyLogin); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/HistorySystemLogsService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/HistorySystemLogsService.java index 04b5f1a95..4ec7deb5d 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/HistorySystemLogsService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/HistorySystemLogsService.java @@ -22,9 +22,9 @@ import org.dromara.maxkey.entity.idm.UserInfo; import org.dromara.mybatis.jpa.service.IJpaService; public interface HistorySystemLogsService extends IJpaService{ - - public void insert(String topic,Object entity,String action,String result,UserInfo operator) ; - - public void insert(String topic,String message,String action,String result,UserInfo operator,Object entity) ; - + + public void insert(String topic,Object entity,String action,String result,UserInfo operator) ; + + public void insert(String topic,String message,String action,String result,UserInfo operator,Object entity) ; + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/InstitutionsService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/InstitutionsService.java index be4fccab7..d1b5c5618 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/InstitutionsService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/InstitutionsService.java @@ -22,8 +22,8 @@ import org.dromara.mybatis.jpa.service.IJpaService; public interface InstitutionsService extends IJpaService{ - public Institutions findByDomain(String domain) ; - - - public Institutions get(String instIdOrDomain) ; + public Institutions findByDomain(String domain) ; + + + public Institutions get(String instIdOrDomain) ; } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/OrganizationsCastService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/OrganizationsCastService.java index aaafe8519..a36677307 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/OrganizationsCastService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/OrganizationsCastService.java @@ -22,6 +22,6 @@ import org.dromara.mybatis.jpa.service.IJpaService; public interface OrganizationsCastService extends IJpaService{ - public boolean updateCast(OrganizationsCast organizationsCast) ; + public boolean updateCast(OrganizationsCast organizationsCast) ; } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/OrganizationsService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/OrganizationsService.java index ad3e7ad69..bf5d03e6b 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/OrganizationsService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/OrganizationsService.java @@ -25,12 +25,12 @@ import org.dromara.mybatis.jpa.service.IJpaService; public interface OrganizationsService extends IJpaService{ - public void saveOrUpdate(Organizations organization) ; - - public List queryOrgs(Organizations organization); - - public boolean delete(Organizations organization) ; + public void saveOrUpdate(Organizations organization) ; + + public List queryOrgs(Organizations organization); + + public boolean delete(Organizations organization) ; - public void reorgNamePath(String instId) ; + public void reorgNamePath(String instId) ; } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/PasswordPolicyValidatorService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/PasswordPolicyValidatorService.java index 432e62d35..d1adc8e7a 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/PasswordPolicyValidatorService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/PasswordPolicyValidatorService.java @@ -21,10 +21,10 @@ import org.dromara.maxkey.entity.ChangePassword; import org.dromara.maxkey.entity.cnf.CnfPasswordPolicy; public interface PasswordPolicyValidatorService { - - public CnfPasswordPolicy getPasswordPolicy(); - - public boolean validator(ChangePassword changePassword); - - public String generateRandomPassword() ; + + public CnfPasswordPolicy getPasswordPolicy(); + + public boolean validator(ChangePassword changePassword); + + public String generateRandomPassword() ; } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/PermissionRoleService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/PermissionRoleService.java index 8d0c860b9..5f4169adc 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/PermissionRoleService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/PermissionRoleService.java @@ -25,10 +25,10 @@ import org.dromara.mybatis.jpa.service.IJpaService; public interface PermissionRoleService extends IJpaService{ - public boolean insertPermissionRoles(List permissionRolesList); + public boolean insertPermissionRoles(List permissionRolesList); + + public boolean deletePermissionRoles(List permissionRolesList) ; - public boolean deletePermissionRoles(List permissionRolesList) ; - public List queryPermissionRoles(PermissionRole permissionRole); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/PermissionService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/PermissionService.java index 3851adf41..533771d08 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/PermissionService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/PermissionService.java @@ -24,10 +24,10 @@ import org.dromara.mybatis.jpa.service.IJpaService; public interface PermissionService extends IJpaService{ - public boolean insertGroupPrivileges(List rolePermissionsList) ; + public boolean insertGroupPrivileges(List rolePermissionsList) ; + + public boolean deleteGroupPrivileges(List rolePermissionsList); - public boolean deleteGroupPrivileges(List rolePermissionsList); - public List queryGroupPrivileges(Permission rolePermissions); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/RegisterService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/RegisterService.java index 526c19528..e441ddca6 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/RegisterService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/RegisterService.java @@ -23,6 +23,6 @@ import org.dromara.mybatis.jpa.service.IJpaService; public interface RegisterService extends IJpaService{ - public UserInfo findByEmail(String email); - + public UserInfo findByEmail(String email); + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/ReportService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/ReportService.java index dbea768fa..2fbc95d6c 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/ReportService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/ReportService.java @@ -25,30 +25,30 @@ import org.dromara.mybatis.jpa.entity.JpaEntity; public interface ReportService extends IJpaService{ - public Integer analysisDay(HashMap reportParameter) ; - - public Integer analysisNewUsers(HashMap reportParameter) ; - - public Integer analysisOnlineUsers(HashMap reportParameter) ; - - public Integer analysisActiveUsers(HashMap reportParameter); - - public Integer totalUsers(HashMap reportParameter); - - public Integer totalDepts(HashMap reportParameter); - - public Integer totalApps(HashMap reportParameter); - - public List> analysisDayHour(HashMap reportParameter); - - public List> analysisMonth(HashMap reportParameter); - - - public List> analysisBrowser(HashMap reportParameter); - - public List> analysisApp(HashMap reportParameter); + public Integer analysisDay(HashMap reportParameter) ; + + public Integer analysisNewUsers(HashMap reportParameter) ; + + public Integer analysisOnlineUsers(HashMap reportParameter) ; + + public Integer analysisActiveUsers(HashMap reportParameter); + + public Integer totalUsers(HashMap reportParameter); + + public Integer totalDepts(HashMap reportParameter); + + public Integer totalApps(HashMap reportParameter); + + public List> analysisDayHour(HashMap reportParameter); + + public List> analysisMonth(HashMap reportParameter); + + + public List> analysisBrowser(HashMap reportParameter); + + public List> analysisApp(HashMap reportParameter); - public List> analysisProvince(HashMap reportParameter); - - public List> analysisCountry(HashMap reportParameter); + public List> analysisProvince(HashMap reportParameter); + + public List> analysisCountry(HashMap reportParameter); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/ResourcesService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/ResourcesService.java index 72db5a171..7362701d8 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/ResourcesService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/ResourcesService.java @@ -23,6 +23,6 @@ import org.dromara.maxkey.entity.permissions.Resources; import org.dromara.mybatis.jpa.service.IJpaService; public interface ResourcesService extends IJpaService{ - - public List queryResourcesTree(Resources resource); + + public List queryResourcesTree(Resources resource); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/RoleMemberService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/RoleMemberService.java index c8e0d3bd6..b3a33b826 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/RoleMemberService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/RoleMemberService.java @@ -28,15 +28,15 @@ import org.dromara.mybatis.jpa.entity.JpaPageResults; public interface RoleMemberService extends IJpaService{ - public int addDynamicRoleMember(Roles dynamicGroup); - - public int deleteDynamicRoleMember(Roles dynamicGroup) ; - - public int deleteByRoleId(String groupId) ; - - public List queryMemberByRoleId(String groupId); - - - public JpaPageResults rolesNoMember(RoleMember entity) ; - + public int addDynamicRoleMember(Roles dynamicGroup); + + public int deleteDynamicRoleMember(Roles dynamicGroup) ; + + public int deleteByRoleId(String groupId) ; + + public List queryMemberByRoleId(String groupId); + + + public JpaPageResults rolesNoMember(RoleMember entity) ; + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/RolesService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/RolesService.java index 34c0297ce..0d8523073 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/RolesService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/RolesService.java @@ -26,14 +26,14 @@ import org.dromara.mybatis.jpa.service.IJpaService; public interface RolesService extends IJpaService { - public List queryDynamicRoles(Roles groups); - - public boolean deleteById(String groupId); - - public List queryRolesByUserId(String userId); - - public void refreshDynamicRoles(Roles dynamicRole); - - public void refreshAllDynamicRoles(); + public List queryDynamicRoles(Roles groups); + + public boolean deleteById(String groupId); + + public List queryRolesByUserId(String userId); + + public void refreshDynamicRoles(Roles dynamicRole); + + public void refreshAllDynamicRoles(); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/SocialsAssociatesService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/SocialsAssociatesService.java index 71b824d5e..b5a24ab95 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/SocialsAssociatesService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/SocialsAssociatesService.java @@ -26,6 +26,6 @@ import org.dromara.mybatis.jpa.service.IJpaService; public interface SocialsAssociatesService extends IJpaService{ - public List queryByUser(UserInfo user); - + public List queryByUser(UserInfo user); + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/SynchroRelatedService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/SynchroRelatedService.java index cebb41977..4cf11736a 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/SynchroRelatedService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/SynchroRelatedService.java @@ -25,11 +25,11 @@ import org.dromara.mybatis.jpa.service.IJpaService; public interface SynchroRelatedService extends IJpaService{ - public int updateSyncTime(SynchroRelated synchroRelated); - - public List findOrgs(Synchronizers synchronizer) ; - - public SynchroRelated findByOriginId(Synchronizers synchronizer,String originId,String classType) ; - - public void updateSynchroRelated(Synchronizers synchronizer,SynchroRelated synchroRelated,String classType) ; + public int updateSyncTime(SynchroRelated synchroRelated); + + public List findOrgs(Synchronizers synchronizer) ; + + public SynchroRelated findByOriginId(Synchronizers synchronizer,String originId,String classType) ; + + public void updateSynchroRelated(Synchronizers synchronizer,SynchroRelated synchroRelated,String classType) ; } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/SynchronizersService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/SynchronizersService.java index 69d13e309..91388dfb9 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/SynchronizersService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/SynchronizersService.java @@ -21,5 +21,5 @@ import org.dromara.maxkey.entity.Synchronizers; import org.dromara.mybatis.jpa.service.IJpaService; public interface SynchronizersService extends IJpaService{ - + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/UserInfoService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/UserInfoService.java index fc24a8273..699e65a63 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/UserInfoService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/UserInfoService.java @@ -27,90 +27,90 @@ import org.dromara.mybatis.jpa.service.IJpaService; * */ public interface UserInfoService extends IJpaService { - + public boolean insert(UserInfo userInfo,boolean passwordEncoder) ; - - public boolean delete(UserInfo userInfo) ; - + + public boolean delete(UserInfo userInfo) ; + //更新账号状态 public void accountUpdate(UserInfo userInfo) ; - public UserInfo findUserRelated(String userId) ; - - public boolean updateGridList(String gridList,UserInfo userInfo); - - - public void saveOrUpdate(UserInfo userInfo) ; - - public boolean updateProtectedApps(UserInfo userinfo) ; + public UserInfo findUserRelated(String userId) ; + + public boolean updateGridList(String gridList,UserInfo userInfo); + + + public void saveOrUpdate(UserInfo userInfo) ; + + public boolean updateProtectedApps(UserInfo userinfo) ; - public UserInfo findByUsername(String username) ; - + public UserInfo findByUsername(String username) ; + public UserInfo findByEmailMobile(String emailMobile) ; - - public UserInfo findByAppIdAndUsername(String appId,String username); - - public ChangePassword passwordEncoder(UserInfo userInfo) ; - - public ChangePassword passwordEncoder(ChangePassword changePassword) ; - - /** - * 认证密码修改 - * @param oldPassword - * @param newPassword - * @param confirmPassword - * @param passwordSetType - * @return - */ - public boolean changePassword( ChangePassword changePassword) ; - - /** - * 后台密码修改 - * @param changeUserInfo - * @param passwordPolicy - * @return - */ + + public UserInfo findByAppIdAndUsername(String appId,String username); + + public ChangePassword passwordEncoder(UserInfo userInfo) ; + + public ChangePassword passwordEncoder(ChangePassword changePassword) ; + + /** + * 认证密码修改 + * @param oldPassword + * @param newPassword + * @param confirmPassword + * @param passwordSetType + * @return + */ + public boolean changePassword( ChangePassword changePassword) ; + + /** + * 后台密码修改 + * @param changeUserInfo + * @param passwordPolicy + * @return + */ public boolean changePassword(ChangePassword changePassword,boolean passwordPolicy) ; - - public String randomPassword() ; - - public void changePasswordProvisioning(ChangePassword changePassworded) ; - - public boolean updateAppLoginPassword(UserInfo userinfo) ; - - - /** - * 锁定用户:islock:1 用户解锁 2 用户锁定 - * @param userInfo - */ - public void locked(UserInfo userInfo) ; + + public String randomPassword() ; + + public void changePasswordProvisioning(ChangePassword changePassworded) ; + + public boolean updateAppLoginPassword(UserInfo userinfo) ; + + + /** + * 锁定用户:islock:1 用户解锁 2 用户锁定 + * @param userInfo + */ + public void locked(UserInfo userInfo) ; - /** - * 用户登录成功后,重置错误密码次数和解锁用户 - * @param userInfo - */ - public void lockout(UserInfo userInfo) ; + /** + * 用户登录成功后,重置错误密码次数和解锁用户 + * @param userInfo + */ + public void lockout(UserInfo userInfo) ; - /** - * 更新错误密码次数 - * @param userInfo - */ - public void badPasswordCount(UserInfo userInfo) ; - - public void badPasswordCountReset(UserInfo userInfo); + /** + * 更新错误密码次数 + * @param userInfo + */ + public void badPasswordCount(UserInfo userInfo) ; + + public void badPasswordCountReset(UserInfo userInfo); - public boolean updateSharedSecret(UserInfo userInfo); - - public boolean updatePasswordQuestion(UserInfo userInfo); - - public boolean updateAuthnType(UserInfo userInfo); - - public boolean updateEmail(UserInfo userInfo); - - public boolean updateMobile(UserInfo userInfo); + public boolean updateSharedSecret(UserInfo userInfo); + + public boolean updatePasswordQuestion(UserInfo userInfo); + + public boolean updateAuthnType(UserInfo userInfo); + + public boolean updateEmail(UserInfo userInfo); + + public boolean updateMobile(UserInfo userInfo); public int updateProfile(UserInfo userInfo); - public boolean updateStatus(UserInfo userInfo); + public boolean updateStatus(UserInfo userInfo); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AccountsServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AccountsServiceImpl.java index 8eb1480f9..28775eb3f 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AccountsServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AccountsServiceImpl.java @@ -60,31 +60,31 @@ public class AccountsServiceImpl extends JpaServiceImpl 0; + return this.getMapper().updateStatus(accounts) > 0; } public boolean remove(String id) { @@ -150,8 +150,8 @@ public class AccountsServiceImpl extends JpaServiceImpl queryByAppIdAndDate(Accounts account) { return getMapper().queryByAppIdAndDate(account); } public List queryByAppIdAndAccount(String appId,String relatedUsername){ - return getMapper().queryByAppIdAndAccount(appId,relatedUsername); + return getMapper().queryByAppIdAndAccount(appId,relatedUsername); } public String generateAccount(UserInfo userInfo,AccountsStrategy accountsStrategy) { - String shortAccount = generateAccount(userInfo,accountsStrategy,true); - String account = generateAccount(userInfo,accountsStrategy,false); - String accountResult = shortAccount; - List accountsList =getMapper().queryByAppIdAndAccount(accountsStrategy.getAppId(),shortAccount +accountsStrategy.getSuffixes()); - if(!accountsList.isEmpty()) { - if(accountsStrategy.getMapping().equalsIgnoreCase("email")) { - accountResult = account; - accountsList =getMapper().queryByAppIdAndAccount(accountsStrategy.getAppId(),account + accountsStrategy.getSuffixes()); - } - if(!accountsList.isEmpty()) { - for(int i =1 ;i < 100 ;i++) { - accountResult = account + i; - accountsList =getMapper().queryByAppIdAndAccount(accountsStrategy.getAppId(),accountResult + accountsStrategy.getSuffixes()); - if(accountsList.isEmpty()) { - break; - } - } - } - } - if(StringUtils.isNotBlank(accountsStrategy.getSuffixes())){ - accountResult = accountResult + accountsStrategy.getSuffixes(); - } + String shortAccount = generateAccount(userInfo,accountsStrategy,true); + String account = generateAccount(userInfo,accountsStrategy,false); + String accountResult = shortAccount; + List accountsList =getMapper().queryByAppIdAndAccount(accountsStrategy.getAppId(),shortAccount +accountsStrategy.getSuffixes()); + if(!accountsList.isEmpty()) { + if(accountsStrategy.getMapping().equalsIgnoreCase("email")) { + accountResult = account; + accountsList =getMapper().queryByAppIdAndAccount(accountsStrategy.getAppId(),account + accountsStrategy.getSuffixes()); + } + if(!accountsList.isEmpty()) { + for(int i =1 ;i < 100 ;i++) { + accountResult = account + i; + accountsList =getMapper().queryByAppIdAndAccount(accountsStrategy.getAppId(),accountResult + accountsStrategy.getSuffixes()); + if(accountsList.isEmpty()) { + break; + } + } + } + } + if(StringUtils.isNotBlank(accountsStrategy.getSuffixes())){ + accountResult = accountResult + accountsStrategy.getSuffixes(); + } return accountResult; } - private String generateAccount(UserInfo userInfo,AccountsStrategy strategy,boolean isShort) { - String account = ""; - if(strategy.getMapping().equalsIgnoreCase("username")) { - account = userInfo.getUsername(); - }else if(strategy.getMapping().equalsIgnoreCase("mobile")) { - account = userInfo.getMobile(); - }else if(strategy.getMapping().equalsIgnoreCase("email")) { - try { - if(isShort) { - account = getPinYinShortName(userInfo.getDisplayName()); - }else { - account = getPinYinName(userInfo.getDisplayName()); - } - }catch(Exception e) { - e.printStackTrace(); - } - }else if(strategy.getMapping().equalsIgnoreCase("employeeNumber")) { - account = userInfo.getEmployeeNumber(); - }else if(strategy.getMapping().equalsIgnoreCase("windowsAccount")) { - account = userInfo.getWindowsAccount(); - }else if(strategy.getMapping().equalsIgnoreCase("idCardNo")) { - account = userInfo.getIdCardNo(); - }else { - account = userInfo.getUsername(); - } - + private String generateAccount(UserInfo userInfo,AccountsStrategy strategy,boolean isShort) { + String account = ""; + if(strategy.getMapping().equalsIgnoreCase("username")) { + account = userInfo.getUsername(); + }else if(strategy.getMapping().equalsIgnoreCase("mobile")) { + account = userInfo.getMobile(); + }else if(strategy.getMapping().equalsIgnoreCase("email")) { + try { + if(isShort) { + account = getPinYinShortName(userInfo.getDisplayName()); + }else { + account = getPinYinName(userInfo.getDisplayName()); + } + }catch(Exception e) { + e.printStackTrace(); + } + }else if(strategy.getMapping().equalsIgnoreCase("employeeNumber")) { + account = userInfo.getEmployeeNumber(); + }else if(strategy.getMapping().equalsIgnoreCase("windowsAccount")) { + account = userInfo.getWindowsAccount(); + }else if(strategy.getMapping().equalsIgnoreCase("idCardNo")) { + account = userInfo.getIdCardNo(); + }else { + account = userInfo.getUsername(); + } + return account; - } - - public static String getPinYinName(String name) throws BadHanyuPinyinOutputFormatCombination { + } + + public static String getPinYinName(String name) throws BadHanyuPinyinOutputFormatCombination { HanyuPinyinOutputFormat pinyinFormat = new HanyuPinyinOutputFormat(); pinyinFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); pinyinFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); pinyinFormat.setVCharType(HanyuPinyinVCharType.WITH_V); return PinyinHelper.toHanYuPinyinString(name, pinyinFormat, "",false); } - - public static String getPinYinShortName(String name) throws BadHanyuPinyinOutputFormatCombination { - char[] strs = name.toCharArray(); - String pinyinName = ""; - for(int i=0;i implements AccountsStrategyService{ static final Logger _logger = LoggerFactory.getLogger(AccountsStrategyServiceImpl.class); - public List queryDynamicGroups(Roles groups){ - return this.getMapper().queryDynamicGroups(groups); - } - - public boolean deleteById(String groupId) { - this.delete(groupId); - //groupMemberService.deleteByGroupId(groupId); - return true; - } - /* - public void refreshDynamicGroups(Groups dynamicGroup){ - if(dynamicGroup.getDynamic().equals("1")) { - boolean isDynamicTimeSupport = false; - boolean isBetweenEffectiveTime = false; - if(dynamicGroup.getResumeTime()!=null&&dynamicGroup.getResumeTime().equals("") - &&dynamicGroup.getSuspendTime()!=null&&dynamicGroup.getSuspendTime().equals("")) { - LocalTime currentTime = LocalDateTime.now().toLocalTime(); - LocalTime resumeTime = LocalTime.parse(dynamicGroup.getResumeTime()); - LocalTime suspendTime = LocalTime.parse(dynamicGroup.getSuspendTime()); - - _logger.info("currentTime: " + currentTime + public List queryDynamicGroups(Roles groups){ + return this.getMapper().queryDynamicGroups(groups); + } + + public boolean deleteById(String groupId) { + this.delete(groupId); + //groupMemberService.deleteByGroupId(groupId); + return true; + } + /* + public void refreshDynamicGroups(Groups dynamicGroup){ + if(dynamicGroup.getDynamic().equals("1")) { + boolean isDynamicTimeSupport = false; + boolean isBetweenEffectiveTime = false; + if(dynamicGroup.getResumeTime()!=null&&dynamicGroup.getResumeTime().equals("") + &&dynamicGroup.getSuspendTime()!=null&&dynamicGroup.getSuspendTime().equals("")) { + LocalTime currentTime = LocalDateTime.now().toLocalTime(); + LocalTime resumeTime = LocalTime.parse(dynamicGroup.getResumeTime()); + LocalTime suspendTime = LocalTime.parse(dynamicGroup.getSuspendTime()); + + _logger.info("currentTime: " + currentTime + " , resumeTime : " + resumeTime + " , suspendTime: " + suspendTime); - isDynamicTimeSupport = true; - - if(resumeTime.isBefore(currentTime) && currentTime.isBefore(suspendTime)) { - isBetweenEffectiveTime = true; - } - - } - - if(dynamicGroup.getOrgIdsList()!=null && !dynamicGroup.getOrgIdsList().equals("")) { - dynamicGroup.setOrgIdsList("'"+dynamicGroup.getOrgIdsList().replace(",", "','")+"'"); - } - String filters = dynamicGroup.getFilters(); - if(StringUtils.filtersSQLInjection(filters.toLowerCase())) { - _logger.info("filters include SQL Injection Attack Risk."); - return; - } - - filters = filters.replace("&", " AND "); - filters = filters.replace("|", " OR "); - - dynamicGroup.setFilters(filters); - - if(isDynamicTimeSupport) { - if(isBetweenEffectiveTime) { - groupMemberService.deleteDynamicGroupMember(dynamicGroup); + isDynamicTimeSupport = true; + + if(resumeTime.isBefore(currentTime) && currentTime.isBefore(suspendTime)) { + isBetweenEffectiveTime = true; + } + + } + + if(dynamicGroup.getOrgIdsList()!=null && !dynamicGroup.getOrgIdsList().equals("")) { + dynamicGroup.setOrgIdsList("'"+dynamicGroup.getOrgIdsList().replace(",", "','")+"'"); + } + String filters = dynamicGroup.getFilters(); + if(StringUtils.filtersSQLInjection(filters.toLowerCase())) { + _logger.info("filters include SQL Injection Attack Risk."); + return; + } + + filters = filters.replace("&", " AND "); + filters = filters.replace("|", " OR "); + + dynamicGroup.setFilters(filters); + + if(isDynamicTimeSupport) { + if(isBetweenEffectiveTime) { + groupMemberService.deleteDynamicGroupMember(dynamicGroup); groupMemberService.addDynamicGroupMember(dynamicGroup); - }else { - groupMemberService.deleteDynamicGroupMember(dynamicGroup); - } - }else{ + }else { + groupMemberService.deleteDynamicGroupMember(dynamicGroup); + } + }else{ groupMemberService.deleteDynamicGroupMember(dynamicGroup); groupMemberService.addDynamicGroupMember(dynamicGroup); } - } + } }*/ - + - + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsCasDetailsServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsCasDetailsServiceImpl.java index 57d2be1ec..f5165bc02 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsCasDetailsServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsCasDetailsServiceImpl.java @@ -31,25 +31,25 @@ import com.github.benmanes.caffeine.cache.Caffeine; @Repository public class AppsCasDetailsServiceImpl extends JpaServiceImpl implements AppsCasDetailsService{ - protected static final Cache detailsCache = + protected static final Cache detailsCache = Caffeine.newBuilder() .expireAfterWrite(30, TimeUnit.MINUTES) .maximumSize(200000) .build(); - - public AppsCasDetails getAppDetails(String id , boolean cached) { - AppsCasDetails details = null; - if(cached) { - details = detailsCache.getIfPresent(id); - if(details == null) { - details = getMapper().getAppDetails(id); - if(details != null) { - detailsCache.put(id, details); - } - } - }else { - details = getMapper().getAppDetails(id); - } - return details; - } + + public AppsCasDetails getAppDetails(String id , boolean cached) { + AppsCasDetails details = null; + if(cached) { + details = detailsCache.getIfPresent(id); + if(details == null) { + details = getMapper().getAppDetails(id); + if(details != null) { + detailsCache.put(id, details); + } + } + }else { + details = getMapper().getAppDetails(id); + } + return details; + } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsFormBasedDetailsServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsFormBasedDetailsServiceImpl.java index 99832bd89..15804fb85 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsFormBasedDetailsServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsFormBasedDetailsServiceImpl.java @@ -31,23 +31,23 @@ import com.github.benmanes.caffeine.cache.Caffeine; @Repository public class AppsFormBasedDetailsServiceImpl extends JpaServiceImpl implements AppsFormBasedDetailsService{ - protected static final Cache detailsCache = + protected static final Cache detailsCache = Caffeine.newBuilder() .expireAfterWrite(30, TimeUnit.MINUTES) .maximumSize(200000) .build(); - public AppsFormBasedDetails getAppDetails(String id,boolean cached) { - AppsFormBasedDetails details = null; - if(cached) { - details = detailsCache.getIfPresent(id); - if(details == null) { - details = getMapper().getAppDetails(id); - detailsCache.put(id, details); - } - }else { - details = getMapper().getAppDetails(id); - } - return details; - } + public AppsFormBasedDetails getAppDetails(String id,boolean cached) { + AppsFormBasedDetails details = null; + if(cached) { + details = detailsCache.getIfPresent(id); + if(details == null) { + details = getMapper().getAppDetails(id); + detailsCache.put(id, details); + } + }else { + details = getMapper().getAppDetails(id); + } + return details; + } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsJwtDetailsServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsJwtDetailsServiceImpl.java index f7498f942..2a6171990 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsJwtDetailsServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsJwtDetailsServiceImpl.java @@ -31,24 +31,24 @@ import com.github.benmanes.caffeine.cache.Caffeine; @Repository public class AppsJwtDetailsServiceImpl extends JpaServiceImpl implements AppsJwtDetailsService{ - protected static final Cache detailsCache = + protected static final Cache detailsCache = Caffeine.newBuilder() .expireAfterWrite(30, TimeUnit.MINUTES) .maximumSize(200000) .build(); - - public AppsJwtDetails getAppDetails(String id , boolean cached) { - AppsJwtDetails details = null; - if(cached) { - details = detailsCache.getIfPresent(id); - if(details == null) { - details = getMapper().getAppDetails(id); - detailsCache.put(id, details); - } - }else { - details = getMapper().getAppDetails(id); - } - return details; - } + + public AppsJwtDetails getAppDetails(String id , boolean cached) { + AppsJwtDetails details = null; + if(cached) { + details = detailsCache.getIfPresent(id); + if(details == null) { + details = getMapper().getAppDetails(id); + detailsCache.put(id, details); + } + }else { + details = getMapper().getAppDetails(id); + } + return details; + } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsSaml20DetailsServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsSaml20DetailsServiceImpl.java index 7ce3e73d2..5584c8f12 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsSaml20DetailsServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsSaml20DetailsServiceImpl.java @@ -31,23 +31,23 @@ import com.github.benmanes.caffeine.cache.Caffeine; @Repository public class AppsSaml20DetailsServiceImpl extends JpaServiceImpl implements AppsSaml20DetailsService{ - protected static final Cache detailsCache = + protected static final Cache detailsCache = Caffeine.newBuilder() .expireAfterWrite(30, TimeUnit.MINUTES) .maximumSize(200000) .build(); - - public AppsSAML20Details getAppDetails(String id , boolean cached){ - AppsSAML20Details details = null; - if(cached) { - details = detailsCache.getIfPresent(id); - if(details == null) { - details = getMapper().getAppDetails(id); - detailsCache.put(id, details); - } - }else { - details = getMapper().getAppDetails(id); - } - return details; - } + + public AppsSAML20Details getAppDetails(String id , boolean cached){ + AppsSAML20Details details = null; + if(cached) { + details = detailsCache.getIfPresent(id); + if(details == null) { + details = getMapper().getAppDetails(id); + detailsCache.put(id, details); + } + }else { + details = getMapper().getAppDetails(id); + } + return details; + } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsServiceImpl.java index a23390fdc..6b2693436 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsServiceImpl.java @@ -32,48 +32,48 @@ import com.github.benmanes.caffeine.cache.Caffeine; @Repository public class AppsServiceImpl extends JpaServiceImpl implements AppsService{ - //maxkey-mgt - public static final String MGT_APP_ID = "622076759805923328"; - - public static final String DETAIL_SUFFIX = "_detail"; - - protected static final Cache detailsCacheStore = - Caffeine.newBuilder() - .expireAfterWrite(30, TimeUnit.MINUTES) - .build(); - - public boolean insertApp(Apps app) { - return ((AppsMapper)super.getMapper()).insertApp(app)>0; - }; - public boolean updateApp(Apps app) { - return ((AppsMapper)super.getMapper()).updateApp(app)>0; - }; - - public boolean updateExtendAttr(Apps app) { - return ((AppsMapper)super.getMapper()).updateExtendAttr(app)>0; - } - + //maxkey-mgt + public static final String MGT_APP_ID = "622076759805923328"; + + public static final String DETAIL_SUFFIX = "_detail"; + + protected static final Cache detailsCacheStore = + Caffeine.newBuilder() + .expireAfterWrite(30, TimeUnit.MINUTES) + .build(); + + public boolean insertApp(Apps app) { + return ((AppsMapper)super.getMapper()).insertApp(app)>0; + }; + public boolean updateApp(Apps app) { + return ((AppsMapper)super.getMapper()).updateApp(app)>0; + }; + + public boolean updateExtendAttr(Apps app) { + return ((AppsMapper)super.getMapper()).updateExtendAttr(app)>0; + } + public List queryMyApps(UserApps userApplications){ return getMapper().queryMyApps(userApplications); } //cache for running public void put(String appId, Apps appDetails) { - detailsCacheStore.put(appId + DETAIL_SUFFIX, appDetails); - } - + detailsCacheStore.put(appId + DETAIL_SUFFIX, appDetails); + } + public Apps get(String appId, boolean cached) { - appId = appId.equalsIgnoreCase("maxkey_mgt") ? MGT_APP_ID : appId; - Apps appDetails = null; - if(cached) { - appDetails = detailsCacheStore.getIfPresent(appId + DETAIL_SUFFIX); - if(appDetails == null) { - appDetails = this.get(appId); - detailsCacheStore.put(appId, appDetails); - } - }else { - appDetails = this.get(appId); - } + appId = appId.equalsIgnoreCase("maxkey_mgt") ? MGT_APP_ID : appId; + Apps appDetails = null; + if(cached) { + appDetails = detailsCacheStore.getIfPresent(appId + DETAIL_SUFFIX); + if(appDetails == null) { + appDetails = this.get(appId); + detailsCacheStore.put(appId, appDetails); + } + }else { + appDetails = this.get(appId); + } return appDetails; } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsTokenBasedDetailsServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsTokenBasedDetailsServiceImpl.java index 926beff1b..e9bead02b 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsTokenBasedDetailsServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AppsTokenBasedDetailsServiceImpl.java @@ -31,23 +31,23 @@ import com.github.benmanes.caffeine.cache.Caffeine; @Repository public class AppsTokenBasedDetailsServiceImpl extends JpaServiceImpl implements AppsTokenBasedDetailsService{ - protected static final Cache detailsCache = + protected static final Cache detailsCache = Caffeine.newBuilder() .expireAfterWrite(30, TimeUnit.MINUTES) .maximumSize(200000) .build(); - public AppsTokenBasedDetails getAppDetails(String id , boolean cached) { - AppsTokenBasedDetails details = null; - if(cached) { - details = detailsCache.getIfPresent(id); - if(details == null) { - details = getMapper().getAppDetails(id); - detailsCache.put(id, details); - } - }else { - details = getMapper().getAppDetails(id); - } - return details; - } + public AppsTokenBasedDetails getAppDetails(String id , boolean cached) { + AppsTokenBasedDetails details = null; + if(cached) { + details = detailsCache.getIfPresent(id); + if(details == null) { + details = getMapper().getAppDetails(id); + detailsCache.put(id, details); + } + }else { + details = getMapper().getAppDetails(id); + } + return details; + } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AuthzResourceServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AuthzResourceServiceImpl.java index 9a9e10448..ebb84cfaf 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AuthzResourceServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/AuthzResourceServiceImpl.java @@ -39,62 +39,62 @@ import org.springframework.stereotype.Repository; @Repository public class AuthzResourceServiceImpl extends JpaServiceImpl implements AuthzResourceService{ - private static final Logger logger = LoggerFactory.getLogger(AuthzResourceServiceImpl.class); + private static final Logger logger = LoggerFactory.getLogger(AuthzResourceServiceImpl.class); - /** - * 根据主体获取用户对应得应用资源清单 - * @param user - * @param app - * @return 资源清单列表 - */ + /** + * 根据主体获取用户对应得应用资源清单 + * @param user + * @param app + * @return 资源清单列表 + */ public Set getResourcesBySubject(UserInfo user,Apps app){ - logger.debug("user {} , app {}",user,app); - Set resourcesList = new HashSet<>(); - - QueryAppResourceDto dto = new QueryAppResourceDto(user.getId(),app.getId()); - - //查询用户的所属用户组 - QueryGroupMembersDto queryGroupMembersDto = new QueryGroupMembersDto(); - queryGroupMembersDto.add(user.getId()); - List listGroup = getMapper().queryGroupsByMembers(queryGroupMembersDto); - for(Groups group : listGroup) { - dto.getGroupIds().add(group.getId()); - } - - //根据用户组获取应用资源 - List groupResourcesList = queryResourcesByGroupId(dto); - resourcesList.addAll(groupResourcesList); - - //查询用户的所属应用角色组 - QueryRoleMembersDto queryRoleMembersDto = new QueryRoleMembersDto(); - queryRoleMembersDto.setAppId(app.getId()); - queryRoleMembersDto.add(user.getId()); - List listRoles = getMapper().queryRolesByMembers(queryRoleMembersDto); - for(Roles role : listRoles) { - dto.getRoleIds().add(role.getId()); - } - //根据角色获取应用资源 - List roleResourcesList = queryResourcesByRoleId(dto); - resourcesList.addAll(roleResourcesList); + logger.debug("user {} , app {}",user,app); + Set resourcesList = new HashSet<>(); + + QueryAppResourceDto dto = new QueryAppResourceDto(user.getId(),app.getId()); + + //查询用户的所属用户组 + QueryGroupMembersDto queryGroupMembersDto = new QueryGroupMembersDto(); + queryGroupMembersDto.add(user.getId()); + List listGroup = getMapper().queryGroupsByMembers(queryGroupMembersDto); + for(Groups group : listGroup) { + dto.getGroupIds().add(group.getId()); + } + + //根据用户组获取应用资源 + List groupResourcesList = queryResourcesByGroupId(dto); + resourcesList.addAll(groupResourcesList); + + //查询用户的所属应用角色组 + QueryRoleMembersDto queryRoleMembersDto = new QueryRoleMembersDto(); + queryRoleMembersDto.setAppId(app.getId()); + queryRoleMembersDto.add(user.getId()); + List listRoles = getMapper().queryRolesByMembers(queryRoleMembersDto); + for(Roles role : listRoles) { + dto.getRoleIds().add(role.getId()); + } + //根据角色获取应用资源 + List roleResourcesList = queryResourcesByRoleId(dto); + resourcesList.addAll(roleResourcesList); - return resourcesList; + return resourcesList; } - /** - * 根据组列表获取资源清单 - * @param dto - * @return - */ - public List queryResourcesByGroupId(QueryAppResourceDto dto) { - return getMapper().queryResourcesByGroupId(dto); - } + /** + * 根据组列表获取资源清单 + * @param dto + * @return + */ + public List queryResourcesByGroupId(QueryAppResourceDto dto) { + return getMapper().queryResourcesByGroupId(dto); + } - /** - * 根据角色列表获取资源清单 - * @param dto - * @return - */ - public List queryResourcesByRoleId(QueryAppResourceDto dto) { - return getMapper().queryResourcesByRoleId(dto); - } + /** + * 根据角色列表获取资源清单 + * @param dto + * @return + */ + public List queryResourcesByRoleId(QueryAppResourceDto dto) { + return getMapper().queryResourcesByRoleId(dto); + } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/CnfEmailSendersServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/CnfEmailSendersServiceImpl.java index 555d57844..58b56c149 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/CnfEmailSendersServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/CnfEmailSendersServiceImpl.java @@ -27,5 +27,5 @@ import org.springframework.stereotype.Repository; @Repository public class CnfEmailSendersServiceImpl extends JpaServiceImpl implements CnfEmailSendersService{ - + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/CnfPasswordPolicyServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/CnfPasswordPolicyServiceImpl.java index ab0b5c750..3ebb94f2a 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/CnfPasswordPolicyServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/CnfPasswordPolicyServiceImpl.java @@ -51,9 +51,9 @@ import com.github.benmanes.caffeine.cache.Caffeine; @Repository public class CnfPasswordPolicyServiceImpl extends JpaServiceImpl implements CnfPasswordPolicyService{ - static final Logger _logger = LoggerFactory.getLogger(CnfPasswordPolicyServiceImpl.class); - - //Dictionary topWeakPassword Source + static final Logger _logger = LoggerFactory.getLogger(CnfPasswordPolicyServiceImpl.class); + + //Dictionary topWeakPassword Source public static final String TOPWEAKPASSWORD_PROPERTYSOURCE = "classpath:/top_weak_password.txt"; //Cache PasswordPolicy in memory ONE_HOUR @@ -67,8 +67,8 @@ public class CnfPasswordPolicyServiceImpl extends JpaServiceImpl passwordPolicyRuleList; private static final String PASSWORD_POLICY_KEY = "PASSWORD_POLICY_KEY"; - - /** + + /** * init PasswordPolicy and load Rules * @return */ @@ -76,8 +76,8 @@ public class CnfPasswordPolicyServiceImpl extends JpaServiceImplquery = new LambdaQuery<>(); - query.notNull(CnfPasswordPolicy::getId); + LambdaQueryquery = new LambdaQuery<>(); + query.notNull(CnfPasswordPolicy::getId); passwordPolicy = this.get(query); _logger.debug("query PasswordPolicy : {}" , passwordPolicy); passwordPolicyStore.put(PASSWORD_POLICY_KEY,passwordPolicy); @@ -149,14 +149,14 @@ public class CnfPasswordPolicyServiceImpl extends JpaServiceImpl getPasswordPolicyRuleList() { - getPasswordPolicy(); - return passwordPolicyRuleList; - } + getPasswordPolicy(); + return passwordPolicyRuleList; + } public void buildTipMessage(CnfPasswordPolicy passwordPolicy){ - - List policMessageList = new ArrayList<>(); - + + List policMessageList = new ArrayList<>(); + String msg; if (passwordPolicy.getMinLength() != 0) { // msg = "新密码长度为"+minLength+"-"+maxLength+"位"; diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/GroupMemberServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/GroupMemberServiceImpl.java index fa708e2ea..c9ffe1cb9 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/GroupMemberServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/GroupMemberServiceImpl.java @@ -32,38 +32,38 @@ import org.springframework.stereotype.Repository; @Repository public class GroupMemberServiceImpl extends JpaServiceImpl implements GroupMemberService{ - static final Logger _logger = LoggerFactory.getLogger(GroupMemberServiceImpl.class); + static final Logger _logger = LoggerFactory.getLogger(GroupMemberServiceImpl.class); - public int addDynamicMember(Groups dynamicGroup) { - return getMapper().addDynamicMember(dynamicGroup); - } - - public int deleteDynamicMember(Groups dynamicGroup) { - return getMapper().deleteDynamicMember(dynamicGroup); - } - - public int deleteByGroupId(String groupId) { + public int addDynamicMember(Groups dynamicGroup) { + return getMapper().addDynamicMember(dynamicGroup); + } + + public int deleteDynamicMember(Groups dynamicGroup) { + return getMapper().deleteDynamicMember(dynamicGroup); + } + + public int deleteByGroupId(String groupId) { return getMapper().deleteByGroupId(groupId); } - - public List queryMemberByGroupId(String groupId){ - return getMapper().queryMemberByGroupId(groupId); - } - - - public JpaPageResults noMember(GroupMember entity) { - entity.build(); - List resultslist = null; - try { - resultslist = getMapper().noMember(entity); - } catch (Exception e) { - _logger.error("queryPageResults Exception " , e); - } - //当前页记录数 - Integer records = JpaPageResults.parseRecords(resultslist); - //总页数 - Integer totalCount =fetchCount(entity, resultslist); - return new JpaPageResults(entity.getPageNumber(),entity.getPageSize(),records,totalCount,resultslist); - } - + + public List queryMemberByGroupId(String groupId){ + return getMapper().queryMemberByGroupId(groupId); + } + + + public JpaPageResults noMember(GroupMember entity) { + entity.build(); + List resultslist = null; + try { + resultslist = getMapper().noMember(entity); + } catch (Exception e) { + _logger.error("queryPageResults Exception " , e); + } + //当前页记录数 + Integer records = JpaPageResults.parseRecords(resultslist); + //总页数 + Integer totalCount =fetchCount(entity, resultslist); + return new JpaPageResults(entity.getPageNumber(),entity.getPageSize(),records,totalCount,resultslist); + } + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/GroupsServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/GroupsServiceImpl.java index 021cafb52..7f7666540 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/GroupsServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/GroupsServiceImpl.java @@ -46,69 +46,69 @@ public class GroupsServiceImpl extends JpaServiceImpl impl @Autowired InstitutionsService institutionsService; - public List queryDynamicGroups(Groups groups){ - return this.getMapper().queryDynamic(groups); - } - - public boolean deleteById(String groupId) { - this.delete(groupId); - groupMemberService.deleteByGroupId(groupId); - return true; - } - - public List queryByUserId(String userId){ - return this.getMapper().queryByUserId(userId); - } - - public void refreshDynamicGroups(Groups dynamicGroup){ - if(dynamicGroup.getCategory().equals(Roles.Category.DYNAMIC)) { - - if(StringUtils.isNotBlank(dynamicGroup.getOrgIdsList())) { - String []orgIds = dynamicGroup.getOrgIdsList().split(","); - StringBuffer orgIdFilters = new StringBuffer(); - for(String orgId : orgIds) { - if(StringUtils.isNotBlank(orgId)) { - if(orgIdFilters.length() > 0) { - orgIdFilters.append(","); - } - orgIdFilters.append("'").append(orgId).append("'"); - } - } - if(orgIdFilters.length() > 0) { - dynamicGroup.setOrgIdsList(orgIdFilters.toString()); - } - } - - String filters = dynamicGroup.getFilters(); - if(StringUtils.isNotBlank(filters)) { - if(StrUtils.filtersSQLInjection(filters.toLowerCase())) { - _logger.info("filters include SQL Injection Attack Risk."); - return; - } - //replace & with AND, | with OR - filters = filters.replace("&", " AND ").replace("|", " OR "); - - dynamicGroup.setFilters(filters); - } - - groupMemberService.deleteDynamicMember(dynamicGroup); - groupMemberService.addDynamicMember(dynamicGroup); - - } + public List queryDynamicGroups(Groups groups){ + return this.getMapper().queryDynamic(groups); + } + + public boolean deleteById(String groupId) { + this.delete(groupId); + groupMemberService.deleteByGroupId(groupId); + return true; + } + + public List queryByUserId(String userId){ + return this.getMapper().queryByUserId(userId); + } + + public void refreshDynamicGroups(Groups dynamicGroup){ + if(dynamicGroup.getCategory().equals(Roles.Category.DYNAMIC)) { + + if(StringUtils.isNotBlank(dynamicGroup.getOrgIdsList())) { + String []orgIds = dynamicGroup.getOrgIdsList().split(","); + StringBuffer orgIdFilters = new StringBuffer(); + for(String orgId : orgIds) { + if(StringUtils.isNotBlank(orgId)) { + if(orgIdFilters.length() > 0) { + orgIdFilters.append(","); + } + orgIdFilters.append("'").append(orgId).append("'"); + } + } + if(orgIdFilters.length() > 0) { + dynamicGroup.setOrgIdsList(orgIdFilters.toString()); + } + } + + String filters = dynamicGroup.getFilters(); + if(StringUtils.isNotBlank(filters)) { + if(StrUtils.filtersSQLInjection(filters.toLowerCase())) { + _logger.info("filters include SQL Injection Attack Risk."); + return; + } + //replace & with AND, | with OR + filters = filters.replace("&", " AND ").replace("|", " OR "); + + dynamicGroup.setFilters(filters); + } + + groupMemberService.deleteDynamicMember(dynamicGroup); + groupMemberService.addDynamicMember(dynamicGroup); + + } + } + + public void refreshAllDynamicGroups(){ + List instList = + institutionsService.find("where status = ? ", new Object[]{ConstsStatus.ACTIVE}, new int[]{Types.INTEGER}); + for(Institutions inst : instList) { + Groups group = new Groups(); + group.setInstId(inst.getId()); + List groupsList = queryDynamicGroups(group); + for(Groups g : groupsList) { + _logger.debug("role {}" , g); + refreshDynamicGroups(g); + } + } } - - public void refreshAllDynamicGroups(){ - List instList = - institutionsService.find("where status = ? ", new Object[]{ConstsStatus.ACTIVE}, new int[]{Types.INTEGER}); - for(Institutions inst : instList) { - Groups group = new Groups(); - group.setInstId(inst.getId()); - List groupsList = queryDynamicGroups(group); - for(Groups g : groupsList) { - _logger.debug("role {}" , g); - refreshDynamicGroups(g); - } - } - } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/HistoryLoginAppsServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/HistoryLoginAppsServiceImpl.java index 91c45f4c2..981f9d926 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/HistoryLoginAppsServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/HistoryLoginAppsServiceImpl.java @@ -26,30 +26,30 @@ import org.springframework.stereotype.Repository; @Repository public class HistoryLoginAppsServiceImpl extends JpaServiceImpl implements HistoryLoginAppsService{ - @Override - public boolean insert(HistoryLoginApps loginAppsHistory){ - //new Thread insert login app history - new Thread(new HistoryLoginAppsRunnable(getMapper(),loginAppsHistory)).start(); - return true; - } - - public class HistoryLoginAppsRunnable implements Runnable{ + @Override + public boolean insert(HistoryLoginApps loginAppsHistory){ + //new Thread insert login app history + new Thread(new HistoryLoginAppsRunnable(getMapper(),loginAppsHistory)).start(); + return true; + } + + public class HistoryLoginAppsRunnable implements Runnable{ - HistoryLoginAppsMapper historyLoginAppsMapper; - - HistoryLoginApps loginAppsHistory; - - public HistoryLoginAppsRunnable(HistoryLoginAppsMapper historyLoginAppsMapper, - HistoryLoginApps loginAppsHistory) { - super(); - this.historyLoginAppsMapper = historyLoginAppsMapper; - this.loginAppsHistory = loginAppsHistory; - } + HistoryLoginAppsMapper historyLoginAppsMapper; + + HistoryLoginApps loginAppsHistory; + + public HistoryLoginAppsRunnable(HistoryLoginAppsMapper historyLoginAppsMapper, + HistoryLoginApps loginAppsHistory) { + super(); + this.historyLoginAppsMapper = historyLoginAppsMapper; + this.loginAppsHistory = loginAppsHistory; + } - @Override - public void run() { - historyLoginAppsMapper.insert(loginAppsHistory); - } - - } + @Override + public void run() { + historyLoginAppsMapper.insert(loginAppsHistory); + } + + } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/HistoryLoginServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/HistoryLoginServiceImpl.java index e767e37d0..886d997e0 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/HistoryLoginServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/HistoryLoginServiceImpl.java @@ -30,37 +30,37 @@ import org.springframework.stereotype.Repository; @Repository public class HistoryLoginServiceImpl extends JpaServiceImpl implements HistoryLoginService{ - private static Logger logger = LoggerFactory.getLogger(HistoryLoginServiceImpl.class); - - public JpaPageResults queryOnlineSession(HistoryLogin historyLogin) { - return this.fetchPageResults("queryOnlineSession",historyLogin); - } - - public void login(HistoryLogin historyLogin) { - historyLogin.setId(WebContext.genId()); - if(StringUtils.isBlank(historyLogin.getInstId())) { - historyLogin.setInstId("1"); - } - //Thread insert - new Thread(new HistoryLoginRunnable(this,historyLogin)).start(); - } - - public class HistoryLoginRunnable implements Runnable{ - - HistoryLoginService historyLoginService; - - HistoryLogin historyLogin; - - public HistoryLoginRunnable(HistoryLoginService historyLoginService, HistoryLogin historyLogin) { - super(); - this.historyLoginService = historyLoginService; - this.historyLogin = historyLogin; - } + private static Logger logger = LoggerFactory.getLogger(HistoryLoginServiceImpl.class); + + public JpaPageResults queryOnlineSession(HistoryLogin historyLogin) { + return this.fetchPageResults("queryOnlineSession",historyLogin); + } + + public void login(HistoryLogin historyLogin) { + historyLogin.setId(WebContext.genId()); + if(StringUtils.isBlank(historyLogin.getInstId())) { + historyLogin.setInstId("1"); + } + //Thread insert + new Thread(new HistoryLoginRunnable(this,historyLogin)).start(); + } + + public class HistoryLoginRunnable implements Runnable{ + + HistoryLoginService historyLoginService; + + HistoryLogin historyLogin; + + public HistoryLoginRunnable(HistoryLoginService historyLoginService, HistoryLogin historyLogin) { + super(); + this.historyLoginService = historyLoginService; + this.historyLogin = historyLogin; + } - @Override - public void run() { - logger.debug("History Login {}" , historyLogin); - this.historyLoginService.insert(historyLogin); - } - } + @Override + public void run() { + logger.debug("History Login {}" , historyLogin); + this.historyLoginService.insert(historyLogin); + } + } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/HistorySystemLogsServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/HistorySystemLogsServiceImpl.java index 394842568..bab1c8b0d 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/HistorySystemLogsServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/HistorySystemLogsServiceImpl.java @@ -42,159 +42,159 @@ import org.springframework.stereotype.Repository; @Repository public class HistorySystemLogsServiceImpl extends JpaServiceImpl implements HistorySystemLogsService{ - static final Logger _logger = LoggerFactory.getLogger(HistorySystemLogsServiceImpl.class); + static final Logger _logger = LoggerFactory.getLogger(HistorySystemLogsServiceImpl.class); - public void insert(String topic,Object entity,String action,String result,UserInfo operator) { - String message = ""; - if(entity != null) { - if(entity instanceof UserInfo userInfo) { - message = buildMsg(userInfo); - }else if(entity instanceof Organizations organization) { - message = buildMsg(organization); - }else if(entity instanceof ChangePassword changePassword) { - message = buildMsg(changePassword); - }else if(entity instanceof Accounts account) { - message = buildMsg(account); - }else if(entity instanceof Roles role) { - message = buildMsg(role); - }else if(entity instanceof RoleMember roleMember) { - message = buildMsg(roleMember); - }else if(entity instanceof Access access) { - message = buildMsg(access); - }else if(entity instanceof Resources resource) { - message = buildMsg(resource); - }else if(entity instanceof Synchronizers synchronizer) { - message = buildMsg(synchronizer); - }else if(entity instanceof SocialsProvider socialsProvider) { - message = buildMsg(socialsProvider); - }else if(entity instanceof Permission permission) { - message = buildMsg(permission); - }else if(entity instanceof String) { - message = entity.toString(); - } - - } - - insert(topic,message,action,result,operator, entity); - } - - public void insert(String topic,String message,String action,String result,UserInfo operator,Object entity) { - HistorySystemLogs systemLog = new HistorySystemLogs(); - systemLog.setId(systemLog.generateId()); - systemLog.setTopic(topic); - systemLog.setMessage(message); - systemLog.setMessageAction(action); - systemLog.setMessageResult(result); - systemLog.setUserId(operator.getId()); - systemLog.setUsername(operator.getUsername()); - systemLog.setDisplayName(operator.getDisplayName()); - systemLog.setInstId(operator.getInstId()); - systemLog.setJsonCotent(JsonUtils.gsonToString(entity)); - systemLog.setExecuteTime(new Date()); - _logger.trace("System Log {}" ,systemLog); - getMapper().insert(systemLog); - } - - public String buildMsg(UserInfo userInfo) { - return new StringBuilder() - .append(userInfo.getDisplayName()) - .append("[") - .append(userInfo.getUsername()) - .append("]") - .toString(); - } - - public String buildMsg(Organizations org) { - return new StringBuilder() - .append(org.getOrgName()) - .append("[") - .append(org.getOrgCode()) - .append("]") - .toString(); - } - - public String buildMsg(Accounts account) { - return new StringBuilder() - .append(account.getRelatedUsername()) - .append("[") - .append(account.getDisplayName()).append(",") - .append(account.getUsername()).append(",") - .append(account.getAppName()) - .append("]") - .toString(); - } - - public String buildMsg(ChangePassword changePassword) { - return new StringBuilder() - .append(changePassword.getDisplayName()) - .append("[") - .append(changePassword.getUsername()) - .append("]") - .toString(); - } - - public String buildMsg(Roles g) { - return new StringBuilder() - .append(g.getRoleName()) - .toString(); - } - - public String buildMsg(RoleMember rm) { - return new StringBuilder() - .append(rm.getRoleName()) - .append("[") - .append(rm.getUsername()).append(",") - .append(rm.getDisplayName()) - .append("]") - .toString(); - } - - public String buildMsg(Access permission) { - return new StringBuilder() - .append(permission.getGroupName()) - .append("[") - .append(permission.getAppName()) - .append("]") - .toString(); - } - - public String buildMsg(Permission privilege) { - return new StringBuilder() - .append(privilege.getGroupId()) - .append("[") - .append(privilege.getResourceId()) - .append("]") - .toString(); - } - - - public String buildMsg(Resources r) { - return new StringBuilder() - .append(r.getResourceName()) - .append("[") - .append(r.getResourceType()) - .append("]") - .toString(); - } - - - public String buildMsg(Synchronizers s) { - return new StringBuilder() - .append(s.getName()) - .append("[") - .append(s.getSourceType()).append(",") - .append(s.getScheduler()).append(",") - .append("]") - .toString(); - } - - public String buildMsg(SocialsProvider s) { - return new StringBuilder() - .append(s.getProviderName()) - .append("[") - .append(s.getProvider()) - .append("]") - .toString(); - } - + public void insert(String topic,Object entity,String action,String result,UserInfo operator) { + String message = ""; + if(entity != null) { + if(entity instanceof UserInfo userInfo) { + message = buildMsg(userInfo); + }else if(entity instanceof Organizations organization) { + message = buildMsg(organization); + }else if(entity instanceof ChangePassword changePassword) { + message = buildMsg(changePassword); + }else if(entity instanceof Accounts account) { + message = buildMsg(account); + }else if(entity instanceof Roles role) { + message = buildMsg(role); + }else if(entity instanceof RoleMember roleMember) { + message = buildMsg(roleMember); + }else if(entity instanceof Access access) { + message = buildMsg(access); + }else if(entity instanceof Resources resource) { + message = buildMsg(resource); + }else if(entity instanceof Synchronizers synchronizer) { + message = buildMsg(synchronizer); + }else if(entity instanceof SocialsProvider socialsProvider) { + message = buildMsg(socialsProvider); + }else if(entity instanceof Permission permission) { + message = buildMsg(permission); + }else if(entity instanceof String) { + message = entity.toString(); + } + + } + + insert(topic,message,action,result,operator, entity); + } + + public void insert(String topic,String message,String action,String result,UserInfo operator,Object entity) { + HistorySystemLogs systemLog = new HistorySystemLogs(); + systemLog.setId(systemLog.generateId()); + systemLog.setTopic(topic); + systemLog.setMessage(message); + systemLog.setMessageAction(action); + systemLog.setMessageResult(result); + systemLog.setUserId(operator.getId()); + systemLog.setUsername(operator.getUsername()); + systemLog.setDisplayName(operator.getDisplayName()); + systemLog.setInstId(operator.getInstId()); + systemLog.setJsonCotent(JsonUtils.gsonToString(entity)); + systemLog.setExecuteTime(new Date()); + _logger.trace("System Log {}" ,systemLog); + getMapper().insert(systemLog); + } + + public String buildMsg(UserInfo userInfo) { + return new StringBuilder() + .append(userInfo.getDisplayName()) + .append("[") + .append(userInfo.getUsername()) + .append("]") + .toString(); + } + + public String buildMsg(Organizations org) { + return new StringBuilder() + .append(org.getOrgName()) + .append("[") + .append(org.getOrgCode()) + .append("]") + .toString(); + } + + public String buildMsg(Accounts account) { + return new StringBuilder() + .append(account.getRelatedUsername()) + .append("[") + .append(account.getDisplayName()).append(",") + .append(account.getUsername()).append(",") + .append(account.getAppName()) + .append("]") + .toString(); + } + + public String buildMsg(ChangePassword changePassword) { + return new StringBuilder() + .append(changePassword.getDisplayName()) + .append("[") + .append(changePassword.getUsername()) + .append("]") + .toString(); + } + + public String buildMsg(Roles g) { + return new StringBuilder() + .append(g.getRoleName()) + .toString(); + } + + public String buildMsg(RoleMember rm) { + return new StringBuilder() + .append(rm.getRoleName()) + .append("[") + .append(rm.getUsername()).append(",") + .append(rm.getDisplayName()) + .append("]") + .toString(); + } + + public String buildMsg(Access permission) { + return new StringBuilder() + .append(permission.getGroupName()) + .append("[") + .append(permission.getAppName()) + .append("]") + .toString(); + } + + public String buildMsg(Permission privilege) { + return new StringBuilder() + .append(privilege.getGroupId()) + .append("[") + .append(privilege.getResourceId()) + .append("]") + .toString(); + } + + + public String buildMsg(Resources r) { + return new StringBuilder() + .append(r.getResourceName()) + .append("[") + .append(r.getResourceType()) + .append("]") + .toString(); + } + + + public String buildMsg(Synchronizers s) { + return new StringBuilder() + .append(s.getName()) + .append("[") + .append(s.getSourceType()).append(",") + .append(s.getScheduler()).append(",") + .append("]") + .toString(); + } + + public String buildMsg(SocialsProvider s) { + return new StringBuilder() + .append(s.getProviderName()) + .append("[") + .append(s.getProvider()) + .append("]") + .toString(); + } + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/InstitutionsServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/InstitutionsServiceImpl.java index acdd408a6..c2672b1ac 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/InstitutionsServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/InstitutionsServiceImpl.java @@ -33,43 +33,43 @@ import com.github.benmanes.caffeine.cache.Caffeine; @Repository public class InstitutionsServiceImpl extends JpaServiceImpl implements InstitutionsService{ - static final Logger _logger = LoggerFactory.getLogger(InstitutionsServiceImpl.class); - + static final Logger _logger = LoggerFactory.getLogger(InstitutionsServiceImpl.class); + private static final String DEFAULT_INSTID = "1"; protected static final Cache institutionsStore = Caffeine.newBuilder() - .expireAfterWrite(60, TimeUnit.MINUTES) - .build(); + .expireAfterWrite(60, TimeUnit.MINUTES) + .build(); - public Institutions findByDomain(String domain) { - return getMapper().findByDomain(domain); - } - - public Institutions get(String instIdOrDomain) { - _logger.trace(" instId {}" , instIdOrDomain); - Institutions inst = getByDomain(instIdOrDomain); - if(inst == null) {//use default inst - inst = getByDomain(DEFAULT_INSTID); - institutionsStore.put(instIdOrDomain, inst); - } - return inst; - } + public Institutions findByDomain(String domain) { + return getMapper().findByDomain(domain); + } + + public Institutions get(String instIdOrDomain) { + _logger.trace(" instId {}" , instIdOrDomain); + Institutions inst = getByDomain(instIdOrDomain); + if(inst == null) {//use default inst + inst = getByDomain(DEFAULT_INSTID); + institutionsStore.put(instIdOrDomain, inst); + } + return inst; + } - private Institutions getByDomain(String instIdOrDomain) { - _logger.trace(" instId {}" , instIdOrDomain); - Institutions inst = institutionsStore.getIfPresent(instIdOrDomain); - if(inst == null) { - Institutions institution = findByDomain(instIdOrDomain); - if(institution != null ) { - inst = institution; - institutionsStore.put(inst.getDomain(), inst); - institutionsStore.put(inst.getConsoleDomain(), inst); - institutionsStore.put(inst.getId(), inst); - } - } + private Institutions getByDomain(String instIdOrDomain) { + _logger.trace(" instId {}" , instIdOrDomain); + Institutions inst = institutionsStore.getIfPresent(instIdOrDomain); + if(inst == null) { + Institutions institution = findByDomain(instIdOrDomain); + if(institution != null ) { + inst = institution; + institutionsStore.put(inst.getDomain(), inst); + institutionsStore.put(inst.getConsoleDomain(), inst); + institutionsStore.put(inst.getId(), inst); + } + } - return inst; - } - + return inst; + } + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/LoginServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/LoginServiceImpl.java index 8e5f4ee7e..d7b5470e1 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/LoginServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/LoginServiceImpl.java @@ -88,38 +88,38 @@ public class LoginServiceImpl implements LoginService{ public UserInfo find(String username, String password) { List listUserInfo = null ; if( LOGIN_ATTRIBUTE_TYPE == 1) { - listUserInfo = findByUsername(username,password); + listUserInfo = findByUsername(username,password); }else if( LOGIN_ATTRIBUTE_TYPE == 2) { - listUserInfo = findByUsernameOrMobile(username,password); + listUserInfo = findByUsernameOrMobile(username,password); }else if( LOGIN_ATTRIBUTE_TYPE == 3) { - listUserInfo = findByUsernameOrMobileOrEmail(username,password); + listUserInfo = findByUsernameOrMobileOrEmail(username,password); } _logger.debug("load UserInfo : {}" , listUserInfo); return (CollectionUtils.isNotEmpty(listUserInfo) ? listUserInfo.get(0) : null); } public List findByUsername(String username, String password) { - return jdbcTemplate.query( - DEFAULT_USERINFO_SELECT_STATEMENT, - new UserInfoRowMapper(), - username - ); + return jdbcTemplate.query( + DEFAULT_USERINFO_SELECT_STATEMENT, + new UserInfoRowMapper(), + username + ); } public List findByUsernameOrMobile(String username, String password) { - return jdbcTemplate.query( - DEFAULT_USERINFO_SELECT_STATEMENT_USERNAME_MOBILE, - new UserInfoRowMapper(), - username,username - ); + return jdbcTemplate.query( + DEFAULT_USERINFO_SELECT_STATEMENT_USERNAME_MOBILE, + new UserInfoRowMapper(), + username,username + ); } public List findByUsernameOrMobileOrEmail(String username, String password) { - return jdbcTemplate.query( - DEFAULT_USERINFO_SELECT_STATEMENT_USERNAME_MOBILE_EMAIL, - new UserInfoRowMapper(), - username,username,username - ); + return jdbcTemplate.query( + DEFAULT_USERINFO_SELECT_STATEMENT_USERNAME_MOBILE_EMAIL, + new UserInfoRowMapper(), + username,username,username + ); } @@ -131,8 +131,8 @@ public class LoginServiceImpl implements LoginService{ */ public boolean passwordPolicyValid(UserInfo userInfo) { - CnfPasswordPolicy passwordPolicy = cnfPasswordPolicyService.getPasswordPolicy(); - + CnfPasswordPolicy passwordPolicy = cnfPasswordPolicyService.getPasswordPolicy(); + DateTime currentdateTime = new DateTime(); /* * check login attempts fail times @@ -181,8 +181,8 @@ public class LoginServiceImpl implements LoginService{ } public void applyPasswordPolicy(UserInfo userInfo) { - CnfPasswordPolicy passwordPolicy = cnfPasswordPolicyService.getPasswordPolicy(); - + CnfPasswordPolicy passwordPolicy = cnfPasswordPolicyService.getPasswordPolicy(); + DateTime currentdateTime = new DateTime(); //initial password need change if(userInfo.getLoginCount()<=0) { @@ -231,8 +231,8 @@ public class LoginServiceImpl implements LoginService{ public void lockUser(UserInfo userInfo) { try { if (userInfo != null - && StringUtils.isNotEmpty(userInfo.getId()) - && userInfo.getIsLocked() == ConstsStatus.ACTIVE) { + && StringUtils.isNotEmpty(userInfo.getId()) + && userInfo.getIsLocked() == ConstsStatus.ACTIVE) { userInfo.setIsLocked(ConstsStatus.LOCK); userInfoService.locked(userInfo); } @@ -282,10 +282,10 @@ public class LoginServiceImpl implements LoginService{ */ private void setBadPasswordCount(String userId,int badPasswordCount) { try { - UserInfo user = new UserInfo(); - user.setId(userId); - user.setBadPasswordCount(badPasswordCount); - userInfoService.badPasswordCount(user); + UserInfo user = new UserInfo(); + user.setId(userId); + user.setBadPasswordCount(badPasswordCount); + userInfoService.badPasswordCount(user); } catch (Exception e) { _logger.error("setBadPasswordCount Exception",e); } @@ -296,16 +296,16 @@ public class LoginServiceImpl implements LoginService{ setBadPasswordCount(userInfo.getId(),userInfo.getBadPasswordCount()); CnfPasswordPolicy passwordPolicy = cnfPasswordPolicyService.getPasswordPolicy(); if(userInfo.getBadPasswordCount() >= passwordPolicy.getAttempts()) { - _logger.debug("Bad Password Count {} , Max Attempts {}", - userInfo.getBadPasswordCount() + 1,passwordPolicy.getAttempts()); - this.lockUser(userInfo); + _logger.debug("Bad Password Count {} , Max Attempts {}", + userInfo.getBadPasswordCount() + 1,passwordPolicy.getAttempts()); + this.lockUser(userInfo); } } } public void resetBadPasswordCount(UserInfo userInfo) { if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId()) && userInfo.getBadPasswordCount()>0) { - setBadPasswordCount(userInfo.getId(),0); + setBadPasswordCount(userInfo.getId(),0); } } @@ -356,8 +356,8 @@ public class LoginServiceImpl implements LoginService{ for (Groups group : listGroups) { grantedAuthority.add(new SimpleGrantedAuthority(group.getId())); if(group.getGroupCode().startsWith("ROLE_") - && !grantedAuthority.contains(new SimpleGrantedAuthority(group.getGroupCode()))) { - grantedAuthority.add(new SimpleGrantedAuthority(group.getGroupCode())); + && !grantedAuthority.contains(new SimpleGrantedAuthority(group.getGroupCode()))) { + grantedAuthority.add(new SimpleGrantedAuthority(group.getGroupCode())); } } _logger.debug("Authority : {}" , grantedAuthority); @@ -369,10 +369,10 @@ public class LoginServiceImpl implements LoginService{ public void updateLastLogin(UserInfo userInfo) { jdbcTemplate.update(LOGIN_USERINFO_UPDATE_STATEMENT, new Object[] { - userInfo.getLastLoginTime(), - userInfo.getLastLoginIp(), - userInfo.getId() - }, + userInfo.getLastLoginTime(), + userInfo.getLastLoginIp(), + userInfo.getId() + }, new int[] { Types.TIMESTAMP, Types.VARCHAR, Types.VARCHAR }); } @@ -494,15 +494,15 @@ public class LoginServiceImpl implements LoginService{ } } - @Override - public UserInfo findById(String userId) { - List listUserInfo = jdbcTemplate.query( - DEFAULT_USERINFO_SELECT_STATEMENT_BY_ID, - new UserInfoRowMapper(), - userId - ); - return (CollectionUtils.isNotEmpty(listUserInfo) ? listUserInfo.get(0) : null); - } + @Override + public UserInfo findById(String userId) { + List listUserInfo = jdbcTemplate.query( + DEFAULT_USERINFO_SELECT_STATEMENT_BY_ID, + new UserInfoRowMapper(), + userId + ); + return (CollectionUtils.isNotEmpty(listUserInfo) ? listUserInfo.get(0) : null); + } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/OrganizationsCastServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/OrganizationsCastServiceImpl.java index 155166f95..53df1ba1a 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/OrganizationsCastServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/OrganizationsCastServiceImpl.java @@ -28,11 +28,11 @@ import org.springframework.stereotype.Repository; @Repository public class OrganizationsCastServiceImpl extends JpaServiceImpl implements OrganizationsCastService{ - static final Logger _logger = LoggerFactory.getLogger(OrganizationsCastServiceImpl.class); + static final Logger _logger = LoggerFactory.getLogger(OrganizationsCastServiceImpl.class); - public boolean updateCast(OrganizationsCast organizationsCast) { - return getMapper().updateCast(organizationsCast) > 0; - } + public boolean updateCast(OrganizationsCast organizationsCast) { + return getMapper().updateCast(organizationsCast) > 0; + } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/OrganizationsServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/OrganizationsServiceImpl.java index 975a00f48..27d635ed1 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/OrganizationsServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/OrganizationsServiceImpl.java @@ -41,123 +41,123 @@ import org.springframework.stereotype.Repository; @Repository public class OrganizationsServiceImpl extends JpaServiceImpl implements OrganizationsService{ - static final Logger _logger = LoggerFactory.getLogger(OrganizationsServiceImpl.class); - + static final Logger _logger = LoggerFactory.getLogger(OrganizationsServiceImpl.class); + @Autowired ProvisionService provisionService; - @Override - public boolean insert(Organizations organization) { - if(super.insert(organization)){ - provisionService.send( + @Override + public boolean insert(Organizations organization) { + if(super.insert(organization)){ + provisionService.send( ProvisionTopic.ORG_TOPIC, organization, ProvisionAct.CREATE); return true; } return false; - } - - @Override - public boolean update(Organizations organization) { - if(super.update(organization)){ - provisionService.send( + } + + @Override + public boolean update(Organizations organization) { + if(super.update(organization)){ + provisionService.send( ProvisionTopic.ORG_TOPIC, organization, ProvisionAct.UPDATE); return true; } return false; } - public void saveOrUpdate(Organizations organization) { - Organizations loadOrg =findOne(" id = ? and instid = ?", - new Object[] { organization.getId(), organization.getInstId() }, + public void saveOrUpdate(Organizations organization) { + Organizations loadOrg =findOne(" id = ? and instid = ?", + new Object[] { organization.getId(), organization.getInstId() }, new int[] { Types.VARCHAR, Types.VARCHAR }); - if( loadOrg == null) { - insert(organization); - }else { - organization.setId(organization.getId()); - update(organization); - } - } - public List queryOrgs(Organizations organization){ - return getMapper().queryOrgs(organization); - } - - public boolean delete(Organizations organization) { - if(super.delete(organization.getId())){ - provisionService.send( + if( loadOrg == null) { + insert(organization); + }else { + organization.setId(organization.getId()); + update(organization); + } + } + public List queryOrgs(Organizations organization){ + return getMapper().queryOrgs(organization); + } + + public boolean delete(Organizations organization) { + if(super.delete(organization.getId())){ + provisionService.send( ProvisionTopic.ORG_TOPIC, organization, ProvisionAct.DELETE); return true; } return false; - } + } - public void reorgNamePath(String instId) { - _logger.debug("instId {}", instId); - if (StringUtils.isBlank(instId)) { - instId = "1"; - } + public void reorgNamePath(String instId) { + _logger.debug("instId {}", instId); + if (StringUtils.isBlank(instId)) { + instId = "1"; + } - HashMap reorgOrgMap = new HashMap<>(); - List orgList = find(" where instid ='" + instId + "'"); - List originOrgList = new ArrayList<>(); - Organizations rootOrg = null; - for (Organizations org : orgList) { - reorgOrgMap.put(org.getId(), org); - if (isRootOrg(org)) { - rootOrg = org; - } - Organizations cloneOrg = new Organizations(); - BeanUtils.copyProperties(org, cloneOrg); - originOrgList.add(cloneOrg); - } - try { - reorg(reorgOrgMap, orgList, rootOrg); - _logger.debug("reorged ."); - long reorgCount = 0; - for (Organizations originOrg : originOrgList) { - Organizations reorgOrg = reorgOrgMap.get(originOrg.getId()); - _logger.trace("reorged Organization {}", reorgOrg); - if (originOrg.getNamePath() == null || !originOrg.getNamePath().equals(reorgOrg.getNamePath())) { - _logger.debug("update reorgCount {} , Organization {}", ++reorgCount, reorgOrg); - getMapper().updateNamePath(reorgOrg); - } - } - _logger.debug("reorg finished ."); - } catch (Exception e) { - _logger.error("reorgNamePath Exception ", e); - } - } + HashMap reorgOrgMap = new HashMap<>(); + List orgList = find(" where instid ='" + instId + "'"); + List originOrgList = new ArrayList<>(); + Organizations rootOrg = null; + for (Organizations org : orgList) { + reorgOrgMap.put(org.getId(), org); + if (isRootOrg(org)) { + rootOrg = org; + } + Organizations cloneOrg = new Organizations(); + BeanUtils.copyProperties(org, cloneOrg); + originOrgList.add(cloneOrg); + } + try { + reorg(reorgOrgMap, orgList, rootOrg); + _logger.debug("reorged ."); + long reorgCount = 0; + for (Organizations originOrg : originOrgList) { + Organizations reorgOrg = reorgOrgMap.get(originOrg.getId()); + _logger.trace("reorged Organization {}", reorgOrg); + if (originOrg.getNamePath() == null || !originOrg.getNamePath().equals(reorgOrg.getNamePath())) { + _logger.debug("update reorgCount {} , Organization {}", ++reorgCount, reorgOrg); + getMapper().updateNamePath(reorgOrg); + } + } + _logger.debug("reorg finished ."); + } catch (Exception e) { + _logger.error("reorgNamePath Exception ", e); + } + } - boolean isRootOrg(Organizations rootOrg) { - if (rootOrg.getParentId() == null || rootOrg.getParentId().equalsIgnoreCase("-1") - || rootOrg.getParentId().equalsIgnoreCase(rootOrg.getId()) - || rootOrg.getParentId().equalsIgnoreCase(rootOrg.getInstId())) { - return true; - } - return false; - } + boolean isRootOrg(Organizations rootOrg) { + if (rootOrg.getParentId() == null || rootOrg.getParentId().equalsIgnoreCase("-1") + || rootOrg.getParentId().equalsIgnoreCase(rootOrg.getId()) + || rootOrg.getParentId().equalsIgnoreCase(rootOrg.getInstId())) { + return true; + } + return false; + } - void reorg(HashMap orgMap, List orgList, Organizations rootOrg) { - if (isRootOrg(rootOrg)) { - rootOrg.setCodePath("/" + rootOrg.getId() + "/"); - rootOrg.setNamePath("/" + rootOrg.getOrgName() + "/"); - } else { - Organizations parent = orgMap.get(rootOrg.getParentId()); - rootOrg.setCodePath(parent.getCodePath() + rootOrg.getId() + "/"); - rootOrg.setNamePath(parent.getNamePath() + rootOrg.getOrgName() + "/"); - } - rootOrg.setReorgNamePath(true); + void reorg(HashMap orgMap, List orgList, Organizations rootOrg) { + if (isRootOrg(rootOrg)) { + rootOrg.setCodePath("/" + rootOrg.getId() + "/"); + rootOrg.setNamePath("/" + rootOrg.getOrgName() + "/"); + } else { + Organizations parent = orgMap.get(rootOrg.getParentId()); + rootOrg.setCodePath(parent.getCodePath() + rootOrg.getId() + "/"); + rootOrg.setNamePath(parent.getNamePath() + rootOrg.getOrgName() + "/"); + } + rootOrg.setReorgNamePath(true); - for (Organizations org : orgList) { - if (org.isReorgNamePath()) - continue; - if (org.getParentId().equalsIgnoreCase(rootOrg.getId())) { - reorg(orgMap, orgList, org); - } - } - } - /** - * 根据数据格式返回数据 + for (Organizations org : orgList) { + if (org.isReorgNamePath()) + continue; + if (org.getParentId().equalsIgnoreCase(rootOrg.getId())) { + reorg(orgMap, orgList, org); + } + } + } + /** + * 根据数据格式返回数据 * * @param cell * @return diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/PasswordPolicyValidatorServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/PasswordPolicyValidatorServiceImpl.java index 5a6f30f51..ae7344dbe 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/PasswordPolicyValidatorServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/PasswordPolicyValidatorServiceImpl.java @@ -57,7 +57,7 @@ public class PasswordPolicyValidatorServiceImpl implements PasswordPolicyValid } public CnfPasswordPolicy getPasswordPolicy(){ - return cnfPasswordPolicyService.getPasswordPolicy(); + return cnfPasswordPolicyService.getPasswordPolicy(); } @@ -118,49 +118,49 @@ public class PasswordPolicyValidatorServiceImpl implements PasswordPolicyValid passwordPolicy.getSpecialChar()); } - public class PasswordPolicyMessageResolver implements MessageResolver{ + public class PasswordPolicyMessageResolver implements MessageResolver{ - /** A accessor for Spring's {@link MessageSource} */ - private final MessageSourceAccessor messageSourceAccessor; + /** A accessor for Spring's {@link MessageSource} */ + private final MessageSourceAccessor messageSourceAccessor; - /** The {@link MessageResolver} for fallback */ - private final MessageResolver fallbackMessageResolver = new PropertiesMessageResolver(); + /** The {@link MessageResolver} for fallback */ + private final MessageResolver fallbackMessageResolver = new PropertiesMessageResolver(); - /** - * Create a new instance with the locale associated with the current thread. - * @param messageSource a message source managed by spring - */ - public PasswordPolicyMessageResolver(final MessageSource messageSource) - { - this.messageSourceAccessor = new MessageSourceAccessor(messageSource); - } + /** + * Create a new instance with the locale associated with the current thread. + * @param messageSource a message source managed by spring + */ + public PasswordPolicyMessageResolver(final MessageSource messageSource) + { + this.messageSourceAccessor = new MessageSourceAccessor(messageSource); + } - /** - * Create a new instance with the specified locale. - * @param messageSource a message source managed by spring - * @param locale the locale to use for message access - */ - public PasswordPolicyMessageResolver(final MessageSource messageSource, final Locale locale) - { - this.messageSourceAccessor = new MessageSourceAccessor(messageSource, locale); - } + /** + * Create a new instance with the specified locale. + * @param messageSource a message source managed by spring + * @param locale the locale to use for message access + */ + public PasswordPolicyMessageResolver(final MessageSource messageSource, final Locale locale) + { + this.messageSourceAccessor = new MessageSourceAccessor(messageSource, locale); + } - /** - * Resolves the message for the supplied rule result detail using Spring's {@link MessageSource}. - * (If the message can't retrieve from a {@link MessageSource}, return default message provided by passay) - * @param detail rule result detail - * @return message for the detail error code - */ - @Override - public String resolve(final RuleResultDetail detail) - { - try { - return this.messageSourceAccessor.getMessage("PasswordPolicy."+detail.getErrorCode(), detail.getValues()); - } catch (NoSuchMessageException e) { - return this.fallbackMessageResolver.resolve(detail); - } - } - } + /** + * Resolves the message for the supplied rule result detail using Spring's {@link MessageSource}. + * (If the message can't retrieve from a {@link MessageSource}, return default message provided by passay) + * @param detail rule result detail + * @return message for the detail error code + */ + @Override + public String resolve(final RuleResultDetail detail) + { + try { + return this.messageSourceAccessor.getMessage("PasswordPolicy."+detail.getErrorCode(), detail.getValues()); + } catch (NoSuchMessageException e) { + return this.fallbackMessageResolver.resolve(detail); + } + } + } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/PermissionRoleServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/PermissionRoleServiceImpl.java index 7bd965449..e6294137c 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/PermissionRoleServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/PermissionRoleServiceImpl.java @@ -30,17 +30,17 @@ import org.springframework.stereotype.Repository; @Repository public class PermissionRoleServiceImpl extends JpaServiceImpl implements PermissionRoleService{ - static final Logger _logger = LoggerFactory.getLogger(PermissionRoleServiceImpl.class); + static final Logger _logger = LoggerFactory.getLogger(PermissionRoleServiceImpl.class); - - public boolean insertPermissionRoles(List permissionRolesList) { - return getMapper().insertPermissionRoles(permissionRolesList)>0; - } - public boolean deletePermissionRoles(List permissionRolesList) { - return getMapper().deletePermissionRoles(permissionRolesList)>=0; - } - + public boolean insertPermissionRoles(List permissionRolesList) { + return getMapper().insertPermissionRoles(permissionRolesList)>0; + } + + public boolean deletePermissionRoles(List permissionRolesList) { + return getMapper().deletePermissionRoles(permissionRolesList)>=0; + } + public List queryPermissionRoles(PermissionRole permissionRole){ return getMapper().queryPermissionRoles(permissionRole); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/PermissionServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/PermissionServiceImpl.java index f99901a29..f00d6df0a 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/PermissionServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/PermissionServiceImpl.java @@ -29,16 +29,16 @@ import org.springframework.stereotype.Repository; @Repository public class PermissionServiceImpl extends JpaServiceImpl implements PermissionService{ - static final Logger _logger = LoggerFactory.getLogger(PermissionServiceImpl.class); + static final Logger _logger = LoggerFactory.getLogger(PermissionServiceImpl.class); - public boolean insertGroupPrivileges(List rolePermissionsList) { - return getMapper().insertGroupPrivileges(rolePermissionsList)>0; - }; + public boolean insertGroupPrivileges(List rolePermissionsList) { + return getMapper().insertGroupPrivileges(rolePermissionsList)>0; + }; + + public boolean deleteGroupPrivileges(List rolePermissionsList) { + return getMapper().deleteGroupPrivileges(rolePermissionsList)>=0; + } - public boolean deleteGroupPrivileges(List rolePermissionsList) { - return getMapper().deleteGroupPrivileges(rolePermissionsList)>=0; - } - public List queryGroupPrivileges(Permission rolePermissions){ return getMapper().queryGroupPrivileges(rolePermissions); } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/RegisterServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/RegisterServiceImpl.java index d01041c87..a60f21bd4 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/RegisterServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/RegisterServiceImpl.java @@ -28,10 +28,10 @@ import org.springframework.stereotype.Repository; @Repository public class RegisterServiceImpl extends JpaServiceImpl implements RegisterService{ - - public UserInfo findByEmail(String email){ - List listUserInfo=getMapper().findByEmail(email); - return listUserInfo.size()>0?listUserInfo.get(0):null; - } - + + public UserInfo findByEmail(String email){ + List listUserInfo=getMapper().findByEmail(email); + return listUserInfo.size()>0?listUserInfo.get(0):null; + } + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/ReportServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/ReportServiceImpl.java index 51da056b8..3bd86de9a 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/ReportServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/ReportServiceImpl.java @@ -30,76 +30,76 @@ import org.springframework.stereotype.Repository; @Repository public class ReportServiceImpl extends JpaServiceImpl implements ReportService{ - public Integer analysisDay(HashMap reportParameter) { - return getMapper().analysisDay(reportParameter); - } - - public Integer analysisNewUsers(HashMap reportParameter) { - return getMapper().analysisNewUsers(reportParameter); - } - - public Integer analysisOnlineUsers(HashMap reportParameter) { - return getMapper().analysisOnlineUsers(reportParameter); - } - - public Integer analysisActiveUsers(HashMap reportParameter) { - return getMapper().analysisActiveUsers(reportParameter); - } - - public Integer totalUsers(HashMap reportParameter) { - return getMapper().totalUsers(reportParameter); - } - - public Integer totalDepts(HashMap reportParameter) { - return getMapper().totalDepts(reportParameter); - } - - public Integer totalApps(HashMap reportParameter) { - return getMapper().totalApps(reportParameter); - } - - public List> analysisDayHour(HashMap reportParameter){ - return getMapper().analysisDayHour(reportParameter); - } - - public List> analysisMonth(HashMap reportParameter){ - return getMapper().analysisMonth(reportParameter); - } - - - public List> analysisBrowser(HashMap reportParameter){ - return getMapper().analysisBrowser(reportParameter); - } - - public List> analysisApp(HashMap reportParameter){ - return getMapper().analysisApp(reportParameter); - } - - public List> analysisProvince(HashMap reportParameter){ - List> maps = getMapper().analysisProvince(reportParameter); - if(null == maps) { - return new ArrayList<>(); - } - for(Map map : maps) { - if(map.containsKey("reportstring")){ - String name = map.get("reportstring").toString(); - if (name.endsWith("省") - || name.endsWith("市") - || name.endsWith("特别行政区") - || name.endsWith("自治区")) { - name = name.replace("省","") - .replace("市","") - .replace("特别行政区","") - .replace("自治区",""); - } - map.put("name",name); - } - } - return maps; - } - - public List> analysisCountry(HashMap reportParameter){ - return getMapper().analysisCountry(reportParameter); - } - + public Integer analysisDay(HashMap reportParameter) { + return getMapper().analysisDay(reportParameter); + } + + public Integer analysisNewUsers(HashMap reportParameter) { + return getMapper().analysisNewUsers(reportParameter); + } + + public Integer analysisOnlineUsers(HashMap reportParameter) { + return getMapper().analysisOnlineUsers(reportParameter); + } + + public Integer analysisActiveUsers(HashMap reportParameter) { + return getMapper().analysisActiveUsers(reportParameter); + } + + public Integer totalUsers(HashMap reportParameter) { + return getMapper().totalUsers(reportParameter); + } + + public Integer totalDepts(HashMap reportParameter) { + return getMapper().totalDepts(reportParameter); + } + + public Integer totalApps(HashMap reportParameter) { + return getMapper().totalApps(reportParameter); + } + + public List> analysisDayHour(HashMap reportParameter){ + return getMapper().analysisDayHour(reportParameter); + } + + public List> analysisMonth(HashMap reportParameter){ + return getMapper().analysisMonth(reportParameter); + } + + + public List> analysisBrowser(HashMap reportParameter){ + return getMapper().analysisBrowser(reportParameter); + } + + public List> analysisApp(HashMap reportParameter){ + return getMapper().analysisApp(reportParameter); + } + + public List> analysisProvince(HashMap reportParameter){ + List> maps = getMapper().analysisProvince(reportParameter); + if(null == maps) { + return new ArrayList<>(); + } + for(Map map : maps) { + if(map.containsKey("reportstring")){ + String name = map.get("reportstring").toString(); + if (name.endsWith("省") + || name.endsWith("市") + || name.endsWith("特别行政区") + || name.endsWith("自治区")) { + name = name.replace("省","") + .replace("市","") + .replace("特别行政区","") + .replace("自治区",""); + } + map.put("name",name); + } + } + return maps; + } + + public List> analysisCountry(HashMap reportParameter){ + return getMapper().analysisCountry(reportParameter); + } + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/ResourcesServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/ResourcesServiceImpl.java index 3fc77e877..9d9ab5474 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/ResourcesServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/ResourcesServiceImpl.java @@ -27,8 +27,8 @@ import org.springframework.stereotype.Repository; @Repository public class ResourcesServiceImpl extends JpaServiceImpl implements ResourcesService{ - - public List queryResourcesTree(Resources resource){ - return getMapper().fetchPageResults(resource); - } + + public List queryResourcesTree(Resources resource){ + return getMapper().fetchPageResults(resource); + } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/RoleMemberServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/RoleMemberServiceImpl.java index 7cdb80260..dfcc134b8 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/RoleMemberServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/RoleMemberServiceImpl.java @@ -33,38 +33,38 @@ import org.springframework.stereotype.Repository; @Repository public class RoleMemberServiceImpl extends JpaServiceImpl implements RoleMemberService{ - static final Logger _logger = LoggerFactory.getLogger(RoleMemberServiceImpl.class); + static final Logger _logger = LoggerFactory.getLogger(RoleMemberServiceImpl.class); - public int addDynamicRoleMember(Roles dynamicGroup) { - return getMapper().addDynamicRoleMember(dynamicGroup); - } - - public int deleteDynamicRoleMember(Roles dynamicGroup) { - return getMapper().deleteDynamicRoleMember(dynamicGroup); - } - - public int deleteByRoleId(String groupId) { + public int addDynamicRoleMember(Roles dynamicGroup) { + return getMapper().addDynamicRoleMember(dynamicGroup); + } + + public int deleteDynamicRoleMember(Roles dynamicGroup) { + return getMapper().deleteDynamicRoleMember(dynamicGroup); + } + + public int deleteByRoleId(String groupId) { return getMapper().deleteByRoleId(groupId); } - - public List queryMemberByRoleId(String groupId){ - return getMapper().queryMemberByRoleId(groupId); - } - - - public JpaPageResults rolesNoMember(RoleMember entity) { - entity.build(); - List resultslist = null; - try { - resultslist = getMapper().rolesNoMember(entity); - } catch (Exception e) { - _logger.error("fetchPageResults Exception " , e); - } - //当前页记录数 - Integer records = JpaPageResults.parseRecords(resultslist); - //总页数 - Integer totalCount =fetchCount(entity, resultslist); - return new JpaPageResults(entity.getPageNumber(),entity.getPageSize(),records,totalCount,resultslist); - } - + + public List queryMemberByRoleId(String groupId){ + return getMapper().queryMemberByRoleId(groupId); + } + + + public JpaPageResults rolesNoMember(RoleMember entity) { + entity.build(); + List resultslist = null; + try { + resultslist = getMapper().rolesNoMember(entity); + } catch (Exception e) { + _logger.error("fetchPageResults Exception " , e); + } + //当前页记录数 + Integer records = JpaPageResults.parseRecords(resultslist); + //总页数 + Integer totalCount =fetchCount(entity, resultslist); + return new JpaPageResults(entity.getPageNumber(),entity.getPageSize(),records,totalCount,resultslist); + } + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/RolesServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/RolesServiceImpl.java index 8327314c6..d4ab61245 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/RolesServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/RolesServiceImpl.java @@ -47,72 +47,72 @@ public class RolesServiceImpl extends JpaServiceImpl impleme @Autowired InstitutionsService institutionsService; - - public List queryDynamicRoles(Roles groups){ - return this.getMapper().queryDynamicRoles(groups); - } - - public boolean deleteById(String groupId) { - this.delete(groupId); - roleMemberService.deleteByRoleId(groupId); - return true; - } - - public List queryRolesByUserId(String userId){ - return this.getMapper().queryRolesByUserId(userId); - } - - public void refreshDynamicRoles(Roles dynamicRole){ - if(dynamicRole.getCategory().equals(Roles.Category.DYNAMIC)) { - - if(StringUtils.isNotBlank(dynamicRole.getOrgIdsList())) { - String []orgIds = dynamicRole.getOrgIdsList().split(","); - StringBuffer orgIdFilters = new StringBuffer(); - for(String orgId : orgIds) { - if(StringUtils.isNotBlank(orgId)) { - if(orgIdFilters.length() > 0) { - orgIdFilters.append(","); - } - orgIdFilters.append("'").append(orgId).append("'"); - } - } - if(orgIdFilters.length() > 0) { - dynamicRole.setOrgIdsList(orgIdFilters.toString()); - } - } - - String filters = dynamicRole.getFilters(); - _logger.debug("filters {}" , filters); - if(StringUtils.isNotBlank(filters)) { - if(StrUtils.filtersSQLInjection(filters.toLowerCase())) { - _logger.info("filters include SQL Injection Attack Risk."); - return; - } - //replace & with AND, | with OR - filters = filters.replace("&", " AND ").replace("\\|", " OR "); - - _logger.debug("set filters {}" , filters); - dynamicRole.setFilters(filters); - } - - roleMemberService.deleteDynamicRoleMember(dynamicRole); - roleMemberService.addDynamicRoleMember(dynamicRole); - - } + + public List queryDynamicRoles(Roles groups){ + return this.getMapper().queryDynamicRoles(groups); + } + + public boolean deleteById(String groupId) { + this.delete(groupId); + roleMemberService.deleteByRoleId(groupId); + return true; + } + + public List queryRolesByUserId(String userId){ + return this.getMapper().queryRolesByUserId(userId); + } + + public void refreshDynamicRoles(Roles dynamicRole){ + if(dynamicRole.getCategory().equals(Roles.Category.DYNAMIC)) { + + if(StringUtils.isNotBlank(dynamicRole.getOrgIdsList())) { + String []orgIds = dynamicRole.getOrgIdsList().split(","); + StringBuffer orgIdFilters = new StringBuffer(); + for(String orgId : orgIds) { + if(StringUtils.isNotBlank(orgId)) { + if(orgIdFilters.length() > 0) { + orgIdFilters.append(","); + } + orgIdFilters.append("'").append(orgId).append("'"); + } + } + if(orgIdFilters.length() > 0) { + dynamicRole.setOrgIdsList(orgIdFilters.toString()); + } + } + + String filters = dynamicRole.getFilters(); + _logger.debug("filters {}" , filters); + if(StringUtils.isNotBlank(filters)) { + if(StrUtils.filtersSQLInjection(filters.toLowerCase())) { + _logger.info("filters include SQL Injection Attack Risk."); + return; + } + //replace & with AND, | with OR + filters = filters.replace("&", " AND ").replace("\\|", " OR "); + + _logger.debug("set filters {}" , filters); + dynamicRole.setFilters(filters); + } + + roleMemberService.deleteDynamicRoleMember(dynamicRole); + roleMemberService.addDynamicRoleMember(dynamicRole); + + } + } + + public void refreshAllDynamicRoles(){ + List instList = + institutionsService.find("where status = ? ", new Object[]{ConstsStatus.ACTIVE}, new int[]{Types.INTEGER}); + for(Institutions inst : instList) { + Roles role = new Roles(); + role.setInstId(inst.getId()); + List rolesList = queryDynamicRoles(role); + for(Roles r : rolesList) { + _logger.debug("role {}" , r); + refreshDynamicRoles(r); + } + } } - - public void refreshAllDynamicRoles(){ - List instList = - institutionsService.find("where status = ? ", new Object[]{ConstsStatus.ACTIVE}, new int[]{Types.INTEGER}); - for(Institutions inst : instList) { - Roles role = new Roles(); - role.setInstId(inst.getId()); - List rolesList = queryDynamicRoles(role); - for(Roles r : rolesList) { - _logger.debug("role {}" , r); - refreshDynamicRoles(r); - } - } - } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/SocialsAssociatesServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/SocialsAssociatesServiceImpl.java index 9fa1248cc..e42e3e873 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/SocialsAssociatesServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/SocialsAssociatesServiceImpl.java @@ -30,8 +30,8 @@ import org.springframework.stereotype.Repository; @Repository public class SocialsAssociatesServiceImpl extends JpaServiceImpl implements SocialsAssociatesService{ - public List queryByUser(UserInfo user) { - return getMapper().queryByUser(user); - } - + public List queryByUser(UserInfo user) { + return getMapper().queryByUser(user); + } + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/SynchroRelatedServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/SynchroRelatedServiceImpl.java index 512db59aa..257af7528 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/SynchroRelatedServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/SynchroRelatedServiceImpl.java @@ -33,34 +33,34 @@ import org.springframework.stereotype.Repository; @Repository public class SynchroRelatedServiceImpl extends JpaServiceImpl implements SynchroRelatedService{ - public int updateSyncTime(SynchroRelated synchroRelated) { - return getMapper().updateSyncTime(synchroRelated); - } - - public List findOrgs(Synchronizers synchronizer) { - return find( - "instid = ? and syncid = ? and objecttype = ? ", - new Object[] { synchronizer.getInstId() ,synchronizer.getId(),Organizations.CLASS_TYPE}, + public int updateSyncTime(SynchroRelated synchroRelated) { + return getMapper().updateSyncTime(synchroRelated); + } + + public List findOrgs(Synchronizers synchronizer) { + return find( + "instid = ? and syncid = ? and objecttype = ? ", + new Object[] { synchronizer.getInstId() ,synchronizer.getId(),Organizations.CLASS_TYPE}, new int[] { Types.VARCHAR,Types.VARCHAR,Types.VARCHAR} - ); - } - - public SynchroRelated findByOriginId(Synchronizers synchronizer,String originId,String classType) { - return findOne("instid = ? and syncId = ? and originid = ? and objecttype = ? ", - new Object[] { synchronizer.getInstId(),synchronizer.getId(),originId,classType }, + ); + } + + public SynchroRelated findByOriginId(Synchronizers synchronizer,String originId,String classType) { + return findOne("instid = ? and syncId = ? and originid = ? and objecttype = ? ", + new Object[] { synchronizer.getInstId(),synchronizer.getId(),originId,classType }, new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,Types.VARCHAR}); - } - - public void updateSynchroRelated(Synchronizers synchronizer,SynchroRelated synchroRelated,String classType) { - SynchroRelated loadSynchroRelated = - findByOriginId( - synchronizer,synchroRelated.getOriginId(),classType ); - if(loadSynchroRelated == null) { - insert(synchroRelated); - }else { - synchroRelated.setId(loadSynchroRelated.getId()); - synchroRelated.setSyncTime(DateUtils.formatDateTime(new Date())); - updateSyncTime(synchroRelated); - } - } + } + + public void updateSynchroRelated(Synchronizers synchronizer,SynchroRelated synchroRelated,String classType) { + SynchroRelated loadSynchroRelated = + findByOriginId( + synchronizer,synchroRelated.getOriginId(),classType ); + if(loadSynchroRelated == null) { + insert(synchroRelated); + }else { + synchroRelated.setId(loadSynchroRelated.getId()); + synchroRelated.setSyncTime(DateUtils.formatDateTime(new Date())); + updateSyncTime(synchroRelated); + } + } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/SynchronizersServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/SynchronizersServiceImpl.java index 76becf0ec..46cac82b4 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/SynchronizersServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/SynchronizersServiceImpl.java @@ -28,5 +28,5 @@ import org.springframework.stereotype.Repository; @Repository public class SynchronizersServiceImpl extends JpaServiceImpl implements SynchronizersService{ static final Logger _logger = LoggerFactory.getLogger(SynchronizersServiceImpl.class); - + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/UserInfoServiceImpl.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/UserInfoServiceImpl.java index 6df0cc6dd..13ebfcb05 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/UserInfoServiceImpl.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/persistence/service/impl/UserInfoServiceImpl.java @@ -52,25 +52,25 @@ import org.springframework.stereotype.Repository; */ @Repository public class UserInfoServiceImpl extends JpaServiceImpl implements UserInfoService{ - static final Logger _logger = LoggerFactory.getLogger(UserInfoServiceImpl.class); - - @Autowired - private PasswordEncoder passwordEncoder; - - @Autowired - PasswordPolicyValidatorService passwordPolicyValidatorService; - - @Autowired - ProvisionService provisionService; + static final Logger _logger = LoggerFactory.getLogger(UserInfoServiceImpl.class); + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + PasswordPolicyValidatorService passwordPolicyValidatorService; + + @Autowired + ProvisionService provisionService; - AccountsService accountsService; - - - @Override + AccountsService accountsService; + + + @Override public boolean insert(UserInfo userInfo) { - this.passwordEncoder(userInfo); + this.passwordEncoder(userInfo); if (super.insert(userInfo)) { - if(provisionService.getApplicationConfig().isProvisionSupport()) { + if(provisionService.getApplicationConfig().isProvisionSupport()) { UserInfo loadUserInfo = findUserRelated(userInfo.getId()); provisionService.send( ProvisionTopic.USERINFO_TOPIC, @@ -85,11 +85,11 @@ public class UserInfoServiceImpl extends JpaServiceImpl } public boolean insert(UserInfo userInfo,boolean passwordEncoder) { - if(passwordEncoder) { - this.passwordEncoder(userInfo); - } + if(passwordEncoder) { + this.passwordEncoder(userInfo); + } if (super.insert(userInfo)) { - if(provisionService.getApplicationConfig().isProvisionSupport()) { + if(provisionService.getApplicationConfig().isProvisionSupport()) { UserInfo loadUserInfo = findUserRelated(userInfo.getId()); provisionService.send( ProvisionTopic.USERINFO_TOPIC, @@ -102,13 +102,13 @@ public class UserInfoServiceImpl extends JpaServiceImpl return false; } - + @Override public boolean update(UserInfo userInfo) { - //更新用户信息,不更新密码 - userInfo.clearPassword(); + //更新用户信息,不更新密码 + userInfo.clearPassword(); if (super.update(userInfo)) { - if(provisionService.getApplicationConfig().isProvisionSupport()) { + if(provisionService.getApplicationConfig().isProvisionSupport()) { UserInfo loadUserInfo = findUserRelated(userInfo.getId()); accountUpdate(loadUserInfo); provisionService.send( @@ -120,24 +120,24 @@ public class UserInfoServiceImpl extends JpaServiceImpl } return false; } - - public boolean delete(UserInfo userInfo) { - UserInfo loadUserInfo = null; - if(provisionService.getApplicationConfig().isProvisionSupport()) { - loadUserInfo = findUserRelated(userInfo.getId()); - } - - if( super.delete(userInfo.getId())){ - provisionService.send( - ProvisionTopic.USERINFO_TOPIC, - loadUserInfo, - ProvisionAct.DELETE); - accountUpdate(loadUserInfo); - return true; - } - return false; - } - + + public boolean delete(UserInfo userInfo) { + UserInfo loadUserInfo = null; + if(provisionService.getApplicationConfig().isProvisionSupport()) { + loadUserInfo = findUserRelated(userInfo.getId()); + } + + if( super.delete(userInfo.getId())){ + provisionService.send( + ProvisionTopic.USERINFO_TOPIC, + loadUserInfo, + ProvisionAct.DELETE); + accountUpdate(loadUserInfo); + return true; + } + return false; + } + //更新账号状态 public void accountUpdate(UserInfo userInfo) { if(userInfo.getStatus() != ConstsStatus.ACTIVE) { @@ -154,144 +154,144 @@ public class UserInfoServiceImpl extends JpaServiceImpl } } - public UserInfo findUserRelated(String userId) { - UserInfo loadUserInfo =this.get(userId); - loadUserInfo.setDepts(getMapper().findDeptsByUserId(userId)); - return loadUserInfo; - } - - public boolean updateGridList(String gridList,UserInfo userInfo) { - try { - if (gridList != null && !gridList.equals("")) { - userInfo.setGridList(Integer.parseInt(gridList)); + public UserInfo findUserRelated(String userId) { + UserInfo loadUserInfo =this.get(userId); + loadUserInfo.setDepts(getMapper().findDeptsByUserId(userId)); + return loadUserInfo; + } + + public boolean updateGridList(String gridList,UserInfo userInfo) { + try { + if (gridList != null && !gridList.equals("")) { + userInfo.setGridList(Integer.parseInt(gridList)); getMapper().updateGridList(userInfo); } - }catch(Exception e) { + }catch(Exception e) { e.printStackTrace(); return false; } - return true; - } - - - public void saveOrUpdate(UserInfo userInfo) { - UserInfo loadUserInfo = findOne(" username = ? and instid = ?", - new Object[] { userInfo.getUsername(),userInfo.getInstId() }, + return true; + } + + + public void saveOrUpdate(UserInfo userInfo) { + UserInfo loadUserInfo = findOne(" username = ? and instid = ?", + new Object[] { userInfo.getUsername(),userInfo.getInstId() }, new int[] { Types.VARCHAR,Types.VARCHAR}); - if(loadUserInfo == null) { - insert(userInfo); - }else { - userInfo.setId(loadUserInfo.getId()); - update(userInfo); - } - } - - public boolean updateProtectedApps(UserInfo userinfo) { - try { - userinfo.setModifiedDate(new Date()); - return getMapper().updateProtectedApps(userinfo) > 0; - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } + if(loadUserInfo == null) { + insert(userInfo); + }else { + userInfo.setId(loadUserInfo.getId()); + update(userInfo); + } + } + + public boolean updateProtectedApps(UserInfo userinfo) { + try { + userinfo.setModifiedDate(new Date()); + return getMapper().updateProtectedApps(userinfo) > 0; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } - public UserInfo findByUsername(String username) { - return getMapper().findByUsername(username); - } - + public UserInfo findByUsername(String username) { + return getMapper().findByUsername(username); + } + public UserInfo findByEmailMobile(String emailMobile) { return getMapper().findByEmailMobile(emailMobile); } - - public UserInfo findByAppIdAndUsername(String appId,String username){ - try { - UserInfo userinfo = new UserInfo(); - userinfo.setUsername(username); - return getMapper().findByAppIdAndUsername(userinfo) ; - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - 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()); - }else { - userInfo.setPassword(null); - userInfo.setDecipherable(null); - } - return changePassword; - } - - public ChangePassword passwordEncoder(ChangePassword changePassword) { - //密码不为空,则需要进行加密处理 - if(StringUtils.isNotBlank(changePassword.getPassword())) { - String password = passwordEncoder.encode(changePassword.getPassword()); - changePassword.setDecipherable(PasswordReciprocal.getInstance().encode(changePassword.getPassword())); + + public UserInfo findByAppIdAndUsername(String appId,String username){ + try { + UserInfo userinfo = new UserInfo(); + userinfo.setUsername(username); + return getMapper().findByAppIdAndUsername(userinfo) ; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + 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()); + }else { + userInfo.setPassword(null); + userInfo.setDecipherable(null); + } + return changePassword; + } + + public ChangePassword passwordEncoder(ChangePassword changePassword) { + //密码不为空,则需要进行加密处理 + 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(new Date()); - }else { - changePassword.setPassword(null); - changePassword.setDecipherable(null); - } + }else { + changePassword.setPassword(null); + changePassword.setDecipherable(null); + } return changePassword; - } - - /** - * 认证密码修改 - * @param oldPassword - * @param newPassword - * @param confirmPassword - * @param passwordSetType - * @return - */ - public boolean changePassword( ChangePassword changePassword) { - try { - WebContext.setAttribute(PasswordPolicyValidatorServiceImpl.PASSWORD_POLICY_VALIDATE_RESULT, ""); - 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(StringUtils.isNotBlank(changePassword.getOldPassword())&& - passwordEncoder.matches(changePassword.getPassword(), userInfo.getPassword())) { - WebContext.setAttribute(PasswordPolicyValidatorServiceImpl.PASSWORD_POLICY_VALIDATE_RESULT, - WebContext.getI18nValue("PasswordPolicy.OLD_PASSWORD_MATCH")); - }else { - WebContext.setAttribute(PasswordPolicyValidatorServiceImpl.PASSWORD_POLICY_VALIDATE_RESULT, - WebContext.getI18nValue("PasswordPolicy.OLD_PASSWORD_NOT_MATCH")); - } - } - }else { - WebContext.setAttribute(PasswordPolicyValidatorServiceImpl.PASSWORD_POLICY_VALIDATE_RESULT, - WebContext.getI18nValue("PasswordPolicy.CONFIRMPASSWORD_NOT_MATCH")); - } - } catch (Exception e) { + } + + /** + * 认证密码修改 + * @param oldPassword + * @param newPassword + * @param confirmPassword + * @param passwordSetType + * @return + */ + public boolean changePassword( ChangePassword changePassword) { + try { + WebContext.setAttribute(PasswordPolicyValidatorServiceImpl.PASSWORD_POLICY_VALIDATE_RESULT, ""); + 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(StringUtils.isNotBlank(changePassword.getOldPassword())&& + passwordEncoder.matches(changePassword.getPassword(), userInfo.getPassword())) { + WebContext.setAttribute(PasswordPolicyValidatorServiceImpl.PASSWORD_POLICY_VALIDATE_RESULT, + WebContext.getI18nValue("PasswordPolicy.OLD_PASSWORD_MATCH")); + }else { + WebContext.setAttribute(PasswordPolicyValidatorServiceImpl.PASSWORD_POLICY_VALIDATE_RESULT, + WebContext.getI18nValue("PasswordPolicy.OLD_PASSWORD_NOT_MATCH")); + } + } + }else { + WebContext.setAttribute(PasswordPolicyValidatorServiceImpl.PASSWORD_POLICY_VALIDATE_RESULT, + WebContext.getI18nValue("PasswordPolicy.CONFIRMPASSWORD_NOT_MATCH")); + } + } catch (Exception e) { e.printStackTrace(); } - - return false; - } - - /** - * 后台密码修改 - * @param changeUserInfo - * @param passwordPolicy - * @return - */ + + return false; + } + + /** + * 后台密码修改 + * @param changeUserInfo + * @param passwordPolicy + * @return + */ public boolean changePassword(ChangePassword changePassword,boolean passwordPolicy) { try { _logger.debug("decipherable old : {}" , changePassword.getDecipherable()); @@ -315,117 +315,117 @@ public class UserInfoServiceImpl extends JpaServiceImpl return false; } - - public String randomPassword() { - return passwordPolicyValidatorService.generateRandomPassword(); - } - - public void changePasswordProvisioning(ChangePassword changePassworded) { - if(changePassworded !=null && StringUtils.isNotBlank(changePassworded.getPassword())) { - UserInfo loadUserInfo = findByUsername(changePassworded.getUsername()); - ChangePassword changePassword = new ChangePassword(loadUserInfo); - provisionService.send(ProvisionTopic.PASSWORD_TOPIC, changePassword, ProvisionAct.PASSWORD); - } - } - - public boolean updateAppLoginPassword(UserInfo userinfo) { - try { - userinfo.setModifiedDate(new Date()); - return getMapper().updateAppLoginPassword(userinfo) > 0; - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - - /** - * 锁定用户:islock:1 解锁 5 锁定 - * @param userInfo - */ - public void locked(UserInfo userInfo) { - try { - if(userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) { - userInfo.setIsLocked(ConstsStatus.LOCK); - getMapper().updateLocked(userInfo); - } - } catch(Exception e) { - e.printStackTrace(); - } - } + + public String randomPassword() { + return passwordPolicyValidatorService.generateRandomPassword(); + } + + public void changePasswordProvisioning(ChangePassword changePassworded) { + if(changePassworded !=null && StringUtils.isNotBlank(changePassworded.getPassword())) { + UserInfo loadUserInfo = findByUsername(changePassworded.getUsername()); + ChangePassword changePassword = new ChangePassword(loadUserInfo); + provisionService.send(ProvisionTopic.PASSWORD_TOPIC, changePassword, ProvisionAct.PASSWORD); + } + } + + public boolean updateAppLoginPassword(UserInfo userinfo) { + try { + userinfo.setModifiedDate(new Date()); + return getMapper().updateAppLoginPassword(userinfo) > 0; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + + /** + * 锁定用户:islock:1 解锁 5 锁定 + * @param userInfo + */ + public void locked(UserInfo userInfo) { + try { + if(userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) { + userInfo.setIsLocked(ConstsStatus.LOCK); + getMapper().updateLocked(userInfo); + } + } catch(Exception e) { + e.printStackTrace(); + } + } - /** - * 用户登录成功后,重置错误密码次数和解锁用户 - * @param userInfo - */ - public void lockout(UserInfo userInfo) { - try { - if(userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) { - userInfo.setIsLocked(ConstsStatus.ACTIVE); - userInfo.setBadPasswordCount(0); - getMapper().updateLockout(userInfo); - } - } catch(Exception e) { - e.printStackTrace(); - } - } + /** + * 用户登录成功后,重置错误密码次数和解锁用户 + * @param userInfo + */ + public void lockout(UserInfo userInfo) { + try { + if(userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) { + userInfo.setIsLocked(ConstsStatus.ACTIVE); + userInfo.setBadPasswordCount(0); + getMapper().updateLockout(userInfo); + } + } catch(Exception e) { + e.printStackTrace(); + } + } - /** - * 更新错误密码次数 - * @param userInfo - */ - public void badPasswordCount(UserInfo userInfo) { - try { - if(userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) { - int updateBadPWDCount = userInfo.getBadPasswordCount() + 1; - userInfo.setBadPasswordCount(updateBadPWDCount); - getMapper().badPasswordCount(userInfo); - } - } catch(Exception e) { - e.printStackTrace(); - } - } - - /** - * 重置错误密码次数 - * @param userInfo - */ - public void badPasswordCountReset(UserInfo userInfo) { - try { - if(userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) { - getMapper().badPasswordCountReset(userInfo); - } - } catch(Exception e) { - e.printStackTrace(); - } - } + /** + * 更新错误密码次数 + * @param userInfo + */ + public void badPasswordCount(UserInfo userInfo) { + try { + if(userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) { + int updateBadPWDCount = userInfo.getBadPasswordCount() + 1; + userInfo.setBadPasswordCount(updateBadPWDCount); + getMapper().badPasswordCount(userInfo); + } + } catch(Exception e) { + e.printStackTrace(); + } + } + + /** + * 重置错误密码次数 + * @param userInfo + */ + public void badPasswordCountReset(UserInfo userInfo) { + try { + if(userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) { + getMapper().badPasswordCountReset(userInfo); + } + } catch(Exception e) { + e.printStackTrace(); + } + } - public boolean updateSharedSecret(UserInfo userInfo){ - return getMapper().updateSharedSecret(userInfo)>0; - } - - public boolean updatePasswordQuestion(UserInfo userInfo){ - return getMapper().updatePasswordQuestion(userInfo)>0; - } - - public boolean updateAuthnType(UserInfo userInfo){ - return getMapper().updateAuthnType(userInfo)>0; - } - - public boolean updateEmail(UserInfo userInfo){ - return getMapper().updateEmail(userInfo)>0; - } - - public boolean updateMobile(UserInfo userInfo){ - return getMapper().updateMobile(userInfo)>0; - } + public boolean updateSharedSecret(UserInfo userInfo){ + return getMapper().updateSharedSecret(userInfo)>0; + } + + public boolean updatePasswordQuestion(UserInfo userInfo){ + return getMapper().updatePasswordQuestion(userInfo)>0; + } + + public boolean updateAuthnType(UserInfo userInfo){ + return getMapper().updateAuthnType(userInfo)>0; + } + + public boolean updateEmail(UserInfo userInfo){ + return getMapper().updateEmail(userInfo)>0; + } + + public boolean updateMobile(UserInfo userInfo){ + return getMapper().updateMobile(userInfo)>0; + } public int updateProfile(UserInfo userInfo){ return getMapper().updateProfile(userInfo); } - public boolean updateStatus(UserInfo userInfo) { - return getMapper().updateStatus(userInfo) > 0; + public boolean updateStatus(UserInfo userInfo) { + return getMapper().updateStatus(userInfo) > 0; } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/ProvisionMessage.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/ProvisionMessage.java index c512c4442..2a516ca15 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/ProvisionMessage.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/ProvisionMessage.java @@ -19,10 +19,10 @@ package org.dromara.maxkey.provision; public class ProvisionMessage { - String id; - String topic; - String actionType; - String sendTime; + String id; + String topic; + String actionType; + String sendTime; String content; int connected; int instId; @@ -54,14 +54,14 @@ public class ProvisionMessage { } public String getId() { - return id; - } + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getContent() { + public String getContent() { return content; } @@ -70,41 +70,41 @@ public class ProvisionMessage { } public int getConnected() { - return connected; - } - - public void setConnected(int connected) { - this.connected = connected; - } - - public Object getSourceObject() { - return sourceObject; - } - - public void setSourceObject(Object sourceObject) { - this.sourceObject = sourceObject; - } - - public int getInstId() { - return instId; - } - - public void setInstId(int instId) { - this.instId = instId; - } - - public ProvisionMessage() { + return connected; } - public ProvisionMessage(String id,String topic, String actionType, String sendTime, String content,Object sourceObject) { - super(); - this.id = id; - this.topic = topic; - this.actionType = actionType; - this.sendTime = sendTime; - this.content = content; - this.sourceObject = sourceObject; - } + public void setConnected(int connected) { + this.connected = connected; + } + + public Object getSourceObject() { + return sourceObject; + } + + public void setSourceObject(Object sourceObject) { + this.sourceObject = sourceObject; + } + + public int getInstId() { + return instId; + } + + public void setInstId(int instId) { + this.instId = instId; + } + + public ProvisionMessage() { + } + + public ProvisionMessage(String id,String topic, String actionType, String sendTime, String content,Object sourceObject) { + super(); + this.id = id; + this.topic = topic; + this.actionType = actionType; + this.sendTime = sendTime; + this.content = content; + this.sourceObject = sourceObject; + } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/ProvisionService.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/ProvisionService.java index 4302add6b..851dd79d7 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/ProvisionService.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/ProvisionService.java @@ -48,36 +48,36 @@ public class ProvisionService { //maxkey.server.message.queue , if not none if(applicationConfig.isProvisionSupport()) { ProvisionMessage message = - new ProvisionMessage( - UUID.randomUUID().toString(), //message id as uuid - topic, //TOPIC - actionType, //action of content - DateUtils.getCurrentDateTimeAsString(), //send time - null, //content Object to json message content - content - ); + new ProvisionMessage( + UUID.randomUUID().toString(), //message id as uuid + topic, //TOPIC + actionType, //action of content + DateUtils.getCurrentDateTimeAsString(), //send time + null, //content Object to json message content + content + ); //sand msg to provision topic Thread thread = null; if(applicationConfig.isProvisionSupport()) { - _logger.trace("message..."); - thread = new ProvisioningThread(jdbcTemplate,message); - thread.start(); + _logger.trace("message..."); + thread = new ProvisioningThread(jdbcTemplate,message); + thread.start(); }else{ - _logger.trace("no send message..."); + _logger.trace("no send message..."); } } } - public void setApplicationConfig(ApplicationConfig applicationConfig) { - this.applicationConfig = applicationConfig; - } + public void setApplicationConfig(ApplicationConfig applicationConfig) { + this.applicationConfig = applicationConfig; + } - public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; - } + public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } - public ApplicationConfig getApplicationConfig() { - return applicationConfig; - } - + public ApplicationConfig getApplicationConfig() { + return applicationConfig; + } + } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/ProvisionTopic.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/ProvisionTopic.java index e75b61ca0..aa8a95fcd 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/ProvisionTopic.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/ProvisionTopic.java @@ -27,19 +27,19 @@ public class ProvisionTopic { public static final String ACCOUNT_TOPIC = "MXK_IDENTITY_ACCOUNT_TOPIC"; - public static final String GROUP_TOPIC = "MXK_GROUP_TOPIC"; + public static final String GROUP_TOPIC = "MXK_GROUP_TOPIC"; - public static final String GROUP_MEMBER_TOPIC = "MXK_GROUP_MEMBER_TOPIC"; + public static final String GROUP_MEMBER_TOPIC = "MXK_GROUP_MEMBER_TOPIC"; - public static final String GROUP_PERMISSIONS_TOPIC = "MXK_GROUP_PERMISSIONS_TOPIC"; + public static final String GROUP_PERMISSIONS_TOPIC = "MXK_GROUP_PERMISSIONS_TOPIC"; - public static final String ROLE_TOPIC = "MXK_ROLE_TOPIC"; + public static final String ROLE_TOPIC = "MXK_ROLE_TOPIC"; - public static final String ROLE_MEMBER_TOPIC = "MXK_ROLE_MEMBER_TOPIC"; + public static final String ROLE_MEMBER_TOPIC = "MXK_ROLE_MEMBER_TOPIC"; - public static final String ROLE_PERMISSIONS_TOPIC = "MXK_ROLE_PERMISSIONS_TOPIC"; + public static final String ROLE_PERMISSIONS_TOPIC = "MXK_ROLE_PERMISSIONS_TOPIC"; - public static final String RESOURCE_TOPIC = "MXK_RESOURCE_TOPIC"; + public static final String RESOURCE_TOPIC = "MXK_RESOURCE_TOPIC"; public static final String CONNECTOR_HISTORY_TOPIC = "MXK_CONNECTOR_HISTORY_TOPIC"; diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/thread/ProvisioningRunner.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/thread/ProvisioningRunner.java index 732e93ab7..053124bf1 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/thread/ProvisioningRunner.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/thread/ProvisioningRunner.java @@ -43,173 +43,173 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; public class ProvisioningRunner { - private static final Logger _logger = LoggerFactory.getLogger(ProvisioningRunner.class); - - static final String PROVISION_SELECT_STATEMENT = "select * from mxk_history_provisions where connected = 0 order by sendtime asc limit 500"; - - static final String PROVISION_UPDATE_STATEMENT = "update mxk_history_provisions set connected = connected + 1 where id = ?"; - - static final String PROVISION_LOG_INSERT_STATEMENT = "insert into mxk_history_connector(id,conname,topic,actiontype,sourceid,sourcename,synctime,result,instid) values (? , ? , ? , ? , ? , ? , ? , ? , ? )"; - - + private static final Logger _logger = LoggerFactory.getLogger(ProvisioningRunner.class); + + static final String PROVISION_SELECT_STATEMENT = "select * from mxk_history_provisions where connected = 0 order by sendtime asc limit 500"; + + static final String PROVISION_UPDATE_STATEMENT = "update mxk_history_provisions set connected = connected + 1 where id = ?"; + + static final String PROVISION_LOG_INSERT_STATEMENT = "insert into mxk_history_connector(id,conname,topic,actiontype,sourceid,sourcename,synctime,result,instid) values (? , ? , ? , ? , ? , ? , ? , ? , ? )"; + + JdbcTemplate jdbcTemplate; ConnectorsService connectorsService; - public ProvisioningRunner(ConnectorsService connectorsService,JdbcTemplate jdbcTemplate) { - this.connectorsService = connectorsService; - this.jdbcTemplate = jdbcTemplate; - } + public ProvisioningRunner(ConnectorsService connectorsService,JdbcTemplate jdbcTemplate) { + this.connectorsService = connectorsService; + this.jdbcTemplate = jdbcTemplate; + } + + + public void provisions() { + try { + List listConnectors = connectorsService.query(new Query().eq("status", 1).eq("justintime", 1)); + List listProvisionMessage = jdbcTemplate.query(PROVISION_SELECT_STATEMENT, new ProvisionMessageRowMapper()); + for(ProvisionMessage msg : listProvisionMessage) { + _logger.debug("Provision message {}",msg); + for(Connectors connector: listConnectors) { + _logger.debug("Provision message to connector {}",connector); + provision(msg,connector); + } + } + }catch(Exception e) { + _logger.error("provisions Exception",e); + } + } + + public void provision(ProvisionMessage provisionMessage,Connectors connector) { + if(Integer.parseInt(connector.getInstId()) == provisionMessage.getInstId()) { + String url = connector.getProviderUrl(); + if(!url.endsWith("/")) { + url = url + "/"; + } + String resultMessage = ""; + String objectId = ""; + String objectName = ""; + if(provisionMessage.getTopic().equalsIgnoreCase(ProvisionTopic.USERINFO_TOPIC)) { + UserInfo user = (UserInfo)ObjectTransformer.deserialize(provisionMessage.getContent()); + user.setPassword(null); + user.setDecipherable(null); + objectId = user.getId(); + objectName = user.getDisplayName()+"("+user.getUsername()+")"; + resultMessage = provisionUser(user,url,provisionMessage.getActionType(),connector); + provisionLog( connector.getConnName(), + "Users", + provisionMessage.getActionType(), + objectId, + objectName, + resultMessage, + provisionMessage.getInstId() + ); + }else if(provisionMessage.getTopic().equalsIgnoreCase(ProvisionTopic.PASSWORD_TOPIC)) { + ChangePassword changePassword = (ChangePassword)ObjectTransformer.deserialize(provisionMessage.getContent()); + objectId = changePassword.getUserId(); + objectName = changePassword.getDisplayName()+"("+changePassword.getUsername()+")"; + resultMessage = provisionChangePassword(changePassword,url,provisionMessage.getActionType(),connector); + provisionLog( connector.getConnName(), + "Password", + provisionMessage.getActionType(), + objectId, + objectName, + resultMessage, + provisionMessage.getInstId() + ); + }else if(provisionMessage.getTopic().equalsIgnoreCase(ProvisionTopic.ORG_TOPIC)) { + Organizations organization = (Organizations)ObjectTransformer.deserialize(provisionMessage.getContent()); + objectId = organization.getId(); + objectName = organization.getOrgName(); + resultMessage = provisionOrganization(organization,url,provisionMessage.getActionType(),connector); + provisionLog( connector.getConnName(), + "Organizations", + provisionMessage.getActionType(), + objectId, + objectName, + resultMessage, + provisionMessage.getInstId() + ); + } + + jdbcTemplate.update(PROVISION_UPDATE_STATEMENT,provisionMessage.getId()); + } + } + + public void provisionLog(String conName,String topic,String actionType,String sourceId,String sourceName,String resultMessage,int instid) { + Message resultMsg = null; + String result = "success"; + + if(resultMessage != null) { + resultMsg = JsonUtils.stringToObject(resultMessage, Message.class); + } + + if(resultMsg == null || resultMsg.getCode() != 0) { + result = "fail"; + } + + jdbcTemplate.update(PROVISION_LOG_INSERT_STATEMENT, + WebContext.genId(), + conName, + topic, + actionType.replace("_ACTION", "").toLowerCase(), + sourceId, + sourceName, + DateUtils.getCurrentDateTimeAsString(), + result, + instid + ); + } + + public String getActionType(String actionType) { + if(actionType.equalsIgnoreCase(ProvisionAct.CREATE)) { + return "create"; + }else if(actionType.equalsIgnoreCase(ProvisionAct.UPDATE)) { + return "update"; + }else if(actionType.equalsIgnoreCase(ProvisionAct.DELETE)) { + return "delete"; + } + return ""; + } + + String provisionUser(UserInfo user,String baseUrl,String actionType,Connectors connector){ + baseUrl = baseUrl + "Users/" + getActionType(actionType); + _logger.debug("URL {} ", baseUrl); + return new HttpRequestAdapter() + .addHeaderAuthorizationBasic( + connector.getPrincipal(), + PasswordReciprocal.getInstance().decoder(connector.getCredentials())) + .post(baseUrl, user); + } + + String provisionOrganization(Organizations organization,String baseUrl,String actionType,Connectors connector){ + baseUrl = baseUrl + "Organizations/"+ getActionType(actionType); + _logger.debug("URL {} ", baseUrl); + return new HttpRequestAdapter() + .addHeaderAuthorizationBasic( + connector.getPrincipal(), + PasswordReciprocal.getInstance().decoder(connector.getCredentials())) + .post(baseUrl, organization); + } + + String provisionChangePassword(ChangePassword changePassword,String baseUrl,String actionType,Connectors connector){ + baseUrl = baseUrl + "Users/changePassword"; + _logger.debug("URL {} ", baseUrl); + return new HttpRequestAdapter() + .addHeaderAuthorizationBasic( + connector.getPrincipal(), + PasswordReciprocal.getInstance().decoder(connector.getCredentials())) + .post(baseUrl, changePassword); + } - - public void provisions() { - try { - List listConnectors = connectorsService.query(new Query().eq("status", 1).eq("justintime", 1)); - List listProvisionMessage = jdbcTemplate.query(PROVISION_SELECT_STATEMENT, new ProvisionMessageRowMapper()); - for(ProvisionMessage msg : listProvisionMessage) { - _logger.debug("Provision message {}",msg); - for(Connectors connector: listConnectors) { - _logger.debug("Provision message to connector {}",connector); - provision(msg,connector); - } - } - }catch(Exception e) { - _logger.error("provisions Exception",e); - } - } - - public void provision(ProvisionMessage provisionMessage,Connectors connector) { - if(Integer.parseInt(connector.getInstId()) == provisionMessage.getInstId()) { - String url = connector.getProviderUrl(); - if(!url.endsWith("/")) { - url = url + "/"; - } - String resultMessage = ""; - String objectId = ""; - String objectName = ""; - if(provisionMessage.getTopic().equalsIgnoreCase(ProvisionTopic.USERINFO_TOPIC)) { - UserInfo user = (UserInfo)ObjectTransformer.deserialize(provisionMessage.getContent()); - user.setPassword(null); - user.setDecipherable(null); - objectId = user.getId(); - objectName = user.getDisplayName()+"("+user.getUsername()+")"; - resultMessage = provisionUser(user,url,provisionMessage.getActionType(),connector); - provisionLog( connector.getConnName(), - "Users", - provisionMessage.getActionType(), - objectId, - objectName, - resultMessage, - provisionMessage.getInstId() - ); - }else if(provisionMessage.getTopic().equalsIgnoreCase(ProvisionTopic.PASSWORD_TOPIC)) { - ChangePassword changePassword = (ChangePassword)ObjectTransformer.deserialize(provisionMessage.getContent()); - objectId = changePassword.getUserId(); - objectName = changePassword.getDisplayName()+"("+changePassword.getUsername()+")"; - resultMessage = provisionChangePassword(changePassword,url,provisionMessage.getActionType(),connector); - provisionLog( connector.getConnName(), - "Password", - provisionMessage.getActionType(), - objectId, - objectName, - resultMessage, - provisionMessage.getInstId() - ); - }else if(provisionMessage.getTopic().equalsIgnoreCase(ProvisionTopic.ORG_TOPIC)) { - Organizations organization = (Organizations)ObjectTransformer.deserialize(provisionMessage.getContent()); - objectId = organization.getId(); - objectName = organization.getOrgName(); - resultMessage = provisionOrganization(organization,url,provisionMessage.getActionType(),connector); - provisionLog( connector.getConnName(), - "Organizations", - provisionMessage.getActionType(), - objectId, - objectName, - resultMessage, - provisionMessage.getInstId() - ); - } - - jdbcTemplate.update(PROVISION_UPDATE_STATEMENT,provisionMessage.getId()); - } - } - - public void provisionLog(String conName,String topic,String actionType,String sourceId,String sourceName,String resultMessage,int instid) { - Message resultMsg = null; - String result = "success"; - - if(resultMessage != null) { - resultMsg = JsonUtils.stringToObject(resultMessage, Message.class); - } - - if(resultMsg == null || resultMsg.getCode() != 0) { - result = "fail"; - } - - jdbcTemplate.update(PROVISION_LOG_INSERT_STATEMENT, - WebContext.genId(), - conName, - topic, - actionType.replace("_ACTION", "").toLowerCase(), - sourceId, - sourceName, - DateUtils.getCurrentDateTimeAsString(), - result, - instid - ); - } - - public String getActionType(String actionType) { - if(actionType.equalsIgnoreCase(ProvisionAct.CREATE)) { - return "create"; - }else if(actionType.equalsIgnoreCase(ProvisionAct.UPDATE)) { - return "update"; - }else if(actionType.equalsIgnoreCase(ProvisionAct.DELETE)) { - return "delete"; - } - return ""; - } - - String provisionUser(UserInfo user,String baseUrl,String actionType,Connectors connector){ - baseUrl = baseUrl + "Users/" + getActionType(actionType); - _logger.debug("URL {} ", baseUrl); - return new HttpRequestAdapter() - .addHeaderAuthorizationBasic( - connector.getPrincipal(), - PasswordReciprocal.getInstance().decoder(connector.getCredentials())) - .post(baseUrl, user); - } - - String provisionOrganization(Organizations organization,String baseUrl,String actionType,Connectors connector){ - baseUrl = baseUrl + "Organizations/"+ getActionType(actionType); - _logger.debug("URL {} ", baseUrl); - return new HttpRequestAdapter() - .addHeaderAuthorizationBasic( - connector.getPrincipal(), - PasswordReciprocal.getInstance().decoder(connector.getCredentials())) - .post(baseUrl, organization); - } - - String provisionChangePassword(ChangePassword changePassword,String baseUrl,String actionType,Connectors connector){ - baseUrl = baseUrl + "Users/changePassword"; - _logger.debug("URL {} ", baseUrl); - return new HttpRequestAdapter() - .addHeaderAuthorizationBasic( - connector.getPrincipal(), - PasswordReciprocal.getInstance().decoder(connector.getCredentials())) - .post(baseUrl, changePassword); - } - public class ProvisionMessageRowMapper implements RowMapper { @Override public ProvisionMessage mapRow(ResultSet rs, int rowNum) throws SQLException { - ProvisionMessage msg = new ProvisionMessage(); - msg.setId(rs.getString("id")); - msg.setActionType(rs.getString("actiontype")); - msg.setTopic(rs.getString("topic")); - msg.setContent(rs.getString("content")); - msg.setConnected(rs.getInt("connected")); - msg.setInstId(rs.getInt("instid")); + ProvisionMessage msg = new ProvisionMessage(); + msg.setId(rs.getString("id")); + msg.setActionType(rs.getString("actiontype")); + msg.setTopic(rs.getString("topic")); + msg.setContent(rs.getString("content")); + msg.setConnected(rs.getInt("connected")); + msg.setInstId(rs.getInt("instid")); return msg; } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/thread/ProvisioningRunnerThread.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/thread/ProvisioningRunnerThread.java index 2881a67c4..020002fef 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/thread/ProvisioningRunnerThread.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/thread/ProvisioningRunnerThread.java @@ -21,26 +21,26 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ProvisioningRunnerThread extends Thread{ - private static final Logger _logger = LoggerFactory.getLogger(ProvisioningRunnerThread.class); - - ProvisioningRunner runner; + private static final Logger _logger = LoggerFactory.getLogger(ProvisioningRunnerThread.class); + + ProvisioningRunner runner; - public ProvisioningRunnerThread(ProvisioningRunner runner) { - super(); - this.runner = runner; - } + public ProvisioningRunnerThread(ProvisioningRunner runner) { + super(); + this.runner = runner; + } - @Override - public void run() { - while(true) { - try { - Thread.sleep(60 * 1000); - _logger.trace("Provisioning start ..."); - runner.provisions(); - _logger.trace("Provisioning end , wait for next ."); - } catch (InterruptedException e) { - _logger.error("InterruptedException", e); - } - } - } + @Override + public void run() { + while(true) { + try { + Thread.sleep(60 * 1000); + _logger.trace("Provisioning start ..."); + runner.provisions(); + _logger.trace("Provisioning end , wait for next ."); + } catch (InterruptedException e) { + _logger.error("InterruptedException", e); + } + } + } } diff --git a/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/thread/ProvisioningThread.java b/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/thread/ProvisioningThread.java index d31a57e47..b9063ab40 100644 --- a/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/thread/ProvisioningThread.java +++ b/maxkey-persistence/src/main/java/org/dromara/maxkey/provision/thread/ProvisioningThread.java @@ -32,29 +32,29 @@ import org.springframework.jdbc.core.JdbcTemplate; * */ public class ProvisioningThread extends Thread{ - private static final Logger _logger = LoggerFactory.getLogger(ProvisioningThread.class); + private static final Logger _logger = LoggerFactory.getLogger(ProvisioningThread.class); - static final String PROVISION_INSERT_STATEMENT = "insert into mxk_history_provisions(id,topic,actiontype,content,sendtime,connected,instid) values (? , ? , ? , ? , ? , ? , ? )"; - - JdbcTemplate jdbcTemplate; + static final String PROVISION_INSERT_STATEMENT = "insert into mxk_history_provisions(id,topic,actiontype,content,sendtime,connected,instid) values (? , ? , ? , ? , ? , ? , ? )"; + + JdbcTemplate jdbcTemplate; ProvisionMessage msg; public ProvisioningThread(JdbcTemplate jdbcTemplate, - ProvisionMessage msg) { - this.jdbcTemplate = jdbcTemplate; + ProvisionMessage msg) { + this.jdbcTemplate = jdbcTemplate; this.msg = msg; } @Override public void run() { - _logger.debug("send message \n{}" ,new JsonPretty().jacksonFormat(msg.getSourceObject())); - msg.setContent(ObjectTransformer.serialize((Serializable)msg.getSourceObject())); - Inst inst = JsonUtils.gsonStringToObject(JsonUtils.gsonToString(msg.getSourceObject()), Inst.class); - jdbcTemplate.update(PROVISION_INSERT_STATEMENT, + _logger.debug("send message \n{}" ,new JsonPretty().jacksonFormat(msg.getSourceObject())); + msg.setContent(ObjectTransformer.serialize((Serializable)msg.getSourceObject())); + Inst inst = JsonUtils.gsonStringToObject(JsonUtils.gsonToString(msg.getSourceObject()), Inst.class); + jdbcTemplate.update(PROVISION_INSERT_STATEMENT, new Object[] { - msg.getId(), msg.getTopic(), msg.getActionType(), msg.getContent(), - msg.getSendTime(),msg.getConnected(),inst.getInstId() + msg.getId(), msg.getTopic(), msg.getActionType(), msg.getContent(), + msg.getSendTime(),msg.getConnected(),inst.getInstId() }, new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, @@ -64,17 +64,17 @@ public class ProvisioningThread extends Thread{ } class Inst{ - - int instId; + + int instId; - public int getInstId() { - return instId; - } + public int getInstId() { + return instId; + } - public void setInstId(int instId) { - this.instId = instId; - } + public void setInstId(int instId) { + this.instId = instId; + } - public Inst() {} + public Inst() {} } } diff --git a/maxkey-persistence/src/test/java/org/apache/mybatis/jpa/test/AccountsServiceTest.java b/maxkey-persistence/src/test/java/org/apache/mybatis/jpa/test/AccountsServiceTest.java index 5b5f8ae06..d53794d28 100644 --- a/maxkey-persistence/src/test/java/org/apache/mybatis/jpa/test/AccountsServiceTest.java +++ b/maxkey-persistence/src/test/java/org/apache/mybatis/jpa/test/AccountsServiceTest.java @@ -30,75 +30,75 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class AccountsServiceTest { - - private static final Logger _logger = LoggerFactory.getLogger(AccountsServiceTest.class); - - public static ApplicationContext context; - - public static AccountsService service; - - public AccountsService getservice() { - service=(AccountsService)MybatisJpaContext.getBean("accountsService"); - return service; - } - + + private static final Logger _logger = LoggerFactory.getLogger(AccountsServiceTest.class); + + public static ApplicationContext context; + + public static AccountsService service; + + public AccountsService getservice() { + service=(AccountsService)MybatisJpaContext.getBean("accountsService"); + return service; + } + - @Test - public void get() throws Exception{ - _logger.info("get..."); - Accounts accounts=service.get("26b1c864-ae81-4b1f-9355-74c4c699cb6b"); - - _logger.info("accounts "+accounts); + @Test + public void get() throws Exception{ + _logger.info("get..."); + Accounts accounts=service.get("26b1c864-ae81-4b1f-9355-74c4c699cb6b"); + + _logger.info("accounts "+accounts); - } - - @Test - public void load() throws Exception{ - _logger.info("get..."); - Accounts queryAccounts=new Accounts("7BF5315CA1004CDB8E614B0361C4D46B","fe86db85-5475-4494-b5aa-dbd3b886ff64"); - Accounts accounts=service.query(queryAccounts).get(0); - - _logger.info("accounts "+accounts); + } + + @Test + public void load() throws Exception{ + _logger.info("get..."); + Accounts queryAccounts=new Accounts("7BF5315CA1004CDB8E614B0361C4D46B","fe86db85-5475-4494-b5aa-dbd3b886ff64"); + Accounts accounts=service.query(queryAccounts).get(0); + + _logger.info("accounts "+accounts); - } - - - @Test - public void findAll() throws Exception{ - _logger.info("findAll..."); - _logger.info("findAll "+service.findAll()); - } - - @Before - public void initSpringContext(){ - if(context!=null) { - return; - } - _logger.info("init Spring Context..."); - SimpleDateFormat sdf_ymdhms =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String startTime=sdf_ymdhms.format(new Date()); + } + + + @Test + public void findAll() throws Exception{ + _logger.info("findAll..."); + _logger.info("findAll "+service.findAll()); + } + + @Before + public void initSpringContext(){ + if(context!=null) { + return; + } + _logger.info("init Spring Context..."); + SimpleDateFormat sdf_ymdhms =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String startTime=sdf_ymdhms.format(new Date()); - try{ - AccountsServiceTest runner=new AccountsServiceTest(); - runner.init(); - - }catch(Exception e){ - e.printStackTrace(); - } - - _logger.info("-- --Init Start at " + startTime+" , End at "+sdf_ymdhms.format(new Date())); - } - - //Initialization ApplicationContext for Project - public void init(){ - _logger.info("init ..."); - - _logger.info("Application dir "+System.getProperty("user.dir")); - context = new ClassPathXmlApplicationContext(new String[] {"spring/applicationContext.xml"}); - MybatisJpaContext.init(context); - getservice(); - System.out.println("init ..."); - - } - + try{ + AccountsServiceTest runner=new AccountsServiceTest(); + runner.init(); + + }catch(Exception e){ + e.printStackTrace(); + } + + _logger.info("-- --Init Start at " + startTime+" , End at "+sdf_ymdhms.format(new Date())); + } + + //Initialization ApplicationContext for Project + public void init(){ + _logger.info("init ..."); + + _logger.info("Application dir "+System.getProperty("user.dir")); + context = new ClassPathXmlApplicationContext(new String[] {"spring/applicationContext.xml"}); + MybatisJpaContext.init(context); + getservice(); + System.out.println("init ..."); + + } + } diff --git a/maxkey-persistence/src/test/java/org/apache/mybatis/jpa/test/AppsServiceTest.java b/maxkey-persistence/src/test/java/org/apache/mybatis/jpa/test/AppsServiceTest.java index d87157eda..e02ceee59 100644 --- a/maxkey-persistence/src/test/java/org/apache/mybatis/jpa/test/AppsServiceTest.java +++ b/maxkey-persistence/src/test/java/org/apache/mybatis/jpa/test/AppsServiceTest.java @@ -30,63 +30,63 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class AppsServiceTest { - - private static final Logger _logger = LoggerFactory.getLogger(AppsServiceTest.class); - - public static ApplicationContext context; - - public static AppsService service; - - public AppsService getservice() { - service=(AppsService)MybatisJpaContext.getBean("appsService"); - return service; - } - + + private static final Logger _logger = LoggerFactory.getLogger(AppsServiceTest.class); + + public static ApplicationContext context; + + public static AppsService service; + + public AppsService getservice() { + service=(AppsService)MybatisJpaContext.getBean("appsService"); + return service; + } + - @Test - public void get() throws Exception{ - _logger.info("get..."); - Apps a=new Apps(); - a.setPageNumber(2); - a.setPageSize(10); - ; - getservice().fetchPageResults(a); - // _logger.info("apps "+); + @Test + public void get() throws Exception{ + _logger.info("get..."); + Apps a=new Apps(); + a.setPageNumber(2); + a.setPageSize(10); + ; + getservice().fetchPageResults(a); + // _logger.info("apps "+); - } - - - - @Before - public void initSpringContext(){ - if(context!=null) { - return; - } - _logger.info("init Spring Context..."); - SimpleDateFormat sdf_ymdhms =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String startTime=sdf_ymdhms.format(new Date()); + } + + + + @Before + public void initSpringContext(){ + if(context!=null) { + return; + } + _logger.info("init Spring Context..."); + SimpleDateFormat sdf_ymdhms =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String startTime=sdf_ymdhms.format(new Date()); - try{ - AppsServiceTest runner=new AppsServiceTest(); - runner.init(); - - }catch(Exception e){ - e.printStackTrace(); - } - - _logger.info("-- --Init Start at " + startTime+" , End at "+sdf_ymdhms.format(new Date())); - } - - //Initialization ApplicationContext for Project - public void init(){ - _logger.info("init ..."); - - _logger.info("Application dir "+System.getProperty("user.dir")); - context = new ClassPathXmlApplicationContext(new String[] {"spring/applicationContext.xml"}); - MybatisJpaContext.init(context); - getservice(); - System.out.println("init ..."); - - } - + try{ + AppsServiceTest runner=new AppsServiceTest(); + runner.init(); + + }catch(Exception e){ + e.printStackTrace(); + } + + _logger.info("-- --Init Start at " + startTime+" , End at "+sdf_ymdhms.format(new Date())); + } + + //Initialization ApplicationContext for Project + public void init(){ + _logger.info("init ..."); + + _logger.info("Application dir "+System.getProperty("user.dir")); + context = new ClassPathXmlApplicationContext(new String[] {"spring/applicationContext.xml"}); + MybatisJpaContext.init(context); + getservice(); + System.out.println("init ..."); + + } + } diff --git a/maxkey-persistence/src/test/java/org/apache/mybatis/jpa/test/FormBasedDetailsServiceTest.java b/maxkey-persistence/src/test/java/org/apache/mybatis/jpa/test/FormBasedDetailsServiceTest.java index 2c47803df..ec228febb 100644 --- a/maxkey-persistence/src/test/java/org/apache/mybatis/jpa/test/FormBasedDetailsServiceTest.java +++ b/maxkey-persistence/src/test/java/org/apache/mybatis/jpa/test/FormBasedDetailsServiceTest.java @@ -33,121 +33,121 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class FormBasedDetailsServiceTest { - - private static final Logger _logger = LoggerFactory.getLogger(FormBasedDetailsServiceTest.class); - - public static ApplicationContext context; - - public static AppsFormBasedDetailsService service; - - public AppsFormBasedDetailsService getservice() { - service=(AppsFormBasedDetailsService)MybatisJpaContext.getBean("appsFormBasedDetailsService"); - return service; - } - - @Test - public void insert() throws Exception{ - _logger.info("insert..."); - - AppsFormBasedDetails formBasedDetails=new AppsFormBasedDetails(); - - service.insert(formBasedDetails); - - Thread.sleep(1000); - service.delete(formBasedDetails.getId()); - - } - - @Test - public void get() throws Exception{ - _logger.info("get..."); - AppsFormBasedDetails formBasedDetails=service.get("850379a1-7923-4f6b-90be-d363b2dfd2ca"); - - _logger.info("formBasedDetails "+formBasedDetails); + + private static final Logger _logger = LoggerFactory.getLogger(FormBasedDetailsServiceTest.class); + + public static ApplicationContext context; + + public static AppsFormBasedDetailsService service; + + public AppsFormBasedDetailsService getservice() { + service=(AppsFormBasedDetailsService)MybatisJpaContext.getBean("appsFormBasedDetailsService"); + return service; + } + + @Test + public void insert() throws Exception{ + _logger.info("insert..."); + + AppsFormBasedDetails formBasedDetails=new AppsFormBasedDetails(); + + service.insert(formBasedDetails); + + Thread.sleep(1000); + service.delete(formBasedDetails.getId()); + + } + + @Test + public void get() throws Exception{ + _logger.info("get..."); + AppsFormBasedDetails formBasedDetails=service.get("850379a1-7923-4f6b-90be-d363b2dfd2ca"); + + _logger.info("formBasedDetails "+formBasedDetails); - } - - - @Test - public void remove() throws Exception{ - - _logger.info("remove..."); - AppsFormBasedDetails formBasedDetails=new AppsFormBasedDetails(); - formBasedDetails.setId("921d3377-937a-4578-b1e2-92fb23b5e512"); - service.delete(formBasedDetails.getId()); - - } - - @Test - public void batchDelete() throws Exception{ - _logger.info("batchDelete..."); - List idList=new ArrayList(); - idList.add("8584804d-b5ac-45d2-9f91-4dd8e7a090a7"); - idList.add("ab7422e9-a91a-4840-9e59-9d911257c918"); - idList.add("12b6ceb8-573b-4f01-ad85-cfb24cfa007c"); - idList.add("dafd5ba4-d2e3-4656-bd42-178841e610fe"); - service.deleteBatch(idList); - } + } + + + @Test + public void remove() throws Exception{ + + _logger.info("remove..."); + AppsFormBasedDetails formBasedDetails=new AppsFormBasedDetails(); + formBasedDetails.setId("921d3377-937a-4578-b1e2-92fb23b5e512"); + service.delete(formBasedDetails.getId()); + + } + + @Test + public void batchDelete() throws Exception{ + _logger.info("batchDelete..."); + List idList=new ArrayList(); + idList.add("8584804d-b5ac-45d2-9f91-4dd8e7a090a7"); + idList.add("ab7422e9-a91a-4840-9e59-9d911257c918"); + idList.add("12b6ceb8-573b-4f01-ad85-cfb24cfa007c"); + idList.add("dafd5ba4-d2e3-4656-bd42-178841e610fe"); + service.deleteBatch(idList); + } - @Test - public void queryPageResults() throws Exception{ - - _logger.info("queryPageResults..."); - AppsFormBasedDetails formBasedDetails=new AppsFormBasedDetails(); - formBasedDetails.setPageNumber(2); - _logger.info("queryPageResults "+service.fetchPageResults(formBasedDetails)); - } - - @Test - public void queryPageResultsByMapperId() throws Exception{ + @Test + public void queryPageResults() throws Exception{ + + _logger.info("queryPageResults..."); + AppsFormBasedDetails formBasedDetails=new AppsFormBasedDetails(); + formBasedDetails.setPageNumber(2); + _logger.info("queryPageResults "+service.fetchPageResults(formBasedDetails)); + } + + @Test + public void queryPageResultsByMapperId() throws Exception{ - _logger.info("queryPageResults by mapperId..."); - AppsFormBasedDetails formBasedDetails=new AppsFormBasedDetails(); + _logger.info("queryPageResults by mapperId..."); + AppsFormBasedDetails formBasedDetails=new AppsFormBasedDetails(); - formBasedDetails.setPageNumber(2); - - _logger.info("queryPageResults by mapperId "+service.fetchPageResults("queryPageResults1",formBasedDetails)); - - } - - - - @Test - public void findAll() throws Exception{ - _logger.info("findAll..."); - _logger.info("findAll "+service.findAll()); - } - - @Before - public void initSpringContext(){ - if(context!=null) { - return; - } - _logger.info("init Spring Context..."); - SimpleDateFormat sdf_ymdhms =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String startTime=sdf_ymdhms.format(new Date()); + formBasedDetails.setPageNumber(2); + + _logger.info("queryPageResults by mapperId "+service.fetchPageResults("queryPageResults1",formBasedDetails)); + + } + + + + @Test + public void findAll() throws Exception{ + _logger.info("findAll..."); + _logger.info("findAll "+service.findAll()); + } + + @Before + public void initSpringContext(){ + if(context!=null) { + return; + } + _logger.info("init Spring Context..."); + SimpleDateFormat sdf_ymdhms =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String startTime=sdf_ymdhms.format(new Date()); - try{ - FormBasedDetailsServiceTest runner=new FormBasedDetailsServiceTest(); - runner.init(); - - }catch(Exception e){ - e.printStackTrace(); - } - - _logger.info("-- --Init Start at " + startTime+" , End at "+sdf_ymdhms.format(new Date())); - } - - //Initialization ApplicationContext for Project - public void init(){ - _logger.info("init ..."); - - _logger.info("Application dir "+System.getProperty("user.dir")); - context = new ClassPathXmlApplicationContext(new String[] {"spring/applicationContext.xml"}); - MybatisJpaContext.init(context); - getservice(); - System.out.println("init ..."); - - } - + try{ + FormBasedDetailsServiceTest runner=new FormBasedDetailsServiceTest(); + runner.init(); + + }catch(Exception e){ + e.printStackTrace(); + } + + _logger.info("-- --Init Start at " + startTime+" , End at "+sdf_ymdhms.format(new Date())); + } + + //Initialization ApplicationContext for Project + public void init(){ + _logger.info("init ..."); + + _logger.info("Application dir "+System.getProperty("user.dir")); + context = new ClassPathXmlApplicationContext(new String[] {"spring/applicationContext.xml"}); + MybatisJpaContext.init(context); + getservice(); + System.out.println("init ..."); + + } + } diff --git a/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/AuthorizeBaseEndpoint.java b/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/AuthorizeBaseEndpoint.java index 2eccc8c69..528802def 100644 --- a/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/AuthorizeBaseEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/AuthorizeBaseEndpoint.java @@ -42,77 +42,77 @@ import org.springframework.web.servlet.ModelAndView; * */ public class AuthorizeBaseEndpoint { - static final Logger _logger = LoggerFactory.getLogger(AuthorizeBaseEndpoint.class); - - @Autowired + static final Logger _logger = LoggerFactory.getLogger(AuthorizeBaseEndpoint.class); + + @Autowired protected ApplicationConfig applicationConfig; - - @Autowired - protected AppsService appsService; - - @Autowired - protected AccountsService accountsService; - - protected Apps getApp(String id){ - Apps app=(Apps)WebContext.getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP); - if(StringUtils.isBlank(id)) { - _logger.error("parameter for app id {} is null.",id); - }else { - //session中为空或者id不一致重新加载 - if(app == null || !app.getId().equalsIgnoreCase(id)) { - app = appsService.get(id,true); - } - WebContext.setAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP, app); - } - if(app == null){ - _logger.error("Applications id {} is not exist.",id); - } - return app; - } - - protected Accounts getAccounts(Apps app,UserInfo userInfo){ - Apps loadApp = getApp(app.getId()); - - Accounts account = new Accounts(userInfo.getId(),loadApp.getId()); - account.setUsername(userInfo.getUsername()); - account.setAppName(app.getAppName()); - - if(loadApp.getCredential().equalsIgnoreCase(Apps.CREDENTIALS.USER_DEFINED)){ - account = accountsService.get( Query.builder().eq("appId", loadApp.getId()).eq("userid", userInfo.getId())); - if(account != null){ - account.setRelatedPassword( - PasswordReciprocal.getInstance().decoder(account.getRelatedPassword())); - } - - }else if(loadApp.getCredential().equalsIgnoreCase(Apps.CREDENTIALS.SHARED)){ - account.setRelatedUsername(loadApp.getSharedUsername()); - account.setRelatedPassword(PasswordReciprocal.getInstance().decoder(loadApp.getSharedPassword())); - }else if(loadApp.getCredential().equalsIgnoreCase( Apps.CREDENTIALS.SYSTEM)){ - account.setUsername( - AbstractAuthorizeAdapter.getValueByUserAttr(userInfo, loadApp.getSystemUserAttr()) - ); - //decoder database stored encode password - account.setRelatedPassword( - PasswordReciprocal.getInstance().decoder(userInfo.getDecipherable())); - }else if(loadApp.getCredential().equalsIgnoreCase(Apps.CREDENTIALS.NONE)){ - account.setUsername(userInfo.getUsername()); - account.setRelatedPassword(userInfo.getUsername()); - - } - return account; - } - - public ModelAndView initCredentialView(String appId,String redirect_uri){ - String initCredentialURL = - "" + - applicationConfig.getFrontendUri() + - "/#/authz/credential?appId=%s&redirect_uri=%s"; - - initCredentialURL = String.format(initCredentialURL,appId, redirect_uri); - _logger.debug("redirect to {}.",initCredentialURL); - ModelAndView modelAndView =new ModelAndView("redirect"); - modelAndView.addObject("redirect_uri", initCredentialURL); - return modelAndView; - } - + + @Autowired + protected AppsService appsService; + + @Autowired + protected AccountsService accountsService; + + protected Apps getApp(String id){ + Apps app=(Apps)WebContext.getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP); + if(StringUtils.isBlank(id)) { + _logger.error("parameter for app id {} is null.",id); + }else { + //session中为空或者id不一致重新加载 + if(app == null || !app.getId().equalsIgnoreCase(id)) { + app = appsService.get(id,true); + } + WebContext.setAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP, app); + } + if(app == null){ + _logger.error("Applications id {} is not exist.",id); + } + return app; + } + + protected Accounts getAccounts(Apps app,UserInfo userInfo){ + Apps loadApp = getApp(app.getId()); + + Accounts account = new Accounts(userInfo.getId(),loadApp.getId()); + account.setUsername(userInfo.getUsername()); + account.setAppName(app.getAppName()); + + if(loadApp.getCredential().equalsIgnoreCase(Apps.CREDENTIALS.USER_DEFINED)){ + account = accountsService.get( Query.builder().eq("appId", loadApp.getId()).eq("userid", userInfo.getId())); + if(account != null){ + account.setRelatedPassword( + PasswordReciprocal.getInstance().decoder(account.getRelatedPassword())); + } + + }else if(loadApp.getCredential().equalsIgnoreCase(Apps.CREDENTIALS.SHARED)){ + account.setRelatedUsername(loadApp.getSharedUsername()); + account.setRelatedPassword(PasswordReciprocal.getInstance().decoder(loadApp.getSharedPassword())); + }else if(loadApp.getCredential().equalsIgnoreCase( Apps.CREDENTIALS.SYSTEM)){ + account.setUsername( + AbstractAuthorizeAdapter.getValueByUserAttr(userInfo, loadApp.getSystemUserAttr()) + ); + //decoder database stored encode password + account.setRelatedPassword( + PasswordReciprocal.getInstance().decoder(userInfo.getDecipherable())); + }else if(loadApp.getCredential().equalsIgnoreCase(Apps.CREDENTIALS.NONE)){ + account.setUsername(userInfo.getUsername()); + account.setRelatedPassword(userInfo.getUsername()); + + } + return account; + } + + public ModelAndView initCredentialView(String appId,String redirect_uri){ + String initCredentialURL = + "" + + applicationConfig.getFrontendUri() + + "/#/authz/credential?appId=%s&redirect_uri=%s"; + + initCredentialURL = String.format(initCredentialURL,appId, redirect_uri); + _logger.debug("redirect to {}.",initCredentialURL); + ModelAndView modelAndView =new ModelAndView("redirect"); + modelAndView.addObject("redirect_uri", initCredentialURL); + return modelAndView; + } + } diff --git a/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/AuthorizeCredentialEndpoint.java b/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/AuthorizeCredentialEndpoint.java index 2166efeec..cf77c7795 100644 --- a/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/AuthorizeCredentialEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/AuthorizeCredentialEndpoint.java @@ -38,50 +38,50 @@ import org.springframework.web.bind.annotation.*; @RequestMapping(value = { "/authz/credential" }) public class AuthorizeCredentialEndpoint extends AuthorizeBaseEndpoint{ - @GetMapping("/get/{appId}") - public Message get( - @PathVariable("appId") String appId, - @CurrentUser UserInfo currentUser){ - Apps app = getApp(appId); - Accounts account = getAccounts(app,currentUser); - if(account == null) { - account =new Accounts (); - account.setId(account.generateId()); - - account.setUserId(currentUser.getId()); - account.setUsername(currentUser.getUsername()); - account.setDisplayName(currentUser.getDisplayName()); - - account.setAppId(appId); - account.setAppName(app.getAppName()); - account.setInstId(currentUser.getInstId()); - account.setCreateType("manual"); - account.setStatus(ConstsStatus.ACTIVE); - } - return new Message<>(account); - } - - @PutMapping("/update") - public Message update( - @RequestBody Accounts account, - @CurrentUser UserInfo currentUser){ - if(StringUtils.isNotEmpty(account.getRelatedUsername()) - &&StringUtils.isNotEmpty(account.getRelatedPassword())){ - account.setInstId(currentUser.getInstId()); - account.setRelatedPassword( - PasswordReciprocal.getInstance().encode(account.getRelatedPassword())); - if(accountsService.get(account.getId()) == null) { - if(accountsService.insert(account)){ - return new Message<>(); - } - }else { - if(accountsService.update(account)){ - return new Message<>(); - } - } - } - - return new Message<>(Message.FAIL); - } - + @GetMapping("/get/{appId}") + public Message get( + @PathVariable("appId") String appId, + @CurrentUser UserInfo currentUser){ + Apps app = getApp(appId); + Accounts account = getAccounts(app,currentUser); + if(account == null) { + account =new Accounts (); + account.setId(account.generateId()); + + account.setUserId(currentUser.getId()); + account.setUsername(currentUser.getUsername()); + account.setDisplayName(currentUser.getDisplayName()); + + account.setAppId(appId); + account.setAppName(app.getAppName()); + account.setInstId(currentUser.getInstId()); + account.setCreateType("manual"); + account.setStatus(ConstsStatus.ACTIVE); + } + return new Message<>(account); + } + + @PutMapping("/update") + public Message update( + @RequestBody Accounts account, + @CurrentUser UserInfo currentUser){ + if(StringUtils.isNotEmpty(account.getRelatedUsername()) + &&StringUtils.isNotEmpty(account.getRelatedPassword())){ + account.setInstId(currentUser.getInstId()); + account.setRelatedPassword( + PasswordReciprocal.getInstance().encode(account.getRelatedPassword())); + if(accountsService.get(account.getId()) == null) { + if(accountsService.insert(account)){ + return new Message<>(); + } + }else { + if(accountsService.update(account)){ + return new Message<>(); + } + } + } + + return new Message<>(Message.FAIL); + } + } diff --git a/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/AuthorizeEndpoint.java b/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/AuthorizeEndpoint.java index eeace10ea..7015c361b 100644 --- a/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/AuthorizeEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/AuthorizeEndpoint.java @@ -45,55 +45,55 @@ import jakarta.servlet.http.HttpServletRequest; @Tag(name = "1-2认证总地址文档模块") @Controller public class AuthorizeEndpoint extends AuthorizeBaseEndpoint{ - static final Logger _logger = LoggerFactory.getLogger(AuthorizeEndpoint.class); - - @Autowired - AppsCasDetailsService casDetailsService; - - //all single sign on url - @Operation(summary = "认证总地址接口", description = "参数应用ID,分发到不同应用的认证地址",method="GET") - @GetMapping("/authz/{id}") - public ModelAndView authorize(HttpServletRequest request,@PathVariable("id") String id){ - Apps app = getApp(id); - WebContext.setAttribute(WebConstants.SINGLE_SIGN_ON_APP_ID, app.getId()); - ModelAndView modelAndView = WebContext.redirect(app.getLoginUrl()); - - if(app.getProtocol().equalsIgnoreCase(ConstsProtocols.EXTEND_API)){ - modelAndView=WebContext.forward("/authz/api/"+app.getId()); - }else if (app.getProtocol().equalsIgnoreCase(ConstsProtocols.FORMBASED)){ - modelAndView=WebContext.forward("/authz/formbased/"+app.getId()); - }else if (app.getProtocol().equalsIgnoreCase(ConstsProtocols.OAUTH20)){ - modelAndView=WebContext.forward("/authz/oauth/v20/"+app.getId()); - }else if (app.getProtocol().equalsIgnoreCase(ConstsProtocols.OAUTH21)){ - modelAndView=WebContext.redirect(app.getLoginUrl()); + static final Logger _logger = LoggerFactory.getLogger(AuthorizeEndpoint.class); + + @Autowired + AppsCasDetailsService casDetailsService; + + //all single sign on url + @Operation(summary = "认证总地址接口", description = "参数应用ID,分发到不同应用的认证地址",method="GET") + @GetMapping("/authz/{id}") + public ModelAndView authorize(HttpServletRequest request,@PathVariable("id") String id){ + Apps app = getApp(id); + WebContext.setAttribute(WebConstants.SINGLE_SIGN_ON_APP_ID, app.getId()); + ModelAndView modelAndView = WebContext.redirect(app.getLoginUrl()); + + if(app.getProtocol().equalsIgnoreCase(ConstsProtocols.EXTEND_API)){ + modelAndView=WebContext.forward("/authz/api/"+app.getId()); + }else if (app.getProtocol().equalsIgnoreCase(ConstsProtocols.FORMBASED)){ + modelAndView=WebContext.forward("/authz/formbased/"+app.getId()); + }else if (app.getProtocol().equalsIgnoreCase(ConstsProtocols.OAUTH20)){ + modelAndView=WebContext.forward("/authz/oauth/v20/"+app.getId()); + }else if (app.getProtocol().equalsIgnoreCase(ConstsProtocols.OAUTH21)){ + modelAndView=WebContext.redirect(app.getLoginUrl()); }else if (app.getProtocol().equalsIgnoreCase(ConstsProtocols.OPEN_ID_CONNECT10)){ modelAndView=WebContext.forward("/authz/oauth/v20/"+app.getId()); - }else if (app.getProtocol().equalsIgnoreCase(ConstsProtocols.SAML20)){ - modelAndView=WebContext.forward("/authz/saml20/idpinit/"+app.getId()); - }else if (app.getProtocol().equalsIgnoreCase(ConstsProtocols.TOKENBASED)){ - modelAndView=WebContext.forward("/authz/tokenbased/"+app.getId()); - }else if (app.getProtocol().equalsIgnoreCase(ConstsProtocols.CAS)){ - modelAndView=WebContext.forward("/authz/cas/"+app.getId()); - }else if (app.getProtocol().equalsIgnoreCase(ConstsProtocols.JWT)){ + }else if (app.getProtocol().equalsIgnoreCase(ConstsProtocols.SAML20)){ + modelAndView=WebContext.forward("/authz/saml20/idpinit/"+app.getId()); + }else if (app.getProtocol().equalsIgnoreCase(ConstsProtocols.TOKENBASED)){ + modelAndView=WebContext.forward("/authz/tokenbased/"+app.getId()); + }else if (app.getProtocol().equalsIgnoreCase(ConstsProtocols.CAS)){ + modelAndView=WebContext.forward("/authz/cas/"+app.getId()); + }else if (app.getProtocol().equalsIgnoreCase(ConstsProtocols.JWT)){ modelAndView=WebContext.forward("/authz/jwt/"+app.getId()); }else if (app.getProtocol().equalsIgnoreCase(ConstsProtocols.BASIC)){ - modelAndView=WebContext.redirect(app.getLoginUrl()); - } + modelAndView=WebContext.redirect(app.getLoginUrl()); + } - _logger.debug("redirect to view {}",modelAndView.getViewName()); - - return modelAndView; - } - - @GetMapping("/authz/refused") - public ModelAndView refused(){ - ModelAndView modelAndView = new ModelAndView("authorize/authorize_refused"); - Apps app = (Apps)WebContext.getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP); - if(app != null) { - app.transIconBase64(); - } - modelAndView.addObject("model", app); - return modelAndView; - } - + _logger.debug("redirect to view {}",modelAndView.getViewName()); + + return modelAndView; + } + + @GetMapping("/authz/refused") + public ModelAndView refused(){ + ModelAndView modelAndView = new ModelAndView("authorize/authorize_refused"); + Apps app = (Apps)WebContext.getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP); + if(app != null) { + app.transIconBase64(); + } + modelAndView.addObject("model", app); + return modelAndView; + } + } diff --git a/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/AuthorizeProtectedEndpoint.java b/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/AuthorizeProtectedEndpoint.java index a7acb2b1f..82dfe3ee4 100644 --- a/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/AuthorizeProtectedEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/AuthorizeProtectedEndpoint.java @@ -39,28 +39,28 @@ import jakarta.servlet.http.HttpServletRequest; @Controller public class AuthorizeProtectedEndpoint{ - @GetMapping("/authz/protected/forward") - public ModelAndView forwardProtectedForward( - HttpServletRequest request ){ - String redirectUri=request.getAttribute("redirect_uri").toString(); - ModelAndView modelAndView=new ModelAndView("authorize/protected/forward"); - modelAndView.addObject("redirect_uri", redirectUri); - return modelAndView; - } - - @GetMapping("/authz/protected") - public ModelAndView authorizeProtected( - @RequestParam("password") String password, - @RequestParam("redirect_uri") String redirectUri, - @CurrentUser UserInfo currentUser){ - if( currentUser.getAppLoginPassword().equals(PasswordReciprocal.getInstance().encode(password))){ - WebContext.setAttribute(WebConstants.CURRENT_SINGLESIGNON_URI, redirectUri); - return WebContext.redirect(redirectUri); - } - - ModelAndView modelAndView=new ModelAndView("authorize/protected/forward"); - modelAndView.addObject("redirect_uri", redirectUri); - return modelAndView; - } - + @GetMapping("/authz/protected/forward") + public ModelAndView forwardProtectedForward( + HttpServletRequest request ){ + String redirectUri=request.getAttribute("redirect_uri").toString(); + ModelAndView modelAndView=new ModelAndView("authorize/protected/forward"); + modelAndView.addObject("redirect_uri", redirectUri); + return modelAndView; + } + + @GetMapping("/authz/protected") + public ModelAndView authorizeProtected( + @RequestParam("password") String password, + @RequestParam("redirect_uri") String redirectUri, + @CurrentUser UserInfo currentUser){ + if( currentUser.getAppLoginPassword().equals(PasswordReciprocal.getInstance().encode(password))){ + WebContext.setAttribute(WebConstants.CURRENT_SINGLESIGNON_URI, redirectUri); + return WebContext.redirect(redirectUri); + } + + ModelAndView modelAndView=new ModelAndView("authorize/protected/forward"); + modelAndView.addObject("redirect_uri", redirectUri); + return modelAndView; + } + } diff --git a/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/adapter/AbstractAuthorizeAdapter.java b/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/adapter/AbstractAuthorizeAdapter.java index b3953ef44..7d6895653 100644 --- a/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/adapter/AbstractAuthorizeAdapter.java +++ b/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/endpoint/adapter/AbstractAuthorizeAdapter.java @@ -36,108 +36,108 @@ import org.slf4j.LoggerFactory; import org.springframework.web.servlet.ModelAndView; public abstract class AbstractAuthorizeAdapter { - static final Logger _logger = LoggerFactory.getLogger(AbstractAuthorizeAdapter.class); - - protected Apps app; - - protected UserInfo userInfo; - - protected Accounts account; - - protected SignPrincipal principal; - - public abstract Object generateInfo(); - - public ModelAndView authorize(ModelAndView modelAndView) { - return modelAndView; - } - - public Object sign(Object data,String signatureKey,String signature){ - if(ConstsBoolean.isTrue(app.getIsSignature())){ - KeyStoreLoader keyStoreLoader = WebContext.getBean("keyStoreLoader",KeyStoreLoader.class); - try { - byte[] signData= CertSigner.sign(data.toString().getBytes(), keyStoreLoader.getKeyStore(), keyStoreLoader.getEntityName(), keyStoreLoader.getKeystorePassword()); - _logger.debug("signed Token : {}",data); - _logger.debug("signature : {}",signData.toString()); - - return Base64Utils.base64UrlEncode(data.toString().getBytes("UTF-8"))+"."+Base64Utils.base64UrlEncode(signData); - } catch (UnsupportedEncodingException e) { - _logger.error("UnsupportedEncodingException " , e); - } catch (Exception e) { - _logger.error("Exception " , e); - } - _logger.debug("Token {}" , data); - - }else{ - _logger.debug("data not need sign ."); - return data; - } - - return null; - } - - public Object encrypt(Object data,String algorithmKey,String algorithm){ - - algorithmKey = PasswordReciprocal.getInstance().decoder(algorithmKey); - _logger.debug("algorithm : {}",algorithm); - _logger.debug("algorithmKey : {}",algorithmKey); - //Chinese , encode data to HEX - try { - data = new String(Hex.encodeHex(data.toString().getBytes("UTF-8"))); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - byte[] encodeData = ReciprocalUtils.encode(data.toString(), algorithmKey, algorithm); - String tokenString = Base64Utils.base64UrlEncode(encodeData); - _logger.trace("Reciprocal then HEX Token : {}",tokenString); - - return tokenString; - } - - public static String getValueByUserAttr(UserInfo userInfo,String userAttr) { - String value = ""; - if(StringUtils.isBlank(userAttr)) { - value = userInfo.getUsername(); - }else if(userAttr.equalsIgnoreCase("username")){ - value = userInfo.getUsername(); - }else if(userAttr.equalsIgnoreCase("userId")){ - value = userInfo.getId(); - }else if(userAttr.equalsIgnoreCase("email")){ - value = userInfo.getEmail(); - }else if(userAttr.equalsIgnoreCase("mobile")){ - value = userInfo.getMobile(); - }else if(userAttr.equalsIgnoreCase("workEmail")) { - value = userInfo.getWorkEmail(); - }else if(userAttr.equalsIgnoreCase("windowsAccount")){ - value = userInfo.getWindowsAccount(); - }else if(userAttr.equalsIgnoreCase("employeeNumber")){ - value = userInfo.getEmployeeNumber(); - }else { - value = userInfo.getId(); - } - - if(StringUtils.isBlank(value)) { - value = userInfo.getUsername(); - } - - return value; - } - - public String serialize() { - return ""; - }; + static final Logger _logger = LoggerFactory.getLogger(AbstractAuthorizeAdapter.class); + + protected Apps app; + + protected UserInfo userInfo; + + protected Accounts account; + + protected SignPrincipal principal; + + public abstract Object generateInfo(); + + public ModelAndView authorize(ModelAndView modelAndView) { + return modelAndView; + } + + public Object sign(Object data,String signatureKey,String signature){ + if(ConstsBoolean.isTrue(app.getIsSignature())){ + KeyStoreLoader keyStoreLoader = WebContext.getBean("keyStoreLoader",KeyStoreLoader.class); + try { + byte[] signData= CertSigner.sign(data.toString().getBytes(), keyStoreLoader.getKeyStore(), keyStoreLoader.getEntityName(), keyStoreLoader.getKeystorePassword()); + _logger.debug("signed Token : {}",data); + _logger.debug("signature : {}",signData.toString()); + + return Base64Utils.base64UrlEncode(data.toString().getBytes("UTF-8"))+"."+Base64Utils.base64UrlEncode(signData); + } catch (UnsupportedEncodingException e) { + _logger.error("UnsupportedEncodingException " , e); + } catch (Exception e) { + _logger.error("Exception " , e); + } + _logger.debug("Token {}" , data); + + }else{ + _logger.debug("data not need sign ."); + return data; + } + + return null; + } + + public Object encrypt(Object data,String algorithmKey,String algorithm){ + + algorithmKey = PasswordReciprocal.getInstance().decoder(algorithmKey); + _logger.debug("algorithm : {}",algorithm); + _logger.debug("algorithmKey : {}",algorithmKey); + //Chinese , encode data to HEX + try { + data = new String(Hex.encodeHex(data.toString().getBytes("UTF-8"))); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + byte[] encodeData = ReciprocalUtils.encode(data.toString(), algorithmKey, algorithm); + String tokenString = Base64Utils.base64UrlEncode(encodeData); + _logger.trace("Reciprocal then HEX Token : {}",tokenString); + + return tokenString; + } + + public static String getValueByUserAttr(UserInfo userInfo,String userAttr) { + String value = ""; + if(StringUtils.isBlank(userAttr)) { + value = userInfo.getUsername(); + }else if(userAttr.equalsIgnoreCase("username")){ + value = userInfo.getUsername(); + }else if(userAttr.equalsIgnoreCase("userId")){ + value = userInfo.getId(); + }else if(userAttr.equalsIgnoreCase("email")){ + value = userInfo.getEmail(); + }else if(userAttr.equalsIgnoreCase("mobile")){ + value = userInfo.getMobile(); + }else if(userAttr.equalsIgnoreCase("workEmail")) { + value = userInfo.getWorkEmail(); + }else if(userAttr.equalsIgnoreCase("windowsAccount")){ + value = userInfo.getWindowsAccount(); + }else if(userAttr.equalsIgnoreCase("employeeNumber")){ + value = userInfo.getEmployeeNumber(); + }else { + value = userInfo.getId(); + } + + if(StringUtils.isBlank(value)) { + value = userInfo.getUsername(); + } + + return value; + } + + public String serialize() { + return ""; + }; - public void setPrincipal(SignPrincipal principal) { - this.principal = principal; - this.userInfo = principal.getUserInfo(); - } + public void setPrincipal(SignPrincipal principal) { + this.principal = principal; + this.userInfo = principal.getUserInfo(); + } - public void setApp(Apps app) { - this.app = app; - } + public void setApp(Apps app) { + this.app = app; + } - public void setAccount(Accounts account) { - this.account = account; - } - + public void setAccount(Accounts account) { + this.account = account; + } + } diff --git a/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/singlelogout/SingleLogout.java b/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/singlelogout/SingleLogout.java index b3407311c..e8f443eaf 100644 --- a/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/singlelogout/SingleLogout.java +++ b/maxkey-protocols/maxkey-protocol-authorize/src/main/java/org/dromara/maxkey/authz/singlelogout/SingleLogout.java @@ -31,7 +31,7 @@ public abstract class SingleLogout { public abstract void sendRequest(Authentication authentication,VisitedDto visited) ; public void postMessage(String url,Map paramMap) { - _logger.debug("post logout message to url {}" , url); - (new HttpRequestAdapter()).post(url , paramMap); + _logger.debug("post logout message to url {}" , url); + (new HttpRequestAdapter()).post(url , paramMap); } } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/Cas10AuthorizeEndpoint.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/Cas10AuthorizeEndpoint.java index d5cfb5536..dae55ed2c 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/Cas10AuthorizeEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/Cas10AuthorizeEndpoint.java @@ -45,16 +45,16 @@ import jakarta.servlet.http.HttpServletResponse; @RestController public class Cas10AuthorizeEndpoint extends CasBaseAuthorizeEndpoint{ - static final Logger _logger = LoggerFactory.getLogger(Cas10AuthorizeEndpoint.class); - - /** - * @param request - * @param response - * @param ticket - * @param service - * @param renew - * @return - * + static final Logger _logger = LoggerFactory.getLogger(Cas10AuthorizeEndpoint.class); + + /** + * @param request + * @param response + * @param ticket + * @param service + * @param renew + * @return + * 2.4. /validate [CAS 1.0] /validate checks the validity of a service ticket. /validate is part of the CAS 1.0 protocol and thus does not handle proxy authentication. CAS MUST respond with a ticket validation failure response when a proxy ticket is passed to /validate. @@ -73,41 +73,41 @@ renew [OPTIONAL] - if this parameter is set, ticket validation will only succeed 2.4.2. response /validate will return one of the following two responses: - On ticket validation success: - yes - username - - On ticket validation failure: - no - - */ - @Operation(summary = "CAS 1.0 ticket验证接口", description = "通过ticket获取当前登录用户信息",method="POST") - @RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_VALIDATE,method={RequestMethod.GET,RequestMethod.POST}) - public String validate( - HttpServletRequest request, - HttpServletResponse response, - @RequestParam(value = CasConstants.PARAMETER.TICKET) String ticket, - @RequestParam(value = CasConstants.PARAMETER.SERVICE) String service, - @RequestParam(value = CasConstants.PARAMETER.RENEW,required=false) String renew){ - _logger.debug("serviceValidate ticket {} , service {} , renew {}" , ticket,service,renew); - - Ticket storedTicket = null; - try { - storedTicket = ticketServices.consumeTicket(ticket); - } catch (Exception e) { - _logger.error("consume Ticket error " , e); - } - - if(storedTicket != null){ - String principal=((SignPrincipal)storedTicket.getAuthentication().getPrincipal()).getUsername(); - _logger.debug("principal {}",principal); - return new Service10ResponseBuilder().success() - .setUser(principal) - .serviceResponseBuilder(); - }else{ - _logger.debug("Ticket not found ."); - return new Service10ResponseBuilder().failure() - .serviceResponseBuilder(); - } - } + On ticket validation success: + yes + username + + On ticket validation failure: + no + + */ + @Operation(summary = "CAS 1.0 ticket验证接口", description = "通过ticket获取当前登录用户信息",method="POST") + @RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_VALIDATE,method={RequestMethod.GET,RequestMethod.POST}) + public String validate( + HttpServletRequest request, + HttpServletResponse response, + @RequestParam(value = CasConstants.PARAMETER.TICKET) String ticket, + @RequestParam(value = CasConstants.PARAMETER.SERVICE) String service, + @RequestParam(value = CasConstants.PARAMETER.RENEW,required=false) String renew){ + _logger.debug("serviceValidate ticket {} , service {} , renew {}" , ticket,service,renew); + + Ticket storedTicket = null; + try { + storedTicket = ticketServices.consumeTicket(ticket); + } catch (Exception e) { + _logger.error("consume Ticket error " , e); + } + + if(storedTicket != null){ + String principal=((SignPrincipal)storedTicket.getAuthentication().getPrincipal()).getUsername(); + _logger.debug("principal {}",principal); + return new Service10ResponseBuilder().success() + .setUser(principal) + .serviceResponseBuilder(); + }else{ + _logger.debug("Ticket not found ."); + return new Service10ResponseBuilder().failure() + .serviceResponseBuilder(); + } + } } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/Cas20AuthorizeEndpoint.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/Cas20AuthorizeEndpoint.java index bd7991044..71152b440 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/Cas20AuthorizeEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/Cas20AuthorizeEndpoint.java @@ -56,17 +56,17 @@ import jakarta.servlet.http.HttpServletResponse; @Tag(name = "2-3-CAS API文档模块") @RestController public class Cas20AuthorizeEndpoint extends CasBaseAuthorizeEndpoint{ - static final Logger _logger = LoggerFactory.getLogger(Cas20AuthorizeEndpoint.class); - - /** - * @param request - * @param response - * @param ticket - * @param service - * @param pgtUrl - * @param renew - * @param format - * @return + static final Logger _logger = LoggerFactory.getLogger(Cas20AuthorizeEndpoint.class); + + /** + * @param request + * @param response + * @param ticket + * @param service + * @param pgtUrl + * @param renew + * @param format + * @return 2.5. /serviceValidate [CAS 2.0] /serviceValidate checks the validity of a service ticket and returns an XML-fragment response. /serviceValidate MUST also generate and issue proxy-granting tickets when requested. /serviceValidate MUST NOT return a successful authentication if it receives a proxy ticket. It is RECOMMENDED that if /serviceValidate receives a proxy ticket, the error message in the XML response SHOULD explain that validation failed because a proxy ticket was passed to /serviceValidate. @@ -90,70 +90,70 @@ format [OPTIONAL] - if this parameter is set, ticket validation response MUST be 2.5.2. response /serviceValidate will return an XML-formatted CAS serviceResponse as described in the XML schema in Appendix A. Below are example responses: - On ticket validation success: - - - username - PGTIOU-84678-8a9d... - - - - { - "serviceResponse" : { - "authenticationSuccess" : { - "user" : "username", - "proxyGrantingTicket" : "PGTIOU-84678-8a9d..." - } - } - } - On ticket validation failure: - - - Ticket ST-1856339-aA5Yuvrxzpv8Tau1cYQ7 not recognized - - - - { - "serviceResponse" : { - "authenticationFailure" : { - "code" : "INVALID_TICKET", - "description" : "Ticket ST-1856339-aA5Yuvrxzpv8Tau1cYQ7 not recognized" - } - } - } - - Example response with custom attributes - - - username - - John - Doe - Mr. - jdoe@example.org - staff - faculty - - PGTIOU-84678-8a9d... - - - - { - "serviceResponse" : { - "authenticationSuccess" : { - "user" : "username", - "proxyGrantingTicket" : "PGTIOU-84678-8a9d...", - "proxies" : [ "https://proxy1/pgtUrl", "https://proxy2/pgtUrl" ], - "attributes" : { - "firstName" : "John", - "affiliation" : [ "staff", "faculty" ], - "title" : "Mr.", - "email" : "jdoe@example.orgmailto:jdoe@example.org", - "lastname" : "Doe" - } - } - } - } + On ticket validation success: + + + username + PGTIOU-84678-8a9d... + + + + { + "serviceResponse" : { + "authenticationSuccess" : { + "user" : "username", + "proxyGrantingTicket" : "PGTIOU-84678-8a9d..." + } + } + } + On ticket validation failure: + + + Ticket ST-1856339-aA5Yuvrxzpv8Tau1cYQ7 not recognized + + + + { + "serviceResponse" : { + "authenticationFailure" : { + "code" : "INVALID_TICKET", + "description" : "Ticket ST-1856339-aA5Yuvrxzpv8Tau1cYQ7 not recognized" + } + } + } + + Example response with custom attributes + + + username + + John + Doe + Mr. + jdoe@example.org + staff + faculty + + PGTIOU-84678-8a9d... + + + + { + "serviceResponse" : { + "authenticationSuccess" : { + "user" : "username", + "proxyGrantingTicket" : "PGTIOU-84678-8a9d...", + "proxies" : [ "https://proxy1/pgtUrl", "https://proxy2/pgtUrl" ], + "attributes" : { + "firstName" : "John", + "affiliation" : [ "staff", "faculty" ], + "title" : "Mr.", + "email" : "jdoe@example.orgmailto:jdoe@example.org", + "lastname" : "Doe" + } + } + } + } 2.5.3. error codes The following values MAY be used as the ��code�� attribute of authentication failure responses. The following is the minimum set of error codes that all CAS servers MUST implement. Implementations MAY include others. @@ -172,77 +172,77 @@ INVALID_SERVICE - the ticket provided was valid, but the service specified did n INTERNAL_ERROR - an internal error occurred during ticket validation For all error codes, it is RECOMMENDED that CAS provide a more detailed message as the body of the \ block of the XML response. - */ - @Operation(summary = "CAS 2.0 ticket验证接口", description = "通过ticket获取当前登录用户信息",method="POST") - @RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_SERVICE_VALIDATE,produces =MediaType.APPLICATION_XML_VALUE,method={RequestMethod.GET,RequestMethod.POST}) - public String serviceValidate( - HttpServletRequest request, - HttpServletResponse response, - @RequestParam(value = CasConstants.PARAMETER.TICKET) String ticket, - @RequestParam(value = CasConstants.PARAMETER.SERVICE) String service, - @RequestParam(value = CasConstants.PARAMETER.PROXY_CALLBACK_URL,required=false) String pgtUrl, - @RequestParam(value = CasConstants.PARAMETER.RENEW,required=false) String renew, - @RequestParam(value = CasConstants.PARAMETER.FORMAT,required=false,defaultValue=HttpResponseConstants.FORMAT_TYPE.XML) String format){ - _logger.debug("serviceValidate ticket {} , service {} , pgtUrl {} , renew {} , format {}" , ticket,service,pgtUrl,renew,format); - - Ticket storedTicket=null; - if(ticket.startsWith(CasConstants.PREFIX.SERVICE_TICKET_PREFIX)) { - try { - storedTicket = ticketServices.consumeTicket(ticket); - } catch (Exception e) { - e.printStackTrace(); - } - } - ServiceResponseBuilder serviceResponseBuilder=new ServiceResponseBuilder(format); - - if(storedTicket!=null){ - SignPrincipal authentication = ((SignPrincipal)storedTicket.getAuthentication().getPrincipal()); - if(StringUtils.isNotBlank(pgtUrl)) { - ProxyGrantingTicketIOUImpl proxyGrantingTicketIOUImpl =new ProxyGrantingTicketIOUImpl(); - String proxyGrantingTicketIOU=casProxyGrantingTicketServices.createTicket(proxyGrantingTicketIOUImpl); - - ProxyGrantingTicketImpl proxyGrantingTicketImpl=new ProxyGrantingTicketImpl(storedTicket.getAuthentication(),storedTicket.getCasDetails()); - String proxyGrantingTicket=casProxyGrantingTicketServices.createTicket(proxyGrantingTicketImpl); - - serviceResponseBuilder.success().setTicket(proxyGrantingTicketIOU); - serviceResponseBuilder.success().setProxy(pgtUrl); - - httpRequestAdapter.post(pgtUrl+"?pgtId="+proxyGrantingTicket+"&pgtIou="+proxyGrantingTicketIOU,null); - } - - if(ConstsBoolean.isTrue(storedTicket.getCasDetails().getIsAdapter())){ - - Object casAdapter = Instance.newInstance(storedTicket.getCasDetails().getAdapter()); - try { - BeanUtils.setProperty(casAdapter, "serviceResponseBuilder", serviceResponseBuilder); - } catch (IllegalAccessException | InvocationTargetException e) { - _logger.error("setProperty error . ", e); - } - - AbstractAuthorizeAdapter adapter =(AbstractAuthorizeAdapter)casAdapter; - adapter.setPrincipal(authentication); - adapter.setApp(storedTicket.getCasDetails()); - adapter.generateInfo(); - }else { - _logger.error("Cas Adapter is not Set . "); - } - }else{ - serviceResponseBuilder.failure() - .setCode(CasConstants.ERROR_CODE.INVALID_TICKET) - .setDescription("Ticket "+ticket+" not recognized"); - } - - return serviceResponseBuilder.serviceResponseBuilder(); - } - - /** - * @param request - * @param response - * @param ticket - * @param service - * @param pgtUrl - * @param renew - * @return + */ + @Operation(summary = "CAS 2.0 ticket验证接口", description = "通过ticket获取当前登录用户信息",method="POST") + @RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_SERVICE_VALIDATE,produces =MediaType.APPLICATION_XML_VALUE,method={RequestMethod.GET,RequestMethod.POST}) + public String serviceValidate( + HttpServletRequest request, + HttpServletResponse response, + @RequestParam(value = CasConstants.PARAMETER.TICKET) String ticket, + @RequestParam(value = CasConstants.PARAMETER.SERVICE) String service, + @RequestParam(value = CasConstants.PARAMETER.PROXY_CALLBACK_URL,required=false) String pgtUrl, + @RequestParam(value = CasConstants.PARAMETER.RENEW,required=false) String renew, + @RequestParam(value = CasConstants.PARAMETER.FORMAT,required=false,defaultValue=HttpResponseConstants.FORMAT_TYPE.XML) String format){ + _logger.debug("serviceValidate ticket {} , service {} , pgtUrl {} , renew {} , format {}" , ticket,service,pgtUrl,renew,format); + + Ticket storedTicket=null; + if(ticket.startsWith(CasConstants.PREFIX.SERVICE_TICKET_PREFIX)) { + try { + storedTicket = ticketServices.consumeTicket(ticket); + } catch (Exception e) { + e.printStackTrace(); + } + } + ServiceResponseBuilder serviceResponseBuilder=new ServiceResponseBuilder(format); + + if(storedTicket!=null){ + SignPrincipal authentication = ((SignPrincipal)storedTicket.getAuthentication().getPrincipal()); + if(StringUtils.isNotBlank(pgtUrl)) { + ProxyGrantingTicketIOUImpl proxyGrantingTicketIOUImpl =new ProxyGrantingTicketIOUImpl(); + String proxyGrantingTicketIOU=casProxyGrantingTicketServices.createTicket(proxyGrantingTicketIOUImpl); + + ProxyGrantingTicketImpl proxyGrantingTicketImpl=new ProxyGrantingTicketImpl(storedTicket.getAuthentication(),storedTicket.getCasDetails()); + String proxyGrantingTicket=casProxyGrantingTicketServices.createTicket(proxyGrantingTicketImpl); + + serviceResponseBuilder.success().setTicket(proxyGrantingTicketIOU); + serviceResponseBuilder.success().setProxy(pgtUrl); + + httpRequestAdapter.post(pgtUrl+"?pgtId="+proxyGrantingTicket+"&pgtIou="+proxyGrantingTicketIOU,null); + } + + if(ConstsBoolean.isTrue(storedTicket.getCasDetails().getIsAdapter())){ + + Object casAdapter = Instance.newInstance(storedTicket.getCasDetails().getAdapter()); + try { + BeanUtils.setProperty(casAdapter, "serviceResponseBuilder", serviceResponseBuilder); + } catch (IllegalAccessException | InvocationTargetException e) { + _logger.error("setProperty error . ", e); + } + + AbstractAuthorizeAdapter adapter =(AbstractAuthorizeAdapter)casAdapter; + adapter.setPrincipal(authentication); + adapter.setApp(storedTicket.getCasDetails()); + adapter.generateInfo(); + }else { + _logger.error("Cas Adapter is not Set . "); + } + }else{ + serviceResponseBuilder.failure() + .setCode(CasConstants.ERROR_CODE.INVALID_TICKET) + .setDescription("Ticket "+ticket+" not recognized"); + } + + return serviceResponseBuilder.serviceResponseBuilder(); + } + + /** + * @param request + * @param response + * @param ticket + * @param service + * @param pgtUrl + * @param renew + * @return 2.6. /proxyValidate [CAS 2.0] /proxyValidate MUST perform the same validation tasks as /serviceValidate and additionally validate proxy tickets. /proxyValidate MUST be capable of validating both service tickets and proxy tickets. See Section 2.5.4 for details. @@ -294,63 +294,63 @@ Response on ticket validation failure: } } } - */ - - @Operation(summary = "CAS 2.0 ticket代理验证接口", description = "通过ticket获取当前登录用户信息",method="POST") - @RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_PROXY_VALIDATE,produces =MediaType.APPLICATION_XML_VALUE,method={RequestMethod.GET,RequestMethod.POST}) - - public String proxy( - HttpServletRequest request, - HttpServletResponse response, - @RequestParam(value = CasConstants.PARAMETER.TICKET) String ticket, - @RequestParam(value = CasConstants.PARAMETER.SERVICE) String service, - @RequestParam(value = CasConstants.PARAMETER.PROXY_CALLBACK_URL,required=false) String pgtUrl, - @RequestParam(value = CasConstants.PARAMETER.RENEW,required=false) String renew, - @RequestParam(value = CasConstants.PARAMETER.FORMAT,required=false,defaultValue=HttpResponseConstants.FORMAT_TYPE.XML) String format){ - _logger.debug("proxyValidate ticket {} , service {} , pgtUrl {} , renew {} , format {}" ,ticket,service, pgtUrl,renew,format); - - Ticket storedTicket=null; - if(ticket.startsWith(CasConstants.PREFIX.PROXY_TICKET_PREFIX)) { - try { - storedTicket = ticketServices.consumeTicket(ticket); - } catch (Exception e) { - e.printStackTrace(); - } - } - ServiceResponseBuilder serviceResponseBuilder=new ServiceResponseBuilder(format); - - if(storedTicket!=null){ - SignPrincipal authentication = ((SignPrincipal)storedTicket.getAuthentication().getPrincipal()); - if(ConstsBoolean.isTrue(storedTicket.getCasDetails().getIsAdapter())){ - Object casAdapter = Instance.newInstance(storedTicket.getCasDetails().getAdapter()); - try { - BeanUtils.setProperty(casAdapter, "serviceResponseBuilder", serviceResponseBuilder); - } catch (IllegalAccessException | InvocationTargetException e) { - _logger.error("setProperty error . ", e); - } - - AbstractAuthorizeAdapter adapter =(AbstractAuthorizeAdapter)casAdapter; - adapter.setPrincipal(authentication); - adapter.setApp(storedTicket.getCasDetails()); - adapter.generateInfo(); - }else { - _logger.error("Cas Adapter is not Set . "); - } - }else{ - serviceResponseBuilder.failure() - .setCode(CasConstants.ERROR_CODE.INVALID_TICKET) - .setDescription("Ticket "+ticket+" not recognized"); - } - - return serviceResponseBuilder.serviceResponseBuilder(); - } - - /** - * @param request - * @param response - * @param pgt - * @param targetService - * @return + */ + + @Operation(summary = "CAS 2.0 ticket代理验证接口", description = "通过ticket获取当前登录用户信息",method="POST") + @RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_PROXY_VALIDATE,produces =MediaType.APPLICATION_XML_VALUE,method={RequestMethod.GET,RequestMethod.POST}) + + public String proxy( + HttpServletRequest request, + HttpServletResponse response, + @RequestParam(value = CasConstants.PARAMETER.TICKET) String ticket, + @RequestParam(value = CasConstants.PARAMETER.SERVICE) String service, + @RequestParam(value = CasConstants.PARAMETER.PROXY_CALLBACK_URL,required=false) String pgtUrl, + @RequestParam(value = CasConstants.PARAMETER.RENEW,required=false) String renew, + @RequestParam(value = CasConstants.PARAMETER.FORMAT,required=false,defaultValue=HttpResponseConstants.FORMAT_TYPE.XML) String format){ + _logger.debug("proxyValidate ticket {} , service {} , pgtUrl {} , renew {} , format {}" ,ticket,service, pgtUrl,renew,format); + + Ticket storedTicket=null; + if(ticket.startsWith(CasConstants.PREFIX.PROXY_TICKET_PREFIX)) { + try { + storedTicket = ticketServices.consumeTicket(ticket); + } catch (Exception e) { + e.printStackTrace(); + } + } + ServiceResponseBuilder serviceResponseBuilder=new ServiceResponseBuilder(format); + + if(storedTicket!=null){ + SignPrincipal authentication = ((SignPrincipal)storedTicket.getAuthentication().getPrincipal()); + if(ConstsBoolean.isTrue(storedTicket.getCasDetails().getIsAdapter())){ + Object casAdapter = Instance.newInstance(storedTicket.getCasDetails().getAdapter()); + try { + BeanUtils.setProperty(casAdapter, "serviceResponseBuilder", serviceResponseBuilder); + } catch (IllegalAccessException | InvocationTargetException e) { + _logger.error("setProperty error . ", e); + } + + AbstractAuthorizeAdapter adapter =(AbstractAuthorizeAdapter)casAdapter; + adapter.setPrincipal(authentication); + adapter.setApp(storedTicket.getCasDetails()); + adapter.generateInfo(); + }else { + _logger.error("Cas Adapter is not Set . "); + } + }else{ + serviceResponseBuilder.failure() + .setCode(CasConstants.ERROR_CODE.INVALID_TICKET) + .setDescription("Ticket "+ticket+" not recognized"); + } + + return serviceResponseBuilder.serviceResponseBuilder(); + } + + /** + * @param request + * @param response + * @param pgt + * @param targetService + * @return 2.7. /proxy [CAS 2.0] /proxy provides proxy tickets to services that have acquired proxy-granting tickets and will be proxying authentication to back-end services. @@ -397,26 +397,26 @@ UNAUTHORIZED_SERVICE - service is unauthorized to perform the proxy request INTERNAL_ERROR - an internal error occurred during ticket validation For all error codes, it is RECOMMENDED that CAS provide a more detailed message as the body of the block of the XML response. - */ - @RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_PROXY ,produces =MediaType.APPLICATION_XML_VALUE,method={RequestMethod.GET,RequestMethod.POST}) - - public String proxy( - HttpServletRequest request, - HttpServletResponse response, - @RequestParam(value = CasConstants.PARAMETER.PROXY_GRANTING_TICKET) String pgt, - @RequestParam(value = CasConstants.PARAMETER.TARGET_SERVICE) String targetService, - @RequestParam(value = CasConstants.PARAMETER.FORMAT,required=false,defaultValue=HttpResponseConstants.FORMAT_TYPE.XML) String format){ - _logger.debug("proxy pgt {} , targetService {} , format {}" ,pgt,targetService, format); - ProxyServiceResponseBuilder proxyServiceResponseBuilder=new ProxyServiceResponseBuilder(format); - - ProxyGrantingTicketImpl proxyGrantingTicketImpl = (ProxyGrantingTicketImpl)casProxyGrantingTicketServices.get(pgt); - if(proxyGrantingTicketImpl != null) { - ProxyTicketImpl proxyTicketImpl = new ProxyTicketImpl(proxyGrantingTicketImpl.getAuthentication(),proxyGrantingTicketImpl.getCasDetails()); - String proxyTicket =ticketServices.createTicket(proxyTicketImpl); - proxyServiceResponseBuilder.success().setTicket(proxyTicket).setFormat(format); - }else { - proxyServiceResponseBuilder.success().setTicket("").setFormat(format); - } - return proxyServiceResponseBuilder.serviceResponseBuilder(); - } + */ + @RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_PROXY ,produces =MediaType.APPLICATION_XML_VALUE,method={RequestMethod.GET,RequestMethod.POST}) + + public String proxy( + HttpServletRequest request, + HttpServletResponse response, + @RequestParam(value = CasConstants.PARAMETER.PROXY_GRANTING_TICKET) String pgt, + @RequestParam(value = CasConstants.PARAMETER.TARGET_SERVICE) String targetService, + @RequestParam(value = CasConstants.PARAMETER.FORMAT,required=false,defaultValue=HttpResponseConstants.FORMAT_TYPE.XML) String format){ + _logger.debug("proxy pgt {} , targetService {} , format {}" ,pgt,targetService, format); + ProxyServiceResponseBuilder proxyServiceResponseBuilder=new ProxyServiceResponseBuilder(format); + + ProxyGrantingTicketImpl proxyGrantingTicketImpl = (ProxyGrantingTicketImpl)casProxyGrantingTicketServices.get(pgt); + if(proxyGrantingTicketImpl != null) { + ProxyTicketImpl proxyTicketImpl = new ProxyTicketImpl(proxyGrantingTicketImpl.getAuthentication(),proxyGrantingTicketImpl.getCasDetails()); + String proxyTicket =ticketServices.createTicket(proxyTicketImpl); + proxyServiceResponseBuilder.success().setTicket(proxyTicket).setFormat(format); + }else { + proxyServiceResponseBuilder.success().setTicket("").setFormat(format); + } + return proxyServiceResponseBuilder.serviceResponseBuilder(); + } } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/Cas30AuthorizeEndpoint.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/Cas30AuthorizeEndpoint.java index 0f141655f..af1c85053 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/Cas30AuthorizeEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/Cas30AuthorizeEndpoint.java @@ -55,135 +55,135 @@ import jakarta.servlet.http.HttpServletResponse; @Controller public class Cas30AuthorizeEndpoint extends CasBaseAuthorizeEndpoint{ - static final Logger _logger = LoggerFactory.getLogger(Cas30AuthorizeEndpoint.class); + static final Logger _logger = LoggerFactory.getLogger(Cas30AuthorizeEndpoint.class); - @Operation(summary = "CAS 3.0 ticket验证接口", description = "通过ticket获取当前登录用户信息") - @RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_SERVICE_VALIDATE_V3,method={RequestMethod.GET,RequestMethod.POST}) - public void serviceValidate( - HttpServletRequest request, - HttpServletResponse response, - @RequestParam(value = CasConstants.PARAMETER.TICKET) String ticket, - @RequestParam(value = CasConstants.PARAMETER.SERVICE) String service, - @RequestParam(value = CasConstants.PARAMETER.PROXY_CALLBACK_URL,required=false) String pgtUrl, - @RequestParam(value = CasConstants.PARAMETER.RENEW,required=false) String renew, - @RequestParam(value = CasConstants.PARAMETER.FORMAT,required=false,defaultValue=HttpResponseConstants.FORMAT_TYPE.XML) String format){ - _logger.debug("serviceValidate ticket {} , service {} , pgtUrl {} , renew {} , format {}", ticket,service,pgtUrl,renew,format); - - Ticket storedTicket=null; - if(ticket.startsWith(CasConstants.PREFIX.SERVICE_TICKET_PREFIX)) { - try { - storedTicket = ticketServices.consumeTicket(ticket); - } catch (Exception e) { - e.printStackTrace(); - } - } - ServiceResponseBuilder serviceResponseBuilder=new ServiceResponseBuilder(format); - - if(storedTicket!=null){ - SignPrincipal authentication = ((SignPrincipal)storedTicket.getAuthentication().getPrincipal()); - if(StringUtils.isNotBlank(pgtUrl)) { - ProxyGrantingTicketIOUImpl proxyGrantingTicketIOUImpl =new ProxyGrantingTicketIOUImpl(); - String proxyGrantingTicketIOU=casProxyGrantingTicketServices.createTicket(proxyGrantingTicketIOUImpl); - - ProxyGrantingTicketImpl proxyGrantingTicketImpl=new ProxyGrantingTicketImpl(storedTicket.getAuthentication(),storedTicket.getCasDetails()); - String proxyGrantingTicket=casProxyGrantingTicketServices.createTicket(proxyGrantingTicketImpl); - - serviceResponseBuilder.success().setTicket(proxyGrantingTicketIOU); - serviceResponseBuilder.success().setProxy(pgtUrl); - - httpRequestAdapter.post(pgtUrl+"?pgtId="+proxyGrantingTicket+"&pgtIou="+proxyGrantingTicketIOU,null); - } - - if(ConstsBoolean.isTrue(storedTicket.getCasDetails().getIsAdapter())){ - Object casAdapter = Instance.newInstance(storedTicket.getCasDetails().getAdapter()); - try { - BeanUtils.setProperty(casAdapter, "serviceResponseBuilder", serviceResponseBuilder); - } catch (IllegalAccessException | InvocationTargetException e) { - _logger.error("setProperty error . ", e); - } - - AbstractAuthorizeAdapter adapter =(AbstractAuthorizeAdapter)casAdapter; - adapter.setPrincipal(authentication); - adapter.setApp(storedTicket.getCasDetails()); - adapter.generateInfo(); - }else { - _logger.error("Cas Adapter is not Set . "); - } - }else{ - serviceResponseBuilder.failure() - .setCode(CasConstants.ERROR_CODE.INVALID_TICKET) - .setDescription("Ticket "+ticket+" not recognized"); - } - - httpResponseAdapter.write(response,serviceResponseBuilder.serviceResponseBuilder(),format); - } - - @Operation(summary = "CAS 3.0 ProxyTicket代理验证接口", description = "通过ProxyGrantingTicket获取ProxyTicket",method="POST") - @RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_PROXY_V3,method={RequestMethod.GET,RequestMethod.POST}) - public void proxy( - HttpServletRequest request, - HttpServletResponse response, - @RequestParam(value = CasConstants.PARAMETER.PROXY_GRANTING_TICKET) String pgt, - @RequestParam(value = CasConstants.PARAMETER.TARGET_SERVICE) String targetService, - @RequestParam(value = CasConstants.PARAMETER.FORMAT,required=false,defaultValue=HttpResponseConstants.FORMAT_TYPE.XML) String format){ - _logger.debug("proxy pgt {} , targetService {} , format {}" , pgt,targetService,format); - ProxyServiceResponseBuilder proxyServiceResponseBuilder=new ProxyServiceResponseBuilder(format); - ProxyGrantingTicketImpl proxyGrantingTicketImpl = (ProxyGrantingTicketImpl)casProxyGrantingTicketServices.get(pgt); - if(proxyGrantingTicketImpl != null) { - ProxyTicketImpl proxyTicketImpl = new ProxyTicketImpl(proxyGrantingTicketImpl.getAuthentication(),proxyGrantingTicketImpl.getCasDetails()); - String proxyTicket =ticketServices.createTicket(proxyTicketImpl); - proxyServiceResponseBuilder.success().setTicket(proxyTicket).setFormat(format); - }else { - proxyServiceResponseBuilder.success().setTicket("").setFormat(format); - } - - httpResponseAdapter.write(response,proxyServiceResponseBuilder.serviceResponseBuilder(),format); - } - - @Operation(summary = "CAS 3.0 ticket代理验证接口", description = "通过ProxyTicket获取当前登录用户信息",method="POST") - @RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_PROXY_VALIDATE_V3,method={RequestMethod.GET,RequestMethod.POST}) - public void proxy( - HttpServletRequest request, - HttpServletResponse response, - @RequestParam(value = CasConstants.PARAMETER.TICKET) String ticket, - @RequestParam(value = CasConstants.PARAMETER.SERVICE) String service, - @RequestParam(value = CasConstants.PARAMETER.PROXY_CALLBACK_URL,required=false) String pgtUrl, - @RequestParam(value = CasConstants.PARAMETER.RENEW,required=false) String renew, - @RequestParam(value = CasConstants.PARAMETER.FORMAT,required=false,defaultValue=HttpResponseConstants.FORMAT_TYPE.XML) String format){ - _logger.debug("proxyValidate ticket {} , service {} , pgtUrl {} , renew {} , format {}" , ticket,service,pgtUrl,renew,format); - - Ticket storedTicket=null; - if(ticket.startsWith(CasConstants.PREFIX.PROXY_TICKET_PREFIX)) { - try { - storedTicket = ticketServices.consumeTicket(ticket); - } catch (Exception e) { - e.printStackTrace(); - } - } - ServiceResponseBuilder serviceResponseBuilder=new ServiceResponseBuilder(format); - - if(storedTicket!=null){ - SignPrincipal authentication = ((SignPrincipal)storedTicket.getAuthentication().getPrincipal()); - if(ConstsBoolean.isTrue(storedTicket.getCasDetails().getIsAdapter())){ - Object casAdapter = Instance.newInstance(storedTicket.getCasDetails().getAdapter()); - try { - BeanUtils.setProperty(casAdapter, "serviceResponseBuilder", serviceResponseBuilder); - } catch (IllegalAccessException | InvocationTargetException e) { - _logger.error("setProperty error . ", e); - } - - AbstractAuthorizeAdapter adapter =(AbstractAuthorizeAdapter)casAdapter; - adapter.setPrincipal(authentication); - adapter.setApp(storedTicket.getCasDetails()); - adapter.generateInfo(); - }else { - _logger.error("Cas Adapter is not Set . "); - } - }else{ - serviceResponseBuilder.failure() - .setCode(CasConstants.ERROR_CODE.INVALID_TICKET) - .setDescription("Ticket "+ticket+" not recognized"); - } - httpResponseAdapter.write(response,serviceResponseBuilder.serviceResponseBuilder(),format); - } + @Operation(summary = "CAS 3.0 ticket验证接口", description = "通过ticket获取当前登录用户信息") + @RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_SERVICE_VALIDATE_V3,method={RequestMethod.GET,RequestMethod.POST}) + public void serviceValidate( + HttpServletRequest request, + HttpServletResponse response, + @RequestParam(value = CasConstants.PARAMETER.TICKET) String ticket, + @RequestParam(value = CasConstants.PARAMETER.SERVICE) String service, + @RequestParam(value = CasConstants.PARAMETER.PROXY_CALLBACK_URL,required=false) String pgtUrl, + @RequestParam(value = CasConstants.PARAMETER.RENEW,required=false) String renew, + @RequestParam(value = CasConstants.PARAMETER.FORMAT,required=false,defaultValue=HttpResponseConstants.FORMAT_TYPE.XML) String format){ + _logger.debug("serviceValidate ticket {} , service {} , pgtUrl {} , renew {} , format {}", ticket,service,pgtUrl,renew,format); + + Ticket storedTicket=null; + if(ticket.startsWith(CasConstants.PREFIX.SERVICE_TICKET_PREFIX)) { + try { + storedTicket = ticketServices.consumeTicket(ticket); + } catch (Exception e) { + e.printStackTrace(); + } + } + ServiceResponseBuilder serviceResponseBuilder=new ServiceResponseBuilder(format); + + if(storedTicket!=null){ + SignPrincipal authentication = ((SignPrincipal)storedTicket.getAuthentication().getPrincipal()); + if(StringUtils.isNotBlank(pgtUrl)) { + ProxyGrantingTicketIOUImpl proxyGrantingTicketIOUImpl =new ProxyGrantingTicketIOUImpl(); + String proxyGrantingTicketIOU=casProxyGrantingTicketServices.createTicket(proxyGrantingTicketIOUImpl); + + ProxyGrantingTicketImpl proxyGrantingTicketImpl=new ProxyGrantingTicketImpl(storedTicket.getAuthentication(),storedTicket.getCasDetails()); + String proxyGrantingTicket=casProxyGrantingTicketServices.createTicket(proxyGrantingTicketImpl); + + serviceResponseBuilder.success().setTicket(proxyGrantingTicketIOU); + serviceResponseBuilder.success().setProxy(pgtUrl); + + httpRequestAdapter.post(pgtUrl+"?pgtId="+proxyGrantingTicket+"&pgtIou="+proxyGrantingTicketIOU,null); + } + + if(ConstsBoolean.isTrue(storedTicket.getCasDetails().getIsAdapter())){ + Object casAdapter = Instance.newInstance(storedTicket.getCasDetails().getAdapter()); + try { + BeanUtils.setProperty(casAdapter, "serviceResponseBuilder", serviceResponseBuilder); + } catch (IllegalAccessException | InvocationTargetException e) { + _logger.error("setProperty error . ", e); + } + + AbstractAuthorizeAdapter adapter =(AbstractAuthorizeAdapter)casAdapter; + adapter.setPrincipal(authentication); + adapter.setApp(storedTicket.getCasDetails()); + adapter.generateInfo(); + }else { + _logger.error("Cas Adapter is not Set . "); + } + }else{ + serviceResponseBuilder.failure() + .setCode(CasConstants.ERROR_CODE.INVALID_TICKET) + .setDescription("Ticket "+ticket+" not recognized"); + } + + httpResponseAdapter.write(response,serviceResponseBuilder.serviceResponseBuilder(),format); + } + + @Operation(summary = "CAS 3.0 ProxyTicket代理验证接口", description = "通过ProxyGrantingTicket获取ProxyTicket",method="POST") + @RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_PROXY_V3,method={RequestMethod.GET,RequestMethod.POST}) + public void proxy( + HttpServletRequest request, + HttpServletResponse response, + @RequestParam(value = CasConstants.PARAMETER.PROXY_GRANTING_TICKET) String pgt, + @RequestParam(value = CasConstants.PARAMETER.TARGET_SERVICE) String targetService, + @RequestParam(value = CasConstants.PARAMETER.FORMAT,required=false,defaultValue=HttpResponseConstants.FORMAT_TYPE.XML) String format){ + _logger.debug("proxy pgt {} , targetService {} , format {}" , pgt,targetService,format); + ProxyServiceResponseBuilder proxyServiceResponseBuilder=new ProxyServiceResponseBuilder(format); + ProxyGrantingTicketImpl proxyGrantingTicketImpl = (ProxyGrantingTicketImpl)casProxyGrantingTicketServices.get(pgt); + if(proxyGrantingTicketImpl != null) { + ProxyTicketImpl proxyTicketImpl = new ProxyTicketImpl(proxyGrantingTicketImpl.getAuthentication(),proxyGrantingTicketImpl.getCasDetails()); + String proxyTicket =ticketServices.createTicket(proxyTicketImpl); + proxyServiceResponseBuilder.success().setTicket(proxyTicket).setFormat(format); + }else { + proxyServiceResponseBuilder.success().setTicket("").setFormat(format); + } + + httpResponseAdapter.write(response,proxyServiceResponseBuilder.serviceResponseBuilder(),format); + } + + @Operation(summary = "CAS 3.0 ticket代理验证接口", description = "通过ProxyTicket获取当前登录用户信息",method="POST") + @RequestMapping(value=CasConstants.ENDPOINT.ENDPOINT_PROXY_VALIDATE_V3,method={RequestMethod.GET,RequestMethod.POST}) + public void proxy( + HttpServletRequest request, + HttpServletResponse response, + @RequestParam(value = CasConstants.PARAMETER.TICKET) String ticket, + @RequestParam(value = CasConstants.PARAMETER.SERVICE) String service, + @RequestParam(value = CasConstants.PARAMETER.PROXY_CALLBACK_URL,required=false) String pgtUrl, + @RequestParam(value = CasConstants.PARAMETER.RENEW,required=false) String renew, + @RequestParam(value = CasConstants.PARAMETER.FORMAT,required=false,defaultValue=HttpResponseConstants.FORMAT_TYPE.XML) String format){ + _logger.debug("proxyValidate ticket {} , service {} , pgtUrl {} , renew {} , format {}" , ticket,service,pgtUrl,renew,format); + + Ticket storedTicket=null; + if(ticket.startsWith(CasConstants.PREFIX.PROXY_TICKET_PREFIX)) { + try { + storedTicket = ticketServices.consumeTicket(ticket); + } catch (Exception e) { + e.printStackTrace(); + } + } + ServiceResponseBuilder serviceResponseBuilder=new ServiceResponseBuilder(format); + + if(storedTicket!=null){ + SignPrincipal authentication = ((SignPrincipal)storedTicket.getAuthentication().getPrincipal()); + if(ConstsBoolean.isTrue(storedTicket.getCasDetails().getIsAdapter())){ + Object casAdapter = Instance.newInstance(storedTicket.getCasDetails().getAdapter()); + try { + BeanUtils.setProperty(casAdapter, "serviceResponseBuilder", serviceResponseBuilder); + } catch (IllegalAccessException | InvocationTargetException e) { + _logger.error("setProperty error . ", e); + } + + AbstractAuthorizeAdapter adapter =(AbstractAuthorizeAdapter)casAdapter; + adapter.setPrincipal(authentication); + adapter.setApp(storedTicket.getCasDetails()); + adapter.generateInfo(); + }else { + _logger.error("Cas Adapter is not Set . "); + } + }else{ + serviceResponseBuilder.failure() + .setCode(CasConstants.ERROR_CODE.INVALID_TICKET) + .setDescription("Ticket "+ticket+" not recognized"); + } + httpResponseAdapter.write(response,serviceResponseBuilder.serviceResponseBuilder(),format); + } } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/CasAuthorizeEndpoint.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/CasAuthorizeEndpoint.java index eda1435e6..e43a151fd 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/CasAuthorizeEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/CasAuthorizeEndpoint.java @@ -53,116 +53,116 @@ import jakarta.servlet.http.HttpServletResponse; @Controller public class CasAuthorizeEndpoint extends CasBaseAuthorizeEndpoint{ - static final Logger _logger = LoggerFactory.getLogger(CasAuthorizeEndpoint.class); - - @Operation(summary = "CAS页面跳转service认证接口", description = "传递参数service",method="GET") - @GetMapping(CasConstants.ENDPOINT.ENDPOINT_LOGIN) - public ModelAndView casLogin(@RequestParam(value=CasConstants.PARAMETER.SERVICE,required=false) String casService, - HttpServletRequest request, - HttpServletResponse response - ){ - - AppsCasDetails casDetails = casDetailsService.getAppDetails(casService , true); - - return buildCasModelAndView(request,response,casDetails,casService); - } - - @Operation(summary = "CAS页面跳转应用ID认证接口", description = "传递参数应用ID",method="GET") - @GetMapping(CasConstants.ENDPOINT.ENDPOINT_BASE + "/{id}") - public ModelAndView authorize( @PathVariable("id") String id, - HttpServletRequest request, - HttpServletResponse response - ){ - - AppsCasDetails casDetails = casDetailsService.getAppDetails(id , true); - - return buildCasModelAndView(request,response,casDetails,casDetails == null ? id : casDetails.getCallbackUrl()); - } - - private ModelAndView buildCasModelAndView( HttpServletRequest request, - HttpServletResponse response, - AppsCasDetails casDetails, - String casService){ - if(casDetails == null) { - _logger.debug("service {} not registered " , casService); - ModelAndView modelAndView = new ModelAndView("authorize/cas_sso_submint"); - modelAndView.addObject("errorMessage", casService); - return modelAndView; - } - - _logger.debug("Detail {}" , casDetails); - Map parameterMap = WebContext.getRequestParameterMap(request); - String service = casService; - _logger.debug("CAS Parameter service = {}" , service); - if(casService.indexOf("?") >-1 ) { - service = casService.substring(casService.indexOf("?") + 1); - if(service.indexOf("=") > -1) { - String [] parameterValues = service.split("="); - if(parameterValues.length == 2) { - parameterMap.put(parameterValues[0], parameterValues[1]); - } - } - _logger.debug("CAS service with Parameter : {}" , parameterMap); - } - WebContext.setAttribute(CasConstants.PARAMETER.PARAMETER_MAP, parameterMap); - WebContext.setAttribute(CasConstants.PARAMETER.ENDPOINT_CAS_DETAILS, casDetails); - WebContext.setAttribute(WebConstants.SINGLE_SIGN_ON_APP_ID, casDetails.getId()); - WebContext.setAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP,casDetails); - return WebContext.redirect(CasConstants.ENDPOINT.ENDPOINT_SERVICE_TICKET_GRANTING); - - } - - @GetMapping(CasConstants.ENDPOINT.ENDPOINT_SERVICE_TICKET_GRANTING) - public ModelAndView grantingTicket( Principal principal, - HttpServletRequest request, - HttpServletResponse response){ - ModelAndView modelAndView = new ModelAndView("authorize/cas_sso_submint"); - AppsCasDetails casDetails = (AppsCasDetails)WebContext.getAttribute(CasConstants.PARAMETER.ENDPOINT_CAS_DETAILS); - - ServiceTicketImpl serviceTicket = new ServiceTicketImpl(AuthorizationUtils.getAuthentication(),casDetails); - - _logger.trace("CAS start create ticket ... "); - String ticket = ticketServices.createTicket(serviceTicket,casDetails.getExpires()); - _logger.trace("CAS ticket {} created . " , ticket); - - StringBuffer callbackUrl = new StringBuffer(casDetails.getCallbackUrl()); - if(casDetails.getCallbackUrl().indexOf("?")==-1) { - callbackUrl.append("?"); - } - - if(callbackUrl.indexOf("&") != -1 ||callbackUrl.indexOf("=") != -1) { - callbackUrl.append("&"); - } - - //append ticket - callbackUrl.append(CasConstants.PARAMETER.TICKET).append("=").append(ticket); - - callbackUrl.append("&"); - //append service - callbackUrl.append(CasConstants.PARAMETER.SERVICE).append("=").append(casDetails.getService()); - - //增加可自定义的参数 - if(WebContext.getAttribute(CasConstants.PARAMETER.PARAMETER_MAP)!=null) { - @SuppressWarnings("unchecked") + static final Logger _logger = LoggerFactory.getLogger(CasAuthorizeEndpoint.class); + + @Operation(summary = "CAS页面跳转service认证接口", description = "传递参数service",method="GET") + @GetMapping(CasConstants.ENDPOINT.ENDPOINT_LOGIN) + public ModelAndView casLogin(@RequestParam(value=CasConstants.PARAMETER.SERVICE,required=false) String casService, + HttpServletRequest request, + HttpServletResponse response + ){ + + AppsCasDetails casDetails = casDetailsService.getAppDetails(casService , true); + + return buildCasModelAndView(request,response,casDetails,casService); + } + + @Operation(summary = "CAS页面跳转应用ID认证接口", description = "传递参数应用ID",method="GET") + @GetMapping(CasConstants.ENDPOINT.ENDPOINT_BASE + "/{id}") + public ModelAndView authorize( @PathVariable("id") String id, + HttpServletRequest request, + HttpServletResponse response + ){ + + AppsCasDetails casDetails = casDetailsService.getAppDetails(id , true); + + return buildCasModelAndView(request,response,casDetails,casDetails == null ? id : casDetails.getCallbackUrl()); + } + + private ModelAndView buildCasModelAndView( HttpServletRequest request, + HttpServletResponse response, + AppsCasDetails casDetails, + String casService){ + if(casDetails == null) { + _logger.debug("service {} not registered " , casService); + ModelAndView modelAndView = new ModelAndView("authorize/cas_sso_submint"); + modelAndView.addObject("errorMessage", casService); + return modelAndView; + } + + _logger.debug("Detail {}" , casDetails); + Map parameterMap = WebContext.getRequestParameterMap(request); + String service = casService; + _logger.debug("CAS Parameter service = {}" , service); + if(casService.indexOf("?") >-1 ) { + service = casService.substring(casService.indexOf("?") + 1); + if(service.indexOf("=") > -1) { + String [] parameterValues = service.split("="); + if(parameterValues.length == 2) { + parameterMap.put(parameterValues[0], parameterValues[1]); + } + } + _logger.debug("CAS service with Parameter : {}" , parameterMap); + } + WebContext.setAttribute(CasConstants.PARAMETER.PARAMETER_MAP, parameterMap); + WebContext.setAttribute(CasConstants.PARAMETER.ENDPOINT_CAS_DETAILS, casDetails); + WebContext.setAttribute(WebConstants.SINGLE_SIGN_ON_APP_ID, casDetails.getId()); + WebContext.setAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP,casDetails); + return WebContext.redirect(CasConstants.ENDPOINT.ENDPOINT_SERVICE_TICKET_GRANTING); + + } + + @GetMapping(CasConstants.ENDPOINT.ENDPOINT_SERVICE_TICKET_GRANTING) + public ModelAndView grantingTicket( Principal principal, + HttpServletRequest request, + HttpServletResponse response){ + ModelAndView modelAndView = new ModelAndView("authorize/cas_sso_submint"); + AppsCasDetails casDetails = (AppsCasDetails)WebContext.getAttribute(CasConstants.PARAMETER.ENDPOINT_CAS_DETAILS); + + ServiceTicketImpl serviceTicket = new ServiceTicketImpl(AuthorizationUtils.getAuthentication(),casDetails); + + _logger.trace("CAS start create ticket ... "); + String ticket = ticketServices.createTicket(serviceTicket,casDetails.getExpires()); + _logger.trace("CAS ticket {} created . " , ticket); + + StringBuffer callbackUrl = new StringBuffer(casDetails.getCallbackUrl()); + if(casDetails.getCallbackUrl().indexOf("?")==-1) { + callbackUrl.append("?"); + } + + if(callbackUrl.indexOf("&") != -1 ||callbackUrl.indexOf("=") != -1) { + callbackUrl.append("&"); + } + + //append ticket + callbackUrl.append(CasConstants.PARAMETER.TICKET).append("=").append(ticket); + + callbackUrl.append("&"); + //append service + callbackUrl.append(CasConstants.PARAMETER.SERVICE).append("=").append(casDetails.getService()); + + //增加可自定义的参数 + if(WebContext.getAttribute(CasConstants.PARAMETER.PARAMETER_MAP)!=null) { + @SuppressWarnings("unchecked") Map parameterMap = (Map )WebContext.getAttribute(CasConstants.PARAMETER.PARAMETER_MAP); - parameterMap.remove(CasConstants.PARAMETER.TICKET); - parameterMap.remove(CasConstants.PARAMETER.SERVICE); - for (Entry entry : parameterMap.entrySet()) { - callbackUrl.append("&").append(entry.getKey()).append("=").append(entry.getValue()); - } - } - - if(casDetails.getLogoutType()==LogoutType.BACK_CHANNEL) { - _logger.debug("CAS LogoutType BACK_CHANNEL ... "); - String sessionId = AuthorizationUtils.getPrincipal().getSessionId(); - VisitedDto visited = new VisitedDto(casDetails,ticket); - sessionManager.visited(sessionId, visited); - _logger.debug("App id {} , name {} , CAS LogoutType BACK_CHANNEL ... " , casDetails.getId(),casDetails.getAppName()); - } - - _logger.debug("redirect to CAS Client URL {}" , callbackUrl); - modelAndView.addObject("callbackUrl", callbackUrl.toString()); - return modelAndView; - } - + parameterMap.remove(CasConstants.PARAMETER.TICKET); + parameterMap.remove(CasConstants.PARAMETER.SERVICE); + for (Entry entry : parameterMap.entrySet()) { + callbackUrl.append("&").append(entry.getKey()).append("=").append(entry.getValue()); + } + } + + if(casDetails.getLogoutType()==LogoutType.BACK_CHANNEL) { + _logger.debug("CAS LogoutType BACK_CHANNEL ... "); + String sessionId = AuthorizationUtils.getPrincipal().getSessionId(); + VisitedDto visited = new VisitedDto(casDetails,ticket); + sessionManager.visited(sessionId, visited); + _logger.debug("App id {} , name {} , CAS LogoutType BACK_CHANNEL ... " , casDetails.getId(),casDetails.getAppName()); + } + + _logger.debug("redirect to CAS Client URL {}" , callbackUrl); + modelAndView.addObject("callbackUrl", callbackUrl.toString()); + return modelAndView; + } + } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/CasLogoutEndpoint.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/CasLogoutEndpoint.java index 073017b00..36fb43ac0 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/CasLogoutEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/CasLogoutEndpoint.java @@ -44,23 +44,23 @@ import jakarta.servlet.http.HttpServletResponse; @Controller public class CasLogoutEndpoint extends CasBaseAuthorizeEndpoint{ - static final Logger _logger = LoggerFactory.getLogger(CasLogoutEndpoint.class); + static final Logger _logger = LoggerFactory.getLogger(CasLogoutEndpoint.class); - /** - * for cas logout then redirect to logout - * @param request - * @param response - * @param casService - * @return - */ - @Operation(summary = "CAS注销接口", description = "CAS注销接口",method="GET") - @GetMapping(CasConstants.ENDPOINT.ENDPOINT_LOGOUT) - public ModelAndView logout(HttpServletRequest request , HttpServletResponse response, - @RequestParam(value = CasConstants.PARAMETER.SERVICE , required = false) String casService){ - StringBuffer logoutUrl = new StringBuffer("/force/logout"); - if(StringUtils.isNotBlank(casService)){ - logoutUrl.append("?").append("redirect_uri=").append(casService); - } - return WebContext.forward(logoutUrl.toString()); - } + /** + * for cas logout then redirect to logout + * @param request + * @param response + * @param casService + * @return + */ + @Operation(summary = "CAS注销接口", description = "CAS注销接口",method="GET") + @GetMapping(CasConstants.ENDPOINT.ENDPOINT_LOGOUT) + public ModelAndView logout(HttpServletRequest request , HttpServletResponse response, + @RequestParam(value = CasConstants.PARAMETER.SERVICE , required = false) String casService){ + StringBuffer logoutUrl = new StringBuffer("/force/logout"); + if(StringUtils.isNotBlank(casService)){ + logoutUrl.append("?").append("redirect_uri=").append(casService); + } + return WebContext.forward(logoutUrl.toString()); + } } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/CasRestV1Endpoint.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/CasRestV1Endpoint.java index 9166b2e03..aad70a1c9 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/CasRestV1Endpoint.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/CasRestV1Endpoint.java @@ -59,34 +59,34 @@ import jakarta.servlet.http.HttpServletResponse; @Tag(name = "2-4-CAS REST API文档模块") @Controller public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{ - static final Logger _logger = LoggerFactory.getLogger(CasRestV1Endpoint.class); - + static final Logger _logger = LoggerFactory.getLogger(CasRestV1Endpoint.class); + @Autowired @Qualifier("authenticationProvider") AbstractAuthenticationProvider authenticationProvider ; @Operation(summary = "CAS REST认证接口", description = "通过用户名密码获取TGT",method="POST") @PostMapping(value=CasConstants.ENDPOINT.ENDPOINT_REST_TICKET_V1, - consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) + consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) public ResponseEntity casLoginRestTickets( HttpServletRequest request, HttpServletResponse response, @RequestParam(value=CasConstants.PARAMETER.SERVICE,required=false) String casService, @RequestParam(value=CasConstants.PARAMETER.REST_USERNAME,required=true) String username, @RequestParam(value=CasConstants.PARAMETER.REST_PASSWORD,required=true) String password){ - try { - if (StringUtils.isBlank(password)) { + try { + if (StringUtils.isBlank(password)) { throw new BadCredentialsException("No credentials are provided or extracted to authenticate the REST request"); } - - LoginCredential loginCredential =new LoginCredential(username,password,"normal"); - - Authentication authentication = authenticationProvider.authenticate(loginCredential); - if(authentication == null) { - _logger.debug("Bad Credentials Exception"); - return new ResponseEntity<>("Bad Credentials", HttpStatus.BAD_REQUEST); - } - + + LoginCredential loginCredential =new LoginCredential(username,password,"normal"); + + Authentication authentication = authenticationProvider.authenticate(loginCredential); + if(authentication == null) { + _logger.debug("Bad Credentials Exception"); + return new ResponseEntity<>("Bad Credentials", HttpStatus.BAD_REQUEST); + } + TicketGrantingTicketImpl ticketGrantingTicket=new TicketGrantingTicketImpl("Random",AuthorizationUtils.getAuthentication(),null); String ticket=casTicketGrantingTicketServices.createTicket(ticketGrantingTicket); @@ -97,27 +97,27 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{ _logger.trace("location {}" , location); return new ResponseEntity<>("Location: " + location, headers ,HttpStatus.CREATED); - } catch (final AuthenticationException e) { - _logger.error("BadCredentialsException ", e); + } catch (final AuthenticationException e) { + _logger.error("BadCredentialsException ", e); return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); } catch (final Exception e) { _logger.error("Exception ", e); return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } - } - + } + @Operation(summary = "CAS REST认证接口", description = "通过TGT获取ST",method="POST") @PostMapping(value=CasConstants.ENDPOINT.ENDPOINT_REST_TICKET_V1+"/{ticketGrantingTicket}", - consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) + consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) public ResponseEntity requestServiceTicket( - HttpServletRequest request, - HttpServletResponse response, - @PathVariable("ticketGrantingTicket") String ticketGrantingTicket, - @RequestParam(value=CasConstants.PARAMETER.SERVICE) String casService, - @RequestParam(value=CasConstants.PARAMETER.RENEW,required=false) String renew, - @RequestParam(value=CasConstants.PARAMETER.REST_USERNAME,required=false) String username, - @RequestParam(value=CasConstants.PARAMETER.REST_PASSWORD,required=false) String password){ - try { + HttpServletRequest request, + HttpServletResponse response, + @PathVariable("ticketGrantingTicket") String ticketGrantingTicket, + @RequestParam(value=CasConstants.PARAMETER.SERVICE) String casService, + @RequestParam(value=CasConstants.PARAMETER.RENEW,required=false) String renew, + @RequestParam(value=CasConstants.PARAMETER.REST_USERNAME,required=false) String username, + @RequestParam(value=CasConstants.PARAMETER.REST_PASSWORD,required=false) String password){ + try { TicketGrantingTicketImpl ticketGrantingTicketImpl = (TicketGrantingTicketImpl) casTicketGrantingTicketServices.get(ticketGrantingTicket); @@ -130,15 +130,15 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{ } catch (Exception e) { e.printStackTrace(); } - return new ResponseEntity<>("", HttpStatus.BAD_REQUEST); - } + return new ResponseEntity<>("", HttpStatus.BAD_REQUEST); + } @Operation(summary = "CAS REST认证接口", description = "检查TGT状态",method="GET") @GetMapping(value=CasConstants.ENDPOINT.ENDPOINT_REST_TICKET_V1 + "/{ticketGrantingTicket}") public ResponseEntity verifyTicketGrantingTicketStatus( - @PathVariable("ticketGrantingTicket") String ticketGrantingTicket, - HttpServletRequest request, - HttpServletResponse response){ - try { + @PathVariable("ticketGrantingTicket") String ticketGrantingTicket, + HttpServletRequest request, + HttpServletResponse response){ + try { TicketGrantingTicketImpl ticketGrantingTicketImpl = (TicketGrantingTicketImpl) casTicketGrantingTicketServices.get(ticketGrantingTicket); if(ticketGrantingTicketImpl != null) { @@ -147,8 +147,8 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{ } catch (Exception e) { e.printStackTrace(); } - return new ResponseEntity<>("", HttpStatus.NOT_FOUND); - } + return new ResponseEntity<>("", HttpStatus.NOT_FOUND); + } @Operation(summary = "CAS REST认证接口", description = "注销TGT状态",method="DELETE") @DeleteMapping(value=CasConstants.ENDPOINT.ENDPOINT_REST_TICKET_V1+"/{ticketGrantingTicket}") @@ -167,5 +167,5 @@ public class CasRestV1Endpoint extends CasBaseAuthorizeEndpoint{ } return new ResponseEntity<>("", HttpStatus.NOT_FOUND); } - + } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/CasRestV1UsersEndpoint.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/CasRestV1UsersEndpoint.java index 91cbd7520..52c29d243 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/CasRestV1UsersEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/CasRestV1UsersEndpoint.java @@ -55,14 +55,14 @@ import jakarta.servlet.http.HttpServletResponse; @Tag(name = "2-4-CAS REST API文档模块") @Controller public class CasRestV1UsersEndpoint extends CasBaseAuthorizeEndpoint{ - static final Logger _logger = LoggerFactory.getLogger(CasRestV1UsersEndpoint.class); - + static final Logger _logger = LoggerFactory.getLogger(CasRestV1UsersEndpoint.class); + @Autowired @Qualifier("authenticationProvider") AbstractAuthenticationProvider authenticationProvider ; - + @Operation(summary = "CAS REST认证接口", description = "用户名密码登录接口",method="POST") - @PostMapping(value=CasConstants.ENDPOINT.ENDPOINT_REST_USERS_V1, + @PostMapping(value=CasConstants.ENDPOINT.ENDPOINT_REST_USERS_V1, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) public ResponseEntity casLoginRestUsers( HttpServletRequest request, @@ -70,7 +70,7 @@ public class CasRestV1UsersEndpoint extends CasBaseAuthorizeEndpoint{ @RequestParam(value=CasConstants.PARAMETER.SERVICE,required=false) String casService, @RequestParam(value=CasConstants.PARAMETER.REST_USERNAME,required=true) String username, @RequestParam(value=CasConstants.PARAMETER.REST_PASSWORD,required=true) String password){ - try { + try { if (password == null || password.isEmpty()) { throw new BadCredentialsException("No credentials are provided or extracted to authenticate the REST request"); } @@ -116,5 +116,5 @@ public class CasRestV1UsersEndpoint extends CasBaseAuthorizeEndpoint{ return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } - + } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/adapter/CasDefaultAdapter.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/adapter/CasDefaultAdapter.java index 941b4c5bb..e8a2f21f3 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/adapter/CasDefaultAdapter.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/adapter/CasDefaultAdapter.java @@ -29,60 +29,60 @@ import org.slf4j.LoggerFactory; import org.springframework.web.servlet.ModelAndView; public class CasDefaultAdapter extends AbstractAuthorizeAdapter { - static final Logger _logger = LoggerFactory.getLogger(CasDefaultAdapter.class); - - static String Charset_UTF8="UTF-8"; - - ServiceResponseBuilder serviceResponseBuilder; - - @Override - public ModelAndView authorize(ModelAndView modelAndView) { + static final Logger _logger = LoggerFactory.getLogger(CasDefaultAdapter.class); + + static String Charset_UTF8="UTF-8"; + + ServiceResponseBuilder serviceResponseBuilder; + + @Override + public ModelAndView authorize(ModelAndView modelAndView) { - return modelAndView; - } + return modelAndView; + } - public String base64Attr(String attrValue){ - String b64=""; - try { - b64=(attrValue == null? "":"base64:"+Base64.encodeBase64String(attrValue.getBytes(Charset_UTF8))); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - return b64; - } - - @Override - public Object generateInfo() { - //user for return - String user = getValueByUserAttr(userInfo,((AppsCasDetails)this.app).getCasUser()); - _logger.debug("cas user {}",user); - serviceResponseBuilder.success().setUser(user); - - //for user - serviceResponseBuilder.setAttribute("uid", userInfo.getId()); - serviceResponseBuilder.setAttribute("username", userInfo.getUsername()); - serviceResponseBuilder.setAttribute("displayName", base64Attr(userInfo.getDisplayName())); - serviceResponseBuilder.setAttribute("firstName", base64Attr(userInfo.getGivenName())); - serviceResponseBuilder.setAttribute("lastname", base64Attr(userInfo.getFamilyName())); - serviceResponseBuilder.setAttribute("mobile", userInfo.getMobile()); - serviceResponseBuilder.setAttribute("birthday", userInfo.getBirthDate()); - serviceResponseBuilder.setAttribute("gender", userInfo.getGender()+""); - - //for work - serviceResponseBuilder.setAttribute("employeeNumber", userInfo.getEmployeeNumber()); - serviceResponseBuilder.setAttribute("title", base64Attr(userInfo.getJobTitle())); - serviceResponseBuilder.setAttribute("email", userInfo.getWorkEmail()); - serviceResponseBuilder.setAttribute("department", base64Attr(userInfo.getDepartment())); - serviceResponseBuilder.setAttribute("departmentId", userInfo.getDepartmentId()); - serviceResponseBuilder.setAttribute("workRegion",base64Attr(userInfo.getWorkRegion())); - serviceResponseBuilder.setAttribute("institution", userInfo.getInstId()); - serviceResponseBuilder.setAttribute(WebConstants.ONLINE_TICKET_NAME,principal.getSessionId()); - - return serviceResponseBuilder; - } + public String base64Attr(String attrValue){ + String b64=""; + try { + b64=(attrValue == null? "":"base64:"+Base64.encodeBase64String(attrValue.getBytes(Charset_UTF8))); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return b64; + } + + @Override + public Object generateInfo() { + //user for return + String user = getValueByUserAttr(userInfo,((AppsCasDetails)this.app).getCasUser()); + _logger.debug("cas user {}",user); + serviceResponseBuilder.success().setUser(user); + + //for user + serviceResponseBuilder.setAttribute("uid", userInfo.getId()); + serviceResponseBuilder.setAttribute("username", userInfo.getUsername()); + serviceResponseBuilder.setAttribute("displayName", base64Attr(userInfo.getDisplayName())); + serviceResponseBuilder.setAttribute("firstName", base64Attr(userInfo.getGivenName())); + serviceResponseBuilder.setAttribute("lastname", base64Attr(userInfo.getFamilyName())); + serviceResponseBuilder.setAttribute("mobile", userInfo.getMobile()); + serviceResponseBuilder.setAttribute("birthday", userInfo.getBirthDate()); + serviceResponseBuilder.setAttribute("gender", userInfo.getGender()+""); + + //for work + serviceResponseBuilder.setAttribute("employeeNumber", userInfo.getEmployeeNumber()); + serviceResponseBuilder.setAttribute("title", base64Attr(userInfo.getJobTitle())); + serviceResponseBuilder.setAttribute("email", userInfo.getWorkEmail()); + serviceResponseBuilder.setAttribute("department", base64Attr(userInfo.getDepartment())); + serviceResponseBuilder.setAttribute("departmentId", userInfo.getDepartmentId()); + serviceResponseBuilder.setAttribute("workRegion",base64Attr(userInfo.getWorkRegion())); + serviceResponseBuilder.setAttribute("institution", userInfo.getInstId()); + serviceResponseBuilder.setAttribute(WebConstants.ONLINE_TICKET_NAME,principal.getSessionId()); + + return serviceResponseBuilder; + } - public void setServiceResponseBuilder(ServiceResponseBuilder serviceResponseBuilder) { - this.serviceResponseBuilder = serviceResponseBuilder; - } + public void setServiceResponseBuilder(ServiceResponseBuilder serviceResponseBuilder) { + this.serviceResponseBuilder = serviceResponseBuilder; + } } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/adapter/CasPlainAdapter.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/adapter/CasPlainAdapter.java index ebd453d34..382a31679 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/adapter/CasPlainAdapter.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/adapter/CasPlainAdapter.java @@ -26,48 +26,48 @@ import org.slf4j.LoggerFactory; import org.springframework.web.servlet.ModelAndView; public class CasPlainAdapter extends AbstractAuthorizeAdapter { - static final Logger _logger = LoggerFactory.getLogger(CasPlainAdapter.class); + static final Logger _logger = LoggerFactory.getLogger(CasPlainAdapter.class); - ServiceResponseBuilder serviceResponseBuilder; - - @Override - public ModelAndView authorize(ModelAndView modelAndView) { + ServiceResponseBuilder serviceResponseBuilder; + + @Override + public ModelAndView authorize(ModelAndView modelAndView) { - return modelAndView; - } + return modelAndView; + } - @Override - public Object generateInfo() { - //user for return - String user = getValueByUserAttr(userInfo,((AppsCasDetails)this.app).getCasUser()); - _logger.debug("cas user {}",user); - serviceResponseBuilder.success().setUser(user); - - //for user - serviceResponseBuilder.setAttribute("uid", userInfo.getId()); - serviceResponseBuilder.setAttribute("username", userInfo.getUsername()); - serviceResponseBuilder.setAttribute("displayName", userInfo.getDisplayName()); - serviceResponseBuilder.setAttribute("firstName", userInfo.getGivenName()); - serviceResponseBuilder.setAttribute("lastname", userInfo.getFamilyName()); - serviceResponseBuilder.setAttribute("mobile", userInfo.getMobile()); - serviceResponseBuilder.setAttribute("birthday", userInfo.getBirthDate()); - serviceResponseBuilder.setAttribute("gender", userInfo.getGender()+""); - - //for work - serviceResponseBuilder.setAttribute("employeeNumber", userInfo.getEmployeeNumber()); - serviceResponseBuilder.setAttribute("title", userInfo.getJobTitle()); - serviceResponseBuilder.setAttribute("email", userInfo.getWorkEmail()); - serviceResponseBuilder.setAttribute("department", userInfo.getDepartment()); - serviceResponseBuilder.setAttribute("departmentId", userInfo.getDepartmentId()); - serviceResponseBuilder.setAttribute("workRegion",userInfo.getWorkRegion()); - serviceResponseBuilder.setAttribute("institution", userInfo.getInstId()); - serviceResponseBuilder.setAttribute(WebConstants.ONLINE_TICKET_NAME,principal.getSessionId()); - - return serviceResponseBuilder; - } + @Override + public Object generateInfo() { + //user for return + String user = getValueByUserAttr(userInfo,((AppsCasDetails)this.app).getCasUser()); + _logger.debug("cas user {}",user); + serviceResponseBuilder.success().setUser(user); + + //for user + serviceResponseBuilder.setAttribute("uid", userInfo.getId()); + serviceResponseBuilder.setAttribute("username", userInfo.getUsername()); + serviceResponseBuilder.setAttribute("displayName", userInfo.getDisplayName()); + serviceResponseBuilder.setAttribute("firstName", userInfo.getGivenName()); + serviceResponseBuilder.setAttribute("lastname", userInfo.getFamilyName()); + serviceResponseBuilder.setAttribute("mobile", userInfo.getMobile()); + serviceResponseBuilder.setAttribute("birthday", userInfo.getBirthDate()); + serviceResponseBuilder.setAttribute("gender", userInfo.getGender()+""); + + //for work + serviceResponseBuilder.setAttribute("employeeNumber", userInfo.getEmployeeNumber()); + serviceResponseBuilder.setAttribute("title", userInfo.getJobTitle()); + serviceResponseBuilder.setAttribute("email", userInfo.getWorkEmail()); + serviceResponseBuilder.setAttribute("department", userInfo.getDepartment()); + serviceResponseBuilder.setAttribute("departmentId", userInfo.getDepartmentId()); + serviceResponseBuilder.setAttribute("workRegion",userInfo.getWorkRegion()); + serviceResponseBuilder.setAttribute("institution", userInfo.getInstId()); + serviceResponseBuilder.setAttribute(WebConstants.ONLINE_TICKET_NAME,principal.getSessionId()); + + return serviceResponseBuilder; + } - public void setServiceResponseBuilder(ServiceResponseBuilder serviceResponseBuilder) { - this.serviceResponseBuilder = serviceResponseBuilder; - } + public void setServiceResponseBuilder(ServiceResponseBuilder serviceResponseBuilder) { + this.serviceResponseBuilder = serviceResponseBuilder; + } } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/response/CasServiceResponse.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/response/CasServiceResponse.java index af9c6a9af..f59650c6b 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/response/CasServiceResponse.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/response/CasServiceResponse.java @@ -25,94 +25,94 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CasServiceResponse { - static final Logger _logger = LoggerFactory.getLogger(CasServiceResponse.class); + static final Logger _logger = LoggerFactory.getLogger(CasServiceResponse.class); - protected String code; - protected String description; - protected boolean result=false; - protected String user; - protected String ticket; - protected String format=HttpResponseConstants.FORMAT_TYPE.XML; - protected ArrayListproxies=new ArrayList(); - - protected HashMap>casAttributes=new HashMap>(); - - public CasServiceResponse() { - - } + protected String code; + protected String description; + protected boolean result=false; + protected String user; + protected String ticket; + protected String format=HttpResponseConstants.FORMAT_TYPE.XML; + protected ArrayListproxies=new ArrayList(); + + protected HashMap>casAttributes=new HashMap>(); + + public CasServiceResponse() { + + } - public String getCode() { - return code; - } + public String getCode() { + return code; + } - public CasServiceResponse setAttribute(String attr,String value){ - if(casAttributes.containsKey(attr)){ - casAttributes.get(attr).add(value); - }else{ - ArrayList newList=new ArrayList(); - newList.add(value); - casAttributes.put(attr, newList); - } - return this; - } - public CasServiceResponse setProxy(String proxy){ - proxies.add(proxy); - return this; - } - public CasServiceResponse setCode(String code) { - this.code = code; - return this; - } + public CasServiceResponse setAttribute(String attr,String value){ + if(casAttributes.containsKey(attr)){ + casAttributes.get(attr).add(value); + }else{ + ArrayList newList=new ArrayList(); + newList.add(value); + casAttributes.put(attr, newList); + } + return this; + } + public CasServiceResponse setProxy(String proxy){ + proxies.add(proxy); + return this; + } + public CasServiceResponse setCode(String code) { + this.code = code; + return this; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public CasServiceResponse setDescription(String description) { - this.description = description; - return this; - } - - public CasServiceResponse success(){ - result=true; - return this; - } - - public CasServiceResponse failure(){ - result=false; - return this; - } - - public String getUser() { - return user; - } + public CasServiceResponse setDescription(String description) { + this.description = description; + return this; + } + + public CasServiceResponse success(){ + result=true; + return this; + } + + public CasServiceResponse failure(){ + result=false; + return this; + } + + public String getUser() { + return user; + } - public CasServiceResponse setUser(String user) { - this.user = user; - return this; - } + public CasServiceResponse setUser(String user) { + this.user = user; + return this; + } - public String getTicket() { - return ticket; - } + public String getTicket() { + return ticket; + } - public CasServiceResponse setTicket(String ticket) { - this.ticket = ticket; - return this; - } + public CasServiceResponse setTicket(String ticket) { + this.ticket = ticket; + return this; + } - public String getFormat() { - return format; - } + public String getFormat() { + return format; + } - public CasServiceResponse setFormat(String format) { - this.format = format; - return this; - } + public CasServiceResponse setFormat(String format) { + this.format = format; + return this; + } - public String serviceResponseBuilder(){ - return null; - } + public String serviceResponseBuilder(){ + return null; + } } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/response/ProxyServiceResponseBuilder.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/response/ProxyServiceResponseBuilder.java index 1679b7454..1250e855e 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/response/ProxyServiceResponseBuilder.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/response/ProxyServiceResponseBuilder.java @@ -21,61 +21,61 @@ import org.dromara.maxkey.web.HttpResponseConstants; public class ProxyServiceResponseBuilder extends ServiceResponseBuilder{ - public ProxyServiceResponseBuilder() { - - } - - public ProxyServiceResponseBuilder(String format) { - this.format = format; - } + public ProxyServiceResponseBuilder() { + + } + + public ProxyServiceResponseBuilder(String format) { + this.format = format; + } - @Override - public String serviceResponseBuilder() { - String responseString = ""; - if(format.equalsIgnoreCase(HttpResponseConstants.FORMAT_TYPE.XML)){ - responseString = serviceResponseXmlBuilder(); - }else{ - responseString =serviceResponseJsonBuilder(); - } - _logger.trace("Response String : "+responseString); - return responseString; - } - - @Override - public String serviceResponseXmlBuilder() { - StringBuffer responseResult=new StringBuffer(""); - responseResult.append(""); - if(result){ - responseResult.append(""); - responseResult.append("").append(ticket).append(""); - responseResult.append(""); - }else{ - responseResult.append(""); - responseResult.append(this.description); - responseResult.append(""); - } - responseResult.append(""); - return responseResult.toString(); - } - - @Override - public String serviceResponseJsonBuilder() { - StringBuffer responseResult=new StringBuffer(""); - responseResult.append("{\"serviceResponse\" :{"); - if(result){ - responseResult.append("\"proxySuccess\" : {"); - responseResult.append("\"proxyTicket\" : \"").append(ticket).append("\""); - responseResult.append("}"); - }else{ - responseResult.append("\"authenticationFailure\" : {"); - responseResult.append("\"code\" : \"").append(this.code).append("\""); - responseResult.append(",\"description\" : \"").append(this.description).append("\""); - responseResult.append("}"); - } - responseResult.append("}"); - responseResult.append("}"); - return responseResult.toString(); - } - + @Override + public String serviceResponseBuilder() { + String responseString = ""; + if(format.equalsIgnoreCase(HttpResponseConstants.FORMAT_TYPE.XML)){ + responseString = serviceResponseXmlBuilder(); + }else{ + responseString =serviceResponseJsonBuilder(); + } + _logger.trace("Response String : "+responseString); + return responseString; + } + + @Override + public String serviceResponseXmlBuilder() { + StringBuffer responseResult=new StringBuffer(""); + responseResult.append(""); + if(result){ + responseResult.append(""); + responseResult.append("").append(ticket).append(""); + responseResult.append(""); + }else{ + responseResult.append(""); + responseResult.append(this.description); + responseResult.append(""); + } + responseResult.append(""); + return responseResult.toString(); + } + + @Override + public String serviceResponseJsonBuilder() { + StringBuffer responseResult=new StringBuffer(""); + responseResult.append("{\"serviceResponse\" :{"); + if(result){ + responseResult.append("\"proxySuccess\" : {"); + responseResult.append("\"proxyTicket\" : \"").append(ticket).append("\""); + responseResult.append("}"); + }else{ + responseResult.append("\"authenticationFailure\" : {"); + responseResult.append("\"code\" : \"").append(this.code).append("\""); + responseResult.append(",\"description\" : \"").append(this.description).append("\""); + responseResult.append("}"); + } + responseResult.append("}"); + responseResult.append("}"); + return responseResult.toString(); + } + } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/response/Service10ResponseBuilder.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/response/Service10ResponseBuilder.java index a816aae8c..5138520d8 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/response/Service10ResponseBuilder.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/response/Service10ResponseBuilder.java @@ -18,16 +18,16 @@ package org.dromara.maxkey.authz.cas.endpoint.response; public class Service10ResponseBuilder extends CasServiceResponse { - - @Override - public String serviceResponseBuilder() { - StringBuffer responseResult=new StringBuffer(""); - if(result){ - responseResult.append("yes").append("\n").append(user); - }else{ - responseResult.append("no").append("\n").append("\n"); - } - return responseResult.toString(); - } + + @Override + public String serviceResponseBuilder() { + StringBuffer responseResult=new StringBuffer(""); + if(result){ + responseResult.append("yes").append("\n").append(user); + }else{ + responseResult.append("no").append("\n").append("\n"); + } + return responseResult.toString(); + } } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/response/ServiceResponseBuilder.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/response/ServiceResponseBuilder.java index 3b82770b1..407af37dd 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/response/ServiceResponseBuilder.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/response/ServiceResponseBuilder.java @@ -25,139 +25,139 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ServiceResponseBuilder extends CasServiceResponse { - static final Logger _logger = LoggerFactory.getLogger(ServiceResponseBuilder.class); - - - public ServiceResponseBuilder(){ - - } - - public ServiceResponseBuilder(String format){ - this.format = format; - } + static final Logger _logger = LoggerFactory.getLogger(ServiceResponseBuilder.class); + + + public ServiceResponseBuilder(){ + + } + + public ServiceResponseBuilder(String format){ + this.format = format; + } - @Override - public String serviceResponseBuilder() { - String responseString = ""; - if(format.equalsIgnoreCase(HttpResponseConstants.FORMAT_TYPE.XML)){ - responseString= serviceResponseXmlBuilder(); - }else{ - responseString= serviceResponseJsonBuilder(); - } - - _logger.trace("Response String : "+responseString); - return responseString; - } - - public String serviceResponseXmlBuilder() { - StringBuffer responseResult=new StringBuffer(""); - responseResult.append(""); - if(result){ - responseResult.append(""); - responseResult.append("").append(user).append(""); - if(ticket!=null){ - responseResult.append("").append(ticket).append(""); - } - if(!casAttributes.isEmpty()){ - responseResult.append(""); - //采用Iterator遍历HashMap - Iterator it = casAttributes.keySet().iterator(); - while(it.hasNext()) { - String key = (String)it.next(); - ArrayList attrList=casAttributes.get(key); - //John - for(String value : attrList){ - responseResult.append(""); - responseResult.append(value); - responseResult.append("\r\n"); - } - } - responseResult.append(""); - } - if(!proxies.isEmpty()){ - responseResult.append(""); - for(String proxy : proxies){ - responseResult.append("").append(proxy).append(""); - } - responseResult.append(""); - } - responseResult.append(""); - }else{ - responseResult.append(""); - responseResult.append(this.description); - responseResult.append(""); - } - responseResult.append(""); - return responseResult.toString(); - } - - public String serviceResponseJsonBuilder() { - StringBuffer responseResult=new StringBuffer(""); - responseResult.append("{\"serviceResponse\" :{"); - if(result){ - responseResult.append("\"authenticationSuccess\" : {"); - responseResult.append("\"user\" : \"").append(user).append("\""); - if(ticket!=null){ - responseResult.append(",\"proxyGrantingTicket\" : \"").append(ticket).append("\""); - } - - if(!casAttributes.isEmpty()){ - responseResult.append(",\"attributes\" : {"); - //采用Iterator遍历HashMap - Iterator it = casAttributes.keySet().iterator(); - int attrCount=1; - while(it.hasNext()) { - String key = (String)it.next(); - ArrayList attrList=casAttributes.get(key); - if(attrCount==1){ - responseResult.append("\"").append(key).append("\":"); - }else{ - responseResult.append(",\"").append(key).append("\":"); - } - //John - String valueString=""; - if(attrList.size()==1){ - valueString="\""+attrList.get(0)+"\""; - }else{ - int valueCount=1; - valueString+="["; - for(String value : attrList){ - if(valueCount!=1){ - valueString+=","; - } - valueString+="\""+value+"\""; - valueCount++; - } - valueString+="]"; - } - responseResult.append(valueString); - attrCount++; - } - responseResult.append("}"); - } - - if(!proxies.isEmpty()){ - responseResult.append(",\"proxies\" : [ "); - int proxyCount=1; - for(String proxy : proxies){ - if(proxyCount!=1){ - responseResult.append(","); - } - responseResult.append("\"").append(proxy).append("\""); - proxyCount++; - } - responseResult.append("]"); - } - responseResult.append("}"); - }else{ - responseResult.append("\"authenticationFailure\" : {"); - responseResult.append("\"code\" : \"").append(this.code).append("\""); - responseResult.append(",\"description\" : \"").append(this.description).append("\""); - responseResult.append("}"); - } - responseResult.append("}"); - responseResult.append("}"); - return responseResult.toString(); - } - + @Override + public String serviceResponseBuilder() { + String responseString = ""; + if(format.equalsIgnoreCase(HttpResponseConstants.FORMAT_TYPE.XML)){ + responseString= serviceResponseXmlBuilder(); + }else{ + responseString= serviceResponseJsonBuilder(); + } + + _logger.trace("Response String : "+responseString); + return responseString; + } + + public String serviceResponseXmlBuilder() { + StringBuffer responseResult=new StringBuffer(""); + responseResult.append(""); + if(result){ + responseResult.append(""); + responseResult.append("").append(user).append(""); + if(ticket!=null){ + responseResult.append("").append(ticket).append(""); + } + if(!casAttributes.isEmpty()){ + responseResult.append(""); + //采用Iterator遍历HashMap + Iterator it = casAttributes.keySet().iterator(); + while(it.hasNext()) { + String key = (String)it.next(); + ArrayList attrList=casAttributes.get(key); + //John + for(String value : attrList){ + responseResult.append(""); + responseResult.append(value); + responseResult.append("\r\n"); + } + } + responseResult.append(""); + } + if(!proxies.isEmpty()){ + responseResult.append(""); + for(String proxy : proxies){ + responseResult.append("").append(proxy).append(""); + } + responseResult.append(""); + } + responseResult.append(""); + }else{ + responseResult.append(""); + responseResult.append(this.description); + responseResult.append(""); + } + responseResult.append(""); + return responseResult.toString(); + } + + public String serviceResponseJsonBuilder() { + StringBuffer responseResult=new StringBuffer(""); + responseResult.append("{\"serviceResponse\" :{"); + if(result){ + responseResult.append("\"authenticationSuccess\" : {"); + responseResult.append("\"user\" : \"").append(user).append("\""); + if(ticket!=null){ + responseResult.append(",\"proxyGrantingTicket\" : \"").append(ticket).append("\""); + } + + if(!casAttributes.isEmpty()){ + responseResult.append(",\"attributes\" : {"); + //采用Iterator遍历HashMap + Iterator it = casAttributes.keySet().iterator(); + int attrCount=1; + while(it.hasNext()) { + String key = (String)it.next(); + ArrayList attrList=casAttributes.get(key); + if(attrCount==1){ + responseResult.append("\"").append(key).append("\":"); + }else{ + responseResult.append(",\"").append(key).append("\":"); + } + //John + String valueString=""; + if(attrList.size()==1){ + valueString="\""+attrList.get(0)+"\""; + }else{ + int valueCount=1; + valueString+="["; + for(String value : attrList){ + if(valueCount!=1){ + valueString+=","; + } + valueString+="\""+value+"\""; + valueCount++; + } + valueString+="]"; + } + responseResult.append(valueString); + attrCount++; + } + responseResult.append("}"); + } + + if(!proxies.isEmpty()){ + responseResult.append(",\"proxies\" : [ "); + int proxyCount=1; + for(String proxy : proxies){ + if(proxyCount!=1){ + responseResult.append(","); + } + responseResult.append("\"").append(proxy).append("\""); + proxyCount++; + } + responseResult.append("]"); + } + responseResult.append("}"); + }else{ + responseResult.append("\"authenticationFailure\" : {"); + responseResult.append("\"code\" : \"").append(this.code).append("\""); + responseResult.append(",\"description\" : \"").append(this.description).append("\""); + responseResult.append("}"); + } + responseResult.append("}"); + responseResult.append("}"); + return responseResult.toString(); + } + } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/AbstractTicket.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/AbstractTicket.java index 2eef76f0d..3486f6df1 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/AbstractTicket.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/AbstractTicket.java @@ -148,16 +148,16 @@ public abstract class AbstractTicket implements Ticket { return this.getId(); } - @Override - public AppsCasDetails getCasDetails() { - return this.casDetails; - } - - @Override - public Authentication getAuthentication() { - return this.authentication; - } - + @Override + public AppsCasDetails getCasDetails() { + return this.casDetails; + } + + @Override + public Authentication getAuthentication() { + return this.authentication; + } + @Override public int compareTo(final Ticket o) { return getId().compareTo(o.getId()); diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/AbstractTicketException.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/AbstractTicketException.java index e7c7ab921..64e309f09 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/AbstractTicketException.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/AbstractTicketException.java @@ -35,8 +35,8 @@ public abstract class AbstractTicketException{ * @param throwable the throwable */ public AbstractTicketException(final String code, final Throwable throwable) { - this.code=code; - this.throwable=throwable; + this.code=code; + this.throwable=throwable; } /** @@ -45,7 +45,7 @@ public abstract class AbstractTicketException{ * @param code the code */ public AbstractTicketException(final String code) { - this.code=code; + this.code=code; } /** @@ -55,7 +55,7 @@ public abstract class AbstractTicketException{ * @param msg the msg */ public AbstractTicketException(final String code, final String msg) { - this.code=code; - this.msg=msg; + this.code=code; + this.msg=msg; } } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/CasConstants.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/CasConstants.java index 38584187d..7bae03091 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/CasConstants.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/CasConstants.java @@ -19,141 +19,141 @@ package org.dromara.maxkey.authz.cas.endpoint.ticket; public class CasConstants { - /* CAS Protocol Parameters. **/ - public static final class PARAMETER{ - public static final String ENDPOINT_CAS_DETAILS = "CAS_AUTHORIZE_ENDPOINT_CAS_DETAILS"; - - public static final String PARAMETER_MAP = "CAS_AUTHORIZE_ENDPOINT_PARAMETER_MAP"; + /* CAS Protocol Parameters. **/ + public static final class PARAMETER{ + public static final String ENDPOINT_CAS_DETAILS = "CAS_AUTHORIZE_ENDPOINT_CAS_DETAILS"; + + public static final String PARAMETER_MAP = "CAS_AUTHORIZE_ENDPOINT_PARAMETER_MAP"; - /** Constant representing the ticket parameter in the request. */ - public static final String TICKET = "ticket"; - - /** Constant representing the service parameter in the request. */ - public static final String SERVICE = "service"; - - /** Constant representing the targetService parameter in the request. */ - public static final String TARGET_SERVICE = "targetService"; - - /** Constant representing the method parameter in the request. */ - public static final String METHOD = "method"; - - /** Constant representing the proxy callback url parameter in the request. */ - public static final String PROXY_CALLBACK_URL = "pgtUrl"; + /** Constant representing the ticket parameter in the request. */ + public static final String TICKET = "ticket"; + + /** Constant representing the service parameter in the request. */ + public static final String SERVICE = "service"; + + /** Constant representing the targetService parameter in the request. */ + public static final String TARGET_SERVICE = "targetService"; + + /** Constant representing the method parameter in the request. */ + public static final String METHOD = "method"; + + /** Constant representing the proxy callback url parameter in the request. */ + public static final String PROXY_CALLBACK_URL = "pgtUrl"; - /** Constant representing the renew parameter in the request. */ - public static final String RENEW = "renew"; + /** Constant representing the renew parameter in the request. */ + public static final String RENEW = "renew"; - /** Constant representing the gateway parameter in the request. */ - public static final String GATEWAY = "gateway"; + /** Constant representing the gateway parameter in the request. */ + public static final String GATEWAY = "gateway"; - /** Constant representing the format parameter in the request. */ - public static final String FORMAT = "format"; - - /** Constant representing the pgtId parameter in the request. */ - public static final String PROXY_GRANTING_TICKET_ID = "pgtId"; + /** Constant representing the format parameter in the request. */ + public static final String FORMAT = "format"; + + /** Constant representing the pgtId parameter in the request. */ + public static final String PROXY_GRANTING_TICKET_ID = "pgtId"; - /** Constant representing the pgt parameter in the request. */ - public static final String PROXY_GRANTING_TICKET = "pgt"; + /** Constant representing the pgt parameter in the request. */ + public static final String PROXY_GRANTING_TICKET = "pgt"; - /** Constant representing the pgtIou parameter in the request. */ - public static final String PROXY_GRANTING_TICKET_IOU = "pgtIou"; - - public static final String REST_USERNAME = "username"; - - public static final String REST_PASSWORD = "password"; - } - - /* CAS Protocol PREFIX */ - public static final class PREFIX{ - /** Proxy ticket prefix applied to unique ids. */ - public static final String PROXY_TICKET_PREFIX = "PT"; - /** - * Prefix generally applied to unique ids generated - * by UniqueTicketIdGenerator. - */ - public static final String SERVICE_TICKET_PREFIX = "ST"; - /** The prefix to use when generating an id for a Proxy Granting Ticket. */ - public static final String PROXY_GRANTING_TICKET_PREFIX = "PGT"; - /** The prefix to use when generating an id for a Proxy Granting Ticket IOU. */ - public static final String PROXY_GRANTING_TICKET_IOU_PREFIX = "PGTIOU"; - - public static final String TICKET_GRANTING_TICKET_PREFIX = "TGT"; - } - - /* CAS Protocol Error Codes. **/ - public static class ERROR_CODE{ - /** Constant representing an invalid request for validation. */ - public static String INVALID_REQUEST = "INVALID_REQUEST"; - /** Constant representing an invalid pgt request. */ - public static String INVALID_REQUEST_PROXY = "INVALID_REQUEST_PROXY"; - public static String INVALID_TICKET_SPEC = "INVALID_TICKET_SPEC"; - /** Constant representing an invalid proxy callback for validation. */ - public static String INVALID_PROXY_CALLBACK = "INVALID_PROXY_CALLBACK"; - /** Constant representing an invalid ticket for validation. */ - public static String INVALID_TICKET = "INVALID_TICKET"; - public static String INVALID_SERVICE = "INVALID_SERVICE"; - public static String INTERNAL_ERROR = "INTERNAL_ERROR"; - - /** Constant representing an invalid service proxy request. */ - public static String UNAUTHORIZED_SERVICE_PROXY = "UNAUTHORIZED_SERVICE_PROXY"; - /** Constant representing an invalid service request. */ - public static String UNAUTHORIZED_SERVICE = "UNAUTHORIZED_SERVICE"; - } - - /* CAS Protocol endpoint. **/ - public static class ENDPOINT{ - public static final String ENDPOINT_BASE = "/authz/cas"; - /** - * Constant representing login. - */ - public static final String ENDPOINT_LOGIN = ENDPOINT_BASE + "/login"; - - /** - * Constant representing logout. - */ - public static final String ENDPOINT_LOGOUT = ENDPOINT_BASE + "/logout"; - - /** - * Constant representing proxy validate. - */ - public static final String ENDPOINT_PROXY_VALIDATE = ENDPOINT_BASE + "/proxyValidate"; - - /** - * Constant representing v3 proxy validate. - */ - public static final String ENDPOINT_PROXY_VALIDATE_V3 = ENDPOINT_BASE + "/p3/proxyValidate"; - - /** - * Constant representing legacy validate. - */ - public static final String ENDPOINT_VALIDATE = ENDPOINT_BASE + "/validate"; - - /** - * Constant representing service validate. - */ - public static final String ENDPOINT_SERVICE_VALIDATE = ENDPOINT_BASE + "/serviceValidate"; - - /** - * Constant representing v3 service validate. - */ - public static final String ENDPOINT_SERVICE_VALIDATE_V3 = ENDPOINT_BASE + "/p3/serviceValidate"; - - /** - * Constant representing proxy endpoint. - */ - public static final String ENDPOINT_PROXY = ENDPOINT_BASE + "/proxy"; - - /** - * Constant representing v3 proxy endpoint. - */ - public static final String ENDPOINT_PROXY_V3 = ENDPOINT_BASE + "/p3/proxy"; - - public static final String ENDPOINT_SERVICE_TICKET_GRANTING = ENDPOINT_BASE + "/granting"; - - public static final String ENDPOINT_REST_TICKET_V1 = ENDPOINT_BASE + "/v1/tickets"; - - public static final String ENDPOINT_REST_USERS_V1 = ENDPOINT_BASE + "/v1/users"; - - - } + /** Constant representing the pgtIou parameter in the request. */ + public static final String PROXY_GRANTING_TICKET_IOU = "pgtIou"; + + public static final String REST_USERNAME = "username"; + + public static final String REST_PASSWORD = "password"; + } + + /* CAS Protocol PREFIX */ + public static final class PREFIX{ + /** Proxy ticket prefix applied to unique ids. */ + public static final String PROXY_TICKET_PREFIX = "PT"; + /** + * Prefix generally applied to unique ids generated + * by UniqueTicketIdGenerator. + */ + public static final String SERVICE_TICKET_PREFIX = "ST"; + /** The prefix to use when generating an id for a Proxy Granting Ticket. */ + public static final String PROXY_GRANTING_TICKET_PREFIX = "PGT"; + /** The prefix to use when generating an id for a Proxy Granting Ticket IOU. */ + public static final String PROXY_GRANTING_TICKET_IOU_PREFIX = "PGTIOU"; + + public static final String TICKET_GRANTING_TICKET_PREFIX = "TGT"; + } + + /* CAS Protocol Error Codes. **/ + public static class ERROR_CODE{ + /** Constant representing an invalid request for validation. */ + public static String INVALID_REQUEST = "INVALID_REQUEST"; + /** Constant representing an invalid pgt request. */ + public static String INVALID_REQUEST_PROXY = "INVALID_REQUEST_PROXY"; + public static String INVALID_TICKET_SPEC = "INVALID_TICKET_SPEC"; + /** Constant representing an invalid proxy callback for validation. */ + public static String INVALID_PROXY_CALLBACK = "INVALID_PROXY_CALLBACK"; + /** Constant representing an invalid ticket for validation. */ + public static String INVALID_TICKET = "INVALID_TICKET"; + public static String INVALID_SERVICE = "INVALID_SERVICE"; + public static String INTERNAL_ERROR = "INTERNAL_ERROR"; + + /** Constant representing an invalid service proxy request. */ + public static String UNAUTHORIZED_SERVICE_PROXY = "UNAUTHORIZED_SERVICE_PROXY"; + /** Constant representing an invalid service request. */ + public static String UNAUTHORIZED_SERVICE = "UNAUTHORIZED_SERVICE"; + } + + /* CAS Protocol endpoint. **/ + public static class ENDPOINT{ + public static final String ENDPOINT_BASE = "/authz/cas"; + /** + * Constant representing login. + */ + public static final String ENDPOINT_LOGIN = ENDPOINT_BASE + "/login"; + + /** + * Constant representing logout. + */ + public static final String ENDPOINT_LOGOUT = ENDPOINT_BASE + "/logout"; + + /** + * Constant representing proxy validate. + */ + public static final String ENDPOINT_PROXY_VALIDATE = ENDPOINT_BASE + "/proxyValidate"; + + /** + * Constant representing v3 proxy validate. + */ + public static final String ENDPOINT_PROXY_VALIDATE_V3 = ENDPOINT_BASE + "/p3/proxyValidate"; + + /** + * Constant representing legacy validate. + */ + public static final String ENDPOINT_VALIDATE = ENDPOINT_BASE + "/validate"; + + /** + * Constant representing service validate. + */ + public static final String ENDPOINT_SERVICE_VALIDATE = ENDPOINT_BASE + "/serviceValidate"; + + /** + * Constant representing v3 service validate. + */ + public static final String ENDPOINT_SERVICE_VALIDATE_V3 = ENDPOINT_BASE + "/p3/serviceValidate"; + + /** + * Constant representing proxy endpoint. + */ + public static final String ENDPOINT_PROXY = ENDPOINT_BASE + "/proxy"; + + /** + * Constant representing v3 proxy endpoint. + */ + public static final String ENDPOINT_PROXY_V3 = ENDPOINT_BASE + "/p3/proxy"; + + public static final String ENDPOINT_SERVICE_TICKET_GRANTING = ENDPOINT_BASE + "/granting"; + + public static final String ENDPOINT_REST_TICKET_V1 = ENDPOINT_BASE + "/v1/tickets"; + + public static final String ENDPOINT_REST_USERS_V1 = ENDPOINT_BASE + "/v1/users"; + + + } } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/ProxyGrantingTicketIOUImpl.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/ProxyGrantingTicketIOUImpl.java index 3387e02cb..8382f73fd 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/ProxyGrantingTicketIOUImpl.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/ProxyGrantingTicketIOUImpl.java @@ -50,7 +50,7 @@ public class ProxyGrantingTicketIOUImpl extends ServiceTicketImpl implements Tic } public ProxyGrantingTicketIOUImpl(Authentication authentication, AppsCasDetails casDetails) { - this.authentication=authentication; - this.casDetails=casDetails; + this.authentication=authentication; + this.casDetails=casDetails; } } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/ProxyGrantingTicketImpl.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/ProxyGrantingTicketImpl.java index 58f3ea78e..a132a5ec6 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/ProxyGrantingTicketImpl.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/ProxyGrantingTicketImpl.java @@ -50,7 +50,7 @@ public class ProxyGrantingTicketImpl extends ServiceTicketImpl implements Ticket } public ProxyGrantingTicketImpl(Authentication authentication, AppsCasDetails casDetails) { - this.authentication=authentication; - this.casDetails=casDetails; + this.authentication=authentication; + this.casDetails=casDetails; } } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/ProxyTicketImpl.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/ProxyTicketImpl.java index 479aa7ff1..f2e99d78f 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/ProxyTicketImpl.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/ProxyTicketImpl.java @@ -50,7 +50,7 @@ public class ProxyTicketImpl extends ServiceTicketImpl implements Ticket { } public ProxyTicketImpl(Authentication authentication, AppsCasDetails casDetails) { - this.authentication=authentication; - this.casDetails=casDetails; + this.authentication=authentication; + this.casDetails=casDetails; } } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/RandomServiceTicketServices.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/RandomServiceTicketServices.java index e0b5dc8f8..3063aa596 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/RandomServiceTicketServices.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/RandomServiceTicketServices.java @@ -22,75 +22,75 @@ import org.dromara.maxkey.authz.cas.endpoint.ticket.generator.DefaultUniqueTicke public abstract class RandomServiceTicketServices implements TicketServices { - //default Random code Generator - //private RandomValueStringGenerator generator = new RandomValueStringGenerator(); - - private DefaultUniqueTicketIdGenerator generator=new DefaultUniqueTicketIdGenerator(); + //default Random code Generator + //private RandomValueStringGenerator generator = new RandomValueStringGenerator(); + + private DefaultUniqueTicketIdGenerator generator=new DefaultUniqueTicketIdGenerator(); - @Override - public String createTicket(Ticket ticket) { - //String code = generator.generate(); - /* - * replace with uuid random code - * add by Crystal.Sea - */ - //String ticket = UUID.randomUUID().toString(); - String ticketId = ""; - if(ticket.getClass().getSimpleName().equalsIgnoreCase("ServiceTicketImpl")){ - ticketId = generator.getNewTicketId(CasConstants.PREFIX.SERVICE_TICKET_PREFIX); - }else if(ticket.getClass().getSimpleName().equalsIgnoreCase("ProxyTicketImpl")){ - ticketId = generator.getNewTicketId(CasConstants.PREFIX.PROXY_TICKET_PREFIX); - }else if(ticket.getClass().getSimpleName().equalsIgnoreCase("TicketGrantingTicketImpl")){ - ticketId = generator.getNewTicketId(CasConstants.PREFIX.TICKET_GRANTING_TICKET_PREFIX); - }else if(ticket.getClass().getSimpleName().equalsIgnoreCase("ProxyGrantingTicketImpl")){ - ticketId = generator.getNewTicketId(CasConstants.PREFIX.PROXY_GRANTING_TICKET_PREFIX); - }else if(ticket.getClass().getSimpleName().equalsIgnoreCase("ProxyGrantingTicketIOUImpl")){ - ticketId = generator.getNewTicketId(CasConstants.PREFIX.PROXY_GRANTING_TICKET_IOU_PREFIX); - return ticketId; - }else { - ticketId = generator.getNewTicketId(CasConstants.PREFIX.SERVICE_TICKET_PREFIX); - } - - store(ticketId, ticket); - return ticketId; - } + @Override + public String createTicket(Ticket ticket) { + //String code = generator.generate(); + /* + * replace with uuid random code + * add by Crystal.Sea + */ + //String ticket = UUID.randomUUID().toString(); + String ticketId = ""; + if(ticket.getClass().getSimpleName().equalsIgnoreCase("ServiceTicketImpl")){ + ticketId = generator.getNewTicketId(CasConstants.PREFIX.SERVICE_TICKET_PREFIX); + }else if(ticket.getClass().getSimpleName().equalsIgnoreCase("ProxyTicketImpl")){ + ticketId = generator.getNewTicketId(CasConstants.PREFIX.PROXY_TICKET_PREFIX); + }else if(ticket.getClass().getSimpleName().equalsIgnoreCase("TicketGrantingTicketImpl")){ + ticketId = generator.getNewTicketId(CasConstants.PREFIX.TICKET_GRANTING_TICKET_PREFIX); + }else if(ticket.getClass().getSimpleName().equalsIgnoreCase("ProxyGrantingTicketImpl")){ + ticketId = generator.getNewTicketId(CasConstants.PREFIX.PROXY_GRANTING_TICKET_PREFIX); + }else if(ticket.getClass().getSimpleName().equalsIgnoreCase("ProxyGrantingTicketIOUImpl")){ + ticketId = generator.getNewTicketId(CasConstants.PREFIX.PROXY_GRANTING_TICKET_IOU_PREFIX); + return ticketId; + }else { + ticketId = generator.getNewTicketId(CasConstants.PREFIX.SERVICE_TICKET_PREFIX); + } + + store(ticketId, ticket); + return ticketId; + } - @Override - public String createTicket(Ticket ticket, int validitySeconds) { - - //String code = generator.generate(); - /* - * replace with uuid random code - * add by Crystal.Sea - */ - //String ticket = UUID.randomUUID().toString(); - String ticketId = ""; - if(ticket.getClass().getSimpleName().equalsIgnoreCase("ServiceTicketImpl")){ - ticketId = generator.getNewTicketId(CasConstants.PREFIX.SERVICE_TICKET_PREFIX); - }else if(ticket.getClass().getSimpleName().equalsIgnoreCase("ProxyTicketImpl")){ - ticketId = generator.getNewTicketId(CasConstants.PREFIX.PROXY_TICKET_PREFIX); - }else if(ticket.getClass().getSimpleName().equalsIgnoreCase("TicketGrantingTicketImpl")){ - ticketId = generator.getNewTicketId(CasConstants.PREFIX.TICKET_GRANTING_TICKET_PREFIX); - }else if(ticket.getClass().getSimpleName().equalsIgnoreCase("ProxyGrantingTicketImpl")){ - ticketId = generator.getNewTicketId(CasConstants.PREFIX.PROXY_GRANTING_TICKET_PREFIX); - }else if(ticket.getClass().getSimpleName().equalsIgnoreCase("ProxyGrantingTicketIOUImpl")){ - ticketId = generator.getNewTicketId(CasConstants.PREFIX.PROXY_GRANTING_TICKET_IOU_PREFIX); - return ticketId; - }else { - ticketId = generator.getNewTicketId(CasConstants.PREFIX.SERVICE_TICKET_PREFIX); - } - - store(ticketId, ticket,validitySeconds); - return ticketId; - } + @Override + public String createTicket(Ticket ticket, int validitySeconds) { + + //String code = generator.generate(); + /* + * replace with uuid random code + * add by Crystal.Sea + */ + //String ticket = UUID.randomUUID().toString(); + String ticketId = ""; + if(ticket.getClass().getSimpleName().equalsIgnoreCase("ServiceTicketImpl")){ + ticketId = generator.getNewTicketId(CasConstants.PREFIX.SERVICE_TICKET_PREFIX); + }else if(ticket.getClass().getSimpleName().equalsIgnoreCase("ProxyTicketImpl")){ + ticketId = generator.getNewTicketId(CasConstants.PREFIX.PROXY_TICKET_PREFIX); + }else if(ticket.getClass().getSimpleName().equalsIgnoreCase("TicketGrantingTicketImpl")){ + ticketId = generator.getNewTicketId(CasConstants.PREFIX.TICKET_GRANTING_TICKET_PREFIX); + }else if(ticket.getClass().getSimpleName().equalsIgnoreCase("ProxyGrantingTicketImpl")){ + ticketId = generator.getNewTicketId(CasConstants.PREFIX.PROXY_GRANTING_TICKET_PREFIX); + }else if(ticket.getClass().getSimpleName().equalsIgnoreCase("ProxyGrantingTicketIOUImpl")){ + ticketId = generator.getNewTicketId(CasConstants.PREFIX.PROXY_GRANTING_TICKET_IOU_PREFIX); + return ticketId; + }else { + ticketId = generator.getNewTicketId(CasConstants.PREFIX.SERVICE_TICKET_PREFIX); + } + + store(ticketId, ticket,validitySeconds); + return ticketId; + } - @Override - public Ticket consumeTicket(String ticketId) throws Exception{ - Ticket ticket = this.remove(ticketId); - if (ticket == null) { - throw new Exception("Invalid authorization code: " + ticketId); - } - return ticket; - } + @Override + public Ticket consumeTicket(String ticketId) throws Exception{ + Ticket ticket = this.remove(ticketId); + if (ticket == null) { + throw new Exception("Invalid authorization code: " + ticketId); + } + return ticket; + } } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/Service.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/Service.java index 3530639fe..9b6a20f0e 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/Service.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/Service.java @@ -31,7 +31,7 @@ package org.dromara.maxkey.authz.cas.endpoint.ticket; *

*/ public interface Service { - String getId(); + String getId(); boolean matches(Service service); } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/ServiceTicketImpl.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/ServiceTicketImpl.java index 520662378..2e8316184 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/ServiceTicketImpl.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/ServiceTicketImpl.java @@ -68,7 +68,7 @@ public class ServiceTicketImpl extends AbstractTicket implements ServiceTicket{ */ public ServiceTicketImpl(Authentication authentication) { // exists for JPA purposes - this.authentication=authentication; + this.authentication=authentication; } /** @@ -76,8 +76,8 @@ public class ServiceTicketImpl extends AbstractTicket implements ServiceTicket{ */ public ServiceTicketImpl(Authentication authentication,AppsCasDetails casDetails) { // exists for JPA purposes - this.authentication=authentication; - this.casDetails=casDetails; + this.authentication=authentication; + this.casDetails=casDetails; } /** diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/TicketServices.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/TicketServices.java index 569ba0695..ac53423fa 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/TicketServices.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/TicketServices.java @@ -19,29 +19,29 @@ package org.dromara.maxkey.authz.cas.endpoint.ticket; public interface TicketServices { - /** - * Create a authorization code for the specified authentications. - * - * @param authentication The authentications to store. - * @return The generated code. - */ - String createTicket(Ticket ticket); - - String createTicket(Ticket ticket , int validitySeconds); + /** + * Create a authorization code for the specified authentications. + * + * @param authentication The authentications to store. + * @return The generated code. + */ + String createTicket(Ticket ticket); + + String createTicket(Ticket ticket , int validitySeconds); - /** - * Consume a authorization code. - * - * @param code The authorization code to consume. - * @return The authentications associated with the code. - * @throws InvalidGrantException If the authorization code is invalid or expired. - */ - Ticket consumeTicket(String ticketId) - throws Exception; - - public void store(String ticketId, Ticket ticket); - - public void store(String ticketId, Ticket ticket, int validitySeconds); + /** + * Consume a authorization code. + * + * @param code The authorization code to consume. + * @return The authentications associated with the code. + * @throws InvalidGrantException If the authorization code is invalid or expired. + */ + Ticket consumeTicket(String ticketId) + throws Exception; + + public void store(String ticketId, Ticket ticket); + + public void store(String ticketId, Ticket ticket, int validitySeconds); public Ticket remove(String ticket); diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/pgt/InMemoryProxyGrantingTicketServices.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/pgt/InMemoryProxyGrantingTicketServices.java index 7dc6f2ad5..23100148f 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/pgt/InMemoryProxyGrantingTicketServices.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/pgt/InMemoryProxyGrantingTicketServices.java @@ -28,28 +28,28 @@ import com.github.benmanes.caffeine.cache.Caffeine; public class InMemoryProxyGrantingTicketServices extends RandomServiceTicketServices { - protected static final Cache casTicketStore = - Caffeine.newBuilder() + protected static final Cache casTicketStore = + Caffeine.newBuilder() .expireAfterWrite(60, TimeUnit.MINUTES) .build(); - - @Override - public void store(String ticketId, Ticket ticket) { - store(ticketId, ticket , 60 * 3); - } + + @Override + public void store(String ticketId, Ticket ticket) { + store(ticketId, ticket , 60 * 3); + } - @Override - public void store(String ticketId, Ticket ticket, int validitySeconds) { - casTicketStore.put(ticketId, ticket); - } + @Override + public void store(String ticketId, Ticket ticket, int validitySeconds) { + casTicketStore.put(ticketId, ticket); + } - @Override - public Ticket remove(String ticketId) { - Ticket ticket=casTicketStore.getIfPresent(ticketId); - casTicketStore.invalidate(ticketId); - return ticket; - } + @Override + public Ticket remove(String ticketId) { + Ticket ticket=casTicketStore.getIfPresent(ticketId); + casTicketStore.invalidate(ticketId); + return ticket; + } @Override public Ticket get(String ticket) { diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/pgt/RedisProxyGrantingTicketServices.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/pgt/RedisProxyGrantingTicketServices.java index 9fc54356a..35669ea12 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/pgt/RedisProxyGrantingTicketServices.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/pgt/RedisProxyGrantingTicketServices.java @@ -25,51 +25,51 @@ import org.dromara.maxkey.persistence.redis.RedisConnectionFactory; public class RedisProxyGrantingTicketServices extends RandomServiceTicketServices { - - protected int serviceTicketValiditySeconds = 60 * 60; //default 60 minutes. - - RedisConnectionFactory connectionFactory; - - public static String PREFIX = "MXK_CAS_TICKET_PGT_"; - /** - * @param connectionFactory - */ - public RedisProxyGrantingTicketServices(RedisConnectionFactory connectionFactory) { - super(); - this.connectionFactory = connectionFactory; - } - - /** - * - */ - public RedisProxyGrantingTicketServices() { - - } + + protected int serviceTicketValiditySeconds = 60 * 60; //default 60 minutes. + + RedisConnectionFactory connectionFactory; + + public static String PREFIX = "MXK_CAS_TICKET_PGT_"; + /** + * @param connectionFactory + */ + public RedisProxyGrantingTicketServices(RedisConnectionFactory connectionFactory) { + super(); + this.connectionFactory = connectionFactory; + } + + /** + * + */ + public RedisProxyGrantingTicketServices() { + + } - public void setConnectionFactory(RedisConnectionFactory connectionFactory) { - this.connectionFactory = connectionFactory; - } + public void setConnectionFactory(RedisConnectionFactory connectionFactory) { + this.connectionFactory = connectionFactory; + } - @Override - public void store(String ticketId, Ticket ticket) { - store(ticketId,ticket,serviceTicketValiditySeconds); - } + @Override + public void store(String ticketId, Ticket ticket) { + store(ticketId,ticket,serviceTicketValiditySeconds); + } - @Override - public void store(String ticketId, Ticket ticket, int validitySeconds) { - RedisConnection conn=connectionFactory.getConnection(); - conn.setexObject(PREFIX+ticketId, validitySeconds, ticket); - conn.close(); - } + @Override + public void store(String ticketId, Ticket ticket, int validitySeconds) { + RedisConnection conn=connectionFactory.getConnection(); + conn.setexObject(PREFIX+ticketId, validitySeconds, ticket); + conn.close(); + } - @Override - public Ticket remove(String ticketId) { - RedisConnection conn=connectionFactory.getConnection(); - Ticket ticket = conn.getObject(PREFIX+ticketId); - conn.delete(PREFIX+ticketId); - conn.close(); - return ticket; - } + @Override + public Ticket remove(String ticketId) { + RedisConnection conn=connectionFactory.getConnection(); + Ticket ticket = conn.getObject(PREFIX+ticketId); + conn.delete(PREFIX+ticketId); + conn.close(); + return ticket; + } @Override public Ticket get(String ticketId) { @@ -79,5 +79,5 @@ public class RedisProxyGrantingTicketServices extends RandomServiceTicketService return ticket; } - + } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/st/InMemoryTicketServices.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/st/InMemoryTicketServices.java index 0282ecbaa..388680291 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/st/InMemoryTicketServices.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/st/InMemoryTicketServices.java @@ -28,28 +28,28 @@ import com.github.benmanes.caffeine.cache.Caffeine; public class InMemoryTicketServices extends RandomServiceTicketServices { - protected static final Cache casTicketStore = - Caffeine.newBuilder() + protected static final Cache casTicketStore = + Caffeine.newBuilder() .expireAfterWrite(60, TimeUnit.MINUTES) .build(); - - @Override - public void store(String ticketId, Ticket ticket) { - store(ticketId, ticket, 60 * 3); - } + + @Override + public void store(String ticketId, Ticket ticket) { + store(ticketId, ticket, 60 * 3); + } - @Override - public void store(String ticketId, Ticket ticket, int validitySeconds) { - casTicketStore.put(ticketId, ticket); - } + @Override + public void store(String ticketId, Ticket ticket, int validitySeconds) { + casTicketStore.put(ticketId, ticket); + } - @Override - public Ticket remove(String ticketId) { - Ticket ticket=casTicketStore.getIfPresent(ticketId); - casTicketStore.invalidate(ticketId); - return ticket; - } + @Override + public Ticket remove(String ticketId) { + Ticket ticket=casTicketStore.getIfPresent(ticketId); + casTicketStore.invalidate(ticketId); + return ticket; + } @Override public Ticket get(String ticket) { diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/st/RedisTicketServices.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/st/RedisTicketServices.java index 2d1da2b15..ff72d16aa 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/st/RedisTicketServices.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/st/RedisTicketServices.java @@ -25,52 +25,52 @@ import org.dromara.maxkey.persistence.redis.RedisConnectionFactory; public class RedisTicketServices extends RandomServiceTicketServices { - - protected int serviceTicketValiditySeconds = 60 * 10; //default 10 minutes. - - RedisConnectionFactory connectionFactory; - - public static String PREFIX="MXK_CAS_TICKET_ST_"; - /** - * @param connectionFactory - */ - public RedisTicketServices(RedisConnectionFactory connectionFactory) { - super(); - this.connectionFactory = connectionFactory; - } - - /** - * - */ - public RedisTicketServices() { - - } + + protected int serviceTicketValiditySeconds = 60 * 10; //default 10 minutes. + + RedisConnectionFactory connectionFactory; + + public static String PREFIX="MXK_CAS_TICKET_ST_"; + /** + * @param connectionFactory + */ + public RedisTicketServices(RedisConnectionFactory connectionFactory) { + super(); + this.connectionFactory = connectionFactory; + } + + /** + * + */ + public RedisTicketServices() { + + } - public void setConnectionFactory(RedisConnectionFactory connectionFactory) { - this.connectionFactory = connectionFactory; - } + public void setConnectionFactory(RedisConnectionFactory connectionFactory) { + this.connectionFactory = connectionFactory; + } - @Override - public void store(String ticketId, Ticket ticket) { - store(ticketId,ticket,serviceTicketValiditySeconds); - } + @Override + public void store(String ticketId, Ticket ticket) { + store(ticketId,ticket,serviceTicketValiditySeconds); + } - @Override - public void store(String ticketId, Ticket ticket, int validitySeconds) { - RedisConnection conn=connectionFactory.getConnection(); - conn.setexObject(prefixTicketId(ticketId), validitySeconds, ticket); - conn.close(); - - } + @Override + public void store(String ticketId, Ticket ticket, int validitySeconds) { + RedisConnection conn=connectionFactory.getConnection(); + conn.setexObject(prefixTicketId(ticketId), validitySeconds, ticket); + conn.close(); + + } - @Override - public Ticket remove(String ticketId) { - RedisConnection conn=connectionFactory.getConnection(); - Ticket ticket = conn.getObject(prefixTicketId(ticketId)); - conn.delete(prefixTicketId(ticketId)); - conn.close(); - return ticket; - } + @Override + public Ticket remove(String ticketId) { + RedisConnection conn=connectionFactory.getConnection(); + Ticket ticket = conn.getObject(prefixTicketId(ticketId)); + conn.delete(prefixTicketId(ticketId)); + conn.close(); + return ticket; + } @Override public Ticket get(String ticketId) { @@ -81,8 +81,8 @@ public class RedisTicketServices extends RandomServiceTicketServices { } public String prefixTicketId(String ticketId) { - return PREFIX + ticketId; + return PREFIX + ticketId; } - + } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/tgt/InMemoryTicketGrantingTicketServices.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/tgt/InMemoryTicketGrantingTicketServices.java index 6045abad6..f477b6d39 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/tgt/InMemoryTicketGrantingTicketServices.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/tgt/InMemoryTicketGrantingTicketServices.java @@ -28,28 +28,28 @@ import com.github.benmanes.caffeine.cache.Caffeine; public class InMemoryTicketGrantingTicketServices extends RandomServiceTicketServices { - protected static final Cache casTicketGrantingTicketStore = - Caffeine.newBuilder() + protected static final Cache casTicketGrantingTicketStore = + Caffeine.newBuilder() .expireAfterWrite(2, TimeUnit.DAYS) .build(); - - @Override - public void store(String ticketId, Ticket ticket) { - store(ticketId, ticket , 60 * 3); - } + + @Override + public void store(String ticketId, Ticket ticket) { + store(ticketId, ticket , 60 * 3); + } - @Override - public void store(String ticketId, Ticket ticket, int validitySeconds) { - casTicketGrantingTicketStore.put(ticketId, ticket); - - } + @Override + public void store(String ticketId, Ticket ticket, int validitySeconds) { + casTicketGrantingTicketStore.put(ticketId, ticket); + + } - @Override - public Ticket remove(String ticketId) { - Ticket ticket=casTicketGrantingTicketStore.getIfPresent(ticketId); - casTicketGrantingTicketStore.invalidate(ticketId); - return ticket; - } + @Override + public Ticket remove(String ticketId) { + Ticket ticket=casTicketGrantingTicketStore.getIfPresent(ticketId); + casTicketGrantingTicketStore.invalidate(ticketId); + return ticket; + } @Override public Ticket get(String ticketId) { diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/tgt/RedisTicketGrantingTicketServices.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/tgt/RedisTicketGrantingTicketServices.java index cdc57588d..d0eb42ec5 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/tgt/RedisTicketGrantingTicketServices.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/authz/cas/endpoint/ticket/tgt/RedisTicketGrantingTicketServices.java @@ -26,49 +26,49 @@ import org.dromara.maxkey.persistence.redis.RedisConnectionFactory; public class RedisTicketGrantingTicketServices extends RandomServiceTicketServices { protected int serviceTicketValiditySeconds = 60 * 60 * 24 * 2; //default 2 day. - - RedisConnectionFactory connectionFactory; - - public static String PREFIX="REDIS_CAS_TICKET_TGT_"; - /** - * @param connectionFactory - */ - public RedisTicketGrantingTicketServices(RedisConnectionFactory connectionFactory) { - super(); - this.connectionFactory = connectionFactory; - } - - /** - * - */ - public RedisTicketGrantingTicketServices() { - - } + + RedisConnectionFactory connectionFactory; + + public static String PREFIX="REDIS_CAS_TICKET_TGT_"; + /** + * @param connectionFactory + */ + public RedisTicketGrantingTicketServices(RedisConnectionFactory connectionFactory) { + super(); + this.connectionFactory = connectionFactory; + } + + /** + * + */ + public RedisTicketGrantingTicketServices() { + + } - public void setConnectionFactory(RedisConnectionFactory connectionFactory) { - this.connectionFactory = connectionFactory; - } + public void setConnectionFactory(RedisConnectionFactory connectionFactory) { + this.connectionFactory = connectionFactory; + } - @Override - public void store(String ticketId, Ticket ticket) { - store(ticketId, ticket, serviceTicketValiditySeconds); - } + @Override + public void store(String ticketId, Ticket ticket) { + store(ticketId, ticket, serviceTicketValiditySeconds); + } - @Override - public void store(String ticketId, Ticket ticket, int validitySeconds) { - RedisConnection conn=connectionFactory.getConnection(); - conn.setexObject(PREFIX+ticketId, validitySeconds, ticket); - conn.close(); - } + @Override + public void store(String ticketId, Ticket ticket, int validitySeconds) { + RedisConnection conn=connectionFactory.getConnection(); + conn.setexObject(PREFIX+ticketId, validitySeconds, ticket); + conn.close(); + } - @Override - public Ticket remove(String ticketId) { - RedisConnection conn=connectionFactory.getConnection(); - Ticket ticket = conn.getObject(PREFIX+ticketId); - conn.delete(PREFIX+ticketId); - conn.close(); - return ticket; - } + @Override + public Ticket remove(String ticketId) { + RedisConnection conn=connectionFactory.getConnection(); + Ticket ticket = conn.getObject(PREFIX+ticketId); + conn.delete(PREFIX+ticketId); + conn.close(); + return ticket; + } @Override public Ticket get(String ticketId) { @@ -78,5 +78,5 @@ public class RedisTicketGrantingTicketServices extends RandomServiceTicketServic return ticket; } - + } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/autoconfigure/CasAutoConfiguration.java b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/autoconfigure/CasAutoConfiguration.java index 8bc29e112..46ef70486 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/autoconfigure/CasAutoConfiguration.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/main/java/org/dromara/maxkey/autoconfigure/CasAutoConfiguration.java @@ -51,13 +51,13 @@ public class CasAutoConfiguration implements InitializingBean { TicketServices casTicketServices( @Value("${maxkey.server.persistence}") int persistence, RedisConnectionFactory redisConnFactory) { - _logger.debug("init casTicketServices."); - TicketServices casTicketServices = null; + _logger.debug("init casTicketServices."); + TicketServices casTicketServices = null; if (persistence == ConstsPersistence.REDIS) { casTicketServices = new RedisTicketServices(redisConnFactory); _logger.debug("RedisTicketServices"); }else { - casTicketServices = new InMemoryTicketServices(); + casTicketServices = new InMemoryTicketServices(); _logger.debug("InMemoryTicketServices"); } return casTicketServices; @@ -73,13 +73,13 @@ public class CasAutoConfiguration implements InitializingBean { TicketServices casTicketGrantingTicketServices( @Value("${maxkey.server.persistence}") int persistence, RedisConnectionFactory redisConnFactory) { - _logger.debug("init casTicketGrantingTicketServices."); - TicketServices casTicketServices = null; + _logger.debug("init casTicketGrantingTicketServices."); + TicketServices casTicketServices = null; if (persistence == ConstsPersistence.REDIS) { casTicketServices = new RedisTicketGrantingTicketServices(redisConnFactory); _logger.debug("RedisTicketGrantingTicketServices"); }else { - casTicketServices = new InMemoryTicketGrantingTicketServices(); + casTicketServices = new InMemoryTicketGrantingTicketServices(); _logger.debug("InMemoryTicketGrantingTicketServices"); } return casTicketServices; @@ -89,13 +89,13 @@ public class CasAutoConfiguration implements InitializingBean { TicketServices casProxyGrantingTicketServices( @Value("${maxkey.server.persistence}") int persistence, RedisConnectionFactory redisConnFactory) { - _logger.debug("init casTicketGrantingTicketServices."); - TicketServices casTicketServices = null; + _logger.debug("init casTicketGrantingTicketServices."); + TicketServices casTicketServices = null; if (persistence == ConstsPersistence.REDIS) { casTicketServices = new RedisProxyGrantingTicketServices(redisConnFactory); _logger.debug("RedisProxyGrantingTicketServices"); }else { - casTicketServices = new InMemoryProxyGrantingTicketServices(); + casTicketServices = new InMemoryProxyGrantingTicketServices(); _logger.debug("InMemoryProxyGrantingTicketServices"); } return casTicketServices; diff --git a/maxkey-protocols/maxkey-protocol-cas/src/test/java/org/maxkey/web/authorize/endpoint/cas/ticket/generator/DefaultUniqueTicketIdGeneratorTest.java b/maxkey-protocols/maxkey-protocol-cas/src/test/java/org/maxkey/web/authorize/endpoint/cas/ticket/generator/DefaultUniqueTicketIdGeneratorTest.java index 96472f616..1012189b7 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/test/java/org/maxkey/web/authorize/endpoint/cas/ticket/generator/DefaultUniqueTicketIdGeneratorTest.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/test/java/org/maxkey/web/authorize/endpoint/cas/ticket/generator/DefaultUniqueTicketIdGeneratorTest.java @@ -20,9 +20,9 @@ import org.dromara.maxkey.authz.cas.endpoint.ticket.generator.DefaultUniqueTicke public class DefaultUniqueTicketIdGeneratorTest { - public static void main(String[] args) { - DefaultUniqueTicketIdGenerator t=new DefaultUniqueTicketIdGenerator(); - System.out.println(t.getNewTicketId("ST")); - } + public static void main(String[] args) { + DefaultUniqueTicketIdGenerator t=new DefaultUniqueTicketIdGenerator(); + System.out.println(t.getNewTicketId("ST")); + } } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/test/java/org/maxkey/web/authorize/endpoint/cas/ticket/generator/InetAddressUtilsTest.java b/maxkey-protocols/maxkey-protocol-cas/src/test/java/org/maxkey/web/authorize/endpoint/cas/ticket/generator/InetAddressUtilsTest.java index 4569de970..33a300c79 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/test/java/org/maxkey/web/authorize/endpoint/cas/ticket/generator/InetAddressUtilsTest.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/test/java/org/maxkey/web/authorize/endpoint/cas/ticket/generator/InetAddressUtilsTest.java @@ -21,11 +21,11 @@ import org.dromara.maxkey.authz.cas.endpoint.ticket.generator.InetAddressUtils; public class InetAddressUtilsTest { - public InetAddressUtilsTest() { - } + public InetAddressUtilsTest() { + } - public static void main(String[] args) { - System.out.println(InetAddressUtils.getCasServerHostName()); - } + public static void main(String[] args) { + System.out.println(InetAddressUtils.getCasServerHostName()); + } } diff --git a/maxkey-protocols/maxkey-protocol-cas/src/test/java/org/maxkey/web/authorize/endpoint/response/ServiceResponseBuilderTest.java b/maxkey-protocols/maxkey-protocol-cas/src/test/java/org/maxkey/web/authorize/endpoint/response/ServiceResponseBuilderTest.java index 867e746de..f60b27b82 100644 --- a/maxkey-protocols/maxkey-protocol-cas/src/test/java/org/maxkey/web/authorize/endpoint/response/ServiceResponseBuilderTest.java +++ b/maxkey-protocols/maxkey-protocol-cas/src/test/java/org/maxkey/web/authorize/endpoint/response/ServiceResponseBuilderTest.java @@ -25,39 +25,39 @@ import org.dromara.maxkey.pretty.impl.XmlPretty; public class ServiceResponseBuilderTest { - public ServiceResponseBuilderTest() { - } + public ServiceResponseBuilderTest() { + } - public static void main(String[] args) throws Exception { - ServiceResponseBuilder srbJson=new ServiceResponseBuilder(); - srbJson.success() - .setUser("shi") - .setAttribute("bbb", "bbb") - .setAttribute("aaa", "1111") - .setAttribute("aaa", "222") - .setProxy("https://proxy1/pgtUrl") - .setProxy("https://proxy2/pgtUrl") - .setFormat("json"); - - System.out.println(srbJson.serviceResponseBuilder()); - System.out.println(new JsonPretty().format(srbJson.serviceResponseBuilder())); - - ServiceResponseBuilder srbXml=new ServiceResponseBuilder(); - srbXml.success() - .setUser("shi") - .setAttribute("bbb", "bbb") - .setAttribute("aaa", "1111") - .setAttribute("aaa", "222") - .setProxy("https://proxy1/pgtUrl") - .setProxy("https://proxy2/pgtUrl"); - System.out.println(new XmlPretty().format(srbXml.serviceResponseBuilder())); - - - ProxyServiceResponseBuilder psrbXml=new ProxyServiceResponseBuilder(); - psrbXml.success() - .setUser("shi") - .setTicket("PT-asdf-JESPjdnJjNjNmMUyTtGFjK"); - System.out.println(new XmlPretty().format(psrbXml.serviceResponseBuilder())); - } + public static void main(String[] args) throws Exception { + ServiceResponseBuilder srbJson=new ServiceResponseBuilder(); + srbJson.success() + .setUser("shi") + .setAttribute("bbb", "bbb") + .setAttribute("aaa", "1111") + .setAttribute("aaa", "222") + .setProxy("https://proxy1/pgtUrl") + .setProxy("https://proxy2/pgtUrl") + .setFormat("json"); + + System.out.println(srbJson.serviceResponseBuilder()); + System.out.println(new JsonPretty().format(srbJson.serviceResponseBuilder())); + + ServiceResponseBuilder srbXml=new ServiceResponseBuilder(); + srbXml.success() + .setUser("shi") + .setAttribute("bbb", "bbb") + .setAttribute("aaa", "1111") + .setAttribute("aaa", "222") + .setProxy("https://proxy1/pgtUrl") + .setProxy("https://proxy2/pgtUrl"); + System.out.println(new XmlPretty().format(srbXml.serviceResponseBuilder())); + + + ProxyServiceResponseBuilder psrbXml=new ProxyServiceResponseBuilder(); + psrbXml.success() + .setUser("shi") + .setTicket("PT-asdf-JESPjdnJjNjNmMUyTtGFjK"); + System.out.println(new XmlPretty().format(psrbXml.serviceResponseBuilder())); + } } diff --git a/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/ExtendApiAuthorizeEndpoint.java b/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/ExtendApiAuthorizeEndpoint.java index a70b410fa..8dc7eef42 100644 --- a/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/ExtendApiAuthorizeEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/ExtendApiAuthorizeEndpoint.java @@ -47,39 +47,39 @@ import jakarta.servlet.http.HttpServletRequest; @Tag(name = "2-8-ExtendApi接口文档模块") @Controller public class ExtendApiAuthorizeEndpoint extends AuthorizeBaseEndpoint{ - static final Logger _logger = LoggerFactory.getLogger(ExtendApiAuthorizeEndpoint.class); + static final Logger _logger = LoggerFactory.getLogger(ExtendApiAuthorizeEndpoint.class); - @Operation(summary = "ExtendApi认证地址接口", description = "参数应用ID") - @GetMapping("/authz/api/{id}") - public ModelAndView authorize( - HttpServletRequest request, - @PathVariable("id") String id, - @CurrentUser UserInfo currentUser){ - - ModelAndView modelAndView = new ModelAndView("authorize/redirect_sso_submit"); - modelAndView.addObject("errorCode", 0); - modelAndView.addObject("errorMessage", ""); - - Apps apps = getApp(id); - _logger.debug("{}" , apps); - if(ConstsBoolean.isTrue(apps.getIsAdapter())){ - _logger.debug("Adapter {}",apps.getAdapter()); - AbstractAuthorizeAdapter adapter = (AbstractAuthorizeAdapter)Instance.newInstance(apps.getAdapter()); - Accounts account = getAccounts(apps,currentUser); - if(apps.getCredential().equalsIgnoreCase(Apps.CREDENTIALS.USER_DEFINED) && account == null) { - return initCredentialView(id,"/authorize/api/"+id); - } - - adapter.setPrincipal(AuthorizationUtils.getPrincipal()); - adapter.setApp(apps); - adapter.setAccount(account); - - return adapter.authorize(modelAndView); - }else{ - _logger.debug("redirect_uri {}",apps.getLoginUrl()); - modelAndView.addObject("redirect_uri", apps.getLoginUrl()); - return modelAndView; - } - - } + @Operation(summary = "ExtendApi认证地址接口", description = "参数应用ID") + @GetMapping("/authz/api/{id}") + public ModelAndView authorize( + HttpServletRequest request, + @PathVariable("id") String id, + @CurrentUser UserInfo currentUser){ + + ModelAndView modelAndView = new ModelAndView("authorize/redirect_sso_submit"); + modelAndView.addObject("errorCode", 0); + modelAndView.addObject("errorMessage", ""); + + Apps apps = getApp(id); + _logger.debug("{}" , apps); + if(ConstsBoolean.isTrue(apps.getIsAdapter())){ + _logger.debug("Adapter {}",apps.getAdapter()); + AbstractAuthorizeAdapter adapter = (AbstractAuthorizeAdapter)Instance.newInstance(apps.getAdapter()); + Accounts account = getAccounts(apps,currentUser); + if(apps.getCredential().equalsIgnoreCase(Apps.CREDENTIALS.USER_DEFINED) && account == null) { + return initCredentialView(id,"/authorize/api/"+id); + } + + adapter.setPrincipal(AuthorizationUtils.getPrincipal()); + adapter.setApp(apps); + adapter.setAccount(account); + + return adapter.authorize(modelAndView); + }else{ + _logger.debug("redirect_uri {}",apps.getLoginUrl()); + modelAndView.addObject("redirect_uri", apps.getLoginUrl()); + return modelAndView; + } + + } } diff --git a/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/ExtendApiMetadata.java b/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/ExtendApiMetadata.java index 56ec0fa03..03adaa31e 100644 --- a/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/ExtendApiMetadata.java +++ b/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/ExtendApiMetadata.java @@ -35,16 +35,16 @@ import jakarta.servlet.http.HttpServletResponse; @Tag(name = "2-8-ExtendApi接口文档模块-元数据") @Controller public class ExtendApiMetadata { - static final Logger _logger = LoggerFactory.getLogger(ExtendApiMetadata.class); - - @Operation(summary = "netease qiye mail RSA Key", description = "网易企业邮箱RSA Key生成器",method="GET") - @RequestMapping( - value = "/metadata/netease/qiye/mail/rsa/gen", - method = {RequestMethod.POST, RequestMethod.GET}) - @ResponseBody - public String metadata(HttpServletRequest request,HttpServletResponse response) { - NeteaseRSATool neteaseRSATool =new NeteaseRSATool(); - neteaseRSATool.genRSAKeyPair(); - return JsonPretty.getInstance().formatln(neteaseRSATool); - } + static final Logger _logger = LoggerFactory.getLogger(ExtendApiMetadata.class); + + @Operation(summary = "netease qiye mail RSA Key", description = "网易企业邮箱RSA Key生成器",method="GET") + @RequestMapping( + value = "/metadata/netease/qiye/mail/rsa/gen", + method = {RequestMethod.POST, RequestMethod.GET}) + @ResponseBody + public String metadata(HttpServletRequest request,HttpServletResponse response) { + NeteaseRSATool neteaseRSATool =new NeteaseRSATool(); + neteaseRSATool.genRSAKeyPair(); + return JsonPretty.getInstance().formatln(neteaseRSATool); + } } diff --git a/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiCndnsApiMailAdapter.java b/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiCndnsApiMailAdapter.java index 55ba411e1..8baa01bef 100644 --- a/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiCndnsApiMailAdapter.java +++ b/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiCndnsApiMailAdapter.java @@ -38,88 +38,88 @@ import org.springframework.web.servlet.ModelAndView; * */ public class ExtendApiCndnsApiMailAdapter extends AbstractAuthorizeAdapter { - static final Logger _logger = LoggerFactory.getLogger(ExtendApiCndnsApiMailAdapter.class); - //sign no parameter - //sign=md5(action=getDomainInfo&appid=***&time=1579736456 + md5(token)) - //sign with parameter - //sign=md5(action=getUserInfo&appid=***&email=admin@maxkey.org&time=1579736456 + md5(token)) + static final Logger _logger = LoggerFactory.getLogger(ExtendApiCndnsApiMailAdapter.class); + //sign no parameter + //sign=md5(action=getDomainInfo&appid=***&time=1579736456 + md5(token)) + //sign with parameter + //sign=md5(action=getUserInfo&appid=***&email=admin@maxkey.org&time=1579736456 + md5(token)) - Accounts account; - - static String SIGN_STRING ="action=getDomainInfo&appid=%s%s"; - - static String SIGN_EMAIL_STRING ="action=getUserInfo&appid=%s&email=%s&time=%s%s"; - - static String ADMIN_AUTHKEY_URI ="https://www.cndnsapi.com/email/clientmanagement?action=getDomailUrl&appid=%s&sign=%s&time=%s"; - - static String AUTHKEY_URI ="https://www.cndnsapi.com/email/clientmanagement?action=getWebMailUrl&appid=%s&sign=%s&time=%s"; - - - @Override - public Object generateInfo() { - return null; - } - - @Override - public Object encrypt(Object data, String algorithmKey, String algorithm) { - return null; - } - - @SuppressWarnings("unchecked") + Accounts account; + + static String SIGN_STRING ="action=getDomainInfo&appid=%s%s"; + + static String SIGN_EMAIL_STRING ="action=getUserInfo&appid=%s&email=%s&time=%s%s"; + + static String ADMIN_AUTHKEY_URI ="https://www.cndnsapi.com/email/clientmanagement?action=getDomailUrl&appid=%s&sign=%s&time=%s"; + + static String AUTHKEY_URI ="https://www.cndnsapi.com/email/clientmanagement?action=getWebMailUrl&appid=%s&sign=%s&time=%s"; + + @Override - public ModelAndView authorize(ModelAndView modelAndView) { - HttpsTrusts.beforeConnection(); - - Apps details=(Apps)app; - //extraAttrs from Applications - ExtraAttrs extraAttrs=null; - String action = "getWebMailUrl"; - String domain = null; - if(details.getIsExtendAttr()==1){ - extraAttrs=new ExtraAttrs(details.getExtendAttr()); - if(extraAttrs.get("action")==null || extraAttrs.get("action").equalsIgnoreCase("getWebMailUrl")) { - action = "getWebMailUrl"; - }else if(extraAttrs.get("action").equalsIgnoreCase("getDomailUrl")){ - action = "getDomailUrl"; - domain = extraAttrs.get("domain"); - } - } - - String timestamp = ""+Instant.now().getEpochSecond(); - - String tokenMd5 =DigestUtils.md5Hex(details.getCredentials()); - HashMap requestParamenter =new HashMap(); - String redirect_uri = ""; - if(action.equalsIgnoreCase("getDomailUrl")) { - String sign =DigestUtils.md5Hex - (String.format( - SIGN_STRING, - details.getPrincipal(),timestamp,tokenMd5)); - requestParamenter.put("domain", domain); - String responseBody = new HttpRequestAdapter().post( - String.format(ADMIN_AUTHKEY_URI,details.getPrincipal(),sign,timestamp),requestParamenter); - - HashMap authKey=JsonUtils.gsonStringToObject(responseBody, HashMap.class); - redirect_uri = authKey.get("adminUrl"); - - }else { - String sign =DigestUtils.md5Hex - (String.format( - SIGN_EMAIL_STRING, - details.getPrincipal(),userInfo.getEmail(),timestamp,tokenMd5)); - requestParamenter.put("email", userInfo.getWorkEmail()); - String responseBody = new HttpRequestAdapter().post( - String.format(AUTHKEY_URI,details.getPrincipal(),sign,timestamp),requestParamenter); - - HashMap authKey=JsonUtils.gsonStringToObject(responseBody, HashMap.class); - redirect_uri=authKey.get("webmailUrl"); - } - - _logger.debug("redirect_uri : "+redirect_uri); - + public Object generateInfo() { + return null; + } + + @Override + public Object encrypt(Object data, String algorithmKey, String algorithm) { + return null; + } + + @SuppressWarnings("unchecked") + @Override + public ModelAndView authorize(ModelAndView modelAndView) { + HttpsTrusts.beforeConnection(); + + Apps details=(Apps)app; + //extraAttrs from Applications + ExtraAttrs extraAttrs=null; + String action = "getWebMailUrl"; + String domain = null; + if(details.getIsExtendAttr()==1){ + extraAttrs=new ExtraAttrs(details.getExtendAttr()); + if(extraAttrs.get("action")==null || extraAttrs.get("action").equalsIgnoreCase("getWebMailUrl")) { + action = "getWebMailUrl"; + }else if(extraAttrs.get("action").equalsIgnoreCase("getDomailUrl")){ + action = "getDomailUrl"; + domain = extraAttrs.get("domain"); + } + } + + String timestamp = ""+Instant.now().getEpochSecond(); + + String tokenMd5 =DigestUtils.md5Hex(details.getCredentials()); + HashMap requestParamenter =new HashMap(); + String redirect_uri = ""; + if(action.equalsIgnoreCase("getDomailUrl")) { + String sign =DigestUtils.md5Hex + (String.format( + SIGN_STRING, + details.getPrincipal(),timestamp,tokenMd5)); + requestParamenter.put("domain", domain); + String responseBody = new HttpRequestAdapter().post( + String.format(ADMIN_AUTHKEY_URI,details.getPrincipal(),sign,timestamp),requestParamenter); + + HashMap authKey=JsonUtils.gsonStringToObject(responseBody, HashMap.class); + redirect_uri = authKey.get("adminUrl"); + + }else { + String sign =DigestUtils.md5Hex + (String.format( + SIGN_EMAIL_STRING, + details.getPrincipal(),userInfo.getEmail(),timestamp,tokenMd5)); + requestParamenter.put("email", userInfo.getWorkEmail()); + String responseBody = new HttpRequestAdapter().post( + String.format(AUTHKEY_URI,details.getPrincipal(),sign,timestamp),requestParamenter); + + HashMap authKey=JsonUtils.gsonStringToObject(responseBody, HashMap.class); + redirect_uri=authKey.get("webmailUrl"); + } + + _logger.debug("redirect_uri : "+redirect_uri); + modelAndView.addObject("redirect_uri", redirect_uri); return modelAndView; - } + } } diff --git a/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiNeteaseQiyeMailAdapter.java b/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiNeteaseQiyeMailAdapter.java index d7340d03f..d2e04ee0f 100644 --- a/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiNeteaseQiyeMailAdapter.java +++ b/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiNeteaseQiyeMailAdapter.java @@ -35,60 +35,60 @@ import org.springframework.web.servlet.ModelAndView; * */ public class ExtendApiNeteaseQiyeMailAdapter extends AbstractAuthorizeAdapter { - static final Logger _logger = LoggerFactory.getLogger(ExtendApiNeteaseQiyeMailAdapter.class); - //https://entryhz.qiye.163.com - static String REDIRECT_PARAMETER = "domain=%s&account_name=%s&time=%s&enc=%s&lang=%s"; - - static String DEFAULT_REDIRECT_URI ="https://entryhz.qiye.163.com/domain/oa/Entry"; + static final Logger _logger = LoggerFactory.getLogger(ExtendApiNeteaseQiyeMailAdapter.class); + //https://entryhz.qiye.163.com + static String REDIRECT_PARAMETER = "domain=%s&account_name=%s&time=%s&enc=%s&lang=%s"; + + static String DEFAULT_REDIRECT_URI ="https://entryhz.qiye.163.com/domain/oa/Entry"; - Accounts account; - - @Override - public Object generateInfo() { - return null; - } + Accounts account; @Override - public ModelAndView authorize(ModelAndView modelAndView) { - - Apps details=(Apps)app; - StringBuffer redirect_uri = new StringBuffer(details.getLoginUrl()); - if(StringUtils.isNotBlank(redirect_uri)) { - if(redirect_uri.indexOf("?")>-1) { - redirect_uri.append("").append( REDIRECT_PARAMETER); - }else { - redirect_uri.append("?").append( REDIRECT_PARAMETER); - } - } - //extraAttrs from App - ExtraAttrs extraAttrs=null; - if(details.getIsExtendAttr() == 1){ - extraAttrs = new ExtraAttrs(details.getExtendAttr()); - for(ExtraAttr attr : extraAttrs.getExtraAttrs()) { - redirect_uri.append("&").append(attr.getAttr()).append("=").append(attr.getValue()); - } - } - - String time = System.currentTimeMillis() + ""; - //域名,请使用企业自己的域名 - String domain = details.getPrincipal(); - - String account_name = this.userInfo.getEmail().substring(0, this.userInfo.getEmail().indexOf("@")); - - String lang = "0"; - String src = account_name + domain + time; - - String privateKey = details.getCredentials(); - _logger.debug("Private Key {} " , privateKey); - - String enc = new NeteaseRSATool().generateSHA1withRSASigature(src, privateKey); - String loginUrl = String.format(redirect_uri.toString(), domain,account_name,time,enc,lang); - - _logger.debug("LoginUrl {} " , loginUrl); - modelAndView.addObject("redirect_uri", loginUrl); + public Object generateInfo() { + return null; + } + + @Override + public ModelAndView authorize(ModelAndView modelAndView) { + + Apps details=(Apps)app; + StringBuffer redirect_uri = new StringBuffer(details.getLoginUrl()); + if(StringUtils.isNotBlank(redirect_uri)) { + if(redirect_uri.indexOf("?")>-1) { + redirect_uri.append("").append( REDIRECT_PARAMETER); + }else { + redirect_uri.append("?").append( REDIRECT_PARAMETER); + } + } + //extraAttrs from App + ExtraAttrs extraAttrs=null; + if(details.getIsExtendAttr() == 1){ + extraAttrs = new ExtraAttrs(details.getExtendAttr()); + for(ExtraAttr attr : extraAttrs.getExtraAttrs()) { + redirect_uri.append("&").append(attr.getAttr()).append("=").append(attr.getValue()); + } + } + + String time = System.currentTimeMillis() + ""; + //域名,请使用企业自己的域名 + String domain = details.getPrincipal(); + + String account_name = this.userInfo.getEmail().substring(0, this.userInfo.getEmail().indexOf("@")); + + String lang = "0"; + String src = account_name + domain + time; + + String privateKey = details.getCredentials(); + _logger.debug("Private Key {} " , privateKey); + + String enc = new NeteaseRSATool().generateSHA1withRSASigature(src, privateKey); + String loginUrl = String.format(redirect_uri.toString(), domain,account_name,time,enc,lang); + + _logger.debug("LoginUrl {} " , loginUrl); + modelAndView.addObject("redirect_uri", loginUrl); return modelAndView; - } + } } diff --git a/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiQQExmailAdapter.java b/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiQQExmailAdapter.java index d3b10176d..21c5fe2f4 100644 --- a/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiQQExmailAdapter.java +++ b/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiQQExmailAdapter.java @@ -41,276 +41,276 @@ import com.github.benmanes.caffeine.cache.Caffeine; * */ public class ExtendApiQQExmailAdapter extends AbstractAuthorizeAdapter { - static final Logger _logger = LoggerFactory.getLogger(ExtendApiQQExmailAdapter.class); - //https://exmail.qq.com/qy_mng_logic/doc#10003 - static String TOKEN_URI = "https://api.exmail.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s"; - //https://exmail.qq.com/qy_mng_logic/doc#10036 - static String AUTHKEY_URI = "https://api.exmail.qq.com/cgi-bin/service/get_login_url?access_token=%s&userid=%s"; - - static final Cache tokenCache = Caffeine.newBuilder() - .expireAfterWrite(7200, TimeUnit.SECONDS) - .build(); - - Accounts account; - - @Override - public Object generateInfo() { - return null; - } + static final Logger _logger = LoggerFactory.getLogger(ExtendApiQQExmailAdapter.class); + //https://exmail.qq.com/qy_mng_logic/doc#10003 + static String TOKEN_URI = "https://api.exmail.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s"; + //https://exmail.qq.com/qy_mng_logic/doc#10036 + static String AUTHKEY_URI = "https://api.exmail.qq.com/cgi-bin/service/get_login_url?access_token=%s&userid=%s"; + + static final Cache tokenCache = Caffeine.newBuilder() + .expireAfterWrite(7200, TimeUnit.SECONDS) + .build(); + + Accounts account; + + @Override + public Object generateInfo() { + return null; + } @Override - public ModelAndView authorize(ModelAndView modelAndView) { - HttpsTrusts.beforeConnection(); - - Apps details=(Apps)app; - //extraAttrs from Applications - ExtraAttrs extraAttrs=null; - if(details.getIsExtendAttr()==1){ - extraAttrs=new ExtraAttrs(details.getExtendAttr()); - } - - _logger.debug("Extra Attrs {}",extraAttrs); - - String accessToken = getToken(details.getPrincipal(),details.getCredentials()); - - ExMailLoginUrl exMailLoginUrl = getLoginUrl(accessToken,userInfo.getUsername()); - - if(exMailLoginUrl.errcode == 0) { - modelAndView.addObject("redirect_uri", exMailLoginUrl.getLogin_url()); - }else { - _logger.error("Exception code {} , message {} , mapping message {} ,", - exMailLoginUrl.getErrcode(), - exMailLoginUrl.getErrmsg(), - exMailMsgMapper.get(exMailLoginUrl.getErrcode()) - ); - //remove accessToken - tokenCache.invalidate(details.getPrincipal()); - modelAndView.addObject("errorCode", exMailLoginUrl.getErrcode()); - modelAndView.addObject("errorMessage", exMailMsgMapper.get(exMailLoginUrl.getErrcode())); - } + public ModelAndView authorize(ModelAndView modelAndView) { + HttpsTrusts.beforeConnection(); + + Apps details=(Apps)app; + //extraAttrs from Applications + ExtraAttrs extraAttrs=null; + if(details.getIsExtendAttr()==1){ + extraAttrs=new ExtraAttrs(details.getExtendAttr()); + } + + _logger.debug("Extra Attrs {}",extraAttrs); + + String accessToken = getToken(details.getPrincipal(),details.getCredentials()); + + ExMailLoginUrl exMailLoginUrl = getLoginUrl(accessToken,userInfo.getUsername()); + + if(exMailLoginUrl.errcode == 0) { + modelAndView.addObject("redirect_uri", exMailLoginUrl.getLogin_url()); + }else { + _logger.error("Exception code {} , message {} , mapping message {} ,", + exMailLoginUrl.getErrcode(), + exMailLoginUrl.getErrmsg(), + exMailMsgMapper.get(exMailLoginUrl.getErrcode()) + ); + //remove accessToken + tokenCache.invalidate(details.getPrincipal()); + modelAndView.addObject("errorCode", exMailLoginUrl.getErrcode()); + modelAndView.addObject("errorMessage", exMailMsgMapper.get(exMailLoginUrl.getErrcode())); + } return modelAndView; - } + } public String getToken(String corpid , String corpsecret) { - String accessToken = tokenCache.getIfPresent(corpid); - if(accessToken == null) { - _logger.debug("corpid {} , corpsecret {}" , corpid , corpsecret); - _logger.debug("get token url {}" , String.format(TOKEN_URI,corpid,corpsecret)); - String responseBody = new HttpRequestAdapter().get(String.format(TOKEN_URI,corpid,corpsecret),null); - _logger.debug("Response Body {}" , responseBody); - Token token = JsonUtils.gsonStringToObject(responseBody,Token.class); - if(token.getErrcode() == 0 ) { - _logger.debug("access_token {}" , token); - accessToken = token.getAccess_token(); - tokenCache.put(corpid, accessToken); - }else { - _logger.debug("Error Code {}" , exMailMsgMapper.get(token.getErrcode()));; - } - } - return accessToken; + String accessToken = tokenCache.getIfPresent(corpid); + if(accessToken == null) { + _logger.debug("corpid {} , corpsecret {}" , corpid , corpsecret); + _logger.debug("get token url {}" , String.format(TOKEN_URI,corpid,corpsecret)); + String responseBody = new HttpRequestAdapter().get(String.format(TOKEN_URI,corpid,corpsecret),null); + _logger.debug("Response Body {}" , responseBody); + Token token = JsonUtils.gsonStringToObject(responseBody,Token.class); + if(token.getErrcode() == 0 ) { + _logger.debug("access_token {}" , token); + accessToken = token.getAccess_token(); + tokenCache.put(corpid, accessToken); + }else { + _logger.debug("Error Code {}" , exMailMsgMapper.get(token.getErrcode()));; + } + } + return accessToken; } public ExMailLoginUrl getLoginUrl(String accessToken,String userId) { - if(accessToken != null) { - _logger.debug("userId {}" , userId); - String authKeyBody = new HttpRequestAdapter().get(String.format(AUTHKEY_URI,accessToken,userId),null); - - ExMailLoginUrl exMailLoginUrl = JsonUtils.gsonStringToObject(authKeyBody, ExMailLoginUrl.class); - _logger.debug("LoginUrl {} " , exMailLoginUrl); - return exMailLoginUrl; - } - return new ExMailLoginUrl(-1,"access_token is null ."); + if(accessToken != null) { + _logger.debug("userId {}" , userId); + String authKeyBody = new HttpRequestAdapter().get(String.format(AUTHKEY_URI,accessToken,userId),null); + + ExMailLoginUrl exMailLoginUrl = JsonUtils.gsonStringToObject(authKeyBody, ExMailLoginUrl.class); + _logger.debug("LoginUrl {} " , exMailLoginUrl); + return exMailLoginUrl; + } + return new ExMailLoginUrl(-1,"access_token is null ."); } - class ExMailMsg{ - - protected long expires_in; - - protected String errmsg; - - protected Integer errcode; + class ExMailMsg{ + + protected long expires_in; + + protected String errmsg; + + protected Integer errcode; - public ExMailMsg() { - } + public ExMailMsg() { + } - public long getExpires_in() { - return expires_in; - } + public long getExpires_in() { + return expires_in; + } - public void setExpires_in(long expires_in) { - this.expires_in = expires_in; - } + public void setExpires_in(long expires_in) { + this.expires_in = expires_in; + } - public String getErrmsg() { - return errmsg; - } + public String getErrmsg() { + return errmsg; + } - public void setErrmsg(String errmsg) { - this.errmsg = errmsg; - } + public void setErrmsg(String errmsg) { + this.errmsg = errmsg; + } - public Integer getErrcode() { - return errcode; - } + public Integer getErrcode() { + return errcode; + } - public void setErrcode(Integer errcode) { - this.errcode = errcode; - } - } - - class Token extends ExMailMsg implements Serializable { - private static final long serialVersionUID = 275756585220635542L; + public void setErrcode(Integer errcode) { + this.errcode = errcode; + } + } + + class Token extends ExMailMsg implements Serializable { + private static final long serialVersionUID = 275756585220635542L; - /** - * access_token - */ - private String access_token; - - public String getAccess_token() { - return access_token; - } + /** + * access_token + */ + private String access_token; + + public String getAccess_token() { + return access_token; + } - public void setAccess_token(String access_token) { - this.access_token = access_token; - } + public void setAccess_token(String access_token) { + this.access_token = access_token; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Token [access_token = "); - builder.append(access_token); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Token [access_token = "); + builder.append(access_token); + builder.append("]"); + return builder.toString(); + } - } - - class ExMailLoginUrl extends ExMailMsg implements Serializable { - private static final long serialVersionUID = 3033047757268214198L; - private String login_url; - - public String getLogin_url() { - return login_url; - } + } + + class ExMailLoginUrl extends ExMailMsg implements Serializable { + private static final long serialVersionUID = 3033047757268214198L; + private String login_url; + + public String getLogin_url() { + return login_url; + } - public void setLogin_url(String login_url) { - this.login_url = login_url; - } - - public ExMailLoginUrl() { - } - - public ExMailLoginUrl(Integer errcode,String errmsg) { - super.errcode = errcode; - super.errmsg = errmsg; - } + public void setLogin_url(String login_url) { + this.login_url = login_url; + } + + public ExMailLoginUrl() { + } + + public ExMailLoginUrl(Integer errcode,String errmsg) { + super.errcode = errcode; + super.errmsg = errmsg; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("LoginUrl [login_url="); - builder.append(login_url); - builder.append("]"); - return builder.toString(); - } - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("LoginUrl [login_url="); + builder.append(login_url); + builder.append("]"); + return builder.toString(); + } + } - public static HashMap exMailMsgMapper = new HashMap(); - - static { - exMailMsgMapper.put(-1, "系统繁忙"); - exMailMsgMapper.put(0, "请求成功"); - exMailMsgMapper.put(40001, "获取access_token时CorpSecret错误,或者access_token无效"); - exMailMsgMapper.put(40003, "不合法的UserID"); - exMailMsgMapper.put(40013, "不合法的corpid"); - exMailMsgMapper.put(40014, "不合法的access_token"); - exMailMsgMapper.put(40057, "不合法的callbackurl或者callbackurl验证失败"); - exMailMsgMapper.put(40091, "无效secert"); - exMailMsgMapper.put(40092, "参数不合法"); - exMailMsgMapper.put(40093, "请求并发过大,请降低并发并重试"); - exMailMsgMapper.put(45009, "接口调用超过限制"); - exMailMsgMapper.put(45024, "帐号数量超过上限"); - exMailMsgMapper.put(50005, "企业已禁用"); - exMailMsgMapper.put(60001, "部门长度不符合限制"); - exMailMsgMapper.put(60002, "部门层级深度超过限制"); - exMailMsgMapper.put(60003, "部门不存在"); - exMailMsgMapper.put(60004, "父部门不存在"); - exMailMsgMapper.put(60005, "不允许删除有成员的部门"); - exMailMsgMapper.put(60006, "不允许删除有子部门的部门"); - exMailMsgMapper.put(60007, "不允许删除根部门"); - exMailMsgMapper.put(60008, "部门名称已存在"); - exMailMsgMapper.put(60009, "部门名称含有非法字符"); - exMailMsgMapper.put(60010, "部门存在循环关系"); - exMailMsgMapper.put(60102, "UserID已存在"); - exMailMsgMapper.put(60103, "手机号码不合法"); - exMailMsgMapper.put(60104, "不合法的position参数"); - exMailMsgMapper.put(60105, "部门ID数量超过上限"); - exMailMsgMapper.put(60106, "不合法的userlist参数"); - exMailMsgMapper.put(60111, "UserID不存在"); - exMailMsgMapper.put(60112, "成员姓名不合法"); - exMailMsgMapper.put(60114, "性别不合法"); - exMailMsgMapper.put(60115, "激活码格式错误"); - exMailMsgMapper.put(60116, "邮箱回收站内已存在相同的帐号"); - exMailMsgMapper.put(60118, "userid在企业微信重复"); - exMailMsgMapper.put(60119, "用户未绑定(删除、回收站状态)"); - exMailMsgMapper.put(60120, "密码和手机号不能同时为空"); - exMailMsgMapper.put(60123, "无效的部门id"); - exMailMsgMapper.put(60124, "无效的父部门id"); - exMailMsgMapper.put(60125, "非法部门名字,长度超过限制、重名等,重名包括与csv文件中同级部门重名或者与旧组织架构包含成员的同级部门重名"); - exMailMsgMapper.put(60126, "创建部门失败"); - exMailMsgMapper.put(60127, "缺少部门id"); - exMailMsgMapper.put(60128, "帐号已绑定手机或微信,需员工修改密码"); - exMailMsgMapper.put(60201, "不合法的标签id"); - exMailMsgMapper.put(60202, "缺少标签id"); - exMailMsgMapper.put(60203, "不合法的标签名"); - exMailMsgMapper.put(60204, "标签名已存在"); - exMailMsgMapper.put(60205, "所有参数都非法"); - exMailMsgMapper.put(60301, "不合法的type参数"); - exMailMsgMapper.put(60302, "不合法的option参数"); - exMailMsgMapper.put(600001, "Userid与别名冲突"); - exMailMsgMapper.put(600002, "Userid与Groupid冲突"); - exMailMsgMapper.put(600003, "无效密码或者是弱密码"); - exMailMsgMapper.put(600004, "别名无效"); - exMailMsgMapper.put(600005, "别名与userid或者Groupid冲突"); - exMailMsgMapper.put(600006, "别名数量达到上限"); - exMailMsgMapper.put(600007, "Groupid无效"); - exMailMsgMapper.put(600008, "邮件群组不存在"); - exMailMsgMapper.put(600009, "群组成员为空"); - exMailMsgMapper.put(600010, "Userlist无效,可能是个别成员无效"); - exMailMsgMapper.put(600011, "Grouplist无效,可能是个别成员无效"); - exMailMsgMapper.put(600012, "Partylist无效,可能是个别成员无效"); - exMailMsgMapper.put(600013, "群发权限类型无效"); - exMailMsgMapper.put(600014, "群发权限成员无效"); - exMailMsgMapper.put(600015, "邮件群组已存在"); - exMailMsgMapper.put(600016, "Userlist部分成员未找到"); - exMailMsgMapper.put(600017, "Partylist部分成员未找到"); - exMailMsgMapper.put(600018, "Grouplist部分成员未找到"); - exMailMsgMapper.put(600019, "邮件群组名称含有非法字符"); - exMailMsgMapper.put(600020, "邮件群组存在循环"); - exMailMsgMapper.put(600021, "邮件群组嵌套超过层数"); - exMailMsgMapper.put(600023, "群发权限成员缺失"); - exMailMsgMapper.put(600024, "Groupid与userid或者别名冲突"); - exMailMsgMapper.put(600025, "座机号码无效"); - exMailMsgMapper.put(600026, "编号无效"); - exMailMsgMapper.put(600027, "批量检查的成员数超过限额"); - exMailMsgMapper.put(600034, "不合法的fuzzy参数"); - exMailMsgMapper.put(600035, "不合法的业务邮箱账号"); - exMailMsgMapper.put(600036, "密码不允许修改"); - exMailMsgMapper.put(600037, "不合法的业务邮箱ID"); - exMailMsgMapper.put(600038, "不合法的业务邮箱名称"); - exMailMsgMapper.put(600039, "业务邮箱账号已存在"); - exMailMsgMapper.put(600040, "业务邮箱名称已存在"); - exMailMsgMapper.put(600041, "业务邮箱ID不存在"); - exMailMsgMapper.put(601001, "日志查询的时间无效"); - exMailMsgMapper.put(601002, "日志查询的时间超过限制"); - exMailMsgMapper.put(601003, "日志查询的域名无效"); - exMailMsgMapper.put(601004, "日志查询的域名不存在"); - exMailMsgMapper.put(601005, "不合法的mailtype参数"); - exMailMsgMapper.put(601006, "不合法的type参数"); - exMailMsgMapper.put(602005, "应用没有访问此API的权限"); - exMailMsgMapper.put(604001, "基础版企业无权限操作专业版功能"); - exMailMsgMapper.put(604002, "企业VIP人员达到上限"); - exMailMsgMapper.put(604003, "不合法的setvip参数"); - } + public static HashMap exMailMsgMapper = new HashMap(); + + static { + exMailMsgMapper.put(-1, "系统繁忙"); + exMailMsgMapper.put(0, "请求成功"); + exMailMsgMapper.put(40001, "获取access_token时CorpSecret错误,或者access_token无效"); + exMailMsgMapper.put(40003, "不合法的UserID"); + exMailMsgMapper.put(40013, "不合法的corpid"); + exMailMsgMapper.put(40014, "不合法的access_token"); + exMailMsgMapper.put(40057, "不合法的callbackurl或者callbackurl验证失败"); + exMailMsgMapper.put(40091, "无效secert"); + exMailMsgMapper.put(40092, "参数不合法"); + exMailMsgMapper.put(40093, "请求并发过大,请降低并发并重试"); + exMailMsgMapper.put(45009, "接口调用超过限制"); + exMailMsgMapper.put(45024, "帐号数量超过上限"); + exMailMsgMapper.put(50005, "企业已禁用"); + exMailMsgMapper.put(60001, "部门长度不符合限制"); + exMailMsgMapper.put(60002, "部门层级深度超过限制"); + exMailMsgMapper.put(60003, "部门不存在"); + exMailMsgMapper.put(60004, "父部门不存在"); + exMailMsgMapper.put(60005, "不允许删除有成员的部门"); + exMailMsgMapper.put(60006, "不允许删除有子部门的部门"); + exMailMsgMapper.put(60007, "不允许删除根部门"); + exMailMsgMapper.put(60008, "部门名称已存在"); + exMailMsgMapper.put(60009, "部门名称含有非法字符"); + exMailMsgMapper.put(60010, "部门存在循环关系"); + exMailMsgMapper.put(60102, "UserID已存在"); + exMailMsgMapper.put(60103, "手机号码不合法"); + exMailMsgMapper.put(60104, "不合法的position参数"); + exMailMsgMapper.put(60105, "部门ID数量超过上限"); + exMailMsgMapper.put(60106, "不合法的userlist参数"); + exMailMsgMapper.put(60111, "UserID不存在"); + exMailMsgMapper.put(60112, "成员姓名不合法"); + exMailMsgMapper.put(60114, "性别不合法"); + exMailMsgMapper.put(60115, "激活码格式错误"); + exMailMsgMapper.put(60116, "邮箱回收站内已存在相同的帐号"); + exMailMsgMapper.put(60118, "userid在企业微信重复"); + exMailMsgMapper.put(60119, "用户未绑定(删除、回收站状态)"); + exMailMsgMapper.put(60120, "密码和手机号不能同时为空"); + exMailMsgMapper.put(60123, "无效的部门id"); + exMailMsgMapper.put(60124, "无效的父部门id"); + exMailMsgMapper.put(60125, "非法部门名字,长度超过限制、重名等,重名包括与csv文件中同级部门重名或者与旧组织架构包含成员的同级部门重名"); + exMailMsgMapper.put(60126, "创建部门失败"); + exMailMsgMapper.put(60127, "缺少部门id"); + exMailMsgMapper.put(60128, "帐号已绑定手机或微信,需员工修改密码"); + exMailMsgMapper.put(60201, "不合法的标签id"); + exMailMsgMapper.put(60202, "缺少标签id"); + exMailMsgMapper.put(60203, "不合法的标签名"); + exMailMsgMapper.put(60204, "标签名已存在"); + exMailMsgMapper.put(60205, "所有参数都非法"); + exMailMsgMapper.put(60301, "不合法的type参数"); + exMailMsgMapper.put(60302, "不合法的option参数"); + exMailMsgMapper.put(600001, "Userid与别名冲突"); + exMailMsgMapper.put(600002, "Userid与Groupid冲突"); + exMailMsgMapper.put(600003, "无效密码或者是弱密码"); + exMailMsgMapper.put(600004, "别名无效"); + exMailMsgMapper.put(600005, "别名与userid或者Groupid冲突"); + exMailMsgMapper.put(600006, "别名数量达到上限"); + exMailMsgMapper.put(600007, "Groupid无效"); + exMailMsgMapper.put(600008, "邮件群组不存在"); + exMailMsgMapper.put(600009, "群组成员为空"); + exMailMsgMapper.put(600010, "Userlist无效,可能是个别成员无效"); + exMailMsgMapper.put(600011, "Grouplist无效,可能是个别成员无效"); + exMailMsgMapper.put(600012, "Partylist无效,可能是个别成员无效"); + exMailMsgMapper.put(600013, "群发权限类型无效"); + exMailMsgMapper.put(600014, "群发权限成员无效"); + exMailMsgMapper.put(600015, "邮件群组已存在"); + exMailMsgMapper.put(600016, "Userlist部分成员未找到"); + exMailMsgMapper.put(600017, "Partylist部分成员未找到"); + exMailMsgMapper.put(600018, "Grouplist部分成员未找到"); + exMailMsgMapper.put(600019, "邮件群组名称含有非法字符"); + exMailMsgMapper.put(600020, "邮件群组存在循环"); + exMailMsgMapper.put(600021, "邮件群组嵌套超过层数"); + exMailMsgMapper.put(600023, "群发权限成员缺失"); + exMailMsgMapper.put(600024, "Groupid与userid或者别名冲突"); + exMailMsgMapper.put(600025, "座机号码无效"); + exMailMsgMapper.put(600026, "编号无效"); + exMailMsgMapper.put(600027, "批量检查的成员数超过限额"); + exMailMsgMapper.put(600034, "不合法的fuzzy参数"); + exMailMsgMapper.put(600035, "不合法的业务邮箱账号"); + exMailMsgMapper.put(600036, "密码不允许修改"); + exMailMsgMapper.put(600037, "不合法的业务邮箱ID"); + exMailMsgMapper.put(600038, "不合法的业务邮箱名称"); + exMailMsgMapper.put(600039, "业务邮箱账号已存在"); + exMailMsgMapper.put(600040, "业务邮箱名称已存在"); + exMailMsgMapper.put(600041, "业务邮箱ID不存在"); + exMailMsgMapper.put(601001, "日志查询的时间无效"); + exMailMsgMapper.put(601002, "日志查询的时间超过限制"); + exMailMsgMapper.put(601003, "日志查询的域名无效"); + exMailMsgMapper.put(601004, "日志查询的域名不存在"); + exMailMsgMapper.put(601005, "不合法的mailtype参数"); + exMailMsgMapper.put(601006, "不合法的type参数"); + exMailMsgMapper.put(602005, "应用没有访问此API的权限"); + exMailMsgMapper.put(604001, "基础版企业无权限操作专业版功能"); + exMailMsgMapper.put(604002, "企业VIP人员达到上限"); + exMailMsgMapper.put(604003, "不合法的setvip参数"); + } } diff --git a/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiTimestampSignAdapter.java b/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiTimestampSignAdapter.java index 5c748d4c8..8bdfc72b6 100644 --- a/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiTimestampSignAdapter.java +++ b/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiTimestampSignAdapter.java @@ -32,66 +32,66 @@ import org.springframework.web.servlet.ModelAndView; * http://target.maxkey.org/demo/login?code=maxkey&time=timestamp&token=token * login url http://target.maxkey.org/demo/login?code=%s×tamp=%s&token=%s * - * $code = 'maxkey'; - * $key = 'a5246932b0f371263c252384076cd3f0'; - * $timestamp = '1557034496'; - * $token = md5($code . $key . $time); + * $code = 'maxkey'; + * $key = 'a5246932b0f371263c252384076cd3f0'; + * $timestamp = '1557034496'; + * $token = md5($code . $key . $time); * * @author shimingxy * */ public class ExtendApiTimestampSignAdapter extends AbstractAuthorizeAdapter { - static final Logger _logger = LoggerFactory.getLogger(ExtendApiTimestampSignAdapter.class); - - Accounts account; - - @Override - public Object generateInfo() { - return null; - } + static final Logger _logger = LoggerFactory.getLogger(ExtendApiTimestampSignAdapter.class); + + Accounts account; + + @Override + public Object generateInfo() { + return null; + } - @Override - public Object encrypt(Object data, String algorithmKey, String algorithm) { - return null; - } + @Override + public Object encrypt(Object data, String algorithmKey, String algorithm) { + return null; + } - @Override - public ModelAndView authorize(ModelAndView modelAndView) { - Apps details=(Apps)app; - - String code = details.getPrincipal(); - String key = details.getCredentials(); - String timestamp = ""+Instant.now().getEpochSecond(); - String token =DigestUtils.md5Hex(code+key+timestamp); - - //extraAttrs from Applications - ExtraAttrs extraAttrs=null; - if(details.getIsExtendAttr()==1){ - extraAttrs=new ExtraAttrs(details.getExtendAttr()); - if(extraAttrs.get("sign") == null || extraAttrs.get("sign").equalsIgnoreCase("md5")) { - - }else if(extraAttrs.get("sign").equalsIgnoreCase("sha") || extraAttrs.get("sign").equalsIgnoreCase("sha1")) { - token =DigestUtils.shaHex(code+key+timestamp); - }else if(extraAttrs.get("sign").equalsIgnoreCase("sha256")) { - token =DigestUtils.sha256Hex(code+key+timestamp); - }else if(extraAttrs.get("sign").equalsIgnoreCase("sha384")) { - token =DigestUtils.sha384Hex(code+key+timestamp); - }else if(extraAttrs.get("sign").equalsIgnoreCase("sha512")) { - token =DigestUtils.sha512Hex(code+key+timestamp); - } - } - - _logger.debug(""+token); - String account = userInfo.getUsername(); - - String redirect_uri = String.format(details.getLoginUrl(),account,code,timestamp,token); + @Override + public ModelAndView authorize(ModelAndView modelAndView) { + Apps details=(Apps)app; + + String code = details.getPrincipal(); + String key = details.getCredentials(); + String timestamp = ""+Instant.now().getEpochSecond(); + String token =DigestUtils.md5Hex(code+key+timestamp); + + //extraAttrs from Applications + ExtraAttrs extraAttrs=null; + if(details.getIsExtendAttr()==1){ + extraAttrs=new ExtraAttrs(details.getExtendAttr()); + if(extraAttrs.get("sign") == null || extraAttrs.get("sign").equalsIgnoreCase("md5")) { + + }else if(extraAttrs.get("sign").equalsIgnoreCase("sha") || extraAttrs.get("sign").equalsIgnoreCase("sha1")) { + token =DigestUtils.shaHex(code+key+timestamp); + }else if(extraAttrs.get("sign").equalsIgnoreCase("sha256")) { + token =DigestUtils.sha256Hex(code+key+timestamp); + }else if(extraAttrs.get("sign").equalsIgnoreCase("sha384")) { + token =DigestUtils.sha384Hex(code+key+timestamp); + }else if(extraAttrs.get("sign").equalsIgnoreCase("sha512")) { + token =DigestUtils.sha512Hex(code+key+timestamp); + } + } + + _logger.debug(""+token); + String account = userInfo.getUsername(); + + String redirect_uri = String.format(details.getLoginUrl(),account,code,timestamp,token); - _logger.debug("redirect_uri : "+redirect_uri); - + _logger.debug("redirect_uri : "+redirect_uri); + modelAndView.addObject("redirect_uri", redirect_uri); return modelAndView; - } + } } \ No newline at end of file diff --git a/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiZentaoAdapter.java b/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiZentaoAdapter.java index daf91ab0a..70c4595cc 100644 --- a/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiZentaoAdapter.java +++ b/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/ExtendApiZentaoAdapter.java @@ -40,59 +40,59 @@ import org.springframework.web.servlet.ModelAndView; * */ public class ExtendApiZentaoAdapter extends AbstractAuthorizeAdapter { - static final Logger _logger = LoggerFactory.getLogger(ExtendApiZentaoAdapter.class); - static String login_url_template="api.php?m=user&f=apilogin&account=%s&code=%s&time=%s&token=%s"; - static String login_url_m_template="account=%s&code=%s&time=%s&token=%s"; - - Accounts account; - - @Override - public Object generateInfo() { - return null; - } + static final Logger _logger = LoggerFactory.getLogger(ExtendApiZentaoAdapter.class); + static String login_url_template="api.php?m=user&f=apilogin&account=%s&code=%s&time=%s&token=%s"; + static String login_url_m_template="account=%s&code=%s&time=%s&token=%s"; + + Accounts account; + + @Override + public Object generateInfo() { + return null; + } - @Override - public Object encrypt(Object data, String algorithmKey, String algorithm) { - return null; - } + @Override + public Object encrypt(Object data, String algorithmKey, String algorithm) { + return null; + } - @Override - public ModelAndView authorize(ModelAndView modelAndView) { - Apps details=(Apps)app; - //extraAttrs from Applications - ExtraAttrs extraAttrs=null; - if(details.getIsExtendAttr()==1){ - extraAttrs=new ExtraAttrs(details.getExtendAttr()); - } - _logger.trace("Extra Attrs " + extraAttrs); - String code = details.getPrincipal(); - String key = details.getCredentials(); - String time = ""+Instant.now().getEpochSecond(); + @Override + public ModelAndView authorize(ModelAndView modelAndView) { + Apps details=(Apps)app; + //extraAttrs from Applications + ExtraAttrs extraAttrs=null; + if(details.getIsExtendAttr()==1){ + extraAttrs=new ExtraAttrs(details.getExtendAttr()); + } + _logger.trace("Extra Attrs " + extraAttrs); + String code = details.getPrincipal(); + String key = details.getCredentials(); + String time = ""+Instant.now().getEpochSecond(); - String token =DigestUtils.md5Hex(code+key+time); - - _logger.debug(""+token); - String account = userInfo.getUsername(); - - String redirect_uri = details.getLoginUrl(); - if(redirect_uri.indexOf("api.php?")<0) { - if(redirect_uri.endsWith("/")) { - redirect_uri += String.format(login_url_template,account,code,time,token); - }else { - redirect_uri +="/" + String.format(login_url_template,account,code,time,token); - } - }else if(redirect_uri.endsWith("&")){ - redirect_uri += String.format(login_url_m_template,account,code,time,token); - }else { - redirect_uri += "&" +String.format(login_url_m_template,account,code,time,token); - } - - _logger.debug("redirect_uri : "+redirect_uri); - modelAndView=new ModelAndView("authorize/redirect_sso_submit"); + String token =DigestUtils.md5Hex(code+key+time); + + _logger.debug(""+token); + String account = userInfo.getUsername(); + + String redirect_uri = details.getLoginUrl(); + if(redirect_uri.indexOf("api.php?")<0) { + if(redirect_uri.endsWith("/")) { + redirect_uri += String.format(login_url_template,account,code,time,token); + }else { + redirect_uri +="/" + String.format(login_url_template,account,code,time,token); + } + }else if(redirect_uri.endsWith("&")){ + redirect_uri += String.format(login_url_m_template,account,code,time,token); + }else { + redirect_uri += "&" +String.format(login_url_m_template,account,code,time,token); + } + + _logger.debug("redirect_uri : "+redirect_uri); + modelAndView=new ModelAndView("authorize/redirect_sso_submit"); modelAndView.addObject("redirect_uri", redirect_uri); - - return modelAndView; - } + + return modelAndView; + } } diff --git a/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/netease/NeteaseRSATool.java b/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/netease/NeteaseRSATool.java index bf227d556..9676608e6 100644 --- a/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/netease/NeteaseRSATool.java +++ b/maxkey-protocols/maxkey-protocol-extendapi/src/main/java/org/dromara/maxkey/authz/exapi/endpoint/adapter/netease/NeteaseRSATool.java @@ -39,289 +39,289 @@ import org.slf4j.LoggerFactory; public class NeteaseRSATool { - static final Logger _logger = LoggerFactory.getLogger(NeteaseRSATool.class); - - private static final char[] bcdLookup = { '0', '1', '2', '3', '4', '5', - '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + static final Logger _logger = LoggerFactory.getLogger(NeteaseRSATool.class); + + private static final char[] bcdLookup = { '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; - private String description = "1024-bit RSA key"; - private String priKey = null; - private String pubKey = null; - + private String description = "1024-bit RSA key"; + private String priKey = null; + private String pubKey = null; + - public String bytesToHexStr(byte[] bcd) { - StringBuffer s = new StringBuffer(bcd.length * 2); + public String bytesToHexStr(byte[] bcd) { + StringBuffer s = new StringBuffer(bcd.length * 2); - for (int i = 0; i < bcd.length; i++) { - s.append(bcdLookup[(bcd[i] >>> 4) & 0x0f]); - s.append(bcdLookup[bcd[i] & 0x0f]); - } + for (int i = 0; i < bcd.length; i++) { + s.append(bcdLookup[(bcd[i] >>> 4) & 0x0f]); + s.append(bcdLookup[bcd[i] & 0x0f]); + } - return s.toString(); - } + return s.toString(); + } - public byte[] hexStrToBytes(String s) { - byte[] bytes; + public byte[] hexStrToBytes(String s) { + byte[] bytes; - bytes = new byte[s.length() / 2]; + bytes = new byte[s.length() / 2]; - for (int i = 0; i < bytes.length; i++) { - bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2), - 16); - } + for (int i = 0; i < bytes.length; i++) { + bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2), + 16); + } - return bytes; - } + return bytes; + } - public void genRSAKeyPair() { - KeyPairGenerator rsaKeyGen = null; - KeyPair rsaKeyPair = null; - try { - _logger.trace("Generating a pair of RSA key ... "); - rsaKeyGen = KeyPairGenerator.getInstance("RSA"); - SecureRandom random = new SecureRandom(); - random.setSeed(System.currentTimeMillis()); + public void genRSAKeyPair() { + KeyPairGenerator rsaKeyGen = null; + KeyPair rsaKeyPair = null; + try { + _logger.trace("Generating a pair of RSA key ... "); + rsaKeyGen = KeyPairGenerator.getInstance("RSA"); + SecureRandom random = new SecureRandom(); + random.setSeed(System.currentTimeMillis()); - rsaKeyGen.initialize(1024, random); + rsaKeyGen.initialize(1024, random); - rsaKeyPair = rsaKeyGen.genKeyPair(); - PublicKey rsaPublic = rsaKeyPair.getPublic(); - PrivateKey rsaPrivate = rsaKeyPair.getPrivate(); + rsaKeyPair = rsaKeyGen.genKeyPair(); + PublicKey rsaPublic = rsaKeyPair.getPublic(); + PrivateKey rsaPrivate = rsaKeyPair.getPrivate(); - pubKey = bytesToHexStr(rsaPublic.getEncoded()); - priKey = bytesToHexStr(rsaPrivate.getEncoded()); - _logger.trace("pubKey: {}" , pubKey); - _logger.trace("priKey: {}" , priKey); - _logger.trace("1024-bit RSA key GENERATED."); - } catch (Exception e) { - _logger.error("Exception genRSAKeyPair:" + e); - } - } + pubKey = bytesToHexStr(rsaPublic.getEncoded()); + priKey = bytesToHexStr(rsaPrivate.getEncoded()); + _logger.trace("pubKey: {}" , pubKey); + _logger.trace("priKey: {}" , priKey); + _logger.trace("1024-bit RSA key GENERATED."); + } catch (Exception e) { + _logger.error("Exception genRSAKeyPair:" + e); + } + } - public String generateSHA1withRSASigature(String src, String priKey) { - try { - byte[] pribyte = hexStrToBytes(priKey.trim()); - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pribyte); - KeyFactory fac = KeyFactory.getInstance("RSA"); - RSAPrivateKey privateKey = (RSAPrivateKey) fac.generatePrivate(keySpec); - - Signature sigEng = Signature.getInstance("SHA1withRSA"); - sigEng.initSign(privateKey); - sigEng.update(src.getBytes()); - byte[] signature = sigEng.sign(); - return bytesToHexStr(signature); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - public String encryptWithPriKey(String src, String priKey) { - try { - byte[] pribyte = hexStrToBytes(priKey.trim()); - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pribyte); - KeyFactory fac = KeyFactory.getInstance("RSA"); - Key privateKey = fac.generatePrivate(keySpec); - - Cipher cipher = Cipher.getInstance("RSA"); - cipher.init(Cipher.ENCRYPT_MODE, privateKey); - - byte[] bytes = src.getBytes(); - byte[] encodedByteArray = new byte[] {}; - for (int i = 0; i < bytes.length; i += 102){ - byte[] subarray = ArrayUtils.subarray(bytes, i, i + 102); - byte[] doFinal = cipher.doFinal(subarray); - encodedByteArray = ArrayUtils.addAll(encodedByteArray, doFinal); - } - return bytesToHexStr(encodedByteArray); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } + public String generateSHA1withRSASigature(String src, String priKey) { + try { + byte[] pribyte = hexStrToBytes(priKey.trim()); + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pribyte); + KeyFactory fac = KeyFactory.getInstance("RSA"); + RSAPrivateKey privateKey = (RSAPrivateKey) fac.generatePrivate(keySpec); + + Signature sigEng = Signature.getInstance("SHA1withRSA"); + sigEng.initSign(privateKey); + sigEng.update(src.getBytes()); + byte[] signature = sigEng.sign(); + return bytesToHexStr(signature); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public String encryptWithPriKey(String src, String priKey) { + try { + byte[] pribyte = hexStrToBytes(priKey.trim()); + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pribyte); + KeyFactory fac = KeyFactory.getInstance("RSA"); + Key privateKey = fac.generatePrivate(keySpec); + + Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(Cipher.ENCRYPT_MODE, privateKey); + + byte[] bytes = src.getBytes(); + byte[] encodedByteArray = new byte[] {}; + for (int i = 0; i < bytes.length; i += 102){ + byte[] subarray = ArrayUtils.subarray(bytes, i, i + 102); + byte[] doFinal = cipher.doFinal(subarray); + encodedByteArray = ArrayUtils.addAll(encodedByteArray, doFinal); + } + return bytesToHexStr(encodedByteArray); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } - public boolean verifySHA1withRSASigature(String sign, String src, - String pubKeyStr) { - try { + public boolean verifySHA1withRSASigature(String sign, String src, + String pubKeyStr) { + try { - Signature sigEng = Signature.getInstance("SHA1withRSA"); + Signature sigEng = Signature.getInstance("SHA1withRSA"); - byte[] pubbyte = hexStrToBytes(pubKeyStr.trim()); + byte[] pubbyte = hexStrToBytes(pubKeyStr.trim()); - X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubbyte); - KeyFactory fac = KeyFactory.getInstance("RSA"); - RSAPublicKey pubKey = (RSAPublicKey) fac.generatePublic(keySpec); + X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubbyte); + KeyFactory fac = KeyFactory.getInstance("RSA"); + RSAPublicKey pubKey = (RSAPublicKey) fac.generatePublic(keySpec); - sigEng.initVerify(pubKey); - sigEng.update(src.getBytes()); + sigEng.initVerify(pubKey); + sigEng.update(src.getBytes()); - byte[] sign1 = hexStrToBytes(sign); - return sigEng.verify(sign1); + byte[] sign1 = hexStrToBytes(sign); + return sigEng.verify(sign1); - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } - - public String encryptLongTextWithPriKey(String src, String priKey) { - final int ENCRYPT_LENGTH = 117; - if (src.length() <= ENCRYPT_LENGTH) { - return encryptWithPriKey(src, priKey); - } - - StringBuffer sb = new StringBuffer(); - int idx = 0; - while (idx < src.length()) { - int end = idx + ENCRYPT_LENGTH > src.length() ? src.length() : idx + ENCRYPT_LENGTH; - String sub = src.substring(idx, end); - String encSub = encryptWithPriKey(sub, priKey); - sb.append(encSub); - idx += ENCRYPT_LENGTH; - } - - return sb.toString(); - } + + public String encryptLongTextWithPriKey(String src, String priKey) { + final int ENCRYPT_LENGTH = 117; + if (src.length() <= ENCRYPT_LENGTH) { + return encryptWithPriKey(src, priKey); + } + + StringBuffer sb = new StringBuffer(); + int idx = 0; + while (idx < src.length()) { + int end = idx + ENCRYPT_LENGTH > src.length() ? src.length() : idx + ENCRYPT_LENGTH; + String sub = src.substring(idx, end); + String encSub = encryptWithPriKey(sub, priKey); + sb.append(encSub); + idx += ENCRYPT_LENGTH; + } + + return sb.toString(); + } - public String encryptWithPriKeyWithBase64(String src, String priKey) { - try { - byte[] pribyte = hexStrToBytes(priKey.trim()); - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pribyte); - KeyFactory fac = KeyFactory.getInstance("RSA"); - Key privateKey = fac.generatePrivate(keySpec); - Cipher cipher = Cipher.getInstance("RSA"); - cipher.init(Cipher.ENCRYPT_MODE, privateKey); - byte[] signature = cipher.doFinal(src.getBytes()); + public String encryptWithPriKeyWithBase64(String src, String priKey) { + try { + byte[] pribyte = hexStrToBytes(priKey.trim()); + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pribyte); + KeyFactory fac = KeyFactory.getInstance("RSA"); + Key privateKey = fac.generatePrivate(keySpec); + Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(Cipher.ENCRYPT_MODE, privateKey); + byte[] signature = cipher.doFinal(src.getBytes()); - return Base64.getEncoder().encodeToString(signature).replaceAll("[^a-zA-Z0-9+/=]", ""); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } + return Base64.getEncoder().encodeToString(signature).replaceAll("[^a-zA-Z0-9+/=]", ""); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } - public String encryptWithPubKey(String src, String pubKey) { - try { - byte[] pubbyte = hexStrToBytes(pubKey.trim()); + public String encryptWithPubKey(String src, String pubKey) { + try { + byte[] pubbyte = hexStrToBytes(pubKey.trim()); - X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubbyte); + X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubbyte); - KeyFactory fac = KeyFactory.getInstance("RSA"); - Key publicKey = fac.generatePublic(keySpec); + KeyFactory fac = KeyFactory.getInstance("RSA"); + Key publicKey = fac.generatePublic(keySpec); - Cipher cipher = Cipher.getInstance("RSA"); - cipher.init(Cipher.ENCRYPT_MODE, publicKey); - byte[] signature = cipher.doFinal(src.getBytes()); + Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(Cipher.ENCRYPT_MODE, publicKey); + byte[] signature = cipher.doFinal(src.getBytes()); - return bytesToHexStr(signature); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } + return bytesToHexStr(signature); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } - public String decryptWithPriKey(String enc, String priKey) { - try { - byte[] pribyte = hexStrToBytes(priKey.trim()); + public String decryptWithPriKey(String enc, String priKey) { + try { + byte[] pribyte = hexStrToBytes(priKey.trim()); - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pribyte); - KeyFactory fac = KeyFactory.getInstance("RSA"); - RSAPrivateKey privateKey = (RSAPrivateKey) fac - .generatePrivate(keySpec); + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pribyte); + KeyFactory fac = KeyFactory.getInstance("RSA"); + RSAPrivateKey privateKey = (RSAPrivateKey) fac + .generatePrivate(keySpec); - // privateKey.getModulus() + privateKey.getPrivateExponent() + - // privateKey.getAlgorithm(); + // privateKey.getModulus() + privateKey.getPrivateExponent() + + // privateKey.getAlgorithm(); - Cipher cipher = Cipher.getInstance("RSA"); - cipher.init(Cipher.DECRYPT_MODE, privateKey); + Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(Cipher.DECRYPT_MODE, privateKey); - byte[] forumcookie = hexStrToBytes(enc); + byte[] forumcookie = hexStrToBytes(enc); - byte[] plainText = cipher.doFinal(forumcookie); + byte[] plainText = cipher.doFinal(forumcookie); - return bytesToHexStr(plainText); + return bytesToHexStr(plainText); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } - public String decryptWithPubKey(String enc, String pubKey) { - try { - byte[] pubbyte = hexStrToBytes(pubKey.trim()); + public String decryptWithPubKey(String enc, String pubKey) { + try { + byte[] pubbyte = hexStrToBytes(pubKey.trim()); - X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubbyte); - KeyFactory fac = KeyFactory.getInstance("RSA"); - Key publicKey = fac.generatePublic(keySpec); + X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubbyte); + KeyFactory fac = KeyFactory.getInstance("RSA"); + Key publicKey = fac.generatePublic(keySpec); - Cipher cipher = Cipher.getInstance("RSA"); - cipher.init(Cipher.DECRYPT_MODE, publicKey); + Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(Cipher.DECRYPT_MODE, publicKey); - byte[] forumcookie = hexStrToBytes(enc); + byte[] forumcookie = hexStrToBytes(enc); - byte[] plainText = cipher.doFinal(forumcookie); + byte[] plainText = cipher.doFinal(forumcookie); - return new String(plainText); + return new String(plainText); - } catch (Exception e) { - System.err.println(e); - e.printStackTrace(System.err); - return null; - } - } + } catch (Exception e) { + System.err.println(e); + e.printStackTrace(System.err); + return null; + } + } - public RSAPrivateKey getPriKey(String priKey) { - try { - byte[] pribyte = hexStrToBytes(priKey.trim()); + public RSAPrivateKey getPriKey(String priKey) { + try { + byte[] pribyte = hexStrToBytes(priKey.trim()); - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pribyte); - KeyFactory fac = KeyFactory.getInstance("RSA"); - RSAPrivateKey key = (RSAPrivateKey) fac.generatePrivate(keySpec); - return key; + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pribyte); + KeyFactory fac = KeyFactory.getInstance("RSA"); + RSAPrivateKey key = (RSAPrivateKey) fac.generatePrivate(keySpec); + return key; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } - public RSAPublicKey getPubKey(String pubKey) { - try { - byte[] pubbyte = hexStrToBytes(pubKey.trim()); + public RSAPublicKey getPubKey(String pubKey) { + try { + byte[] pubbyte = hexStrToBytes(pubKey.trim()); - X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubbyte); - KeyFactory fac = KeyFactory.getInstance("RSA"); - RSAPublicKey key = (RSAPublicKey) fac.generatePublic(keySpec); - return key; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } + X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubbyte); + KeyFactory fac = KeyFactory.getInstance("RSA"); + RSAPublicKey key = (RSAPublicKey) fac.generatePublic(keySpec); + return key; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } - public String getPri() { - return priKey; - } + public String getPri() { + return priKey; + } - public void setPri(String pri) { - this.priKey = pri; - } + public void setPri(String pri) { + this.priKey = pri; + } - public String getPub() { - return pubKey; - } + public String getPub() { + return pubKey; + } - public void setPub(String pub) { - this.pubKey = pub; - } + public void setPub(String pub) { + this.pubKey = pub; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } } diff --git a/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/FormBasedAuthorizeEndpoint.java b/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/FormBasedAuthorizeEndpoint.java index a5ea57d24..d2f45d375 100644 --- a/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/FormBasedAuthorizeEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/FormBasedAuthorizeEndpoint.java @@ -51,53 +51,53 @@ import jakarta.servlet.http.HttpServletRequest; @Tag(name = "2-7-FormBased接口文档模块") @Controller public class FormBasedAuthorizeEndpoint extends AuthorizeBaseEndpoint{ - static final Logger _logger = LoggerFactory.getLogger(FormBasedAuthorizeEndpoint.class); - - @Autowired - AppsFormBasedDetailsService formBasedDetailsService; - - FormBasedDefaultAdapter defaultFormBasedAdapter=new FormBasedDefaultAdapter(); - - @Operation(summary = "FormBased认证地址接口", description = "参数应用ID",method="GET") - @RequestMapping("/authz/formbased/{id}") - public ModelAndView authorize( - HttpServletRequest request, - @PathVariable("id") String id, - @CurrentUser UserInfo currentUser){ - - AppsFormBasedDetails formBasedDetails = formBasedDetailsService.getAppDetails(id , true); - _logger.debug("formBasedDetails {}",formBasedDetails); - Apps application = getApp(id); - formBasedDetails.setAdapter(application.getAdapter()); - formBasedDetails.setIsAdapter(application.getIsAdapter()); - ModelAndView modelAndView=null; - - Accounts account = getAccounts(formBasedDetails,currentUser); - _logger.debug("Accounts {}",account); - - if(account == null){ - return initCredentialView(id,"/authz/formbased/"+id); - }else{ - modelAndView=new ModelAndView(); - - AbstractAuthorizeAdapter adapter; - - if(ConstsBoolean.isTrue(formBasedDetails.getIsAdapter())){ - Object formBasedAdapter = Instance.newInstance(formBasedDetails.getAdapter()); - adapter =(AbstractAuthorizeAdapter)formBasedAdapter; - }else{ - FormBasedDefaultAdapter formBasedDefaultAdapter =new FormBasedDefaultAdapter(); - adapter =(AbstractAuthorizeAdapter)formBasedDefaultAdapter; - } - adapter.setPrincipal(AuthorizationUtils.getPrincipal()); - adapter.setApp(formBasedDetails); - adapter.setAccount(account); - - modelAndView = adapter.authorize(modelAndView); - } - - _logger.debug("FormBased View Name {}" , modelAndView.getViewName()); - - return modelAndView; - } + static final Logger _logger = LoggerFactory.getLogger(FormBasedAuthorizeEndpoint.class); + + @Autowired + AppsFormBasedDetailsService formBasedDetailsService; + + FormBasedDefaultAdapter defaultFormBasedAdapter=new FormBasedDefaultAdapter(); + + @Operation(summary = "FormBased认证地址接口", description = "参数应用ID",method="GET") + @RequestMapping("/authz/formbased/{id}") + public ModelAndView authorize( + HttpServletRequest request, + @PathVariable("id") String id, + @CurrentUser UserInfo currentUser){ + + AppsFormBasedDetails formBasedDetails = formBasedDetailsService.getAppDetails(id , true); + _logger.debug("formBasedDetails {}",formBasedDetails); + Apps application = getApp(id); + formBasedDetails.setAdapter(application.getAdapter()); + formBasedDetails.setIsAdapter(application.getIsAdapter()); + ModelAndView modelAndView=null; + + Accounts account = getAccounts(formBasedDetails,currentUser); + _logger.debug("Accounts {}",account); + + if(account == null){ + return initCredentialView(id,"/authz/formbased/"+id); + }else{ + modelAndView=new ModelAndView(); + + AbstractAuthorizeAdapter adapter; + + if(ConstsBoolean.isTrue(formBasedDetails.getIsAdapter())){ + Object formBasedAdapter = Instance.newInstance(formBasedDetails.getAdapter()); + adapter =(AbstractAuthorizeAdapter)formBasedAdapter; + }else{ + FormBasedDefaultAdapter formBasedDefaultAdapter =new FormBasedDefaultAdapter(); + adapter =(AbstractAuthorizeAdapter)formBasedDefaultAdapter; + } + adapter.setPrincipal(AuthorizationUtils.getPrincipal()); + adapter.setApp(formBasedDetails); + adapter.setAccount(account); + + modelAndView = adapter.authorize(modelAndView); + } + + _logger.debug("FormBased View Name {}" , modelAndView.getViewName()); + + return modelAndView; + } } diff --git a/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/adapter/FormBasedDefaultAdapter.java b/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/adapter/FormBasedDefaultAdapter.java index 94401605d..b4146dd97 100644 --- a/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/adapter/FormBasedDefaultAdapter.java +++ b/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/adapter/FormBasedDefaultAdapter.java @@ -28,53 +28,53 @@ import org.springframework.web.servlet.ModelAndView; public class FormBasedDefaultAdapter extends AbstractAuthorizeAdapter { - static String _HEX = "_HEX"; - - @Override - public Object generateInfo() { - return null; - } - - @Override - public ModelAndView authorize(ModelAndView modelAndView) { - modelAndView.setViewName("authorize/formbased_sso_submint"); - AppsFormBasedDetails details=(AppsFormBasedDetails)app; - - String password = account.getRelatedPassword(); - String passwordAlgorithm = details.getPasswordAlgorithm(); - + static String _HEX = "_HEX"; + + @Override + public Object generateInfo() { + return null; + } + + @Override + public ModelAndView authorize(ModelAndView modelAndView) { + modelAndView.setViewName("authorize/formbased_sso_submint"); + AppsFormBasedDetails details=(AppsFormBasedDetails)app; + + String password = account.getRelatedPassword(); + String passwordAlgorithm = details.getPasswordAlgorithm(); + if(StringUtils.isBlank(passwordAlgorithm) - || passwordAlgorithm.equalsIgnoreCase("NONE")){ - //do nothing + || passwordAlgorithm.equalsIgnoreCase("NONE")){ + //do nothing }else if(passwordAlgorithm.indexOf(_HEX) > -1){ - passwordAlgorithm = passwordAlgorithm.substring(0,passwordAlgorithm.indexOf(_HEX)); + passwordAlgorithm = passwordAlgorithm.substring(0,passwordAlgorithm.indexOf(_HEX)); password = DigestUtils.digestHex(account.getRelatedPassword(),passwordAlgorithm); }else{ password = DigestUtils.digestBase64(account.getRelatedPassword(),passwordAlgorithm); } modelAndView.addObject("id", details.getId()); - modelAndView.addObject("action", details.getRedirectUri()); - modelAndView.addObject("redirectUri", details.getRedirectUri()); - modelAndView.addObject("loginUrl", details.getLoginUrl()); - modelAndView.addObject("usernameMapping", details.getUsernameMapping()); - modelAndView.addObject("passwordMapping", details.getPasswordMapping()); - modelAndView.addObject("username", account.getRelatedUsername()); + modelAndView.addObject("action", details.getRedirectUri()); + modelAndView.addObject("redirectUri", details.getRedirectUri()); + modelAndView.addObject("loginUrl", details.getLoginUrl()); + modelAndView.addObject("usernameMapping", details.getUsernameMapping()); + modelAndView.addObject("passwordMapping", details.getPasswordMapping()); + modelAndView.addObject("username", account.getRelatedUsername()); modelAndView.addObject("password", password); modelAndView.addObject("timestamp", "" + Instant.now().getEpochSecond()); - - if(ConstsBoolean.isTrue(details.getIsExtendAttr())){ - modelAndView.addObject("extendAttr", details.getExtendAttr()); - modelAndView.addObject("isExtendAttr", true); + + if(ConstsBoolean.isTrue(details.getIsExtendAttr())){ + modelAndView.addObject("extendAttr", details.getExtendAttr()); + modelAndView.addObject("isExtendAttr", true); }else{ modelAndView.addObject("isExtendAttr", false); } - - if(StringUtils.isNotBlank(details.getAuthorizeView())){ - modelAndView.setViewName("authorize/"+details.getAuthorizeView()); - } - - return modelAndView; - } + + if(StringUtils.isNotBlank(details.getAuthorizeView())){ + modelAndView.setViewName("authorize/"+details.getAuthorizeView()); + } + + return modelAndView; + } } diff --git a/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/adapter/FormBasedNetease163EmailAdapter.java b/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/adapter/FormBasedNetease163EmailAdapter.java index d807a2074..0d8fcc1c2 100644 --- a/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/adapter/FormBasedNetease163EmailAdapter.java +++ b/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/adapter/FormBasedNetease163EmailAdapter.java @@ -23,31 +23,31 @@ import org.dromara.maxkey.entity.apps.AppsFormBasedDetails; import org.springframework.web.servlet.ModelAndView; public class FormBasedNetease163EmailAdapter extends AbstractAuthorizeAdapter { - - @Override - public String generateInfo() { - return null; - } + + @Override + public String generateInfo() { + return null; + } - @Override - public ModelAndView authorize(ModelAndView modelAndView) { - modelAndView.setViewName("authorize/formbased_163email_sso_submint"); - AppsFormBasedDetails details=(AppsFormBasedDetails)app; - modelAndView.addObject("username", account.getRelatedUsername().substring(account.getRelatedUsername().indexOf("@"))); - modelAndView.addObject("email", account.getRelatedUsername()); - modelAndView.addObject("password", account.getRelatedPassword()); - - if(ConstsBoolean.isTrue(details.getIsExtendAttr())){ - modelAndView.addObject("extendAttr", details.getExtendAttr()); - modelAndView.addObject("isExtendAttr", true); - }else{ - modelAndView.addObject("isExtendAttr", false); - } - - modelAndView.addObject("action", details.getRedirectUri()); - modelAndView.addObject("usernameMapping", details.getUsernameMapping()); - modelAndView.addObject("passwordMapping", details.getPasswordMapping()); - return modelAndView; - } + @Override + public ModelAndView authorize(ModelAndView modelAndView) { + modelAndView.setViewName("authorize/formbased_163email_sso_submint"); + AppsFormBasedDetails details=(AppsFormBasedDetails)app; + modelAndView.addObject("username", account.getRelatedUsername().substring(account.getRelatedUsername().indexOf("@"))); + modelAndView.addObject("email", account.getRelatedUsername()); + modelAndView.addObject("password", account.getRelatedPassword()); + + if(ConstsBoolean.isTrue(details.getIsExtendAttr())){ + modelAndView.addObject("extendAttr", details.getExtendAttr()); + modelAndView.addObject("isExtendAttr", true); + }else{ + modelAndView.addObject("isExtendAttr", false); + } + + modelAndView.addObject("action", details.getRedirectUri()); + modelAndView.addObject("usernameMapping", details.getUsernameMapping()); + modelAndView.addObject("passwordMapping", details.getPasswordMapping()); + return modelAndView; + } } diff --git a/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/adapter/FormBasedNeteaseNoteYoudaoAdapter.java b/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/adapter/FormBasedNeteaseNoteYoudaoAdapter.java index ab4aa0a9a..954e39592 100644 --- a/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/adapter/FormBasedNeteaseNoteYoudaoAdapter.java +++ b/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/adapter/FormBasedNeteaseNoteYoudaoAdapter.java @@ -26,20 +26,20 @@ import org.springframework.web.servlet.ModelAndView; public class FormBasedNeteaseNoteYoudaoAdapter extends AbstractAuthorizeAdapter { - @Override - public Object generateInfo() { - return null; - } + @Override + public Object generateInfo() { + return null; + } - @Override - public ModelAndView authorize(ModelAndView modelAndView) { - modelAndView.setViewName("authorize/formbased_wy_youdao_sso_submint"); - AppsFormBasedDetails details=(AppsFormBasedDetails)app; - modelAndView.addObject("username", account.getRelatedUsername()); - modelAndView.addObject("password", DigestUtils.md5Hex(account.getRelatedPassword())); - modelAndView.addObject("currentTime", (new Date()).getTime()); - return modelAndView; - } + @Override + public ModelAndView authorize(ModelAndView modelAndView) { + modelAndView.setViewName("authorize/formbased_wy_youdao_sso_submint"); + AppsFormBasedDetails details=(AppsFormBasedDetails)app; + modelAndView.addObject("username", account.getRelatedUsername()); + modelAndView.addObject("password", DigestUtils.md5Hex(account.getRelatedPassword())); + modelAndView.addObject("currentTime", (new Date()).getTime()); + return modelAndView; + } } diff --git a/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/adapter/FormBasedRedirectAdapter.java b/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/adapter/FormBasedRedirectAdapter.java index 26c167972..10fa9094f 100644 --- a/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/adapter/FormBasedRedirectAdapter.java +++ b/maxkey-protocols/maxkey-protocol-formbased/src/main/java/org/dromara/maxkey/authz/formbased/endpoint/adapter/FormBasedRedirectAdapter.java @@ -28,17 +28,17 @@ import org.springframework.web.servlet.ModelAndView; public class FormBasedRedirectAdapter extends AbstractAuthorizeAdapter { - @Override - public Object generateInfo() { - return null; - } + @Override + public Object generateInfo() { + return null; + } - @Override - public ModelAndView authorize(ModelAndView modelAndView) { - modelAndView.setViewName("authorize/formbased_redirect_submint"); - AppsFormBasedDetails details=(AppsFormBasedDetails)app; - - String password = account.getRelatedPassword(); + @Override + public ModelAndView authorize(ModelAndView modelAndView) { + modelAndView.setViewName("authorize/formbased_redirect_submint"); + AppsFormBasedDetails details=(AppsFormBasedDetails)app; + + String password = account.getRelatedPassword(); if(null==details.getPasswordAlgorithm()||details.getPasswordAlgorithm().equals("")){ }else if(details.getPasswordAlgorithm().indexOf("HEX")>-1){ password = DigestUtils.digestHex(account.getRelatedPassword(),details.getPasswordAlgorithm().substring(0, details.getPasswordAlgorithm().indexOf("HEX"))); @@ -46,36 +46,36 @@ public class FormBasedRedirectAdapter extends AbstractAuthorizeAdapter { password = DigestUtils.digestBase64(account.getRelatedPassword(),details.getPasswordAlgorithm()); } - modelAndView.addObject("id", details.getId()); - modelAndView.addObject("action", details.getRedirectUri()); - modelAndView.addObject("redirectUri", details.getRedirectUri()); - modelAndView.addObject("loginUrl", details.getLoginUrl()); - modelAndView.addObject("usernameMapping", details.getUsernameMapping()); - modelAndView.addObject("passwordMapping", details.getPasswordMapping()); - modelAndView.addObject("username", account.getRelatedUsername()); + modelAndView.addObject("id", details.getId()); + modelAndView.addObject("action", details.getRedirectUri()); + modelAndView.addObject("redirectUri", details.getRedirectUri()); + modelAndView.addObject("loginUrl", details.getLoginUrl()); + modelAndView.addObject("usernameMapping", details.getUsernameMapping()); + modelAndView.addObject("passwordMapping", details.getPasswordMapping()); + modelAndView.addObject("username", account.getRelatedUsername()); modelAndView.addObject("password", password); modelAndView.addObject("timestamp", ""+Instant.now().getEpochSecond()); - - if(WebContext.getAttribute("formbased_redirect_submint")==null){ - modelAndView.setViewName("authorize/formbased_redirect_submint"); - WebContext.setAttribute("formbased_redirect_submint", "formbased_redirect_submint"); - }else{ - modelAndView.setViewName("authorize/formbased_redirect_post_submint"); - if(details.getAuthorizeView()!=null&&!details.getAuthorizeView().equals("")){ - modelAndView.setViewName("authorize/"+details.getAuthorizeView()); - } - WebContext.removeAttribute("formbased_redirect_submint"); - } - - - if(ConstsBoolean.isTrue(details.getIsExtendAttr())){ - modelAndView.addObject("extendAttr", details.getExtendAttr()); - modelAndView.addObject("isExtendAttr", true); - }else{ - modelAndView.addObject("isExtendAttr", false); - } - - return modelAndView; - } + + if(WebContext.getAttribute("formbased_redirect_submint")==null){ + modelAndView.setViewName("authorize/formbased_redirect_submint"); + WebContext.setAttribute("formbased_redirect_submint", "formbased_redirect_submint"); + }else{ + modelAndView.setViewName("authorize/formbased_redirect_post_submint"); + if(details.getAuthorizeView()!=null&&!details.getAuthorizeView().equals("")){ + modelAndView.setViewName("authorize/"+details.getAuthorizeView()); + } + WebContext.removeAttribute("formbased_redirect_submint"); + } + + + if(ConstsBoolean.isTrue(details.getIsExtendAttr())){ + modelAndView.addObject("extendAttr", details.getExtendAttr()); + modelAndView.addObject("isExtendAttr", true); + }else{ + modelAndView.addObject("isExtendAttr", false); + } + + return modelAndView; + } } diff --git a/maxkey-protocols/maxkey-protocol-jwt/src/main/java/org/dromara/maxkey/authz/jwt/endpoint/adapter/JwtAdapter.java b/maxkey-protocols/maxkey-protocol-jwt/src/main/java/org/dromara/maxkey/authz/jwt/endpoint/adapter/JwtAdapter.java index 857a4bb40..69403b482 100644 --- a/maxkey-protocols/maxkey-protocol-jwt/src/main/java/org/dromara/maxkey/authz/jwt/endpoint/adapter/JwtAdapter.java +++ b/maxkey-protocols/maxkey-protocol-jwt/src/main/java/org/dromara/maxkey/authz/jwt/endpoint/adapter/JwtAdapter.java @@ -44,150 +44,150 @@ import com.nimbusds.jwt.PlainJWT; import com.nimbusds.jwt.SignedJWT; public class JwtAdapter extends AbstractAuthorizeAdapter { - static final Logger _logger = LoggerFactory.getLogger(JwtAdapter.class); + static final Logger _logger = LoggerFactory.getLogger(JwtAdapter.class); - AppsJwtDetails jwtDetails; - - JWT jwtToken; - - JWEObject jweObject; - - JWTClaimsSet jwtClaims; - - public JwtAdapter() { + AppsJwtDetails jwtDetails; + + JWT jwtToken; + + JWEObject jweObject; + + JWTClaimsSet jwtClaims; + + public JwtAdapter() { - } + } - public JwtAdapter(AppsJwtDetails jwtDetails) { - this.jwtDetails = jwtDetails; - } + public JwtAdapter(AppsJwtDetails jwtDetails) { + this.jwtDetails = jwtDetails; + } - @Override - public Object generateInfo() { - DateTime currentDateTime = DateTime.now(); - Date expirationTime = currentDateTime.plusSeconds(jwtDetails.getExpires()).toDate(); - _logger.debug("expiration Time : {}" , expirationTime); - String subject = getValueByUserAttr(userInfo,jwtDetails.getSubject()); - _logger.trace("jwt subject : {}" , subject); - - jwtClaims =new JWTClaimsSet.Builder() - .issuer(jwtDetails.getIssuer()) - .subject(subject) - .audience(Arrays.asList(jwtDetails.getId())) - .jwtID(UUID.randomUUID().toString()) - .issueTime(currentDateTime.toDate()) - .expirationTime(expirationTime) - .claim("email", userInfo.getWorkEmail()) - .claim("name", userInfo.getUsername()) - .claim("user_id", userInfo.getId()) - .claim("external_id", userInfo.getId()) - .claim("locale", userInfo.getLocale()) - .claim(WebConstants.ONLINE_TICKET_NAME, principal.getSessionId()) - .claim("kid", jwtDetails.getId()+ "_sig") - .claim("institution", userInfo.getInstId()) - .build(); - - _logger.trace("jwt Claims : {}" , jwtClaims); - - jwtToken = new PlainJWT(jwtClaims); - - return jwtToken; - } + @Override + public Object generateInfo() { + DateTime currentDateTime = DateTime.now(); + Date expirationTime = currentDateTime.plusSeconds(jwtDetails.getExpires()).toDate(); + _logger.debug("expiration Time : {}" , expirationTime); + String subject = getValueByUserAttr(userInfo,jwtDetails.getSubject()); + _logger.trace("jwt subject : {}" , subject); + + jwtClaims =new JWTClaimsSet.Builder() + .issuer(jwtDetails.getIssuer()) + .subject(subject) + .audience(Arrays.asList(jwtDetails.getId())) + .jwtID(UUID.randomUUID().toString()) + .issueTime(currentDateTime.toDate()) + .expirationTime(expirationTime) + .claim("email", userInfo.getWorkEmail()) + .claim("name", userInfo.getUsername()) + .claim("user_id", userInfo.getId()) + .claim("external_id", userInfo.getId()) + .claim("locale", userInfo.getLocale()) + .claim(WebConstants.ONLINE_TICKET_NAME, principal.getSessionId()) + .claim("kid", jwtDetails.getId()+ "_sig") + .claim("institution", userInfo.getInstId()) + .build(); + + _logger.trace("jwt Claims : {}" , jwtClaims); + + jwtToken = new PlainJWT(jwtClaims); + + return jwtToken; + } - @Override - public Object sign(Object data,String signatureKey,String signature) { - if(!jwtDetails.getSignature().equalsIgnoreCase("none")) { - try { - DefaultJwtSigningAndValidationService jwtSignerService = - new DefaultJwtSigningAndValidationService( - jwtDetails.getSignatureKey(), - jwtDetails.getId() + "_sig", - jwtDetails.getSignature() - ); - - jwtToken = new SignedJWT( - new JWSHeader(jwtSignerService.getDefaultSigningAlgorithm()), - jwtClaims - ); - // sign it with the server's key - jwtSignerService.signJwt((SignedJWT) jwtToken); - return jwtToken; - } catch (NoSuchAlgorithmException e) { - _logger.error("NoSuchAlgorithmException", e); - } catch (InvalidKeySpecException e) { - _logger.error("InvalidKeySpecException", e); - } catch (JOSEException e) { - _logger.error("JOSEException", e); - } - } - return data; - } + @Override + public Object sign(Object data,String signatureKey,String signature) { + if(!jwtDetails.getSignature().equalsIgnoreCase("none")) { + try { + DefaultJwtSigningAndValidationService jwtSignerService = + new DefaultJwtSigningAndValidationService( + jwtDetails.getSignatureKey(), + jwtDetails.getId() + "_sig", + jwtDetails.getSignature() + ); + + jwtToken = new SignedJWT( + new JWSHeader(jwtSignerService.getDefaultSigningAlgorithm()), + jwtClaims + ); + // sign it with the server's key + jwtSignerService.signJwt((SignedJWT) jwtToken); + return jwtToken; + } catch (NoSuchAlgorithmException e) { + _logger.error("NoSuchAlgorithmException", e); + } catch (InvalidKeySpecException e) { + _logger.error("InvalidKeySpecException", e); + } catch (JOSEException e) { + _logger.error("JOSEException", e); + } + } + return data; + } - @Override - public Object encrypt(Object data, String algorithmKey, String algorithm) { - if(!jwtDetails.getAlgorithm().equalsIgnoreCase("none")) { - try { - DefaultJwtEncryptionAndDecryptionService jwtEncryptionService = - new DefaultJwtEncryptionAndDecryptionService( - jwtDetails.getAlgorithmKey(), - jwtDetails.getId() + "_enc", - jwtDetails.getAlgorithm() - ); + @Override + public Object encrypt(Object data, String algorithmKey, String algorithm) { + if(!jwtDetails.getAlgorithm().equalsIgnoreCase("none")) { + try { + DefaultJwtEncryptionAndDecryptionService jwtEncryptionService = + new DefaultJwtEncryptionAndDecryptionService( + jwtDetails.getAlgorithmKey(), + jwtDetails.getId() + "_enc", + jwtDetails.getAlgorithm() + ); - Payload payload; - if(jwtToken instanceof SignedJWT) { - payload = ((SignedJWT)jwtToken).getPayload(); - }else { - payload = ((PlainJWT)jwtToken).getPayload(); - } - // Example Request JWT encrypted with RSA-OAEP-256 and 128-bit AES/GCM - //JWEHeader jweHeader = new JWEHeader(JWEAlgorithm.RSA1_5, EncryptionMethod.A128GCM); - JWEHeader jweHeader = new JWEHeader( - jwtEncryptionService.getDefaultAlgorithm(jwtDetails.getAlgorithm()), - jwtEncryptionService.parseEncryptionMethod(jwtDetails.getEncryptionMethod()) - ); - jweObject = new JWEObject( - new JWEHeader.Builder(jweHeader) - .contentType("JWT") // required to indicate nested JWT - .build(), - payload); - - jwtEncryptionService.encryptJwt(jweObject); - - } catch (NoSuchAlgorithmException | InvalidKeySpecException | JOSEException e) { - _logger.error("Encrypt Exception", e); - } - } - return data; - } - - @Override - public ModelAndView authorize(ModelAndView modelAndView) { - modelAndView.setViewName("authorize/jwt_sso_submint"); - modelAndView.addObject("action", jwtDetails.getRedirectUri()); - - modelAndView.addObject("token",serialize()); - modelAndView.addObject("jwtName",jwtDetails.getJwtName()); - - modelAndView.addObject("tokenType",jwtDetails.getTokenType().toLowerCase()); - - return modelAndView; - } + Payload payload; + if(jwtToken instanceof SignedJWT) { + payload = ((SignedJWT)jwtToken).getPayload(); + }else { + payload = ((PlainJWT)jwtToken).getPayload(); + } + // Example Request JWT encrypted with RSA-OAEP-256 and 128-bit AES/GCM + //JWEHeader jweHeader = new JWEHeader(JWEAlgorithm.RSA1_5, EncryptionMethod.A128GCM); + JWEHeader jweHeader = new JWEHeader( + jwtEncryptionService.getDefaultAlgorithm(jwtDetails.getAlgorithm()), + jwtEncryptionService.parseEncryptionMethod(jwtDetails.getEncryptionMethod()) + ); + jweObject = new JWEObject( + new JWEHeader.Builder(jweHeader) + .contentType("JWT") // required to indicate nested JWT + .build(), + payload); + + jwtEncryptionService.encryptJwt(jweObject); + + } catch (NoSuchAlgorithmException | InvalidKeySpecException | JOSEException e) { + _logger.error("Encrypt Exception", e); + } + } + return data; + } + + @Override + public ModelAndView authorize(ModelAndView modelAndView) { + modelAndView.setViewName("authorize/jwt_sso_submint"); + modelAndView.addObject("action", jwtDetails.getRedirectUri()); + + modelAndView.addObject("token",serialize()); + modelAndView.addObject("jwtName",jwtDetails.getJwtName()); + + modelAndView.addObject("tokenType",jwtDetails.getTokenType().toLowerCase()); + + return modelAndView; + } - public void setJwtDetails(AppsJwtDetails jwtDetails) { - this.jwtDetails = jwtDetails; - } + public void setJwtDetails(AppsJwtDetails jwtDetails) { + this.jwtDetails = jwtDetails; + } - @Override - public String serialize() { - String tokenString = ""; - if(jweObject != null) { - tokenString = jweObject.serialize(); - }else { - tokenString = jwtToken.serialize(); - } - _logger.debug("jwt Token : {}" , tokenString); - return tokenString; - } + @Override + public String serialize() { + String tokenString = ""; + if(jweObject != null) { + tokenString = jweObject.serialize(); + }else { + tokenString = jwtToken.serialize(); + } + _logger.debug("jwt Token : {}" , tokenString); + return tokenString; + } } diff --git a/maxkey-protocols/maxkey-protocol-jwt/src/main/java/org/dromara/maxkey/authz/token/endpoint/JwtAuthorizeEndpoint.java b/maxkey-protocols/maxkey-protocol-jwt/src/main/java/org/dromara/maxkey/authz/token/endpoint/JwtAuthorizeEndpoint.java index 326d0f155..138770937 100644 --- a/maxkey-protocols/maxkey-protocol-jwt/src/main/java/org/dromara/maxkey/authz/token/endpoint/JwtAuthorizeEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-jwt/src/main/java/org/dromara/maxkey/authz/token/endpoint/JwtAuthorizeEndpoint.java @@ -61,80 +61,80 @@ import jakarta.servlet.http.HttpServletResponse; @Controller public class JwtAuthorizeEndpoint extends AuthorizeBaseEndpoint{ - static final Logger _logger = LoggerFactory.getLogger(JwtAuthorizeEndpoint.class); - - @Autowired - AppsJwtDetailsService jwtDetailsService; - - @Operation(summary = "JWT应用ID认证接口", description = "应用ID") - @GetMapping("/authz/jwt/{id}") - public ModelAndView authorize( - HttpServletRequest request, - HttpServletResponse response, - @PathVariable("id") String id, - @CurrentUser UserInfo currentUser){ - ModelAndView modelAndView=new ModelAndView(); - Apps application = getApp(id); - AppsJwtDetails jwtDetails = jwtDetailsService.getAppDetails(application.getId() , true); - _logger.debug("jwtDetails {}",jwtDetails); - jwtDetails.setAdapter(application.getAdapter()); - jwtDetails.setIsAdapter(application.getIsAdapter()); - - AbstractAuthorizeAdapter adapter; - if(ConstsBoolean.isTrue(jwtDetails.getIsAdapter())){ - Object jwtAdapter = Instance.newInstance(jwtDetails.getAdapter()); - try { - BeanUtils.setProperty(jwtAdapter, "jwtDetails", jwtDetails); - } catch (IllegalAccessException | InvocationTargetException e) { - _logger.error("setProperty error . ", e); - } - adapter = (AbstractAuthorizeAdapter)jwtAdapter; - }else{ - adapter =new JwtAdapter(jwtDetails); - } - - adapter.setPrincipal(AuthorizationUtils.getPrincipal()); - - adapter.generateInfo(); - //sign - adapter.sign(null,jwtDetails.getSignatureKey(), jwtDetails.getSignature()); - //encrypt - adapter.encrypt(null, jwtDetails.getAlgorithmKey(), jwtDetails.getAlgorithm()); - - return adapter.authorize(modelAndView); - } + static final Logger _logger = LoggerFactory.getLogger(JwtAuthorizeEndpoint.class); + + @Autowired + AppsJwtDetailsService jwtDetailsService; + + @Operation(summary = "JWT应用ID认证接口", description = "应用ID") + @GetMapping("/authz/jwt/{id}") + public ModelAndView authorize( + HttpServletRequest request, + HttpServletResponse response, + @PathVariable("id") String id, + @CurrentUser UserInfo currentUser){ + ModelAndView modelAndView=new ModelAndView(); + Apps application = getApp(id); + AppsJwtDetails jwtDetails = jwtDetailsService.getAppDetails(application.getId() , true); + _logger.debug("jwtDetails {}",jwtDetails); + jwtDetails.setAdapter(application.getAdapter()); + jwtDetails.setIsAdapter(application.getIsAdapter()); + + AbstractAuthorizeAdapter adapter; + if(ConstsBoolean.isTrue(jwtDetails.getIsAdapter())){ + Object jwtAdapter = Instance.newInstance(jwtDetails.getAdapter()); + try { + BeanUtils.setProperty(jwtAdapter, "jwtDetails", jwtDetails); + } catch (IllegalAccessException | InvocationTargetException e) { + _logger.error("setProperty error . ", e); + } + adapter = (AbstractAuthorizeAdapter)jwtAdapter; + }else{ + adapter =new JwtAdapter(jwtDetails); + } + + adapter.setPrincipal(AuthorizationUtils.getPrincipal()); + + adapter.generateInfo(); + //sign + adapter.sign(null,jwtDetails.getSignatureKey(), jwtDetails.getSignature()); + //encrypt + adapter.encrypt(null, jwtDetails.getAlgorithmKey(), jwtDetails.getAlgorithm()); + + return adapter.authorize(modelAndView); + } - @Operation(summary = "JWT JWK元数据接口", description = "参数mxk_metadata_APPID") - @GetMapping(value = "/metadata/jwt/" + WebConstants.MXK_METADATA_PREFIX + "{appid}.{mediaType}") - @ResponseBody - public String metadata(HttpServletRequest request, - HttpServletResponse response, - @PathVariable("appid") String appId, - @PathVariable("mediaType") String mediaType) { - AppsJwtDetails jwtDetails = jwtDetailsService.getAppDetails(appId , true); - if(jwtDetails != null) { - String jwkSetString = ""; - if(!jwtDetails.getSignature().equalsIgnoreCase("none")) { - jwkSetString = jwtDetails.getSignatureKey(); - } - if(!jwtDetails.getAlgorithm().equalsIgnoreCase("none")) { - if(StringUtils.isBlank(jwkSetString)) { - jwkSetString = jwtDetails.getAlgorithmKey(); - }else { - jwkSetString = jwkSetString + "," +jwtDetails.getAlgorithmKey(); - } - } - - JWKSetKeyStore jwkSetKeyStore = new JWKSetKeyStore("{\"keys\": [" + jwkSetString + "]}"); - if(StringUtils.isNotBlank(mediaType) - && mediaType.equalsIgnoreCase("xml")) { - response.setContentType(ContentType.APPLICATION_XML_UTF8); - }else { - response.setContentType(ContentType.APPLICATION_JSON_UTF8); - } - return jwkSetKeyStore.toString(mediaType); - - } - return appId + " not exist. \n" + WebContext.version(); - } + @Operation(summary = "JWT JWK元数据接口", description = "参数mxk_metadata_APPID") + @GetMapping(value = "/metadata/jwt/" + WebConstants.MXK_METADATA_PREFIX + "{appid}.{mediaType}") + @ResponseBody + public String metadata(HttpServletRequest request, + HttpServletResponse response, + @PathVariable("appid") String appId, + @PathVariable("mediaType") String mediaType) { + AppsJwtDetails jwtDetails = jwtDetailsService.getAppDetails(appId , true); + if(jwtDetails != null) { + String jwkSetString = ""; + if(!jwtDetails.getSignature().equalsIgnoreCase("none")) { + jwkSetString = jwtDetails.getSignatureKey(); + } + if(!jwtDetails.getAlgorithm().equalsIgnoreCase("none")) { + if(StringUtils.isBlank(jwkSetString)) { + jwkSetString = jwtDetails.getAlgorithmKey(); + }else { + jwkSetString = jwkSetString + "," +jwtDetails.getAlgorithmKey(); + } + } + + JWKSetKeyStore jwkSetKeyStore = new JWKSetKeyStore("{\"keys\": [" + jwkSetString + "]}"); + if(StringUtils.isNotBlank(mediaType) + && mediaType.equalsIgnoreCase("xml")) { + response.setContentType(ContentType.APPLICATION_XML_UTF8); + }else { + response.setContentType(ContentType.APPLICATION_JSON_UTF8); + } + return jwkSetKeyStore.toString(mediaType); + + } + return appId + " not exist. \n" + WebContext.version(); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/DefaultExpiringOAuth2RefreshToken.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/DefaultExpiringOAuth2RefreshToken.java index f1a8a7921..981a6e2c0 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/DefaultExpiringOAuth2RefreshToken.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/DefaultExpiringOAuth2RefreshToken.java @@ -24,26 +24,26 @@ import java.util.Date; */ public class DefaultExpiringOAuth2RefreshToken extends DefaultOAuth2RefreshToken implements ExpiringOAuth2RefreshToken { - private static final long serialVersionUID = 3449554332764129719L; + private static final long serialVersionUID = 3449554332764129719L; - private final Date expiration; + private final Date expiration; - /** - * @param value - */ - public DefaultExpiringOAuth2RefreshToken(String value, Date expiration) { - super(value); - this.expiration = expiration; - } + /** + * @param value + */ + public DefaultExpiringOAuth2RefreshToken(String value, Date expiration) { + super(value); + this.expiration = expiration; + } - /** - * The instant the token expires. - * - * @return The instant the token expires. - */ - @Override - public Date getExpiration() { - return expiration; - } + /** + * The instant the token expires. + * + * @return The instant the token expires. + */ + @Override + public Date getExpiration() { + return expiration; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/DefaultOAuth2AccessToken.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/DefaultOAuth2AccessToken.java index 6641d30dc..2a861d014 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/DefaultOAuth2AccessToken.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/DefaultOAuth2AccessToken.java @@ -83,7 +83,7 @@ public class DefaultOAuth2AccessToken implements Serializable, OAuth2AccessToken } public DefaultOAuth2AccessToken(OAuth2Exception oauth2Exception) { - this.oauth2Exception = oauth2Exception; + this.oauth2Exception = oauth2Exception; } public void setValue(String value) { @@ -274,10 +274,10 @@ public class DefaultOAuth2AccessToken implements Serializable, OAuth2AccessToken this.additionalInformation = new LinkedHashMap(additionalInformation); } - @Override - public OAuth2Exception getOAuth2Exception() { - - return this.oauth2Exception; - } + @Override + public OAuth2Exception getOAuth2Exception() { + + return this.oauth2Exception; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/ExpiringOAuth2RefreshToken.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/ExpiringOAuth2RefreshToken.java index 17bdfd916..a40242f2d 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/ExpiringOAuth2RefreshToken.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/ExpiringOAuth2RefreshToken.java @@ -20,6 +20,6 @@ import java.util.Date; */ public interface ExpiringOAuth2RefreshToken extends OAuth2RefreshToken { - Date getExpiration(); + Date getExpiration(); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2AccessToken.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2AccessToken.java index 88366b24b..fc91d7853 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2AccessToken.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2AccessToken.java @@ -28,67 +28,67 @@ import org.dromara.maxkey.authz.oauth2.common.exceptions.OAuth2Exception; public interface OAuth2AccessToken extends Serializable { - public static String BEARER_TYPE = "Bearer"; + public static String BEARER_TYPE = "Bearer"; - public static String OAUTH2_TYPE = "OAuth2"; + public static String OAUTH2_TYPE = "OAuth2"; - /** - * The access token issued by the authorization server. This value is REQUIRED. - */ - public static String ACCESS_TOKEN = "access_token"; + /** + * The access token issued by the authorization server. This value is REQUIRED. + */ + public static String ACCESS_TOKEN = "access_token"; - /** - * The type of the token issued as described in Section 7.1. Value is case insensitive. - * This value is REQUIRED. - */ - public static String TOKEN_TYPE = "token_type"; + /** + * The type of the token issued as described in Section 7.1. Value is case insensitive. + * This value is REQUIRED. + */ + public static String TOKEN_TYPE = "token_type"; - /** - * The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will - * expire in one hour from the time the response was generated. This value is OPTIONAL. - */ - public static String EXPIRES_IN = "expires_in"; + /** + * The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will + * expire in one hour from the time the response was generated. This value is OPTIONAL. + */ + public static String EXPIRES_IN = "expires_in"; - /** - * The refresh token which can be used to obtain new access tokens using the same authorization grant as described - * in Section 6. This value is OPTIONAL. - */ - public static String REFRESH_TOKEN = "refresh_token"; + /** + * The refresh token which can be used to obtain new access tokens using the same authorization grant as described + * in Section 6. This value is OPTIONAL. + */ + public static String REFRESH_TOKEN = "refresh_token"; - /** - * The scope of the access token as described by Section 3.3 - */ - public static String SCOPE = "scope"; - - public static String ERROR = "error"; - - public static String ERROR_DESCRIPTION = "error_description"; - + /** + * The scope of the access token as described by Section 3.3 + */ + public static String SCOPE = "scope"; + + public static String ERROR = "error"; + + public static String ERROR_DESCRIPTION = "error_description"; + - /** - * The additionalInformation map is used by the token serializers to export any fields used by extensions of OAuth. - * @return a map from the field name in the serialized token to the value to be exported. The default serializers - * make use of Jackson's automatic JSON mapping for Java objects (for the Token Endpoint flows) or implicitly call - * .toString() on the "value" object (for the implicit flow) as part of the serialization process. - */ - Map getAdditionalInformation(); + /** + * The additionalInformation map is used by the token serializers to export any fields used by extensions of OAuth. + * @return a map from the field name in the serialized token to the value to be exported. The default serializers + * make use of Jackson's automatic JSON mapping for Java objects (for the Token Endpoint flows) or implicitly call + * .toString() on the "value" object (for the implicit flow) as part of the serialization process. + */ + Map getAdditionalInformation(); - Set getScope(); + Set getScope(); - OAuth2RefreshToken getRefreshToken(); + OAuth2RefreshToken getRefreshToken(); - String getTokenType(); - - OAuth2Exception getOAuth2Exception(); + String getTokenType(); + + OAuth2Exception getOAuth2Exception(); - boolean isExpired(); + boolean isExpired(); - Date getExpiration(); + Date getExpiration(); - int getExpiresIn(); + int getExpiresIn(); - String getValue(); + String getValue(); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2AccessTokenJackson2Deserializer.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2AccessTokenJackson2Deserializer.java index 315bcbf54..1900a705c 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2AccessTokenJackson2Deserializer.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2AccessTokenJackson2Deserializer.java @@ -45,62 +45,62 @@ import com.fasterxml.jackson.databind.deser.std.StdDeserializer; @SuppressWarnings("serial") public final class OAuth2AccessTokenJackson2Deserializer extends StdDeserializer { - public OAuth2AccessTokenJackson2Deserializer() { - super(OAuth2AccessToken.class); - } + public OAuth2AccessTokenJackson2Deserializer() { + super(OAuth2AccessToken.class); + } - @Override - public OAuth2AccessToken deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, - JsonProcessingException { + @Override + public OAuth2AccessToken deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, + JsonProcessingException { - String tokenValue = null; - String tokenType = null; - String refreshToken = null; - Long expiresIn = null; - Set scope = null; - Map additionalInformation = new LinkedHashMap(); + String tokenValue = null; + String tokenType = null; + String refreshToken = null; + Long expiresIn = null; + Set scope = null; + Map additionalInformation = new LinkedHashMap(); - // What should occur if a parameter exists twice - while (jp.nextToken() != JsonToken.END_OBJECT) { - String name = jp.currentName(); - jp.nextToken(); - if (OAuth2AccessToken.ACCESS_TOKEN.equals(name)) { - tokenValue = jp.getText(); - } - else if (OAuth2AccessToken.TOKEN_TYPE.equals(name)) { - tokenType = jp.getText(); - } - else if (OAuth2AccessToken.REFRESH_TOKEN.equals(name)) { - refreshToken = jp.getText(); - } - else if (OAuth2AccessToken.EXPIRES_IN.equals(name)) { - try { - expiresIn = jp.getLongValue(); - } catch (JsonParseException e) { - expiresIn = Long.valueOf(jp.getText()); - } - } - else if (OAuth2AccessToken.SCOPE.equals(name)) { - String text = jp.getText(); - scope = OAuth2Utils.parseParameterList(text); - } else { - additionalInformation.put(name, jp.readValueAs(Object.class)); - } - } + // What should occur if a parameter exists twice + while (jp.nextToken() != JsonToken.END_OBJECT) { + String name = jp.currentName(); + jp.nextToken(); + if (OAuth2AccessToken.ACCESS_TOKEN.equals(name)) { + tokenValue = jp.getText(); + } + else if (OAuth2AccessToken.TOKEN_TYPE.equals(name)) { + tokenType = jp.getText(); + } + else if (OAuth2AccessToken.REFRESH_TOKEN.equals(name)) { + refreshToken = jp.getText(); + } + else if (OAuth2AccessToken.EXPIRES_IN.equals(name)) { + try { + expiresIn = jp.getLongValue(); + } catch (JsonParseException e) { + expiresIn = Long.valueOf(jp.getText()); + } + } + else if (OAuth2AccessToken.SCOPE.equals(name)) { + String text = jp.getText(); + scope = OAuth2Utils.parseParameterList(text); + } else { + additionalInformation.put(name, jp.readValueAs(Object.class)); + } + } - // What should occur if a required parameter (tokenValue or tokenType) is missing? + // What should occur if a required parameter (tokenValue or tokenType) is missing? - DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(tokenValue); - accessToken.setTokenType(tokenType); - if (expiresIn != null) { - accessToken.setExpiration(new Date(System.currentTimeMillis() + (expiresIn * 1000))); - } - if (refreshToken != null) { - accessToken.setRefreshToken(new DefaultOAuth2RefreshToken(refreshToken)); - } - accessToken.setScope(scope); - accessToken.setAdditionalInformation(additionalInformation); + DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(tokenValue); + accessToken.setTokenType(tokenType); + if (expiresIn != null) { + accessToken.setExpiration(new Date(System.currentTimeMillis() + (expiresIn * 1000))); + } + if (refreshToken != null) { + accessToken.setRefreshToken(new DefaultOAuth2RefreshToken(refreshToken)); + } + accessToken.setScope(scope); + accessToken.setAdditionalInformation(additionalInformation); - return accessToken; - } + return accessToken; + } } \ No newline at end of file diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2AccessTokenJackson2Serializer.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2AccessTokenJackson2Serializer.java index 20709c6d9..78d45e98c 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2AccessTokenJackson2Serializer.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2AccessTokenJackson2Serializer.java @@ -34,49 +34,49 @@ import com.fasterxml.jackson.databind.ser.std.StdSerializer; */ public final class OAuth2AccessTokenJackson2Serializer extends StdSerializer { - /** - * - */ - private static final long serialVersionUID = -7323248504425950254L; + /** + * + */ + private static final long serialVersionUID = -7323248504425950254L; - public OAuth2AccessTokenJackson2Serializer() { - super(OAuth2AccessToken.class); - } + public OAuth2AccessTokenJackson2Serializer() { + super(OAuth2AccessToken.class); + } - @Override - public void serialize(OAuth2AccessToken token, JsonGenerator jgen, SerializerProvider provider) throws IOException, - JsonGenerationException { - jgen.writeStartObject(); - if(token.getOAuth2Exception()==null) { - jgen.writeStringField(OAuth2AccessToken.ACCESS_TOKEN, token.getValue()); - jgen.writeStringField(OAuth2AccessToken.TOKEN_TYPE, token.getTokenType()); - OAuth2RefreshToken refreshToken = token.getRefreshToken(); - if (refreshToken != null) { - jgen.writeStringField(OAuth2AccessToken.REFRESH_TOKEN, refreshToken.getValue()); - } - Date expiration = token.getExpiration(); - if (expiration != null) { - long now = System.currentTimeMillis(); - jgen.writeNumberField(OAuth2AccessToken.EXPIRES_IN, (expiration.getTime() - now) / 1000); - } - Set scope = token.getScope(); - if (scope != null && !scope.isEmpty()) { - StringBuffer scopes = new StringBuffer(); - for (String s : scope) { - Assert.hasLength(s, "Scopes cannot be null or empty. Got " + scope + ""); - scopes.append(s); - scopes.append(" "); - } - jgen.writeStringField(OAuth2AccessToken.SCOPE, scopes.substring(0, scopes.length() - 1)); - } - }else { - jgen.writeStringField(OAuth2AccessToken.ERROR, token.getOAuth2Exception().getOAuth2ErrorCode()); - jgen.writeStringField(OAuth2AccessToken.ERROR_DESCRIPTION, token.getOAuth2Exception().getMessage()); - } - Map additionalInformation = token.getAdditionalInformation(); - for (String key : additionalInformation.keySet()) { - jgen.writeObjectField(key, additionalInformation.get(key)); - } - jgen.writeEndObject(); - } + @Override + public void serialize(OAuth2AccessToken token, JsonGenerator jgen, SerializerProvider provider) throws IOException, + JsonGenerationException { + jgen.writeStartObject(); + if(token.getOAuth2Exception()==null) { + jgen.writeStringField(OAuth2AccessToken.ACCESS_TOKEN, token.getValue()); + jgen.writeStringField(OAuth2AccessToken.TOKEN_TYPE, token.getTokenType()); + OAuth2RefreshToken refreshToken = token.getRefreshToken(); + if (refreshToken != null) { + jgen.writeStringField(OAuth2AccessToken.REFRESH_TOKEN, refreshToken.getValue()); + } + Date expiration = token.getExpiration(); + if (expiration != null) { + long now = System.currentTimeMillis(); + jgen.writeNumberField(OAuth2AccessToken.EXPIRES_IN, (expiration.getTime() - now) / 1000); + } + Set scope = token.getScope(); + if (scope != null && !scope.isEmpty()) { + StringBuffer scopes = new StringBuffer(); + for (String s : scope) { + Assert.hasLength(s, "Scopes cannot be null or empty. Got " + scope + ""); + scopes.append(s); + scopes.append(" "); + } + jgen.writeStringField(OAuth2AccessToken.SCOPE, scopes.substring(0, scopes.length() - 1)); + } + }else { + jgen.writeStringField(OAuth2AccessToken.ERROR, token.getOAuth2Exception().getOAuth2ErrorCode()); + jgen.writeStringField(OAuth2AccessToken.ERROR_DESCRIPTION, token.getOAuth2Exception().getMessage()); + } + Map additionalInformation = token.getAdditionalInformation(); + for (String key : additionalInformation.keySet()) { + jgen.writeObjectField(key, additionalInformation.get(key)); + } + jgen.writeEndObject(); + } } \ No newline at end of file diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2Constants.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2Constants.java index 497f531cf..3fba0362e 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2Constants.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2Constants.java @@ -18,115 +18,115 @@ package org.dromara.maxkey.authz.oauth2.common; public class OAuth2Constants { - - public static final class PARAMETER{ - /** - * Constant to use while parsing and formatting parameter maps for OAuth2 requests - */ - public static final String CLIENT_ID = "client_id"; - - public static final String CLIENT_SECRET = "client_secret"; - - /** - * Constant to use while parsing and formatting parameter maps for OAuth2 requests - */ - public static final String STATE = "state"; + + public static final class PARAMETER{ + /** + * Constant to use while parsing and formatting parameter maps for OAuth2 requests + */ + public static final String CLIENT_ID = "client_id"; + + public static final String CLIENT_SECRET = "client_secret"; + + /** + * Constant to use while parsing and formatting parameter maps for OAuth2 requests + */ + public static final String STATE = "state"; - /** - * Constant to use while parsing and formatting parameter maps for OAuth2 requests - */ - public static final String SCOPE = "scope"; + /** + * Constant to use while parsing and formatting parameter maps for OAuth2 requests + */ + public static final String SCOPE = "scope"; - public static final String CODE = "code"; - - - - public static final String TOKEN = "token"; - - public static final String TOKEN_TYPE = "token_type"; - - public static final String EXPIRES_IN = "expires_in"; - - /** - * Constant to use while parsing and formatting parameter maps for OAuth2 requests - */ - public static final String REDIRECT_URI = "redirect_uri"; + public static final String CODE = "code"; + + + + public static final String TOKEN = "token"; + + public static final String TOKEN_TYPE = "token_type"; + + public static final String EXPIRES_IN = "expires_in"; + + /** + * Constant to use while parsing and formatting parameter maps for OAuth2 requests + */ + public static final String REDIRECT_URI = "redirect_uri"; - /** - * Constant to use while parsing and formatting parameter maps for OAuth2 requests - */ - public static final String RESPONSE_TYPE = "response_type"; + /** + * Constant to use while parsing and formatting parameter maps for OAuth2 requests + */ + public static final String RESPONSE_TYPE = "response_type"; - /** - * Constant to use while parsing and formatting parameter maps for OAuth2 requests - */ - public static final String USER_OAUTH_APPROVAL = "user_oauth_approval"; + /** + * Constant to use while parsing and formatting parameter maps for OAuth2 requests + */ + public static final String USER_OAUTH_APPROVAL = "user_oauth_approval"; - /** - * Constant to use as a prefix for scope approval - */ - public static final String SCOPE_PREFIX = "scope."; + /** + * Constant to use as a prefix for scope approval + */ + public static final String SCOPE_PREFIX = "scope."; - /** - * Constant to use while parsing and formatting parameter maps for OAuth2 requests - */ - public static final String GRANT_TYPE = "grant_type"; - public static final String GRANT_TYPE_CODE = "code"; - public static final String GRANT_TYPE_PASSWORD = "password"; - public static final String GRANT_TYPE_IMPLICIT = "implicit"; - public static final String GRANT_TYPE_AUTHORIZATION_CODE = "authorization_code"; - public static final String GRANT_TYPE_CLIENT_CREDENTIALS = "client_credentials"; - public static final String GRANT_TYPE_REFRESH_TOKEN = "refresh_token"; - - - public static final String ACCESS_TOKEN = "access_token"; - - public static final String APPROVAL_PROMPT = "approval_prompt"; - - //https://datatracker.ietf.org/doc/html/rfc7636 PKCE - //Proof Key for Code Exchange by OAuth Public Clients - public static final String CODE_CHALLENGE = "code_challenge" ; - - public static final String CODE_CHALLENGE_METHOD = "code_challenge_method" ; - - public static final String CODE_VERIFIER = "code_verifier" ; - - - - } - - public static class PKCE_TYPE{ - public static final String PKCE_TYPE_YES = "YES" ; + /** + * Constant to use while parsing and formatting parameter maps for OAuth2 requests + */ + public static final String GRANT_TYPE = "grant_type"; + public static final String GRANT_TYPE_CODE = "code"; + public static final String GRANT_TYPE_PASSWORD = "password"; + public static final String GRANT_TYPE_IMPLICIT = "implicit"; + public static final String GRANT_TYPE_AUTHORIZATION_CODE = "authorization_code"; + public static final String GRANT_TYPE_CLIENT_CREDENTIALS = "client_credentials"; + public static final String GRANT_TYPE_REFRESH_TOKEN = "refresh_token"; + + + public static final String ACCESS_TOKEN = "access_token"; + + public static final String APPROVAL_PROMPT = "approval_prompt"; + + //https://datatracker.ietf.org/doc/html/rfc7636 PKCE + //Proof Key for Code Exchange by OAuth Public Clients + public static final String CODE_CHALLENGE = "code_challenge" ; + + public static final String CODE_CHALLENGE_METHOD = "code_challenge_method" ; + + public static final String CODE_VERIFIER = "code_verifier" ; + + + + } + + public static class PKCE_TYPE{ + public static final String PKCE_TYPE_YES = "YES" ; public static final String PKCE_TYPE_NO = "NO" ; - } - - public static class CODE_CHALLENGE_METHOD_TYPE{ + } + + public static class CODE_CHALLENGE_METHOD_TYPE{ public static final String PLAIN = "plain" ; public static final String S256 = "S256" ; } - - public static class ENDPOINT{ - - public static final String ENDPOINT_BASE = "/authz/oauth/v20"; - - public static final String ENDPOINT_AUTHORIZE = ENDPOINT_BASE + "/authorize"; - - public static final String ENDPOINT_TOKEN = ENDPOINT_BASE + "/token"; - - public static final String ENDPOINT_CHECK_TOKEN = ENDPOINT_BASE + "/check_token"; - - public static final String ENDPOINT_TOKEN_KEY = ENDPOINT_BASE + "/token_key"; - - public static final String ENDPOINT_APPROVAL_CONFIRM = ENDPOINT_BASE + "/approval_confirm"; - - public static final String ENDPOINT_ERROR = ENDPOINT_BASE + "/error"; - - public static final String ENDPOINT_USERINFO = "/api/oauth/v20/me"; - - public static final String ENDPOINT_OPENID_CONNECT_USERINFO = "/api/connect/v10/userinfo"; - - public static final String ENDPOINT_TENCENT_IOA_AUTHORIZE = "/oauth2/authorize"; - public static final String ENDPOINT_TENCENT_IOA_TOKEN = "/oauth2/token"; - - } + + public static class ENDPOINT{ + + public static final String ENDPOINT_BASE = "/authz/oauth/v20"; + + public static final String ENDPOINT_AUTHORIZE = ENDPOINT_BASE + "/authorize"; + + public static final String ENDPOINT_TOKEN = ENDPOINT_BASE + "/token"; + + public static final String ENDPOINT_CHECK_TOKEN = ENDPOINT_BASE + "/check_token"; + + public static final String ENDPOINT_TOKEN_KEY = ENDPOINT_BASE + "/token_key"; + + public static final String ENDPOINT_APPROVAL_CONFIRM = ENDPOINT_BASE + "/approval_confirm"; + + public static final String ENDPOINT_ERROR = ENDPOINT_BASE + "/error"; + + public static final String ENDPOINT_USERINFO = "/api/oauth/v20/me"; + + public static final String ENDPOINT_OPENID_CONNECT_USERINFO = "/api/connect/v10/userinfo"; + + public static final String ENDPOINT_TENCENT_IOA_AUTHORIZE = "/oauth2/authorize"; + public static final String ENDPOINT_TENCENT_IOA_TOKEN = "/oauth2/token"; + + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2RefreshToken.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2RefreshToken.java index fa07cd3f8..89cc099d4 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2RefreshToken.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/OAuth2RefreshToken.java @@ -23,12 +23,12 @@ import com.fasterxml.jackson.annotation.JsonValue; */ public interface OAuth2RefreshToken extends Serializable { - /** - * The value of the token. - * - * @return The value of the token. - */ - @JsonValue - String getValue(); + /** + * The value of the token. + * + * @return The value of the token. + */ + @JsonValue + String getValue(); } \ No newline at end of file diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/BadClientCredentialsException.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/BadClientCredentialsException.java index d93da2e95..9605ce05f 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/BadClientCredentialsException.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/BadClientCredentialsException.java @@ -26,17 +26,17 @@ package org.dromara.maxkey.authz.oauth2.common.exceptions; @SuppressWarnings("serial") public class BadClientCredentialsException extends ClientAuthenticationException { - public BadClientCredentialsException() { - super("Bad client credentials"); // Don't reveal source of error - } + public BadClientCredentialsException() { + super("Bad client credentials"); // Don't reveal source of error + } - @Override - public int getHttpErrorCode() { - return 401; - } + @Override + public int getHttpErrorCode() { + return 401; + } - @Override - public String getOAuth2ErrorCode() { - return "invalid_client"; - } + @Override + public String getOAuth2ErrorCode() { + return "invalid_client"; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/ClientAuthenticationException.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/ClientAuthenticationException.java index 71b5148c5..cb62cec0d 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/ClientAuthenticationException.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/ClientAuthenticationException.java @@ -26,20 +26,20 @@ package org.dromara.maxkey.authz.oauth2.common.exceptions; @SuppressWarnings("serial") public abstract class ClientAuthenticationException extends OAuth2Exception { - public ClientAuthenticationException(String msg, Throwable t) { - super(msg, t); - } + public ClientAuthenticationException(String msg, Throwable t) { + super(msg, t); + } - public ClientAuthenticationException(String msg) { - super(msg); - } + public ClientAuthenticationException(String msg) { + super(msg); + } - @Override - public int getHttpErrorCode() { - // The spec says this is a bad request (not unauthorized) - return 400; - } + @Override + public int getHttpErrorCode() { + // The spec says this is a bad request (not unauthorized) + return 400; + } - @Override - public abstract String getOAuth2ErrorCode(); + @Override + public abstract String getOAuth2ErrorCode(); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InsufficientScopeException.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InsufficientScopeException.java index 6d9319139..6149d26a6 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InsufficientScopeException.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InsufficientScopeException.java @@ -30,24 +30,24 @@ import org.dromara.maxkey.authz.oauth2.common.util.OAuth2Utils; @SuppressWarnings("serial") public class InsufficientScopeException extends OAuth2Exception { - public InsufficientScopeException(String msg, Set validScope) { - this(msg); - addAdditionalInformation("scope", OAuth2Utils.formatParameterList(validScope)); - } + public InsufficientScopeException(String msg, Set validScope) { + this(msg); + addAdditionalInformation("scope", OAuth2Utils.formatParameterList(validScope)); + } - public InsufficientScopeException(String msg) { - super(msg); - } + public InsufficientScopeException(String msg) { + super(msg); + } - @Override - public int getHttpErrorCode() { - return 403; - } + @Override + public int getHttpErrorCode() { + return 403; + } - @Override - public String getOAuth2ErrorCode() { - // Not defined in the spec, so not really an OAuth2Exception - return "insufficient_scope"; - } + @Override + public String getOAuth2ErrorCode() { + // Not defined in the spec, so not really an OAuth2Exception + return "insufficient_scope"; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidClientException.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidClientException.java index 1e0a6fde3..98b0882cd 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidClientException.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidClientException.java @@ -26,17 +26,17 @@ package org.dromara.maxkey.authz.oauth2.common.exceptions; @SuppressWarnings("serial") public class InvalidClientException extends ClientAuthenticationException { - public InvalidClientException(String msg) { - super(msg); - } + public InvalidClientException(String msg) { + super(msg); + } - @Override - public int getHttpErrorCode() { - return 401; - } + @Override + public int getHttpErrorCode() { + return 401; + } - @Override - public String getOAuth2ErrorCode() { - return "invalid_client"; - } + @Override + public String getOAuth2ErrorCode() { + return "invalid_client"; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidGrantException.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidGrantException.java index dc353fbbe..2c66c506d 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidGrantException.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidGrantException.java @@ -24,16 +24,16 @@ package org.dromara.maxkey.authz.oauth2.common.exceptions; @SuppressWarnings("serial") public class InvalidGrantException extends ClientAuthenticationException { - public InvalidGrantException(String msg, Throwable t) { - super(msg, t); - } + public InvalidGrantException(String msg, Throwable t) { + super(msg, t); + } - public InvalidGrantException(String msg) { - super(msg); - } + public InvalidGrantException(String msg) { + super(msg); + } - @Override - public String getOAuth2ErrorCode() { - return "invalid_grant"; - } + @Override + public String getOAuth2ErrorCode() { + return "invalid_grant"; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidRequestException.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidRequestException.java index cd6c837aa..493ed2eb5 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidRequestException.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidRequestException.java @@ -23,16 +23,16 @@ package org.dromara.maxkey.authz.oauth2.common.exceptions; @SuppressWarnings("serial") public class InvalidRequestException extends ClientAuthenticationException { - public InvalidRequestException(String msg, Throwable t) { - super(msg, t); - } + public InvalidRequestException(String msg, Throwable t) { + super(msg, t); + } - public InvalidRequestException(String msg) { - super(msg); - } + public InvalidRequestException(String msg) { + super(msg); + } - @Override - public String getOAuth2ErrorCode() { - return "invalid_request"; - } + @Override + public String getOAuth2ErrorCode() { + return "invalid_request"; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidScopeException.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidScopeException.java index 6ead15c85..f264b526e 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidScopeException.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidScopeException.java @@ -32,18 +32,18 @@ import org.dromara.maxkey.authz.oauth2.common.util.OAuth2Utils; @SuppressWarnings("serial") public class InvalidScopeException extends OAuth2Exception { - public InvalidScopeException(String msg, Set validScope) { - this(msg); - addAdditionalInformation("scope", OAuth2Utils.formatParameterList(validScope)); - } + public InvalidScopeException(String msg, Set validScope) { + this(msg); + addAdditionalInformation("scope", OAuth2Utils.formatParameterList(validScope)); + } - public InvalidScopeException(String msg) { - super(msg); - } + public InvalidScopeException(String msg) { + super(msg); + } - @Override - public String getOAuth2ErrorCode() { - return "invalid_scope"; - } + @Override + public String getOAuth2ErrorCode() { + return "invalid_scope"; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidTokenException.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidTokenException.java index 18894f0fd..8d969c8b4 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidTokenException.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/InvalidTokenException.java @@ -22,21 +22,21 @@ package org.dromara.maxkey.authz.oauth2.common.exceptions; @SuppressWarnings("serial") public class InvalidTokenException extends ClientAuthenticationException { - public InvalidTokenException(String msg, Throwable t) { - super(msg, t); - } + public InvalidTokenException(String msg, Throwable t) { + super(msg, t); + } - public InvalidTokenException(String msg) { - super(msg); - } + public InvalidTokenException(String msg) { + super(msg); + } - @Override - public int getHttpErrorCode() { - return 401; - } + @Override + public int getHttpErrorCode() { + return 401; + } - @Override - public String getOAuth2ErrorCode() { - return "invalid_token"; - } + @Override + public String getOAuth2ErrorCode() { + return "invalid_token"; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2Exception.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2Exception.java index b767cb402..4f893e280 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2Exception.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2Exception.java @@ -33,175 +33,175 @@ import java.util.TreeMap; @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = OAuth2ExceptionJackson2Deserializer.class) public class OAuth2Exception extends RuntimeException { - public static final String ERROR = "error"; - public static final String DESCRIPTION = "error_description"; - public static final String URI = "error_uri"; - public static final String INVALID_REQUEST = "invalid_request"; - public static final String INVALID_CLIENT = "invalid_client"; - public static final String INVALID_GRANT = "invalid_grant"; - public static final String UNAUTHORIZED_CLIENT = "unauthorized_client"; - public static final String UNSUPPORTED_GRANT_TYPE = "unsupported_grant_type"; - public static final String INVALID_SCOPE = "invalid_scope"; - public static final String INSUFFICIENT_SCOPE = "insufficient_scope"; - public static final String INVALID_TOKEN = "invalid_token"; - public static final String REDIRECT_URI_MISMATCH ="redirect_uri_mismatch"; - public static final String UNSUPPORTED_RESPONSE_TYPE ="unsupported_response_type"; - public static final String ACCESS_DENIED = "access_denied"; + public static final String ERROR = "error"; + public static final String DESCRIPTION = "error_description"; + public static final String URI = "error_uri"; + public static final String INVALID_REQUEST = "invalid_request"; + public static final String INVALID_CLIENT = "invalid_client"; + public static final String INVALID_GRANT = "invalid_grant"; + public static final String UNAUTHORIZED_CLIENT = "unauthorized_client"; + public static final String UNSUPPORTED_GRANT_TYPE = "unsupported_grant_type"; + public static final String INVALID_SCOPE = "invalid_scope"; + public static final String INSUFFICIENT_SCOPE = "insufficient_scope"; + public static final String INVALID_TOKEN = "invalid_token"; + public static final String REDIRECT_URI_MISMATCH ="redirect_uri_mismatch"; + public static final String UNSUPPORTED_RESPONSE_TYPE ="unsupported_response_type"; + public static final String ACCESS_DENIED = "access_denied"; - private Map additionalInformation = null; + private Map additionalInformation = null; - public OAuth2Exception(String msg, Throwable t) { - super(msg, t); - } + public OAuth2Exception(String msg, Throwable t) { + super(msg, t); + } - public OAuth2Exception(String msg) { - super(msg); - } + public OAuth2Exception(String msg) { + super(msg); + } - /** - * The OAuth2 error code. - * - * @return The OAuth2 error code. - */ - public String getOAuth2ErrorCode() { - return "invalid_request"; - } + /** + * The OAuth2 error code. + * + * @return The OAuth2 error code. + */ + public String getOAuth2ErrorCode() { + return "invalid_request"; + } - /** - * The HTTP error code associated with this error. - * - * @return The HTTP error code associated with this error. - */ - public int getHttpErrorCode() { - return 400; - } + /** + * The HTTP error code associated with this error. + * + * @return The HTTP error code associated with this error. + */ + public int getHttpErrorCode() { + return 400; + } - /** - * Get any additional information associated with this error. - * - * @return Additional information, or null if none. - */ - public Map getAdditionalInformation() { - return this.additionalInformation; - } + /** + * Get any additional information associated with this error. + * + * @return Additional information, or null if none. + */ + public Map getAdditionalInformation() { + return this.additionalInformation; + } - /** - * Add some additional information with this OAuth error. - * - * @param key The key. - * @param value The value. - */ - public void addAdditionalInformation(String key, String value) { - if (this.additionalInformation == null) { - this.additionalInformation = new TreeMap(); - } + /** + * Add some additional information with this OAuth error. + * + * @param key The key. + * @param value The value. + */ + public void addAdditionalInformation(String key, String value) { + if (this.additionalInformation == null) { + this.additionalInformation = new TreeMap(); + } - this.additionalInformation.put(key, value); + this.additionalInformation.put(key, value); - } + } - /** - * Creates the appropriate subclass of OAuth2Exception given the errorCode. - * @param errorCode - * @param errorMessage - * @return - */ - public static OAuth2Exception create(String errorCode, String errorMessage) { - if (errorMessage == null) { - errorMessage = errorCode == null ? "OAuth Error" : errorCode; - } - if (INVALID_CLIENT.equals(errorCode)) { - return new InvalidClientException(errorMessage); - } - else if (UNAUTHORIZED_CLIENT.equals(errorCode)) { - return new UnauthorizedUserException(errorMessage); - } - else if (INVALID_GRANT.equals(errorCode)) { - return new InvalidGrantException(errorMessage); - } - else if (INVALID_SCOPE.equals(errorCode)) { - return new InvalidScopeException(errorMessage); - } - else if (INVALID_TOKEN.equals(errorCode)) { - return new InvalidTokenException(errorMessage); - } - else if (INVALID_REQUEST.equals(errorCode)) { - return new InvalidRequestException(errorMessage); - } - else if (REDIRECT_URI_MISMATCH.equals(errorCode)) { - return new RedirectMismatchException(errorMessage); - } - else if (UNSUPPORTED_GRANT_TYPE.equals(errorCode)) { - return new UnsupportedGrantTypeException(errorMessage); - } - else if (UNSUPPORTED_RESPONSE_TYPE.equals(errorCode)) { - return new UnsupportedResponseTypeException(errorMessage); - } - else if (ACCESS_DENIED.equals(errorCode)) { - return new UserDeniedAuthorizationException(errorMessage); - } - else { - return new OAuth2Exception(errorMessage); - } - } + /** + * Creates the appropriate subclass of OAuth2Exception given the errorCode. + * @param errorCode + * @param errorMessage + * @return + */ + public static OAuth2Exception create(String errorCode, String errorMessage) { + if (errorMessage == null) { + errorMessage = errorCode == null ? "OAuth Error" : errorCode; + } + if (INVALID_CLIENT.equals(errorCode)) { + return new InvalidClientException(errorMessage); + } + else if (UNAUTHORIZED_CLIENT.equals(errorCode)) { + return new UnauthorizedUserException(errorMessage); + } + else if (INVALID_GRANT.equals(errorCode)) { + return new InvalidGrantException(errorMessage); + } + else if (INVALID_SCOPE.equals(errorCode)) { + return new InvalidScopeException(errorMessage); + } + else if (INVALID_TOKEN.equals(errorCode)) { + return new InvalidTokenException(errorMessage); + } + else if (INVALID_REQUEST.equals(errorCode)) { + return new InvalidRequestException(errorMessage); + } + else if (REDIRECT_URI_MISMATCH.equals(errorCode)) { + return new RedirectMismatchException(errorMessage); + } + else if (UNSUPPORTED_GRANT_TYPE.equals(errorCode)) { + return new UnsupportedGrantTypeException(errorMessage); + } + else if (UNSUPPORTED_RESPONSE_TYPE.equals(errorCode)) { + return new UnsupportedResponseTypeException(errorMessage); + } + else if (ACCESS_DENIED.equals(errorCode)) { + return new UserDeniedAuthorizationException(errorMessage); + } + else { + return new OAuth2Exception(errorMessage); + } + } - /** - * Creates an {@link OAuth2Exception} from a Map. - * - * @param errorParams - * @return - */ - public static OAuth2Exception valueOf(Map errorParams) { - String errorCode = errorParams.get(ERROR); - String errorMessage = errorParams.containsKey(DESCRIPTION) ? errorParams.get(DESCRIPTION) - : null; - OAuth2Exception ex = create(errorCode, errorMessage); - Set> entries = errorParams.entrySet(); - for (Map.Entry entry : entries) { - String key = entry.getKey(); - if (!ERROR.equals(key) && !DESCRIPTION.equals(key)) { - ex.addAdditionalInformation(key, entry.getValue()); - } - } + /** + * Creates an {@link OAuth2Exception} from a Map. + * + * @param errorParams + * @return + */ + public static OAuth2Exception valueOf(Map errorParams) { + String errorCode = errorParams.get(ERROR); + String errorMessage = errorParams.containsKey(DESCRIPTION) ? errorParams.get(DESCRIPTION) + : null; + OAuth2Exception ex = create(errorCode, errorMessage); + Set> entries = errorParams.entrySet(); + for (Map.Entry entry : entries) { + String key = entry.getKey(); + if (!ERROR.equals(key) && !DESCRIPTION.equals(key)) { + ex.addAdditionalInformation(key, entry.getValue()); + } + } - return ex; - } - - @Override - public String toString() { - return getSummary(); - } + return ex; + } + + @Override + public String toString() { + return getSummary(); + } - /** - * @return a comma-delimited list of details (key=value pairs) - */ - public String getSummary() { - - StringBuilder builder = new StringBuilder(); + /** + * @return a comma-delimited list of details (key=value pairs) + */ + public String getSummary() { + + StringBuilder builder = new StringBuilder(); - String delim = ""; + String delim = ""; - String error = this.getOAuth2ErrorCode(); - if (error != null) { - builder.append(delim).append("error=\"").append(error).append("\""); - delim = ", "; - } + String error = this.getOAuth2ErrorCode(); + if (error != null) { + builder.append(delim).append("error=\"").append(error).append("\""); + delim = ", "; + } - String errorMessage = this.getMessage(); - if (errorMessage != null) { - builder.append(delim).append("error_description=\"").append(errorMessage).append("\""); - delim = ", "; - } + String errorMessage = this.getMessage(); + if (errorMessage != null) { + builder.append(delim).append("error_description=\"").append(errorMessage).append("\""); + delim = ", "; + } - Map additionalParams = this.getAdditionalInformation(); - if (additionalParams != null) { - for (Map.Entry param : additionalParams.entrySet()) { - builder.append(delim).append(param.getKey()).append("=\"").append(param.getValue()).append("\""); - delim = ", "; - } - } - - return builder.toString(); + Map additionalParams = this.getAdditionalInformation(); + if (additionalParams != null) { + for (Map.Entry param : additionalParams.entrySet()) { + builder.append(delim).append(param.getKey()).append("=\"").append(param.getValue()).append("\""); + delim = ", "; + } + } + + return builder.toString(); - } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2ExceptionJackson1Deserializer.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2ExceptionJackson1Deserializer.java index ea458f2eb..7940948fc 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2ExceptionJackson1Deserializer.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2ExceptionJackson1Deserializer.java @@ -32,100 +32,100 @@ import com.fasterxml.jackson.databind.JsonDeserializer; */ public class OAuth2ExceptionJackson1Deserializer extends JsonDeserializer { - @Override - public OAuth2Exception deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, - JsonProcessingException { + @Override + public OAuth2Exception deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, + JsonProcessingException { - JsonToken t = jp.getCurrentToken(); - if (t == JsonToken.START_OBJECT) { - t = jp.nextToken(); - } - Map errorParams = new HashMap(); - for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) { - // Must point to field name - String fieldName = jp.currentName(); - // And then the value... - t = jp.nextToken(); - // Note: must handle null explicitly here; value deserializers won't - Object value; - if (t == JsonToken.VALUE_NULL) { - value = null; - } - // Some servers might send back complex content - else if (t == JsonToken.START_ARRAY) { - value = jp.readValueAs(List.class); - } - else if (t == JsonToken.START_OBJECT) { - value = jp.readValueAs(Map.class); - } - else { - value = jp.getText(); - } - errorParams.put(fieldName, value); - } + JsonToken t = jp.getCurrentToken(); + if (t == JsonToken.START_OBJECT) { + t = jp.nextToken(); + } + Map errorParams = new HashMap(); + for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) { + // Must point to field name + String fieldName = jp.currentName(); + // And then the value... + t = jp.nextToken(); + // Note: must handle null explicitly here; value deserializers won't + Object value; + if (t == JsonToken.VALUE_NULL) { + value = null; + } + // Some servers might send back complex content + else if (t == JsonToken.START_ARRAY) { + value = jp.readValueAs(List.class); + } + else if (t == JsonToken.START_OBJECT) { + value = jp.readValueAs(Map.class); + } + else { + value = jp.getText(); + } + errorParams.put(fieldName, value); + } - Object errorCode = errorParams.get("error"); - String errorMessage = errorParams.containsKey("error_description") ? errorParams.get("error_description") - .toString() : null; - if (errorMessage == null) { - errorMessage = errorCode == null ? "OAuth Error" : errorCode.toString(); - } + Object errorCode = errorParams.get("error"); + String errorMessage = errorParams.containsKey("error_description") ? errorParams.get("error_description") + .toString() : null; + if (errorMessage == null) { + errorMessage = errorCode == null ? "OAuth Error" : errorCode.toString(); + } - OAuth2Exception ex; - if ("invalid_client".equals(errorCode)) { - ex = new InvalidClientException(errorMessage); - } - else if ("unauthorized_client".equals(errorCode)) { - ex = new UnauthorizedUserException(errorMessage); - } - else if ("invalid_grant".equals(errorCode)) { - if (errorMessage.toLowerCase().contains("redirect") && errorMessage.toLowerCase().contains("match")) { - ex = new RedirectMismatchException(errorMessage); - } - else { - ex = new InvalidGrantException(errorMessage); - } - } - else if ("invalid_scope".equals(errorCode)) { - ex = new InvalidScopeException(errorMessage); - } - else if ("invalid_token".equals(errorCode)) { - ex = new InvalidTokenException(errorMessage); - } - else if ("invalid_request".equals(errorCode)) { - ex = new InvalidRequestException(errorMessage); - } - else if ("redirect_uri_mismatch".equals(errorCode)) { - ex = new RedirectMismatchException(errorMessage); - } - else if ("unsupported_grant_type".equals(errorCode)) { - ex = new UnsupportedGrantTypeException(errorMessage); - } - else if ("unsupported_response_type".equals(errorCode)) { - ex = new UnsupportedResponseTypeException(errorMessage); - } - else if ("access_denied".equals(errorCode)) { - ex = new UserDeniedAuthorizationException(errorMessage); - } - else if ("insufficient_scope".equals(errorCode)) { - ex = new InsufficientScopeException(errorMessage, OAuth2Utils.parseParameterList((String) errorParams - .get("scope"))); - } - else { - ex = new OAuth2Exception(errorMessage); - } + OAuth2Exception ex; + if ("invalid_client".equals(errorCode)) { + ex = new InvalidClientException(errorMessage); + } + else if ("unauthorized_client".equals(errorCode)) { + ex = new UnauthorizedUserException(errorMessage); + } + else if ("invalid_grant".equals(errorCode)) { + if (errorMessage.toLowerCase().contains("redirect") && errorMessage.toLowerCase().contains("match")) { + ex = new RedirectMismatchException(errorMessage); + } + else { + ex = new InvalidGrantException(errorMessage); + } + } + else if ("invalid_scope".equals(errorCode)) { + ex = new InvalidScopeException(errorMessage); + } + else if ("invalid_token".equals(errorCode)) { + ex = new InvalidTokenException(errorMessage); + } + else if ("invalid_request".equals(errorCode)) { + ex = new InvalidRequestException(errorMessage); + } + else if ("redirect_uri_mismatch".equals(errorCode)) { + ex = new RedirectMismatchException(errorMessage); + } + else if ("unsupported_grant_type".equals(errorCode)) { + ex = new UnsupportedGrantTypeException(errorMessage); + } + else if ("unsupported_response_type".equals(errorCode)) { + ex = new UnsupportedResponseTypeException(errorMessage); + } + else if ("access_denied".equals(errorCode)) { + ex = new UserDeniedAuthorizationException(errorMessage); + } + else if ("insufficient_scope".equals(errorCode)) { + ex = new InsufficientScopeException(errorMessage, OAuth2Utils.parseParameterList((String) errorParams + .get("scope"))); + } + else { + ex = new OAuth2Exception(errorMessage); + } - Set> entries = errorParams.entrySet(); - for (Map.Entry entry : entries) { - String key = entry.getKey(); - if (!"error".equals(key) && !"error_description".equals(key)) { - Object value = entry.getValue(); - ex.addAdditionalInformation(key, value == null ? null : value.toString()); - } - } + Set> entries = errorParams.entrySet(); + for (Map.Entry entry : entries) { + String key = entry.getKey(); + if (!"error".equals(key) && !"error_description".equals(key)) { + Object value = entry.getValue(); + ex.addAdditionalInformation(key, value == null ? null : value.toString()); + } + } - return ex; + return ex; - } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2ExceptionJackson1Serializer.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2ExceptionJackson1Serializer.java index 87e62819d..6d863fdca 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2ExceptionJackson1Serializer.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2ExceptionJackson1Serializer.java @@ -26,20 +26,20 @@ import com.fasterxml.jackson.databind.SerializerProvider; */ public class OAuth2ExceptionJackson1Serializer extends JsonSerializer { - @Override - public void serialize(OAuth2Exception value, JsonGenerator jgen, SerializerProvider provider) throws IOException, - JsonProcessingException { + @Override + public void serialize(OAuth2Exception value, JsonGenerator jgen, SerializerProvider provider) throws IOException, + JsonProcessingException { jgen.writeStartObject(); - jgen.writeStringField("error", value.getOAuth2ErrorCode()); - jgen.writeStringField("error_description", value.getMessage()); - if (value.getAdditionalInformation()!=null) { - for (Entry entry : value.getAdditionalInformation().entrySet()) { - String key = entry.getKey(); - String add = entry.getValue(); - jgen.writeStringField(key, add); - } - } + jgen.writeStringField("error", value.getOAuth2ErrorCode()); + jgen.writeStringField("error_description", value.getMessage()); + if (value.getAdditionalInformation()!=null) { + for (Entry entry : value.getAdditionalInformation().entrySet()) { + String key = entry.getKey(); + String add = entry.getValue(); + jgen.writeStringField(key, add); + } + } jgen.writeEndObject(); - } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2ExceptionJackson2Deserializer.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2ExceptionJackson2Deserializer.java index bc5e849c9..8c7a87f7c 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2ExceptionJackson2Deserializer.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2ExceptionJackson2Deserializer.java @@ -33,104 +33,104 @@ import org.dromara.maxkey.authz.oauth2.common.util.OAuth2Utils; @SuppressWarnings("serial") public class OAuth2ExceptionJackson2Deserializer extends StdDeserializer { - public OAuth2ExceptionJackson2Deserializer() { - super(OAuth2Exception.class); - } + public OAuth2ExceptionJackson2Deserializer() { + super(OAuth2Exception.class); + } - @Override - public OAuth2Exception deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, - JsonProcessingException { + @Override + public OAuth2Exception deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, + JsonProcessingException { - JsonToken t = jp.getCurrentToken(); - if (t == JsonToken.START_OBJECT) { - t = jp.nextToken(); - } - Map errorParams = new HashMap(); - for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) { - // Must point to field name - String fieldName = jp.currentName(); - // And then the value... - t = jp.nextToken(); - // Note: must handle null explicitly here; value deserializers won't - Object value; - if (t == JsonToken.VALUE_NULL) { - value = null; - } - // Some servers might send back complex content - else if (t == JsonToken.START_ARRAY) { - value = jp.readValueAs(List.class); - } - else if (t == JsonToken.START_OBJECT) { - value = jp.readValueAs(Map.class); - } - else { - value = jp.getText(); - } - errorParams.put(fieldName, value); - } + JsonToken t = jp.getCurrentToken(); + if (t == JsonToken.START_OBJECT) { + t = jp.nextToken(); + } + Map errorParams = new HashMap(); + for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) { + // Must point to field name + String fieldName = jp.currentName(); + // And then the value... + t = jp.nextToken(); + // Note: must handle null explicitly here; value deserializers won't + Object value; + if (t == JsonToken.VALUE_NULL) { + value = null; + } + // Some servers might send back complex content + else if (t == JsonToken.START_ARRAY) { + value = jp.readValueAs(List.class); + } + else if (t == JsonToken.START_OBJECT) { + value = jp.readValueAs(Map.class); + } + else { + value = jp.getText(); + } + errorParams.put(fieldName, value); + } - Object errorCode = errorParams.get("error"); - String errorMessage = errorParams.containsKey("error_description") ? errorParams.get("error_description") - .toString() : null; - if (errorMessage == null) { - errorMessage = errorCode == null ? "OAuth Error" : errorCode.toString(); - } + Object errorCode = errorParams.get("error"); + String errorMessage = errorParams.containsKey("error_description") ? errorParams.get("error_description") + .toString() : null; + if (errorMessage == null) { + errorMessage = errorCode == null ? "OAuth Error" : errorCode.toString(); + } - OAuth2Exception ex; - if ("invalid_client".equals(errorCode)) { - ex = new InvalidClientException(errorMessage); - } - else if ("unauthorized_client".equals(errorCode)) { - ex = new UnauthorizedUserException(errorMessage); - } - else if ("invalid_grant".equals(errorCode)) { - if (errorMessage.toLowerCase().contains("redirect") && errorMessage.toLowerCase().contains("match")) { - ex = new RedirectMismatchException(errorMessage); - } - else { - ex = new InvalidGrantException(errorMessage); - } - } - else if ("invalid_scope".equals(errorCode)) { - ex = new InvalidScopeException(errorMessage); - } - else if ("invalid_token".equals(errorCode)) { - ex = new InvalidTokenException(errorMessage); - } - else if ("invalid_request".equals(errorCode)) { - ex = new InvalidRequestException(errorMessage); - } - else if ("redirect_uri_mismatch".equals(errorCode)) { - ex = new RedirectMismatchException(errorMessage); - } - else if ("unsupported_grant_type".equals(errorCode)) { - ex = new UnsupportedGrantTypeException(errorMessage); - } - else if ("unsupported_response_type".equals(errorCode)) { - ex = new UnsupportedResponseTypeException(errorMessage); - } - else if ("insufficient_scope".equals(errorCode)) { - ex = new InsufficientScopeException(errorMessage, OAuth2Utils.parseParameterList((String) errorParams - .get("scope"))); - } - else if ("access_denied".equals(errorCode)) { - ex = new UserDeniedAuthorizationException(errorMessage); - } - else { - ex = new OAuth2Exception(errorMessage); - } + OAuth2Exception ex; + if ("invalid_client".equals(errorCode)) { + ex = new InvalidClientException(errorMessage); + } + else if ("unauthorized_client".equals(errorCode)) { + ex = new UnauthorizedUserException(errorMessage); + } + else if ("invalid_grant".equals(errorCode)) { + if (errorMessage.toLowerCase().contains("redirect") && errorMessage.toLowerCase().contains("match")) { + ex = new RedirectMismatchException(errorMessage); + } + else { + ex = new InvalidGrantException(errorMessage); + } + } + else if ("invalid_scope".equals(errorCode)) { + ex = new InvalidScopeException(errorMessage); + } + else if ("invalid_token".equals(errorCode)) { + ex = new InvalidTokenException(errorMessage); + } + else if ("invalid_request".equals(errorCode)) { + ex = new InvalidRequestException(errorMessage); + } + else if ("redirect_uri_mismatch".equals(errorCode)) { + ex = new RedirectMismatchException(errorMessage); + } + else if ("unsupported_grant_type".equals(errorCode)) { + ex = new UnsupportedGrantTypeException(errorMessage); + } + else if ("unsupported_response_type".equals(errorCode)) { + ex = new UnsupportedResponseTypeException(errorMessage); + } + else if ("insufficient_scope".equals(errorCode)) { + ex = new InsufficientScopeException(errorMessage, OAuth2Utils.parseParameterList((String) errorParams + .get("scope"))); + } + else if ("access_denied".equals(errorCode)) { + ex = new UserDeniedAuthorizationException(errorMessage); + } + else { + ex = new OAuth2Exception(errorMessage); + } - Set> entries = errorParams.entrySet(); - for (Map.Entry entry : entries) { - String key = entry.getKey(); - if (!"error".equals(key) && !"error_description".equals(key)) { - Object value = entry.getValue(); - ex.addAdditionalInformation(key, value == null ? null : value.toString()); - } - } + Set> entries = errorParams.entrySet(); + for (Map.Entry entry : entries) { + String key = entry.getKey(); + if (!"error".equals(key) && !"error_description".equals(key)) { + Object value = entry.getValue(); + ex.addAdditionalInformation(key, value == null ? null : value.toString()); + } + } - return ex; + return ex; - } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2ExceptionJackson2Serializer.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2ExceptionJackson2Serializer.java index 4039ed4d0..b5eabb015 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2ExceptionJackson2Serializer.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/OAuth2ExceptionJackson2Serializer.java @@ -35,20 +35,20 @@ public class OAuth2ExceptionJackson2Serializer extends StdSerializer entry : value.getAdditionalInformation().entrySet()) { - String key = entry.getKey(); - String add = entry.getValue(); - jgen.writeStringField(key, add); - } - } + jgen.writeStringField("error", value.getOAuth2ErrorCode()); + jgen.writeStringField("error_description", value.getMessage()); + if (value.getAdditionalInformation()!=null) { + for (Entry entry : value.getAdditionalInformation().entrySet()) { + String key = entry.getKey(); + String add = entry.getValue(); + jgen.writeStringField(key, add); + } + } jgen.writeEndObject(); - } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/UnauthorizedClientException.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/UnauthorizedClientException.java index fcd06a23a..7ce9b3003 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/UnauthorizedClientException.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/UnauthorizedClientException.java @@ -25,22 +25,22 @@ package org.dromara.maxkey.authz.oauth2.common.exceptions; @SuppressWarnings("serial") public class UnauthorizedClientException extends ClientAuthenticationException { - public UnauthorizedClientException(String msg, Throwable t) { - super(msg, t); - } + public UnauthorizedClientException(String msg, Throwable t) { + super(msg, t); + } - public UnauthorizedClientException(String msg) { - super(msg); - } + public UnauthorizedClientException(String msg) { + super(msg); + } - @Override - public int getHttpErrorCode() { - // The spec says this can be unauthorized - return 401; - } + @Override + public int getHttpErrorCode() { + // The spec says this can be unauthorized + return 401; + } - @Override - public String getOAuth2ErrorCode() { - return "unauthorized_client"; - } + @Override + public String getOAuth2ErrorCode() { + return "unauthorized_client"; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/UnauthorizedUserException.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/UnauthorizedUserException.java index 24db25e3c..c5b6921a8 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/UnauthorizedUserException.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/exceptions/UnauthorizedUserException.java @@ -25,23 +25,23 @@ package org.dromara.maxkey.authz.oauth2.common.exceptions; @SuppressWarnings("serial") public class UnauthorizedUserException extends OAuth2Exception { - public UnauthorizedUserException(String msg, Throwable t) { - super(msg, t); - } + public UnauthorizedUserException(String msg, Throwable t) { + super(msg, t); + } - public UnauthorizedUserException(String msg) { - super(msg); - } + public UnauthorizedUserException(String msg) { + super(msg); + } - @Override - public int getHttpErrorCode() { - // The spec says this can be unauthorized - return 401; - } + @Override + public int getHttpErrorCode() { + // The spec says this can be unauthorized + return 401; + } - @Override - public String getOAuth2ErrorCode() { - // Not in the spec - return "unauthorized_user"; - } + @Override + public String getOAuth2ErrorCode() { + // Not in the spec + return "unauthorized_user"; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/DefaultJdbcListFactory.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/DefaultJdbcListFactory.java index 18ab88c8f..8cc7be3f2 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/DefaultJdbcListFactory.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/DefaultJdbcListFactory.java @@ -28,17 +28,17 @@ import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; */ public class DefaultJdbcListFactory implements JdbcListFactory { - private final NamedParameterJdbcOperations jdbcTemplate; + private final NamedParameterJdbcOperations jdbcTemplate; - /** - * @param jdbcTemplate the jdbc template to use - */ - public DefaultJdbcListFactory(NamedParameterJdbcOperations jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; - } + /** + * @param jdbcTemplate the jdbc template to use + */ + public DefaultJdbcListFactory(NamedParameterJdbcOperations jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } - public List getList(String sql, Map parameters, RowMapper rowMapper) { - return jdbcTemplate.query(sql, parameters, rowMapper); - } + public List getList(String sql, Map parameters, RowMapper rowMapper) { + return jdbcTemplate.query(sql, parameters, rowMapper); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/Jackson2JsonParser.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/Jackson2JsonParser.java index 373bbd4c8..3db1fad95 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/Jackson2JsonParser.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/Jackson2JsonParser.java @@ -24,28 +24,28 @@ import com.fasterxml.jackson.databind.ObjectMapper; * */ public class Jackson2JsonParser implements JsonParser { - - private ObjectMapper mapper = new ObjectMapper(); + + private ObjectMapper mapper = new ObjectMapper(); - @SuppressWarnings("unchecked") - @Override - public Map parseMap(String json) { - try { - return mapper.readValue(json, Map.class); - } - catch (Exception e) { - throw new IllegalArgumentException("Cannot parse json", e); - } - } - - @Override - public String formatMap(Map map) { - try { - return mapper.writeValueAsString(map); - } - catch (Exception e) { - throw new IllegalArgumentException("Cannot format json", e); - } - } + @SuppressWarnings("unchecked") + @Override + public Map parseMap(String json) { + try { + return mapper.readValue(json, Map.class); + } + catch (Exception e) { + throw new IllegalArgumentException("Cannot parse json", e); + } + } + + @Override + public String formatMap(Map map) { + try { + return mapper.writeValueAsString(map); + } + catch (Exception e) { + throw new IllegalArgumentException("Cannot format json", e); + } + } } \ No newline at end of file diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JdbcListFactory.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JdbcListFactory.java index 19921430a..6e9095e9c 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JdbcListFactory.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JdbcListFactory.java @@ -27,11 +27,11 @@ import org.springframework.jdbc.core.RowMapper; */ public interface JdbcListFactory { - /** - * @param sql - * @param parameters - * @return a list of {@link T} - */ - List getList(String sql, Map parameters, RowMapper rowMapper); + /** + * @param sql + * @param parameters + * @return a list of {@link T} + */ + List getList(String sql, Map parameters, RowMapper rowMapper); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JsonDateDeserializer.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JsonDateDeserializer.java index d696fd94a..11e9d079e 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JsonDateDeserializer.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JsonDateDeserializer.java @@ -47,21 +47,21 @@ import com.fasterxml.jackson.databind.JsonDeserializer; * */ public class JsonDateDeserializer extends JsonDeserializer { - + private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - @Override - public Date deserialize(com.fasterxml.jackson.core.JsonParser parser, DeserializationContext ctxt) - throws IOException, JsonProcessingException { - try { - synchronized (dateFormat) { - return dateFormat.parse(parser.toString()); - } - } - catch (ParseException e) { - throw new JsonParseException( parser,"Could not parse date ",e); - } - } + @Override + public Date deserialize(com.fasterxml.jackson.core.JsonParser parser, DeserializationContext ctxt) + throws IOException, JsonProcessingException { + try { + synchronized (dateFormat) { + return dateFormat.parse(parser.toString()); + } + } + catch (ParseException e) { + throw new JsonParseException( parser,"Could not parse date ",e); + } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JsonDateSerializer.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JsonDateSerializer.java index b2549445c..5e2fbec43 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JsonDateSerializer.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JsonDateSerializer.java @@ -47,15 +47,15 @@ import com.fasterxml.jackson.databind.SerializerProvider; */ public class JsonDateSerializer extends JsonSerializer { - private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - @Override - public void serialize(Date date, JsonGenerator generator, SerializerProvider provider) throws IOException, - JsonProcessingException { - synchronized (dateFormat) { - String formatted = dateFormat.format(date); - generator.writeString(formatted); - } - } + @Override + public void serialize(Date date, JsonGenerator generator, SerializerProvider provider) throws IOException, + JsonProcessingException { + synchronized (dateFormat) { + String formatted = dateFormat.format(date); + generator.writeString(formatted); + } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JsonParser.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JsonParser.java index 20373a83c..a8b3caded 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JsonParser.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JsonParser.java @@ -21,18 +21,18 @@ import java.util.Map; */ public interface JsonParser { - /** - * Parse the specified JSON string into a Map. - * @param json the JSON to parse - * @return the parsed JSON as a map - */ - Map parseMap(String json); - - /** - * Convert the Map to JSON - * @param map a map to format - * @return a JSON representation of the map - */ - String formatMap(Map map); + /** + * Parse the specified JSON string into a Map. + * @param json the JSON to parse + * @return the parsed JSON as a map + */ + Map parseMap(String json); + + /** + * Convert the Map to JSON + * @param map a map to format + * @return a JSON representation of the map + */ + String formatMap(Map map); } \ No newline at end of file diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JsonParserFactory.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JsonParserFactory.java index aa7c1bfa1..958f237db 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JsonParserFactory.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/JsonParserFactory.java @@ -21,12 +21,12 @@ import org.springframework.util.ClassUtils; */ public class JsonParserFactory { - public static JsonParser create() { - if (ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", null)) { - return new Jackson2JsonParser(); - } + public static JsonParser create() { + if (ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", null)) { + return new Jackson2JsonParser(); + } - throw new IllegalStateException("No Jackson parser found. Please add Jackson to your classpath."); - } + throw new IllegalStateException("No Jackson parser found. Please add Jackson to your classpath."); + } } \ No newline at end of file diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/OAuth2Utils.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/OAuth2Utils.java index 92d309db2..f4dc02f86 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/OAuth2Utils.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/OAuth2Utils.java @@ -32,60 +32,60 @@ import org.springframework.util.StringUtils; */ public abstract class OAuth2Utils { - /** - * Parses a string parameter value into a set of strings. - * - * @param values The values of the set. - * @return The set. - */ - public static Set parseParameterList(String values) { - Set result = new TreeSet(); - if (values != null && values.trim().length() > 0) { - // the spec says the scope is separated by spaces - String[] tokens = values.split("[\\s+]"); - result.addAll(Arrays.asList(tokens)); - } - return result; - } + /** + * Parses a string parameter value into a set of strings. + * + * @param values The values of the set. + * @return The set. + */ + public static Set parseParameterList(String values) { + Set result = new TreeSet(); + if (values != null && values.trim().length() > 0) { + // the spec says the scope is separated by spaces + String[] tokens = values.split("[\\s+]"); + result.addAll(Arrays.asList(tokens)); + } + return result; + } - /** - * Formats a set of string values into a format appropriate for sending as a single-valued form value. - * - * @param value The value of the parameter. - * @return The value formatted for form submission etc, or null if the input is empty - */ - public static String formatParameterList(Collection value) { - return value == null ? null : StringUtils.collectionToDelimitedString(value, " "); - } + /** + * Formats a set of string values into a format appropriate for sending as a single-valued form value. + * + * @param value The value of the parameter. + * @return The value formatted for form submission etc, or null if the input is empty + */ + public static String formatParameterList(Collection value) { + return value == null ? null : StringUtils.collectionToDelimitedString(value, " "); + } - /** - * Extract a map from a query string. - * - * @param query a query (or fragment) string from a URI - * @return a Map of the values in the query - */ - public static Map extractMap(String query) { - Map map = new HashMap(); - Properties properties = StringUtils.splitArrayElementsIntoProperties( - StringUtils.delimitedListToStringArray(query, "&"), "="); - if (properties != null) { - for (Object key : properties.keySet()) { - map.put(key.toString(), properties.get(key).toString()); - } - } - return map; - } + /** + * Extract a map from a query string. + * + * @param query a query (or fragment) string from a URI + * @return a Map of the values in the query + */ + public static Map extractMap(String query) { + Map map = new HashMap(); + Properties properties = StringUtils.splitArrayElementsIntoProperties( + StringUtils.delimitedListToStringArray(query, "&"), "="); + if (properties != null) { + for (Object key : properties.keySet()) { + map.put(key.toString(), properties.get(key).toString()); + } + } + return map; + } - /** - * Compare 2 sets and check that one contains all members of the other. - * - * @param target set of strings to check - * @param members the members to compare to - * @return true if all members are in the target - */ - public static boolean containsAll(Set target, Set members) { - target = new HashSet(target); - target.retainAll(members); - return target.size() == members.size(); - } + /** + * Compare 2 sets and check that one contains all members of the other. + * + * @param target set of strings to check + * @param members the members to compare to + * @return true if all members are in the target + */ + public static boolean containsAll(Set target, Set members) { + target = new HashSet(target); + target.retainAll(members); + return target.size() == members.size(); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/RandomValueStringGenerator.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/RandomValueStringGenerator.java index 14afc1254..8c3b032e0 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/RandomValueStringGenerator.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/common/util/RandomValueStringGenerator.java @@ -28,67 +28,67 @@ import java.util.Random; */ public class RandomValueStringGenerator { - private static final char[] DEFAULT_CODEC = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" - .toCharArray(); + private static final char[] DEFAULT_CODEC = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + .toCharArray(); - private Random random = new SecureRandom(); + private Random random = new SecureRandom(); - private int length; + private int length; - /** - * Create a generator with the default length (6). - */ - public RandomValueStringGenerator() { - this(6); - } + /** + * Create a generator with the default length (6). + */ + public RandomValueStringGenerator() { + this(6); + } - /** - * Create a generator of random strings of the length provided - * - * @param length the length of the strings generated - */ - public RandomValueStringGenerator(int length) { - this.length = length; - } + /** + * Create a generator of random strings of the length provided + * + * @param length the length of the strings generated + */ + public RandomValueStringGenerator(int length) { + this.length = length; + } - public String generate() { - byte[] verifierBytes = new byte[length]; - random.nextBytes(verifierBytes); - return getAuthorizationCodeString(verifierBytes); - } + public String generate() { + byte[] verifierBytes = new byte[length]; + random.nextBytes(verifierBytes); + return getAuthorizationCodeString(verifierBytes); + } - /** - * Convert these random bytes to a verifier string. The length of the byte array can be - * {@link #setLength(int) configured}. The default implementation mods the bytes to fit into the - * ASCII letters 1-9, A-Z, a-z . - * - * @param verifierBytes The bytes. - * @return The string. - */ - protected String getAuthorizationCodeString(byte[] verifierBytes) { - char[] chars = new char[verifierBytes.length]; - for (int i = 0; i < verifierBytes.length; i++) { - chars[i] = DEFAULT_CODEC[((verifierBytes[i] & 0xFF) % DEFAULT_CODEC.length)]; - } - return new String(chars); - } + /** + * Convert these random bytes to a verifier string. The length of the byte array can be + * {@link #setLength(int) configured}. The default implementation mods the bytes to fit into the + * ASCII letters 1-9, A-Z, a-z . + * + * @param verifierBytes The bytes. + * @return The string. + */ + protected String getAuthorizationCodeString(byte[] verifierBytes) { + char[] chars = new char[verifierBytes.length]; + for (int i = 0; i < verifierBytes.length; i++) { + chars[i] = DEFAULT_CODEC[((verifierBytes[i] & 0xFF) % DEFAULT_CODEC.length)]; + } + return new String(chars); + } - /** - * The random value generator used to create token secrets. - * - * @param random The random value generator used to create token secrets. - */ - public void setRandom(Random random) { - this.random = random; - } - - /** - * The length of string to generate. - * - * @param length the length to set - */ - public void setLength(int length) { - this.length = length; - } + /** + * The random value generator used to create token secrets. + * + * @param random The random value generator used to create token secrets. + */ + public void setRandom(Random random) { + this.random = random; + } + + /** + * The length of string to generate. + * + * @param length the length to set + */ + public void setLength(int length) { + this.length = length; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/AlgorithmMetadata.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/AlgorithmMetadata.java index 98631a0ce..9ac24ed6d 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/AlgorithmMetadata.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/AlgorithmMetadata.java @@ -16,8 +16,8 @@ package org.dromara.maxkey.authz.oauth2.jwt; * @author Luke Taylor */ public interface AlgorithmMetadata { - /** - * @return the JCA/JCE algorithm name. - */ - String algorithm(); + /** + * @return the JCA/JCE algorithm name. + */ + String algorithm(); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/BinaryFormat.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/BinaryFormat.java index 583016533..d168d2465 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/BinaryFormat.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/BinaryFormat.java @@ -16,5 +16,5 @@ package org.dromara.maxkey.authz.oauth2.jwt; * @author Luke Taylor */ public interface BinaryFormat { - byte[] bytes(); + byte[] bytes(); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/Jwt.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/Jwt.java index abce6217d..4779cddc6 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/Jwt.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/Jwt.java @@ -18,9 +18,9 @@ import org.dromara.maxkey.authz.oauth2.jwt.crypto.sign.SignatureVerifier; * @author Luke Taylor */ public interface Jwt extends BinaryFormat { - String getClaims(); + String getClaims(); - String getEncoded(); + String getEncoded(); - void verifySignature(SignatureVerifier verifier); + void verifySignature(SignatureVerifier verifier); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/JwtAlgorithms.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/JwtAlgorithms.java index 8971aacfd..6df50f211 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/JwtAlgorithms.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/JwtAlgorithms.java @@ -21,59 +21,59 @@ import org.dromara.maxkey.authz.oauth2.jwt.crypto.cipher.CipherMetadata; * @author Luke Taylor */ public class JwtAlgorithms { - private static final Map sigAlgs = new HashMap(); - private static final Map javaToSigAlgs = new HashMap(); - private static final Map keyAlgs = new HashMap(); - private static final Map javaToKeyAlgs = new HashMap(); + private static final Map sigAlgs = new HashMap(); + private static final Map javaToSigAlgs = new HashMap(); + private static final Map keyAlgs = new HashMap(); + private static final Map javaToKeyAlgs = new HashMap(); - static { - sigAlgs.put("HS256", "HMACSHA256"); - sigAlgs.put("HS384" , "HMACSHA384"); - sigAlgs.put("HS512" , "HMACSHA512"); - sigAlgs.put("RS256" , "SHA256withRSA"); - sigAlgs.put("RS512" , "SHA512withRSA"); + static { + sigAlgs.put("HS256", "HMACSHA256"); + sigAlgs.put("HS384" , "HMACSHA384"); + sigAlgs.put("HS512" , "HMACSHA512"); + sigAlgs.put("RS256" , "SHA256withRSA"); + sigAlgs.put("RS512" , "SHA512withRSA"); - keyAlgs.put("RSA1_5" , "RSA/ECB/PKCS1Padding"); + keyAlgs.put("RSA1_5" , "RSA/ECB/PKCS1Padding"); - for(Map.Entry e: sigAlgs.entrySet()) { - javaToSigAlgs.put(e.getValue(), e.getKey()); - } - for(Map.Entry e: keyAlgs.entrySet()) { - javaToKeyAlgs.put(e.getValue(), e.getKey()); - } + for(Map.Entry e: sigAlgs.entrySet()) { + javaToSigAlgs.put(e.getValue(), e.getKey()); + } + for(Map.Entry e: keyAlgs.entrySet()) { + javaToKeyAlgs.put(e.getValue(), e.getKey()); + } - } + } - static String sigAlg(String javaName){ - String alg = javaToSigAlgs.get(javaName); + static String sigAlg(String javaName){ + String alg = javaToSigAlgs.get(javaName); - if (alg == null) { - throw new IllegalArgumentException("Invalid or unsupported signature algorithm: " + javaName); - } + if (alg == null) { + throw new IllegalArgumentException("Invalid or unsupported signature algorithm: " + javaName); + } - return alg; - } + return alg; + } - static String keyEncryptionAlg(String javaName) { - String alg = javaToKeyAlgs.get(javaName); + static String keyEncryptionAlg(String javaName) { + String alg = javaToKeyAlgs.get(javaName); - if (alg == null) { - throw new IllegalArgumentException("Invalid or unsupported key encryption algorithm: " + javaName); - } + if (alg == null) { + throw new IllegalArgumentException("Invalid or unsupported key encryption algorithm: " + javaName); + } - return alg; - } + return alg; + } - static String enc(CipherMetadata cipher) { - if (!cipher.algorithm().equalsIgnoreCase("AES/CBC/PKCS5Padding")) { - throw new IllegalArgumentException("Unknown or unsupported algorithm"); - } - if (cipher.keySize() == 128) { - return "A128CBC"; - } else if (cipher.keySize() == 256) { - return "A256CBC"; - } else { - throw new IllegalArgumentException("Unsupported key size"); - } - } + static String enc(CipherMetadata cipher) { + if (!cipher.algorithm().equalsIgnoreCase("AES/CBC/PKCS5Padding")) { + throw new IllegalArgumentException("Unknown or unsupported algorithm"); + } + if (cipher.keySize() == 128) { + return "A128CBC"; + } else if (cipher.keySize() == 256) { + return "A256CBC"; + } else { + throw new IllegalArgumentException("Unsupported key size"); + } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/JwtHelper.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/JwtHelper.java index 59cf20991..74170643e 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/JwtHelper.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/JwtHelper.java @@ -35,55 +35,55 @@ import com.fasterxml.jackson.core.JsonToken; * @author Luke Taylor */ public class JwtHelper { - static byte[] PERIOD = utf8Encode("."); + static byte[] PERIOD = utf8Encode("."); - /** - * Creates a token from an encoded token string. - * - * @param token the (non-null) encoded token (three Base-64 encoded strings separated by "." characters) - */ - public static Jwt decode(String token) { - int firstPeriod = token.indexOf('.'); - int lastPeriod = token.lastIndexOf('.'); + /** + * Creates a token from an encoded token string. + * + * @param token the (non-null) encoded token (three Base-64 encoded strings separated by "." characters) + */ + public static Jwt decode(String token) { + int firstPeriod = token.indexOf('.'); + int lastPeriod = token.lastIndexOf('.'); - if (firstPeriod <=0 || lastPeriod <= firstPeriod) { - throw new IllegalArgumentException("JWT must have 3 tokens"); - } - CharBuffer buffer = CharBuffer.wrap(token, 0, firstPeriod); - // Use a Reader which supports CharBuffer - JwtHeader header = JwtHeaderHelper.create(buffer.toString()); + if (firstPeriod <=0 || lastPeriod <= firstPeriod) { + throw new IllegalArgumentException("JWT must have 3 tokens"); + } + CharBuffer buffer = CharBuffer.wrap(token, 0, firstPeriod); + // Use a Reader which supports CharBuffer + JwtHeader header = JwtHeaderHelper.create(buffer.toString()); - buffer.limit(lastPeriod).position(firstPeriod + 1); - byte[] claims = b64UrlDecode(buffer); - boolean emptyCrypto = lastPeriod == token.length() - 1; + buffer.limit(lastPeriod).position(firstPeriod + 1); + byte[] claims = b64UrlDecode(buffer); + boolean emptyCrypto = lastPeriod == token.length() - 1; - byte[] crypto; + byte[] crypto; - if (emptyCrypto) { - if (!"none".equals(header.parameters.alg)) { - throw new IllegalArgumentException("Signed or encrypted token must have non-empty crypto segment"); - } - crypto = new byte[0]; - } else { - buffer.limit(token.length()).position(lastPeriod + 1); - crypto = b64UrlDecode(buffer); - } - return new JwtImpl(header, claims, crypto); - } + if (emptyCrypto) { + if (!"none".equals(header.parameters.alg)) { + throw new IllegalArgumentException("Signed or encrypted token must have non-empty crypto segment"); + } + crypto = new byte[0]; + } else { + buffer.limit(token.length()).position(lastPeriod + 1); + crypto = b64UrlDecode(buffer); + } + return new JwtImpl(header, claims, crypto); + } - public static Jwt decodeAndVerify(String token, SignatureVerifier verifier) { - Jwt jwt = decode(token); - jwt.verifySignature(verifier); + public static Jwt decodeAndVerify(String token, SignatureVerifier verifier) { + Jwt jwt = decode(token); + jwt.verifySignature(verifier); - return jwt; - } + return jwt; + } - public static Jwt encode(CharSequence content, Signer signer) { - JwtHeader header = JwtHeaderHelper.create(signer); - byte[] claims = utf8Encode(content); - byte[] crypto = signer.sign(concat(b64UrlEncode(header.bytes()), PERIOD, b64UrlEncode(claims))); - return new JwtImpl(header, claims, crypto); - } + public static Jwt encode(CharSequence content, Signer signer) { + JwtHeader header = JwtHeaderHelper.create(signer); + byte[] claims = utf8Encode(content); + byte[] crypto = signer.sign(concat(b64UrlEncode(header.bytes()), PERIOD, b64UrlEncode(claims))); + return new JwtImpl(header, claims, crypto); + } } /** @@ -92,103 +92,103 @@ public class JwtHelper { * Handles the JSON parsing and serialization. */ class JwtHeaderHelper { - private static final JsonFactory f = new JsonFactory(); + private static final JsonFactory f = new JsonFactory(); - static JwtHeader create(String header) { - byte[] bytes = b64UrlDecode(header); - return new JwtHeader(bytes, parseParams(bytes)); - } + static JwtHeader create(String header) { + byte[] bytes = b64UrlDecode(header); + return new JwtHeader(bytes, parseParams(bytes)); + } - static JwtHeader create(Signer signer) { - HeaderParameters p = new HeaderParameters(sigAlg(signer.algorithm()), null, null); - return new JwtHeader(serializeParams(p), p); - } + static JwtHeader create(Signer signer) { + HeaderParameters p = new HeaderParameters(sigAlg(signer.algorithm()), null, null); + return new JwtHeader(serializeParams(p), p); + } - static JwtHeader create(String alg, String enc, byte[] iv) { - HeaderParameters p = new HeaderParameters(alg, enc, utf8Decode(b64UrlEncode(iv))); - return new JwtHeader(serializeParams(p), p); - } + static JwtHeader create(String alg, String enc, byte[] iv) { + HeaderParameters p = new HeaderParameters(alg, enc, utf8Decode(b64UrlEncode(iv))); + return new JwtHeader(serializeParams(p), p); + } - static HeaderParameters parseParams(byte[] header) { - JsonParser jp = null; - try { - jp = f.createParser(header); - String alg = null, enc = null, iv = null; - jp.nextToken(); - while (jp.nextToken() != JsonToken.END_OBJECT) { - String fieldname = jp.currentName(); - jp.nextToken(); - if (!JsonToken.VALUE_STRING.equals(jp.getCurrentToken())) { - throw new IllegalArgumentException("Header fields must be strings"); - } - String value = jp.getText(); - if ("alg".equals(fieldname)) { - if (alg != null) { - throw new IllegalArgumentException("Duplicate 'alg' field"); - } - alg = value; - } else if ("enc".equals(fieldname)) { - if (enc != null) { - throw new IllegalArgumentException("Duplicate 'enc' field"); - } - enc = value; - } if ("iv".equals(fieldname)) { - if (iv != null) { - throw new IllegalArgumentException("Duplicate 'iv' field"); - } - iv = jp.nextToken().asString(); - } else if ("typ".equals(fieldname)) { - if (!"JWT".equalsIgnoreCase(value)) { - throw new IllegalArgumentException("typ is not \"JWT\""); - } - } - } + static HeaderParameters parseParams(byte[] header) { + JsonParser jp = null; + try { + jp = f.createParser(header); + String alg = null, enc = null, iv = null; + jp.nextToken(); + while (jp.nextToken() != JsonToken.END_OBJECT) { + String fieldname = jp.currentName(); + jp.nextToken(); + if (!JsonToken.VALUE_STRING.equals(jp.getCurrentToken())) { + throw new IllegalArgumentException("Header fields must be strings"); + } + String value = jp.getText(); + if ("alg".equals(fieldname)) { + if (alg != null) { + throw new IllegalArgumentException("Duplicate 'alg' field"); + } + alg = value; + } else if ("enc".equals(fieldname)) { + if (enc != null) { + throw new IllegalArgumentException("Duplicate 'enc' field"); + } + enc = value; + } if ("iv".equals(fieldname)) { + if (iv != null) { + throw new IllegalArgumentException("Duplicate 'iv' field"); + } + iv = jp.nextToken().asString(); + } else if ("typ".equals(fieldname)) { + if (!"JWT".equalsIgnoreCase(value)) { + throw new IllegalArgumentException("typ is not \"JWT\""); + } + } + } - return new HeaderParameters(alg, enc, iv); - } catch (IOException io) { - throw new RuntimeException(io); - } finally { - if (jp != null) { - try { - jp.close(); - } catch (IOException ignore) { - } - } - } - } + return new HeaderParameters(alg, enc, iv); + } catch (IOException io) { + throw new RuntimeException(io); + } finally { + if (jp != null) { + try { + jp.close(); + } catch (IOException ignore) { + } + } + } + } - private static byte[] serializeParams(HeaderParameters params) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - JsonGenerator g = null; + private static byte[] serializeParams(HeaderParameters params) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonGenerator g = null; - try { - g = f.createGenerator(baos); - g.writeStartObject(); - g.writeStringField("alg", params.alg); - if (params.enc != null) { - g.writeStringField("enc", params.enc); - } - if (params.iv != null) { - g.writeStringField("iv", params.iv); - } - g.writeEndObject(); - g.flush(); + try { + g = f.createGenerator(baos); + g.writeStartObject(); + g.writeStringField("alg", params.alg); + if (params.enc != null) { + g.writeStringField("enc", params.enc); + } + if (params.iv != null) { + g.writeStringField("iv", params.iv); + } + g.writeEndObject(); + g.flush(); - return baos.toByteArray(); - } - catch (IOException io) { - throw new RuntimeException(io); - } finally { - if (g != null) { - try { - g.close(); - } catch (IOException ignore) { - } - } - } + return baos.toByteArray(); + } + catch (IOException io) { + throw new RuntimeException(io); + } finally { + if (g != null) { + try { + g.close(); + } catch (IOException ignore) { + } + } + } - } + } } /** @@ -196,98 +196,98 @@ class JwtHeaderHelper { * */ class JwtHeader implements BinaryFormat { - private final byte[] bytes; - final HeaderParameters parameters; + private final byte[] bytes; + final HeaderParameters parameters; - /** - * @param bytes the decoded header - * @param parameters the parameter values contained in the header - */ - JwtHeader(byte[] bytes, HeaderParameters parameters) { - this.bytes = bytes; - this.parameters = parameters; - } + /** + * @param bytes the decoded header + * @param parameters the parameter values contained in the header + */ + JwtHeader(byte[] bytes, HeaderParameters parameters) { + this.bytes = bytes; + this.parameters = parameters; + } - public byte[] bytes() { - return bytes; - } + public byte[] bytes() { + return bytes; + } - @Override - public String toString() { - return utf8Decode(bytes); - } + @Override + public String toString() { + return utf8Decode(bytes); + } } class HeaderParameters { - final String alg; - final String enc; - final String iv; + final String alg; + final String enc; + final String iv; - HeaderParameters(String alg) { - this(alg, null, null); - } + HeaderParameters(String alg) { + this(alg, null, null); + } - HeaderParameters(String alg, String enc, String iv) { - if (alg == null) { - throw new IllegalArgumentException("alg is required"); - } - this.alg = alg; - this.enc = enc; - this.iv = iv; - } + HeaderParameters(String alg, String enc, String iv) { + if (alg == null) { + throw new IllegalArgumentException("alg is required"); + } + this.alg = alg; + this.enc = enc; + this.iv = iv; + } } class JwtImpl implements Jwt { - private final JwtHeader header; - private final byte[] content; - private final byte[] crypto; - private String claims; + private final JwtHeader header; + private final byte[] content; + private final byte[] crypto; + private String claims; - /** - * @param header the header, containing the JWS/JWE algorithm information. - * @param content the base64-decoded "claims" segment (may be encrypted, depending on header information). - * @param crypto the base64-decoded "crypto" segment. - */ - JwtImpl(JwtHeader header, byte[] content, byte[] crypto) { - this.header = header; - this.content = content; - this.crypto = crypto; - claims = utf8Decode(content); - } + /** + * @param header the header, containing the JWS/JWE algorithm information. + * @param content the base64-decoded "claims" segment (may be encrypted, depending on header information). + * @param crypto the base64-decoded "crypto" segment. + */ + JwtImpl(JwtHeader header, byte[] content, byte[] crypto) { + this.header = header; + this.content = content; + this.crypto = crypto; + claims = utf8Decode(content); + } - /** - * Validates a signature contained in the 'crypto' segment. - * - * @param verifier the signature verifier - */ - public void verifySignature(SignatureVerifier verifier) { - verifier.verify(signingInput(), crypto); - } + /** + * Validates a signature contained in the 'crypto' segment. + * + * @param verifier the signature verifier + */ + public void verifySignature(SignatureVerifier verifier) { + verifier.verify(signingInput(), crypto); + } - private byte[] signingInput() { - return concat(b64UrlEncode(header.bytes()), JwtHelper.PERIOD, b64UrlEncode(content)); - } + private byte[] signingInput() { + return concat(b64UrlEncode(header.bytes()), JwtHelper.PERIOD, b64UrlEncode(content)); + } /** * Allows retrieval of the full token. * * @return the encoded header, claims and crypto segments concatenated with "." characters */ - public byte[] bytes() { - return concat(b64UrlEncode(header.bytes()), JwtHelper.PERIOD, b64UrlEncode(content), JwtHelper.PERIOD, b64UrlEncode(crypto)); - } + public byte[] bytes() { + return concat(b64UrlEncode(header.bytes()), JwtHelper.PERIOD, b64UrlEncode(content), JwtHelper.PERIOD, b64UrlEncode(crypto)); + } - public String getClaims() { - return utf8Decode(content); - } + public String getClaims() { + return utf8Decode(content); + } - public String getEncoded() { - return utf8Decode(bytes()); - } + public String getEncoded() { + return utf8Decode(bytes()); + } - @Override - public String toString() { - return header + " " + claims + " ["+ crypto.length + " crypto bytes]"; - } + @Override + public String toString() { + return header + " " + claims + " ["+ crypto.length + " crypto bytes]"; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/codec/Codecs.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/codec/Codecs.java index 5e70dd598..02b580562 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/codec/Codecs.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/codec/Codecs.java @@ -23,181 +23,181 @@ import java.nio.charset.Charset; * @author Luke Taylor */ public class Codecs { - private static Charset UTF8 = Charset.forName("UTF-8"); + private static Charset UTF8 = Charset.forName("UTF-8"); - /** - * Base 64 - */ - public static byte[] b64Encode(byte[] bytes) { - return Base64Codec.encode(bytes); - } + /** + * Base 64 + */ + public static byte[] b64Encode(byte[] bytes) { + return Base64Codec.encode(bytes); + } - public static byte[] b64Decode(byte[] bytes) { - return Base64Codec.decode(bytes); - } + public static byte[] b64Decode(byte[] bytes) { + return Base64Codec.decode(bytes); + } - // URL-safe versions with no padding chars - public static byte[] b64UrlEncode(byte[] bytes) { - return Base64.urlEncode(bytes); - } + // URL-safe versions with no padding chars + public static byte[] b64UrlEncode(byte[] bytes) { + return Base64.urlEncode(bytes); + } - public static byte[] b64UrlEncode(CharSequence value) { - return b64UrlEncode(utf8Encode(value)); - } + public static byte[] b64UrlEncode(CharSequence value) { + return b64UrlEncode(utf8Encode(value)); + } - public static byte[] b64UrlDecode(byte[] bytes) { - return Base64.urlDecode(bytes); - } + public static byte[] b64UrlDecode(byte[] bytes) { + return Base64.urlDecode(bytes); + } - public static byte[] b64UrlDecode(CharSequence value) { - return b64UrlDecode(utf8Encode(value)); - } + public static byte[] b64UrlDecode(CharSequence value) { + return b64UrlDecode(utf8Encode(value)); + } - /** - * UTF-8 encoding/decoding. Using a charset rather than `String.getBytes` is less forgiving - * and will raise an exception for invalid data. - */ - public static byte[] utf8Encode(CharSequence string) { - try { - ByteBuffer bytes = UTF8.newEncoder().encode(CharBuffer.wrap(string)); - byte[] bytesCopy = new byte[bytes.limit()]; - System.arraycopy(bytes.array(), 0, bytesCopy, 0, bytes.limit()); - return bytesCopy; - } - catch (CharacterCodingException e) { - throw new RuntimeException(e); - } - } + /** + * UTF-8 encoding/decoding. Using a charset rather than `String.getBytes` is less forgiving + * and will raise an exception for invalid data. + */ + public static byte[] utf8Encode(CharSequence string) { + try { + ByteBuffer bytes = UTF8.newEncoder().encode(CharBuffer.wrap(string)); + byte[] bytesCopy = new byte[bytes.limit()]; + System.arraycopy(bytes.array(), 0, bytesCopy, 0, bytes.limit()); + return bytesCopy; + } + catch (CharacterCodingException e) { + throw new RuntimeException(e); + } + } - public static String utf8Decode(byte[] bytes) { - return utf8Decode(ByteBuffer.wrap(bytes)); - } + public static String utf8Decode(byte[] bytes) { + return utf8Decode(ByteBuffer.wrap(bytes)); + } - public static String utf8Decode(ByteBuffer bytes) { - try { - return UTF8.newDecoder().decode(bytes).toString(); - } - catch (CharacterCodingException e) { - throw new RuntimeException(e); - } - } + public static String utf8Decode(ByteBuffer bytes) { + try { + return UTF8.newDecoder().decode(bytes).toString(); + } + catch (CharacterCodingException e) { + throw new RuntimeException(e); + } + } - public static char[] hexEncode(byte[] bytes) { - return Hex.encode(bytes); - } + public static char[] hexEncode(byte[] bytes) { + return Hex.encode(bytes); + } - public static byte[] hexDecode(CharSequence s) { - return Hex.decode(s); - } + public static byte[] hexDecode(CharSequence s) { + return Hex.decode(s); + } - // Substitute for Scala's Array.concat() - public static byte[] concat(byte[]... arrays) { - int size = 0; - for (byte[] a: arrays) { - size += a.length; - } - byte[] result = new byte[size]; - int index = 0; - for (byte[] a: arrays) { - System.arraycopy(a, 0, result, index, a.length); - index += a.length; - } - return result; - } + // Substitute for Scala's Array.concat() + public static byte[] concat(byte[]... arrays) { + int size = 0; + for (byte[] a: arrays) { + size += a.length; + } + byte[] result = new byte[size]; + int index = 0; + for (byte[] a: arrays) { + System.arraycopy(a, 0, result, index, a.length); + index += a.length; + } + return result; + } } class Base64 { - private static byte EQUALS = (byte)'='; + private static byte EQUALS = (byte)'='; - static byte[] encode(byte[] bytes) { - return Base64Codec.encode(bytes); - } + static byte[] encode(byte[] bytes) { + return Base64Codec.encode(bytes); + } - static byte[] decode(byte[] bytes) { - return Base64Codec.decode(bytes); - } + static byte[] decode(byte[] bytes) { + return Base64Codec.decode(bytes); + } - static byte[] urlEncode(byte[] bytes) { - byte[] b64Bytes = Base64Codec.encodeBytesToBytes(bytes, 0, bytes.length, Base64Codec.URL_SAFE); + static byte[] urlEncode(byte[] bytes) { + byte[] b64Bytes = Base64Codec.encodeBytesToBytes(bytes, 0, bytes.length, Base64Codec.URL_SAFE); - int length = b64Bytes.length; + int length = b64Bytes.length; - while(b64Bytes[length - 1] == EQUALS) { - length -= 1; - } + while(b64Bytes[length - 1] == EQUALS) { + length -= 1; + } - byte[] result = new byte[length]; - System.arraycopy(b64Bytes, 0, result, 0, length); + byte[] result = new byte[length]; + System.arraycopy(b64Bytes, 0, result, 0, length); - return result; - } + return result; + } - static byte[] urlDecode(byte[] b64) { - // Pad with '=' as necessary before feeding to standard decoder - byte[] b64Bytes = null; + static byte[] urlDecode(byte[] b64) { + // Pad with '=' as necessary before feeding to standard decoder + byte[] b64Bytes = null; - int lMod4 = b64.length % 4; + int lMod4 = b64.length % 4; - if (lMod4 == 0) { - b64Bytes = b64; - } else if (lMod4 == 2) { - b64Bytes = pad(b64, 2); - } else if (lMod4 == 3) { - b64Bytes = pad(b64, 1); - } else { - throw new IllegalArgumentException("Invalid Base64 string"); - } + if (lMod4 == 0) { + b64Bytes = b64; + } else if (lMod4 == 2) { + b64Bytes = pad(b64, 2); + } else if (lMod4 == 3) { + b64Bytes = pad(b64, 1); + } else { + throw new IllegalArgumentException("Invalid Base64 string"); + } - return Base64Codec.decode(b64Bytes, 0, b64Bytes.length, Base64Codec.URL_SAFE); - } + return Base64Codec.decode(b64Bytes, 0, b64Bytes.length, Base64Codec.URL_SAFE); + } - private static byte[] pad(byte[] bytes, int n) { - int l = bytes.length; - byte[] padded = new byte[l + n]; - System.arraycopy(bytes, 0, padded, 0, l); - for (int i = l; i < l + n; i++) { - padded[i] = EQUALS; - } - return padded; - } + private static byte[] pad(byte[] bytes, int n) { + int l = bytes.length; + byte[] padded = new byte[l + n]; + System.arraycopy(bytes, 0, padded, 0, l); + for (int i = l; i < l + n; i++) { + padded[i] = EQUALS; + } + return padded; + } } class Hex { - private static final char[] HEX = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + private static final char[] HEX = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; - static char[] encode(byte[] bytes) { - int nBytes = bytes.length; - char[] result = new char[2 * nBytes]; + static char[] encode(byte[] bytes) { + int nBytes = bytes.length; + char[] result = new char[2 * nBytes]; - int j = 0; - for (int i = 0; i < nBytes; i++) { - // Char for top 4 bits - result[j] = HEX[(0xF0 & bytes[i]) >>> 4]; - // Bottom 4 - result[j + 1] = HEX[(0x0F & bytes[i])]; - j += 2; - } - return result; - } + int j = 0; + for (int i = 0; i < nBytes; i++) { + // Char for top 4 bits + result[j] = HEX[(0xF0 & bytes[i]) >>> 4]; + // Bottom 4 + result[j + 1] = HEX[(0x0F & bytes[i])]; + j += 2; + } + return result; + } - static byte[] decode(CharSequence s) { - int nChars = s.length(); - if (nChars % 2 != 0) { - throw new IllegalArgumentException("Hex-encoded string must have an even number of characters"); - } + static byte[] decode(CharSequence s) { + int nChars = s.length(); + if (nChars % 2 != 0) { + throw new IllegalArgumentException("Hex-encoded string must have an even number of characters"); + } - byte[] result = new byte[nChars / 2]; + byte[] result = new byte[nChars / 2]; - for (int i = 0; i < nChars; i += 2) { - int msb = Character.digit(s.charAt(i), 16); - int lsb = Character.digit(s.charAt(i + 1), 16); - if (msb <= 0 || lsb <= 0) { - throw new IllegalArgumentException("Non-hex character in input: " + s); - } - result[i / 2] = (byte) ((msb << 4) | lsb); - } - return result; - } + for (int i = 0; i < nChars; i += 2) { + int msb = Character.digit(s.charAt(i), 16); + int lsb = Character.digit(s.charAt(i + 1), 16); + if (msb <= 0 || lsb <= 0) { + throw new IllegalArgumentException("Non-hex character in input: " + s); + } + result[i / 2] = (byte) ((msb << 4) | lsb); + } + return result; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/cipher/CipherMetadata.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/cipher/CipherMetadata.java index 7b3cd9261..efe5974fd 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/cipher/CipherMetadata.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/cipher/CipherMetadata.java @@ -18,8 +18,8 @@ import org.dromara.maxkey.authz.oauth2.jwt.AlgorithmMetadata; * @author Luke Taylor */ public interface CipherMetadata extends AlgorithmMetadata { - /** - * @return Size of the key in bits. - */ - int keySize(); + /** + * @return Size of the key in bits. + */ + int keySize(); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/MacSigner.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/MacSigner.java index 039d93ad9..5869d189d 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/MacSigner.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/MacSigner.java @@ -21,40 +21,40 @@ import javax.crypto.spec.SecretKeySpec; * @author Luke Taylor */ public class MacSigner implements SignerVerifier { - private static final String DEFAULT_ALGORITHM = "HMACSHA256"; + private static final String DEFAULT_ALGORITHM = "HMACSHA256"; - private final String algorithm; - private final SecretKey key; + private final String algorithm; + private final SecretKey key; - public MacSigner(byte[] key) { - this(new SecretKeySpec(key, DEFAULT_ALGORITHM)); - } + public MacSigner(byte[] key) { + this(new SecretKeySpec(key, DEFAULT_ALGORITHM)); + } - public MacSigner(String key) { - this(new SecretKeySpec(key.getBytes(), DEFAULT_ALGORITHM)); - } + public MacSigner(String key) { + this(new SecretKeySpec(key.getBytes(), DEFAULT_ALGORITHM)); + } - public MacSigner(SecretKey key) { - this(DEFAULT_ALGORITHM, key); - } + public MacSigner(SecretKey key) { + this(DEFAULT_ALGORITHM, key); + } - public MacSigner(String algorithm, SecretKey key) { - this.key = key; - this.algorithm = algorithm; - } + public MacSigner(String algorithm, SecretKey key) { + this.key = key; + this.algorithm = algorithm; + } -// val keyLength = key.getEncoded.length * 8 +// val keyLength = key.getEncoded.length * 8 - public byte[] sign(byte[] bytes) { - try { - Mac mac = Mac.getInstance(algorithm); - mac.init(key); - return mac.doFinal(bytes); - } - catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - } + public byte[] sign(byte[] bytes) { + try { + Mac mac = Mac.getInstance(algorithm); + mac.init(key); + return mac.doFinal(bytes); + } + catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } public void verify(byte[] content, byte[] signature) { byte[] signed = sign(content); @@ -75,12 +75,12 @@ public class MacSigner implements SignerVerifier { return xor == 0; } - public String algorithm() { - return algorithm; - } + public String algorithm() { + return algorithm; + } - @Override - public String toString() { - return "MacSigner: " + algorithm; - } + @Override + public String toString() { + return "MacSigner: " + algorithm; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/RsaKeyHelper.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/RsaKeyHelper.java index a0c34472e..a4b79314a 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/RsaKeyHelper.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/RsaKeyHelper.java @@ -34,131 +34,131 @@ import org.bouncycastle.asn1.ASN1Sequence; * @author Luke Taylor */ class RsaKeyHelper { - private static String BEGIN = "-----BEGIN"; - private static Pattern PEM_DATA = Pattern.compile("-----BEGIN (.*)-----(.*)-----END (.*)-----", Pattern.DOTALL); + private static String BEGIN = "-----BEGIN"; + private static Pattern PEM_DATA = Pattern.compile("-----BEGIN (.*)-----(.*)-----END (.*)-----", Pattern.DOTALL); - static KeyPair parseKeyPair(String pemData) { - Matcher m = PEM_DATA.matcher(pemData.trim()); + static KeyPair parseKeyPair(String pemData) { + Matcher m = PEM_DATA.matcher(pemData.trim()); - if (!m.matches()) { - throw new IllegalArgumentException("String is not PEM encoded data"); - } + if (!m.matches()) { + throw new IllegalArgumentException("String is not PEM encoded data"); + } - String type = m.group(1); - final byte[] content = b64Decode(utf8Encode(m.group(2))); + String type = m.group(1); + final byte[] content = b64Decode(utf8Encode(m.group(2))); - PublicKey publicKey; - PrivateKey privateKey = null; + PublicKey publicKey; + PrivateKey privateKey = null; - try { - KeyFactory fact = KeyFactory.getInstance("RSA"); - if (type.equals("RSA PRIVATE KEY")) { - ASN1Sequence seq = ASN1Sequence.getInstance(content); - if (seq.size() != 9) { - throw new IllegalArgumentException("Invalid RSA Private Key ASN1 sequence."); - } - org.bouncycastle.asn1.pkcs.RSAPrivateKey key = org.bouncycastle.asn1.pkcs.RSAPrivateKey.getInstance(seq); - RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent()); - RSAPrivateCrtKeySpec privSpec = new RSAPrivateCrtKeySpec(key.getModulus(), key.getPublicExponent(), - key.getPrivateExponent(), key.getPrime1(), key.getPrime2(), key.getExponent1(), key.getExponent2(), - key.getCoefficient()); - publicKey = fact.generatePublic(pubSpec); - privateKey = fact.generatePrivate(privSpec); - } else if (type.equals("PUBLIC KEY")) { - KeySpec keySpec = new X509EncodedKeySpec(content); - publicKey = fact.generatePublic(keySpec); - } else if (type.equals("RSA PUBLIC KEY")) { - ASN1Sequence seq = ASN1Sequence.getInstance(content); - org.bouncycastle.asn1.pkcs.RSAPublicKey key = org.bouncycastle.asn1.pkcs.RSAPublicKey.getInstance(seq); - RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent()); - publicKey = fact.generatePublic(pubSpec); - } else { - throw new IllegalArgumentException(type + " is not a supported format"); - } + try { + KeyFactory fact = KeyFactory.getInstance("RSA"); + if (type.equals("RSA PRIVATE KEY")) { + ASN1Sequence seq = ASN1Sequence.getInstance(content); + if (seq.size() != 9) { + throw new IllegalArgumentException("Invalid RSA Private Key ASN1 sequence."); + } + org.bouncycastle.asn1.pkcs.RSAPrivateKey key = org.bouncycastle.asn1.pkcs.RSAPrivateKey.getInstance(seq); + RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent()); + RSAPrivateCrtKeySpec privSpec = new RSAPrivateCrtKeySpec(key.getModulus(), key.getPublicExponent(), + key.getPrivateExponent(), key.getPrime1(), key.getPrime2(), key.getExponent1(), key.getExponent2(), + key.getCoefficient()); + publicKey = fact.generatePublic(pubSpec); + privateKey = fact.generatePrivate(privSpec); + } else if (type.equals("PUBLIC KEY")) { + KeySpec keySpec = new X509EncodedKeySpec(content); + publicKey = fact.generatePublic(keySpec); + } else if (type.equals("RSA PUBLIC KEY")) { + ASN1Sequence seq = ASN1Sequence.getInstance(content); + org.bouncycastle.asn1.pkcs.RSAPublicKey key = org.bouncycastle.asn1.pkcs.RSAPublicKey.getInstance(seq); + RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent()); + publicKey = fact.generatePublic(pubSpec); + } else { + throw new IllegalArgumentException(type + " is not a supported format"); + } - return new KeyPair(publicKey, privateKey); - } - catch (InvalidKeySpecException e) { - throw new RuntimeException(e); - } - catch (NoSuchAlgorithmException e) { - throw new IllegalStateException(e); - } - } + return new KeyPair(publicKey, privateKey); + } + catch (InvalidKeySpecException e) { + throw new RuntimeException(e); + } + catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } - private static final Pattern SSH_PUB_KEY = Pattern.compile("ssh-(rsa|dsa) ([A-Za-z0-9/+]+=*) (.*)"); + private static final Pattern SSH_PUB_KEY = Pattern.compile("ssh-(rsa|dsa) ([A-Za-z0-9/+]+=*) (.*)"); - static RSAPublicKey parsePublicKey(String key) { - Matcher m = SSH_PUB_KEY.matcher(key); + static RSAPublicKey parsePublicKey(String key) { + Matcher m = SSH_PUB_KEY.matcher(key); - if (m.matches()) { - String alg = m.group(1); - String encKey = m.group(2); - //String id = m.group(3); + if (m.matches()) { + String alg = m.group(1); + String encKey = m.group(2); + //String id = m.group(3); - if (!"rsa".equalsIgnoreCase(alg)) { - throw new IllegalArgumentException("Only RSA is currently supported, but algorithm was " + alg); - } + if (!"rsa".equalsIgnoreCase(alg)) { + throw new IllegalArgumentException("Only RSA is currently supported, but algorithm was " + alg); + } - return parseSSHPublicKey(encKey); - } else if (!key.startsWith(BEGIN)) { - // Assume it's the plain Base64 encoded ssh key without the "ssh-rsa" at the start - return parseSSHPublicKey(key); - } + return parseSSHPublicKey(encKey); + } else if (!key.startsWith(BEGIN)) { + // Assume it's the plain Base64 encoded ssh key without the "ssh-rsa" at the start + return parseSSHPublicKey(key); + } - KeyPair kp = parseKeyPair(key); + KeyPair kp = parseKeyPair(key); - if (kp.getPublic() == null) { - throw new IllegalArgumentException("Key data does not contain a public key"); - } + if (kp.getPublic() == null) { + throw new IllegalArgumentException("Key data does not contain a public key"); + } - return (RSAPublicKey) kp.getPublic(); - } + return (RSAPublicKey) kp.getPublic(); + } - private static RSAPublicKey parseSSHPublicKey(String encKey) { - final byte[] PREFIX = new byte[] {0,0,0,7, 's','s','h','-','r','s','a'}; - ByteArrayInputStream in = new ByteArrayInputStream(b64Decode(utf8Encode(encKey))); + private static RSAPublicKey parseSSHPublicKey(String encKey) { + final byte[] PREFIX = new byte[] {0,0,0,7, 's','s','h','-','r','s','a'}; + ByteArrayInputStream in = new ByteArrayInputStream(b64Decode(utf8Encode(encKey))); - byte[] prefix = new byte[11]; + byte[] prefix = new byte[11]; - try { - if (in.read(prefix) != 11 || !Arrays.equals(PREFIX, prefix)) { - throw new IllegalArgumentException("SSH key prefix not found"); - } + try { + if (in.read(prefix) != 11 || !Arrays.equals(PREFIX, prefix)) { + throw new IllegalArgumentException("SSH key prefix not found"); + } - BigInteger e = new BigInteger(readBigInteger(in)); - BigInteger n = new BigInteger(readBigInteger(in)); + BigInteger e = new BigInteger(readBigInteger(in)); + BigInteger n = new BigInteger(readBigInteger(in)); - return createPublicKey(n, e); - } catch (IOException e) { - throw new RuntimeException(e); - } - } + return createPublicKey(n, e); + } catch (IOException e) { + throw new RuntimeException(e); + } + } - static RSAPublicKey createPublicKey(BigInteger n, BigInteger e) { - try { - return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(n, e)); - } - catch (Exception ex) { - throw new RuntimeException(ex); - } - } + static RSAPublicKey createPublicKey(BigInteger n, BigInteger e) { + try { + return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(n, e)); + } + catch (Exception ex) { + throw new RuntimeException(ex); + } + } - private static byte[] readBigInteger(ByteArrayInputStream in) throws IOException { - byte[] b = new byte[4]; + private static byte[] readBigInteger(ByteArrayInputStream in) throws IOException { + byte[] b = new byte[4]; - if (in.read(b) != 4) { - throw new IOException("Expected length data as 4 bytes"); - } + if (in.read(b) != 4) { + throw new IOException("Expected length data as 4 bytes"); + } - int l = (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]; + int l = (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]; - b = new byte[l]; + b = new byte[l]; - if (in.read(b) != l) { - throw new IOException("Expected " + l + " key bytes"); - } + if (in.read(b) != l) { + throw new IOException("Expected " + l + " key bytes"); + } - return b; - } + return b; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/RsaSigner.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/RsaSigner.java index 25fdeee15..36604aa45 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/RsaSigner.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/RsaSigner.java @@ -26,60 +26,60 @@ import java.security.spec.RSAPrivateKeySpec; * @author Luke Taylor */ public class RsaSigner implements Signer { - static final String DEFAULT_ALGORITHM = "SHA256withRSA"; + static final String DEFAULT_ALGORITHM = "SHA256withRSA"; - private final RSAPrivateKey key; - private final String algorithm; + private final RSAPrivateKey key; + private final String algorithm; - public RsaSigner(BigInteger n, BigInteger d) { - this(createPrivateKey(n,d)); - } + public RsaSigner(BigInteger n, BigInteger d) { + this(createPrivateKey(n,d)); + } - public RsaSigner(RSAPrivateKey key) { - this(key, DEFAULT_ALGORITHM); - } + public RsaSigner(RSAPrivateKey key) { + this(key, DEFAULT_ALGORITHM); + } - public RsaSigner(RSAPrivateKey key, String algorithm) { - this.key = key; - this.algorithm = algorithm; - } + public RsaSigner(RSAPrivateKey key, String algorithm) { + this.key = key; + this.algorithm = algorithm; + } - public RsaSigner(String sshKey) { - this(loadPrivateKey(sshKey)); - } + public RsaSigner(String sshKey) { + this(loadPrivateKey(sshKey)); + } - public byte[] sign(byte[] bytes) { - try { - Signature signature = Signature.getInstance(algorithm); - signature.initSign(key); - signature.update(bytes); - return signature.sign(); - } - catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - } + public byte[] sign(byte[] bytes) { + try { + Signature signature = Signature.getInstance(algorithm); + signature.initSign(key); + signature.update(bytes); + return signature.sign(); + } + catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } - public String algorithm() { - return algorithm; - } + public String algorithm() { + return algorithm; + } - private static RSAPrivateKey createPrivateKey(BigInteger n, BigInteger d) { - try { - return (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new RSAPrivateKeySpec(n, d)); - } - catch (Exception e) { - throw new RuntimeException(e); - } - } + private static RSAPrivateKey createPrivateKey(BigInteger n, BigInteger d) { + try { + return (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new RSAPrivateKeySpec(n, d)); + } + catch (Exception e) { + throw new RuntimeException(e); + } + } - private static RSAPrivateKey loadPrivateKey(String key) { - KeyPair kp = RsaKeyHelper.parseKeyPair(key); + private static RSAPrivateKey loadPrivateKey(String key) { + KeyPair kp = RsaKeyHelper.parseKeyPair(key); - if (kp.getPrivate() == null) { - throw new IllegalArgumentException("Not a private key"); - } + if (kp.getPrivate() == null) { + throw new IllegalArgumentException("Not a private key"); + } - return (RSAPrivateKey) kp.getPrivate(); - } + return (RSAPrivateKey) kp.getPrivate(); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/RsaVerifier.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/RsaVerifier.java index b0e23b8fe..7f224b030 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/RsaVerifier.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/RsaVerifier.java @@ -25,42 +25,42 @@ import java.security.interfaces.RSAPublicKey; * @author Luke Taylor */ public class RsaVerifier implements SignatureVerifier { - private final RSAPublicKey key; - private final String algorithm; + private final RSAPublicKey key; + private final String algorithm; - public RsaVerifier(BigInteger n, BigInteger e) { - this(RsaKeyHelper.createPublicKey(n, e)); - } + public RsaVerifier(BigInteger n, BigInteger e) { + this(RsaKeyHelper.createPublicKey(n, e)); + } - public RsaVerifier(RSAPublicKey key) { - this(key, RsaSigner.DEFAULT_ALGORITHM); - } + public RsaVerifier(RSAPublicKey key) { + this(key, RsaSigner.DEFAULT_ALGORITHM); + } - public RsaVerifier(RSAPublicKey key, String algorithm) { - this.key = key; - this.algorithm = algorithm; - } + public RsaVerifier(RSAPublicKey key, String algorithm) { + this.key = key; + this.algorithm = algorithm; + } - public RsaVerifier(String key) { - this(RsaKeyHelper.parsePublicKey(key.trim()), RsaSigner.DEFAULT_ALGORITHM); - } + public RsaVerifier(String key) { + this(RsaKeyHelper.parsePublicKey(key.trim()), RsaSigner.DEFAULT_ALGORITHM); + } - public void verify(byte[] content, byte[] sig) { - try { - Signature signature = Signature.getInstance(algorithm); - signature.initVerify(key); - signature.update(content); + public void verify(byte[] content, byte[] sig) { + try { + Signature signature = Signature.getInstance(algorithm); + signature.initVerify(key); + signature.update(content); - if (!signature.verify(sig)) { - throw new InvalidSignatureException("RSA Signature did not match content"); - } - } - catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - } + if (!signature.verify(sig)) { + throw new InvalidSignatureException("RSA Signature did not match content"); + } + } + catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } - public String algorithm() { - return algorithm; - } + public String algorithm() { + return algorithm; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/SignatureVerifier.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/SignatureVerifier.java index d7fc7f38a..033825f83 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/SignatureVerifier.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/SignatureVerifier.java @@ -18,5 +18,5 @@ import org.dromara.maxkey.authz.oauth2.jwt.AlgorithmMetadata; * @author Luke Taylor */ public interface SignatureVerifier extends AlgorithmMetadata { - void verify(byte[] content, byte[] signature); + void verify(byte[] content, byte[] signature); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/Signer.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/Signer.java index a662dce8a..fc14d3501 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/Signer.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/jwt/crypto/sign/Signer.java @@ -18,5 +18,5 @@ import org.dromara.maxkey.authz.oauth2.jwt.AlgorithmMetadata; * @author Luke Taylor */ public interface Signer extends AlgorithmMetadata { - byte[] sign(byte[] bytes); + byte[] sign(byte[] bytes); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/AuthorizationRequest.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/AuthorizationRequest.java index db31a1646..34cc3136d 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/AuthorizationRequest.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/AuthorizationRequest.java @@ -56,252 +56,252 @@ import org.springframework.web.bind.annotation.SessionAttributes; @SuppressWarnings("serial") public class AuthorizationRequest extends BaseRequest implements Serializable { - /** - * Map to hold the original, unchanged parameter set submitted by a user to - * signal approval of the token grant approval. Once set this should not be - * modified. - */ - private Map approvalParameters = Collections.unmodifiableMap(new HashMap()); + /** + * Map to hold the original, unchanged parameter set submitted by a user to + * signal approval of the token grant approval. Once set this should not be + * modified. + */ + private Map approvalParameters = Collections.unmodifiableMap(new HashMap()); - /** - * The value of the "state" parameter sent by the client in the request, if - * sent by the client. As this must be echoed back to the client unchanged, - * it should not be modified by any processing classes. - */ - private String state; + /** + * The value of the "state" parameter sent by the client in the request, if + * sent by the client. As this must be echoed back to the client unchanged, + * it should not be modified by any processing classes. + */ + private String state; - /** - * Resolved requested response types initialized (by the - * OAuth2RequestFactory) with the response types originally requested. - */ - private Set responseTypes = new HashSet(); + /** + * Resolved requested response types initialized (by the + * OAuth2RequestFactory) with the response types originally requested. + */ + private Set responseTypes = new HashSet(); - /** - * Resolved resource IDs. This set may change during request processing. - */ - private Set resourceIds = new HashSet(); + /** + * Resolved resource IDs. This set may change during request processing. + */ + private Set resourceIds = new HashSet(); - /** - * Resolved granted authorities for this request. May change during request - * processing. - */ - private Collection authorities = new HashSet(); + /** + * Resolved granted authorities for this request. May change during request + * processing. + */ + private Collection authorities = new HashSet(); - /** - * Whether the request has been approved by the end user (or other process). - * This will be altered by the User Approval Endpoint and/or the - * UserApprovalHandler as appropriate. - */ - private boolean approved = false; + /** + * Whether the request has been approved by the end user (or other process). + * This will be altered by the User Approval Endpoint and/or the + * UserApprovalHandler as appropriate. + */ + private boolean approved = false; - /** - * The resolved redirect URI of this request. A URI may be present in the - * original request, in the authorizationParameters, or it may not be - * provided, in which case it will be defaulted (by processing classes) to - * the Client's default registered value. - */ - private String redirectUri; + /** + * The resolved redirect URI of this request. A URI may be present in the + * original request, in the authorizationParameters, or it may not be + * provided, in which case it will be defaulted (by processing classes) to + * the Client's default registered value. + */ + private String redirectUri; - /** - * Extension point for custom processing classes which may wish to store - * additional information about the OAuth2 request. Since this class will - * create a serializable OAuth2Request, all members of this extension map - * must be serializable. - */ - private Map extensions = new HashMap(); - - //support oauth 2.1, PKCE - /** - * A challenge derived from the code verifier that is sent in the + /** + * Extension point for custom processing classes which may wish to store + * additional information about the OAuth2 request. Since this class will + * create a serializable OAuth2Request, all members of this extension map + * must be serializable. + */ + private Map extensions = new HashMap(); + + //support oauth 2.1, PKCE + /** + * A challenge derived from the code verifier that is sent in the * authorization request, to be verified against later. - */ - private String codeChallenge; - - /** - * A method that was used to derive code challenge. - * - * plain + */ + private String codeChallenge; + + /** + * A method that was used to derive code challenge. + * + * plain * code_challenge = code_verifier * * S256 * code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier))) - */ - private String codeChallengeMethod = "S256"; + */ + private String codeChallengeMethod = "S256"; - /** - * Default constructor. - */ - public AuthorizationRequest() { - } + /** + * Default constructor. + */ + public AuthorizationRequest() { + } - /** - * Full constructor. - */ - public AuthorizationRequest(Map authorizationParameters, Map approvalParameters, String clientId, Set scope, Set resourceIds, Collection authorities, boolean approved, String state, String redirectUri, - Set responseTypes,String codeChallenge,String codeChallengeMethod) { - setClientId(clientId); - setRequestParameters(authorizationParameters); // in case we need to - // wrap the collection - setScope(scope); // in case we need to parse - if (resourceIds != null) { - this.resourceIds = new HashSet(resourceIds); - } - if (authorities != null) { - this.authorities = new HashSet(authorities); - } - this.approved = approved; - this.resourceIds = resourceIds; - this.redirectUri = redirectUri; - if (responseTypes != null) { - this.responseTypes = responseTypes; - } - this.state = state; - //add oauth 2.1 PKCE - this.codeChallenge = codeChallenge; - if (codeChallengeMethod != null) { - this.codeChallengeMethod = codeChallengeMethod; - } - } + /** + * Full constructor. + */ + public AuthorizationRequest(Map authorizationParameters, Map approvalParameters, String clientId, Set scope, Set resourceIds, Collection authorities, boolean approved, String state, String redirectUri, + Set responseTypes,String codeChallenge,String codeChallengeMethod) { + setClientId(clientId); + setRequestParameters(authorizationParameters); // in case we need to + // wrap the collection + setScope(scope); // in case we need to parse + if (resourceIds != null) { + this.resourceIds = new HashSet(resourceIds); + } + if (authorities != null) { + this.authorities = new HashSet(authorities); + } + this.approved = approved; + this.resourceIds = resourceIds; + this.redirectUri = redirectUri; + if (responseTypes != null) { + this.responseTypes = responseTypes; + } + this.state = state; + //add oauth 2.1 PKCE + this.codeChallenge = codeChallenge; + if (codeChallengeMethod != null) { + this.codeChallengeMethod = codeChallengeMethod; + } + } - public OAuth2Request createOAuth2Request() { - return new OAuth2Request(getRequestParameters(), getClientId(), getAuthorities(), isApproved(), getScope(), getResourceIds(), getRedirectUri(), getResponseTypes(), getCodeChallenge(),getCodeChallengeMethod(),getExtensions()); - } + public OAuth2Request createOAuth2Request() { + return new OAuth2Request(getRequestParameters(), getClientId(), getAuthorities(), isApproved(), getScope(), getResourceIds(), getRedirectUri(), getResponseTypes(), getCodeChallenge(),getCodeChallengeMethod(),getExtensions()); + } - /** - * Convenience constructor for unit tests, where client ID and scope are - * often the only needed fields. - * - * @param clientId - * @param scopes - */ - public AuthorizationRequest(String clientId, Collection scopes) { - setClientId(clientId); - setScope(scopes); // in case we need to parse - } + /** + * Convenience constructor for unit tests, where client ID and scope are + * often the only needed fields. + * + * @param clientId + * @param scopes + */ + public AuthorizationRequest(String clientId, Collection scopes) { + setClientId(clientId); + setScope(scopes); // in case we need to parse + } - /** - * Convenience method to set resourceIds and authorities on this request by - * inheriting from a ClientDetails object. - * - * @param clientDetails - */ - public void setResourceIdsAndAuthoritiesFromClientDetails(ClientDetails clientDetails) { - setResourceIds(clientDetails.getResourceIds()); - setAuthorities(clientDetails.getAuthorities()); - } + /** + * Convenience method to set resourceIds and authorities on this request by + * inheriting from a ClientDetails object. + * + * @param clientDetails + */ + public void setResourceIdsAndAuthoritiesFromClientDetails(ClientDetails clientDetails) { + setResourceIds(clientDetails.getResourceIds()); + setAuthorities(clientDetails.getAuthorities()); + } - public Map getApprovalParameters() { - return approvalParameters; - } + public Map getApprovalParameters() { + return approvalParameters; + } - public void setApprovalParameters(Map approvalParameters) { - this.approvalParameters = approvalParameters; - } + public void setApprovalParameters(Map approvalParameters) { + this.approvalParameters = approvalParameters; + } - public String getState() { - return state; - } + public String getState() { + return state; + } - public void setState(String state) { - this.state = state; - } + public void setState(String state) { + this.state = state; + } - public Set getResponseTypes() { - return responseTypes; - } + public Set getResponseTypes() { + return responseTypes; + } - public void setResponseTypes(Set responseTypes) { - this.responseTypes = responseTypes; - } + public void setResponseTypes(Set responseTypes) { + this.responseTypes = responseTypes; + } - public void setRedirectUri(String redirectUri) { - this.redirectUri = redirectUri; - } + public void setRedirectUri(String redirectUri) { + this.redirectUri = redirectUri; + } - public void setApproved(boolean approved) { - this.approved = approved; - } + public void setApproved(boolean approved) { + this.approved = approved; + } - public void setAuthorities(Collection authorities) { - if (authorities != null) { - this.authorities = new HashSet(authorities); - } - } + public void setAuthorities(Collection authorities) { + if (authorities != null) { + this.authorities = new HashSet(authorities); + } + } - /** - * @return the extensions - */ - public Map getExtensions() { - return extensions; - } + /** + * @return the extensions + */ + public Map getExtensions() { + return extensions; + } - public void setExtensions(Map extensions) { - this.extensions = extensions; - } + public void setExtensions(Map extensions) { + this.extensions = extensions; + } - public void setResourceIds(Set resourceIds) { - this.resourceIds = resourceIds; - } + public void setResourceIds(Set resourceIds) { + this.resourceIds = resourceIds; + } - public void setClientId(String clientId) { - super.setClientId(clientId); - } + public void setClientId(String clientId) { + super.setClientId(clientId); + } - /** - * Set the scope value. If the collection contains only a single scope - * value, this method will parse that value into a collection using - * {@link OAuth2Utils.parseParameterList}. - * - * @see TokenRequest.setScope - * - * @param scope - */ - public void setScope(Collection scope) { - super.setScope(scope); - } + /** + * Set the scope value. If the collection contains only a single scope + * value, this method will parse that value into a collection using + * {@link OAuth2Utils.parseParameterList}. + * + * @see TokenRequest.setScope + * + * @param scope + */ + public void setScope(Collection scope) { + super.setScope(scope); + } - /** - * Set the Request Parameters on this authorization request, which represent - * the original request parameters and should never be changed during - * processing. The map passed in is wrapped in an unmodifiable map instance. - * - * @see TokenRequest.setRequestParameters - * - * @param requestParameters - */ - public void setRequestParameters(Map requestParameters) { - super.setRequestParameters(requestParameters); - } + /** + * Set the Request Parameters on this authorization request, which represent + * the original request parameters and should never be changed during + * processing. The map passed in is wrapped in an unmodifiable map instance. + * + * @see TokenRequest.setRequestParameters + * + * @param requestParameters + */ + public void setRequestParameters(Map requestParameters) { + super.setRequestParameters(requestParameters); + } - /** - * @return the resourceIds - */ - public Set getResourceIds() { - return resourceIds; - } + /** + * @return the resourceIds + */ + public Set getResourceIds() { + return resourceIds; + } - /** - * @return the authorities - */ - public Collection getAuthorities() { - return authorities; - } + /** + * @return the authorities + */ + public Collection getAuthorities() { + return authorities; + } - /** - * @return the approved - */ - public boolean isApproved() { - return approved; - } + /** + * @return the approved + */ + public boolean isApproved() { + return approved; + } - /** - * @return the redirectUri - */ - public String getRedirectUri() { - return redirectUri; - } + /** + * @return the redirectUri + */ + public String getRedirectUri() { + return redirectUri; + } - public String getCodeChallenge() { + public String getCodeChallenge() { return codeChallenge; } @@ -318,40 +318,40 @@ public class AuthorizationRequest extends BaseRequest implements Serializable { } @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((approvalParameters == null) ? 0 : approvalParameters.hashCode()); - result = prime * result + ((responseTypes == null) ? 0 : responseTypes.hashCode()); - result = prime * result + ((state == null) ? 0 : state.hashCode()); - return result; - } + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((approvalParameters == null) ? 0 : approvalParameters.hashCode()); + result = prime * result + ((responseTypes == null) ? 0 : responseTypes.hashCode()); + result = prime * result + ((state == null) ? 0 : state.hashCode()); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - AuthorizationRequest other = (AuthorizationRequest) obj; - if (approvalParameters == null) { - if (other.approvalParameters != null) - return false; - } else if (!approvalParameters.equals(other.approvalParameters)) - return false; - if (responseTypes == null) { - if (other.responseTypes != null) - return false; - } else if (!responseTypes.equals(other.responseTypes)) - return false; - if (state == null) { - if (other.state != null) - return false; - } else if (!state.equals(other.state)) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + AuthorizationRequest other = (AuthorizationRequest) obj; + if (approvalParameters == null) { + if (other.approvalParameters != null) + return false; + } else if (!approvalParameters.equals(other.approvalParameters)) + return false; + if (responseTypes == null) { + if (other.responseTypes != null) + return false; + } else if (!responseTypes.equals(other.responseTypes)) + return false; + if (state == null) { + if (other.state != null) + return false; + } else if (!state.equals(other.state)) + return false; + return true; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/BaseRequest.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/BaseRequest.java index f461b72d4..0504d566e 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/BaseRequest.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/BaseRequest.java @@ -40,123 +40,123 @@ import org.dromara.maxkey.authz.oauth2.common.util.OAuth2Utils; @SuppressWarnings("serial") abstract class BaseRequest implements Serializable { - /** - * Resolved client ID. This may be present in the original request - * parameters, or in some cases may be inferred by a processing class and - * inserted here. - */ - private String clientId; + /** + * Resolved client ID. This may be present in the original request + * parameters, or in some cases may be inferred by a processing class and + * inserted here. + */ + private String clientId; - /** - * Resolved scope set, initialized (by the OAuth2RequestFactory) with the - * scopes originally requested. Further processing and user interaction may - * alter the set of scopes that is finally granted and stored when the - * request processing is complete. - */ - private Set scope = new HashSet(); + /** + * Resolved scope set, initialized (by the OAuth2RequestFactory) with the + * scopes originally requested. Further processing and user interaction may + * alter the set of scopes that is finally granted and stored when the + * request processing is complete. + */ + private Set scope = new HashSet(); - /** - * Map of parameters passed in to the Authorization Endpoint or Token - * Endpoint, preserved unchanged from the original request. This map should - * not be modified after initialization. In general, classes should not - * retrieve values from this map directly, and should instead use the - * individual members on this class. - * - * The OAuth2RequestFactory is responsible for initializing all members of - * this class, usually by parsing the values inside the requestParmaeters - * map. - * - */ - private Map requestParameters = Collections - .unmodifiableMap(new HashMap()); + /** + * Map of parameters passed in to the Authorization Endpoint or Token + * Endpoint, preserved unchanged from the original request. This map should + * not be modified after initialization. In general, classes should not + * retrieve values from this map directly, and should instead use the + * individual members on this class. + * + * The OAuth2RequestFactory is responsible for initializing all members of + * this class, usually by parsing the values inside the requestParmaeters + * map. + * + */ + private Map requestParameters = Collections + .unmodifiableMap(new HashMap()); - public String getClientId() { - return clientId; - } + public String getClientId() { + return clientId; + } - public Set getScope() { - return scope; - } + public Set getScope() { + return scope; + } - /** - * Warning: most clients should use the individual properties of this class, - * such as {{@link #getScope()} or { {@link #getClientId()}, rather than - * retrieving values from this map. - * - * @return the original, unchanged set of request parameters - */ - public Map getRequestParameters() { - return requestParameters; - } + /** + * Warning: most clients should use the individual properties of this class, + * such as {{@link #getScope()} or { {@link #getClientId()}, rather than + * retrieving values from this map. + * + * @return the original, unchanged set of request parameters + */ + public Map getRequestParameters() { + return requestParameters; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((clientId == null) ? 0 : clientId.hashCode()); - result = prime - * result - + ((requestParameters == null) ? 0 : requestParameters - .hashCode()); - result = prime * result + ((scope == null) ? 0 : scope.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + + ((clientId == null) ? 0 : clientId.hashCode()); + result = prime + * result + + ((requestParameters == null) ? 0 : requestParameters + .hashCode()); + result = prime * result + ((scope == null) ? 0 : scope.hashCode()); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - BaseRequest other = (BaseRequest) obj; - if (clientId == null) { - if (other.clientId != null) - return false; - } else if (!clientId.equals(other.clientId)) - return false; - if (requestParameters == null) { - if (other.requestParameters != null) - return false; - } else if (!requestParameters.equals(other.requestParameters)) - return false; - if (scope == null) { - if (other.scope != null) - return false; - } else if (!scope.equals(other.scope)) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + BaseRequest other = (BaseRequest) obj; + if (clientId == null) { + if (other.clientId != null) + return false; + } else if (!clientId.equals(other.clientId)) + return false; + if (requestParameters == null) { + if (other.requestParameters != null) + return false; + } else if (!requestParameters.equals(other.requestParameters)) + return false; + if (scope == null) { + if (other.scope != null) + return false; + } else if (!scope.equals(other.scope)) + return false; + return true; + } - protected void setScope(Collection scope) { - if (scope != null && scope.size() == 1) { - String value = scope.iterator().next(); - /* - * This is really an error, but it can catch out unsuspecting users - * and it's easy to fix. It happens when an AuthorizationRequest - * gets bound accidentally from request parameters using - * @ModelAttribute. - */ - if (value.contains(" ") || value.contains(",")) { - scope = OAuth2Utils.parseParameterList(value); - } - } - this.scope = Collections - .unmodifiableSet(scope == null ? new LinkedHashSet() - : new LinkedHashSet(scope)); - } + protected void setScope(Collection scope) { + if (scope != null && scope.size() == 1) { + String value = scope.iterator().next(); + /* + * This is really an error, but it can catch out unsuspecting users + * and it's easy to fix. It happens when an AuthorizationRequest + * gets bound accidentally from request parameters using + * @ModelAttribute. + */ + if (value.contains(" ") || value.contains(",")) { + scope = OAuth2Utils.parseParameterList(value); + } + } + this.scope = Collections + .unmodifiableSet(scope == null ? new LinkedHashSet() + : new LinkedHashSet(scope)); + } - protected void setRequestParameters(Map requestParameters) { - if (requestParameters != null) { - this.requestParameters = Collections - .unmodifiableMap(requestParameters); - } - } + protected void setRequestParameters(Map requestParameters) { + if (requestParameters != null) { + this.requestParameters = Collections + .unmodifiableMap(requestParameters); + } + } - protected void setClientId(String clientId) { - this.clientId = clientId; - } + protected void setClientId(String clientId) { + this.clientId = clientId; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/ClientAlreadyExistsException.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/ClientAlreadyExistsException.java index 058b65529..6c8a64abe 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/ClientAlreadyExistsException.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/ClientAlreadyExistsException.java @@ -24,12 +24,12 @@ package org.dromara.maxkey.authz.oauth2.provider; @SuppressWarnings("serial") public class ClientAlreadyExistsException extends ClientRegistrationException { - public ClientAlreadyExistsException(String msg) { - super(msg); - } + public ClientAlreadyExistsException(String msg) { + super(msg); + } - public ClientAlreadyExistsException(String msg, Throwable cause) { - super(msg, cause); - } + public ClientAlreadyExistsException(String msg, Throwable cause) { + super(msg, cause); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/ClientRegistrationException.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/ClientRegistrationException.java index a902a252d..8dccd4b5a 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/ClientRegistrationException.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/ClientRegistrationException.java @@ -21,13 +21,13 @@ package org.dromara.maxkey.authz.oauth2.provider; */ @SuppressWarnings("serial") public class ClientRegistrationException extends RuntimeException { - - public ClientRegistrationException(String msg) { - super(msg); - } + + public ClientRegistrationException(String msg) { + super(msg); + } - public ClientRegistrationException(String msg, Throwable cause) { - super(msg, cause); - } + public ClientRegistrationException(String msg, Throwable cause) { + super(msg, cause); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/ClientRegistrationService.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/ClientRegistrationService.java index 0e06a7b9d..e2042200a 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/ClientRegistrationService.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/ClientRegistrationService.java @@ -28,14 +28,14 @@ import org.dromara.maxkey.entity.apps.oauth2.provider.ClientDetails; */ public interface ClientRegistrationService { - void addClientDetails(ClientDetails clientDetails) throws ClientAlreadyExistsException; + void addClientDetails(ClientDetails clientDetails) throws ClientAlreadyExistsException; - void updateClientDetails(ClientDetails clientDetails) throws NoSuchClientException; + void updateClientDetails(ClientDetails clientDetails) throws NoSuchClientException; - void updateClientSecret(String clientId, String secret) throws NoSuchClientException; + void updateClientSecret(String clientId, String secret) throws NoSuchClientException; - void removeClientDetails(String clientId) throws NoSuchClientException; - - List listClientDetails(); + void removeClientDetails(String clientId) throws NoSuchClientException; + + List listClientDetails(); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/CompositeTokenGranter.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/CompositeTokenGranter.java index 4175fb219..456468c28 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/CompositeTokenGranter.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/CompositeTokenGranter.java @@ -27,20 +27,20 @@ import org.dromara.maxkey.authz.oauth2.common.OAuth2AccessToken; */ public class CompositeTokenGranter implements TokenGranter { - private final List tokenGranters; + private final List tokenGranters; - public CompositeTokenGranter(List tokenGranters) { - this.tokenGranters = new ArrayList(tokenGranters); - } - - public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) { - for (TokenGranter granter : tokenGranters) { - OAuth2AccessToken grant = granter.grant(grantType, tokenRequest); - if (grant!=null) { - return grant; - } - } - return null; - } + public CompositeTokenGranter(List tokenGranters) { + this.tokenGranters = new ArrayList(tokenGranters); + } + + public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) { + for (TokenGranter granter : tokenGranters) { + OAuth2AccessToken grant = granter.grant(grantType, tokenRequest); + if (grant!=null) { + return grant; + } + } + return null; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/DefaultSecurityContextAccessor.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/DefaultSecurityContextAccessor.java index 885501250..2ce2e717d 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/DefaultSecurityContextAccessor.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/DefaultSecurityContextAccessor.java @@ -29,31 +29,31 @@ import org.springframework.security.core.context.SecurityContextHolder; */ public class DefaultSecurityContextAccessor implements SecurityContextAccessor { - @Override - public boolean isUser() { - Authentication authentication = getUserAuthentication(); - return authentication != null; - } - - @Override - public Set getAuthorities() { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication == null) { - return Collections.emptySet(); - } - return Collections.unmodifiableSet(new HashSet(authentication.getAuthorities())); - } + @Override + public boolean isUser() { + Authentication authentication = getUserAuthentication(); + return authentication != null; + } + + @Override + public Set getAuthorities() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication == null) { + return Collections.emptySet(); + } + return Collections.unmodifiableSet(new HashSet(authentication.getAuthorities())); + } - private Authentication getUserAuthentication() { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication == null) { - return null; - } - if (authentication instanceof OAuth2Authentication) { - OAuth2Authentication oauth = (OAuth2Authentication) authentication; - return oauth.getUserAuthentication(); - } - return authentication; - } + private Authentication getUserAuthentication() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication == null) { + return null; + } + if (authentication instanceof OAuth2Authentication) { + OAuth2Authentication oauth = (OAuth2Authentication) authentication; + return oauth.getUserAuthentication(); + } + return authentication; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/NoSuchClientException.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/NoSuchClientException.java index 54a5fa4d4..020a5c2be 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/NoSuchClientException.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/NoSuchClientException.java @@ -22,12 +22,12 @@ package org.dromara.maxkey.authz.oauth2.provider; @SuppressWarnings("serial") public class NoSuchClientException extends ClientRegistrationException { - public NoSuchClientException(String msg) { - super(msg); - } + public NoSuchClientException(String msg) { + super(msg); + } - public NoSuchClientException(String msg, Throwable cause) { - super(msg, cause); - } + public NoSuchClientException(String msg, Throwable cause) { + super(msg, cause); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2Authentication.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2Authentication.java index 3e80c3d06..97ba72806 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2Authentication.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2Authentication.java @@ -28,98 +28,98 @@ import org.springframework.security.core.Authentication; */ public class OAuth2Authentication extends AbstractAuthenticationToken { - private static final long serialVersionUID = -4809832298438307309L; + private static final long serialVersionUID = -4809832298438307309L; - private final OAuth2Request storedRequest; + private final OAuth2Request storedRequest; - private final Authentication userAuthentication; + private final Authentication userAuthentication; - /** - * Construct an OAuth 2 authentication. Since some grant types don't require user authentication, the user - * authentication may be null. - * - * @param storedRequest The authorization request (must not be null). - * @param userAuthentication The user authentication (possibly null). - */ - public OAuth2Authentication(OAuth2Request storedRequest, Authentication userAuthentication) { - super(userAuthentication == null ? storedRequest.getAuthorities() : userAuthentication.getAuthorities()); - this.storedRequest = storedRequest; - this.userAuthentication = userAuthentication; - } + /** + * Construct an OAuth 2 authentication. Since some grant types don't require user authentication, the user + * authentication may be null. + * + * @param storedRequest The authorization request (must not be null). + * @param userAuthentication The user authentication (possibly null). + */ + public OAuth2Authentication(OAuth2Request storedRequest, Authentication userAuthentication) { + super(userAuthentication == null ? storedRequest.getAuthorities() : userAuthentication.getAuthorities()); + this.storedRequest = storedRequest; + this.userAuthentication = userAuthentication; + } - public Object getCredentials() { - return ""; - } + public Object getCredentials() { + return ""; + } - public Object getPrincipal() { - return this.userAuthentication == null ? this.storedRequest.getClientId() : this.userAuthentication - .getPrincipal(); - } + public Object getPrincipal() { + return this.userAuthentication == null ? this.storedRequest.getClientId() : this.userAuthentication + .getPrincipal(); + } - /** - * Convenience method to check if there is a user associated with this token, or just a client application. - * - * @return true if this token represents a client app not acting on behalf of a user - */ - public boolean isClientOnly() { - return userAuthentication == null; - } + /** + * Convenience method to check if there is a user associated with this token, or just a client application. + * + * @return true if this token represents a client app not acting on behalf of a user + */ + public boolean isClientOnly() { + return userAuthentication == null; + } - /** - * The authorization request containing details of the client application. - * - * @return The client authentication. - */ - public OAuth2Request getOAuth2Request() { - return storedRequest; - } + /** + * The authorization request containing details of the client application. + * + * @return The client authentication. + */ + public OAuth2Request getOAuth2Request() { + return storedRequest; + } - /** - * The user authentication. - * - * @return The user authentication. - */ - public Authentication getUserAuthentication() { - return userAuthentication; - } + /** + * The user authentication. + * + * @return The user authentication. + */ + public Authentication getUserAuthentication() { + return userAuthentication; + } - @Override - public boolean isAuthenticated() { - return this.storedRequest.isApproved() - && (this.userAuthentication == null || this.userAuthentication.isAuthenticated()); - } + @Override + public boolean isAuthenticated() { + return this.storedRequest.isApproved() + && (this.userAuthentication == null || this.userAuthentication.isAuthenticated()); + } - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof OAuth2Authentication)) { - return false; - } - if (!super.equals(o)) { - return false; - } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof OAuth2Authentication)) { + return false; + } + if (!super.equals(o)) { + return false; + } - OAuth2Authentication that = (OAuth2Authentication) o; + OAuth2Authentication that = (OAuth2Authentication) o; - if (!storedRequest.equals(that.storedRequest)) { - return false; - } - if (userAuthentication != null ? !userAuthentication.equals(that.userAuthentication) - : that.userAuthentication != null) { - return false; - } + if (!storedRequest.equals(that.storedRequest)) { + return false; + } + if (userAuthentication != null ? !userAuthentication.equals(that.userAuthentication) + : that.userAuthentication != null) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + storedRequest.hashCode(); - result = 31 * result + (userAuthentication != null ? userAuthentication.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + storedRequest.hashCode(); + result = 31 * result + (userAuthentication != null ? userAuthentication.hashCode() : 0); + return result; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2Request.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2Request.java index 35e49e68d..e1e153cd8 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2Request.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2Request.java @@ -38,44 +38,44 @@ import org.springframework.security.core.GrantedAuthority; */ public class OAuth2Request extends BaseRequest implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - /** - * Resolved resource IDs. This set may change during request processing. - */ - private Set resourceIds = new HashSet(); + /** + * Resolved resource IDs. This set may change during request processing. + */ + private Set resourceIds = new HashSet(); - /** - * Resolved granted authorities for this request. May change during request processing. - */ - private Collection authorities = new HashSet(); + /** + * Resolved granted authorities for this request. May change during request processing. + */ + private Collection authorities = new HashSet(); - /** - * Whether the request has been approved by the end user (or other process). This will be altered by the User - * Approval Endpoint and/or the UserApprovalHandler as appropriate. - */ - private boolean approved = false; + /** + * Whether the request has been approved by the end user (or other process). This will be altered by the User + * Approval Endpoint and/or the UserApprovalHandler as appropriate. + */ + private boolean approved = false; - /** - * Will be non-null if the request is for a token to be refreshed (the original grant type might still be available - * via {@link #getGrantType()}). - */ - private TokenRequest refresh = null; + /** + * Will be non-null if the request is for a token to be refreshed (the original grant type might still be available + * via {@link #getGrantType()}). + */ + private TokenRequest refresh = null; - /** - * The resolved redirect URI of this request. A URI may be present in the original request, in the - * authorizationParameters, or it may not be provided, in which case it will be defaulted (by processing classes) to - * the Client's default registered value. - */ - private String redirectUri; + /** + * The resolved redirect URI of this request. A URI may be present in the original request, in the + * authorizationParameters, or it may not be provided, in which case it will be defaulted (by processing classes) to + * the Client's default registered value. + */ + private String redirectUri; - /** - * Resolved requested response types initialized (by the OAuth2RequestFactory) with the response types originally - * requested. - */ - private Set responseTypes = new HashSet(); - - //support oauth 2.1, PKCE + /** + * Resolved requested response types initialized (by the OAuth2RequestFactory) with the response types originally + * requested. + */ + private Set responseTypes = new HashSet(); + + //support oauth 2.1, PKCE /** * A challenge derived from the code verifier that is sent in the * authorization request, to be verified against later. @@ -93,76 +93,76 @@ public class OAuth2Request extends BaseRequest implements Serializable { */ private String codeChallengeMethod = "S256"; - /** - * Extension point for custom processing classes which may wish to store additional information about the OAuth2 - * request. Since this class is serializable, all members of this map must also be serializable. - */ - private Map extensions = new HashMap(); + /** + * Extension point for custom processing classes which may wish to store additional information about the OAuth2 + * request. Since this class is serializable, all members of this map must also be serializable. + */ + private Map extensions = new HashMap(); - public OAuth2Request(Map requestParameters, String clientId, - Collection authorities, boolean approved, Set scope, - Set resourceIds, String redirectUri, Set responseTypes, - String codeChallenge,String codeChallengeMethod, - Map extensionProperties) { - setClientId(clientId); - setRequestParameters(requestParameters); - setScope(scope); - if (resourceIds != null) { - this.resourceIds = new HashSet(resourceIds); - } - if (authorities != null) { - this.authorities = new HashSet(authorities); - } - this.approved = approved; - this.resourceIds = resourceIds; - if (responseTypes != null) { - this.responseTypes = new HashSet(responseTypes); - } - this.codeChallenge = codeChallenge; - this.codeChallengeMethod = codeChallengeMethod; - this.redirectUri = redirectUri; - if (extensionProperties != null) { - this.extensions = extensionProperties; - } - } + public OAuth2Request(Map requestParameters, String clientId, + Collection authorities, boolean approved, Set scope, + Set resourceIds, String redirectUri, Set responseTypes, + String codeChallenge,String codeChallengeMethod, + Map extensionProperties) { + setClientId(clientId); + setRequestParameters(requestParameters); + setScope(scope); + if (resourceIds != null) { + this.resourceIds = new HashSet(resourceIds); + } + if (authorities != null) { + this.authorities = new HashSet(authorities); + } + this.approved = approved; + this.resourceIds = resourceIds; + if (responseTypes != null) { + this.responseTypes = new HashSet(responseTypes); + } + this.codeChallenge = codeChallenge; + this.codeChallengeMethod = codeChallengeMethod; + this.redirectUri = redirectUri; + if (extensionProperties != null) { + this.extensions = extensionProperties; + } + } - protected OAuth2Request(OAuth2Request other) { - this(other.getRequestParameters(), other.getClientId(), other.getAuthorities(), other.isApproved(), other - .getScope(), other.getResourceIds(), other.getRedirectUri(), other.getResponseTypes(), - other.getCodeChallenge(),other.getCodeChallengeMethod(), - other.getExtensions()); - } + protected OAuth2Request(OAuth2Request other) { + this(other.getRequestParameters(), other.getClientId(), other.getAuthorities(), other.isApproved(), other + .getScope(), other.getResourceIds(), other.getRedirectUri(), other.getResponseTypes(), + other.getCodeChallenge(),other.getCodeChallengeMethod(), + other.getExtensions()); + } - protected OAuth2Request(String clientId) { - setClientId(clientId); - } + protected OAuth2Request(String clientId) { + setClientId(clientId); + } - protected OAuth2Request() { - super(); - } + protected OAuth2Request() { + super(); + } - public String getRedirectUri() { - return redirectUri; - } + public String getRedirectUri() { + return redirectUri; + } - public Set getResponseTypes() { - return responseTypes; - } + public Set getResponseTypes() { + return responseTypes; + } - public Collection getAuthorities() { - return authorities; - } + public Collection getAuthorities() { + return authorities; + } - public boolean isApproved() { - return approved; - } + public boolean isApproved() { + return approved; + } - public Set getResourceIds() { - return resourceIds; - } - + public Set getResourceIds() { + return resourceIds; + } + - public String getCodeChallenge() { + public String getCodeChallenge() { return codeChallenge; } @@ -171,130 +171,130 @@ public class OAuth2Request extends BaseRequest implements Serializable { } public Map getExtensions() { - return extensions; - } + return extensions; + } - /** - * Update the request parameters and return a new object with the same properties except the parameters. - * @param parameters new parameters replacing the existing ones - * @return a new OAuth2Request - */ - public OAuth2Request createOAuth2Request(Map parameters) { - return new OAuth2Request(parameters, getClientId(), authorities, approved, getScope(), resourceIds, - redirectUri, responseTypes, codeChallenge, codeChallengeMethod,extensions); - } + /** + * Update the request parameters and return a new object with the same properties except the parameters. + * @param parameters new parameters replacing the existing ones + * @return a new OAuth2Request + */ + public OAuth2Request createOAuth2Request(Map parameters) { + return new OAuth2Request(parameters, getClientId(), authorities, approved, getScope(), resourceIds, + redirectUri, responseTypes, codeChallenge, codeChallengeMethod,extensions); + } - /** - * Update the scope and create a new request. All the other properties are the same (including the request - * parameters). - * - * @param scope the new scope - * @return a new request with the narrowed scope - */ - public OAuth2Request narrowScope(Set scope) { - OAuth2Request request = new OAuth2Request(getRequestParameters(), getClientId(), authorities, approved, scope, - resourceIds, redirectUri, responseTypes, codeChallenge, codeChallengeMethod, extensions); - request.refresh = this.refresh; - return request; - } + /** + * Update the scope and create a new request. All the other properties are the same (including the request + * parameters). + * + * @param scope the new scope + * @return a new request with the narrowed scope + */ + public OAuth2Request narrowScope(Set scope) { + OAuth2Request request = new OAuth2Request(getRequestParameters(), getClientId(), authorities, approved, scope, + resourceIds, redirectUri, responseTypes, codeChallenge, codeChallengeMethod, extensions); + request.refresh = this.refresh; + return request; + } - public OAuth2Request refresh(TokenRequest tokenRequest) { - OAuth2Request request = new OAuth2Request(getRequestParameters(), getClientId(), authorities, approved, - getScope(), resourceIds, redirectUri, responseTypes, codeChallenge, codeChallengeMethod,extensions); - request.refresh = tokenRequest; - return request; - } + public OAuth2Request refresh(TokenRequest tokenRequest) { + OAuth2Request request = new OAuth2Request(getRequestParameters(), getClientId(), authorities, approved, + getScope(), resourceIds, redirectUri, responseTypes, codeChallenge, codeChallengeMethod,extensions); + request.refresh = tokenRequest; + return request; + } - /** - * @return true if this request is known to be for a token to be refreshed - */ - public boolean isRefresh() { - return refresh != null; - } + /** + * @return true if this request is known to be for a token to be refreshed + */ + public boolean isRefresh() { + return refresh != null; + } - /** - * If this request was for an access token to be refreshed, then the {@link TokenRequest} that led to the refresh - * may be available here if it is known. - * - * @return the refresh token request (may be null) - */ - public TokenRequest getRefreshTokenRequest() { - return refresh; - } + /** + * If this request was for an access token to be refreshed, then the {@link TokenRequest} that led to the refresh + * may be available here if it is known. + * + * @return the refresh token request (may be null) + */ + public TokenRequest getRefreshTokenRequest() { + return refresh; + } - /** - * Tries to discover the grant type requested for the token associated with this request. - * - * @return the grant type if known, or null otherwise - */ - public String getGrantType() { - if (getRequestParameters().containsKey(OAuth2Constants.PARAMETER.GRANT_TYPE)) { - return getRequestParameters().get(OAuth2Constants.PARAMETER.GRANT_TYPE); - } - if (getRequestParameters().containsKey(OAuth2Constants.PARAMETER.RESPONSE_TYPE)) { - String response = getRequestParameters().get(OAuth2Constants.PARAMETER.RESPONSE_TYPE); - if (response.contains("token")) { - return "implicit"; - } - } - return null; - } + /** + * Tries to discover the grant type requested for the token associated with this request. + * + * @return the grant type if known, or null otherwise + */ + public String getGrantType() { + if (getRequestParameters().containsKey(OAuth2Constants.PARAMETER.GRANT_TYPE)) { + return getRequestParameters().get(OAuth2Constants.PARAMETER.GRANT_TYPE); + } + if (getRequestParameters().containsKey(OAuth2Constants.PARAMETER.RESPONSE_TYPE)) { + String response = getRequestParameters().get(OAuth2Constants.PARAMETER.RESPONSE_TYPE); + if (response.contains("token")) { + return "implicit"; + } + } + return null; + } - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + (approved ? 1231 : 1237); - result = prime * result + ((authorities == null) ? 0 : authorities.hashCode()); - result = prime * result + ((extensions == null) ? 0 : extensions.hashCode()); - result = prime * result + ((redirectUri == null) ? 0 : redirectUri.hashCode()); - result = prime * result + ((resourceIds == null) ? 0 : resourceIds.hashCode()); - result = prime * result + ((responseTypes == null) ? 0 : responseTypes.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + (approved ? 1231 : 1237); + result = prime * result + ((authorities == null) ? 0 : authorities.hashCode()); + result = prime * result + ((extensions == null) ? 0 : extensions.hashCode()); + result = prime * result + ((redirectUri == null) ? 0 : redirectUri.hashCode()); + result = prime * result + ((resourceIds == null) ? 0 : resourceIds.hashCode()); + result = prime * result + ((responseTypes == null) ? 0 : responseTypes.hashCode()); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - OAuth2Request other = (OAuth2Request) obj; - if (approved != other.approved) - return false; - if (authorities == null) { - if (other.authorities != null) - return false; - } - else if (!authorities.equals(other.authorities)) - return false; - if (extensions == null) { - if (other.extensions != null) - return false; - } - else if (!extensions.equals(other.extensions)) - return false; - if (redirectUri == null) { - if (other.redirectUri != null) - return false; - } - else if (!redirectUri.equals(other.redirectUri)) - return false; - if (resourceIds == null) { - if (other.resourceIds != null) - return false; - } - else if (!resourceIds.equals(other.resourceIds)) - return false; - if (responseTypes == null) { - if (other.responseTypes != null) - return false; - } - else if (!responseTypes.equals(other.responseTypes)) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + OAuth2Request other = (OAuth2Request) obj; + if (approved != other.approved) + return false; + if (authorities == null) { + if (other.authorities != null) + return false; + } + else if (!authorities.equals(other.authorities)) + return false; + if (extensions == null) { + if (other.extensions != null) + return false; + } + else if (!extensions.equals(other.extensions)) + return false; + if (redirectUri == null) { + if (other.redirectUri != null) + return false; + } + else if (!redirectUri.equals(other.redirectUri)) + return false; + if (resourceIds == null) { + if (other.resourceIds != null) + return false; + } + else if (!resourceIds.equals(other.resourceIds)) + return false; + if (responseTypes == null) { + if (other.responseTypes != null) + return false; + } + else if (!responseTypes.equals(other.responseTypes)) + return false; + return true; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2RequestFactory.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2RequestFactory.java index e8bdbaddd..13ac59fb8 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2RequestFactory.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2RequestFactory.java @@ -26,58 +26,58 @@ import org.dromara.maxkey.entity.apps.oauth2.provider.ClientDetails; */ public interface OAuth2RequestFactory { - /** - * Create a new {@link AuthorizationRequest} extracting all the needed information from the incoming parameter map, - * and initializing all individual fields on the {@link AuthorizationRequest} to reasonable values. When a class - * uses the factory to create an {@link AuthorizationRequest}, it should not need to access the parameter map - * directly afterwards. - * - * Typical implementations would initialize the individual fields on the {@link AuthorizationRequest} with the - * values requested in the original parameter map. It may also load the client details from the client id provided - * and validate the grant type and scopes, populating any fields in the request that are known only to the - * authorization server. - * - * @param authorizationParameters the parameters in the request - * @return a new AuthorizationRequest - */ - AuthorizationRequest createAuthorizationRequest(Map authorizationParameters); + /** + * Create a new {@link AuthorizationRequest} extracting all the needed information from the incoming parameter map, + * and initializing all individual fields on the {@link AuthorizationRequest} to reasonable values. When a class + * uses the factory to create an {@link AuthorizationRequest}, it should not need to access the parameter map + * directly afterwards. + * + * Typical implementations would initialize the individual fields on the {@link AuthorizationRequest} with the + * values requested in the original parameter map. It may also load the client details from the client id provided + * and validate the grant type and scopes, populating any fields in the request that are known only to the + * authorization server. + * + * @param authorizationParameters the parameters in the request + * @return a new AuthorizationRequest + */ + AuthorizationRequest createAuthorizationRequest(Map authorizationParameters); - /** - * Create a new {@link OAuth2Request} by extracting the needed information from the current - * {@link AuthorizationRequest} object. - * - * @param request the request to be converted - * @return an immutable object for storage - */ - OAuth2Request createOAuth2Request(AuthorizationRequest request); + /** + * Create a new {@link OAuth2Request} by extracting the needed information from the current + * {@link AuthorizationRequest} object. + * + * @param request the request to be converted + * @return an immutable object for storage + */ + OAuth2Request createOAuth2Request(AuthorizationRequest request); - /** - * Create a new {@link OAuth2Request} by extracting the needed information from the current {@link TokenRequest} - * object. - * @param client - * @param tokenRequest the request to be converted - * - * @return am immutable object for storage - */ - OAuth2Request createOAuth2Request(ClientDetails client, TokenRequest tokenRequest); + /** + * Create a new {@link OAuth2Request} by extracting the needed information from the current {@link TokenRequest} + * object. + * @param client + * @param tokenRequest the request to be converted + * + * @return am immutable object for storage + */ + OAuth2Request createOAuth2Request(ClientDetails client, TokenRequest tokenRequest); - /** - * Create a new {@link TokenRequest} by extracting the needed information from the incoming request parameter map. - * - * @param requestParameters the parameters in the request - * @param authenticatedClient the client that authenticated during the token request - * @return a new TokenRequest - */ - TokenRequest createTokenRequest(Map requestParameters, ClientDetails authenticatedClient); + /** + * Create a new {@link TokenRequest} by extracting the needed information from the incoming request parameter map. + * + * @param requestParameters the parameters in the request + * @param authenticatedClient the client that authenticated during the token request + * @return a new TokenRequest + */ + TokenRequest createTokenRequest(Map requestParameters, ClientDetails authenticatedClient); - /** - * Create a new {@link TokenRequest} from an {@link AuthorizationRequest}. Principally used by the - * AuthorizationEndpoint during the implicit flow. - * - * @param authorizationRequest the incoming request - * @param grantType the grant type for the token request - * @return a new token request - */ - TokenRequest createTokenRequest(AuthorizationRequest authorizationRequest, String grantType); + /** + * Create a new {@link TokenRequest} from an {@link AuthorizationRequest}. Principally used by the + * AuthorizationEndpoint during the implicit flow. + * + * @param authorizationRequest the incoming request + * @param grantType the grant type for the token request + * @return a new token request + */ + TokenRequest createTokenRequest(AuthorizationRequest authorizationRequest, String grantType); } \ No newline at end of file diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2RequestValidator.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2RequestValidator.java index bda870d02..358cf0e8f 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2RequestValidator.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2RequestValidator.java @@ -29,22 +29,22 @@ import org.dromara.maxkey.entity.apps.oauth2.provider.ClientDetails; */ public interface OAuth2RequestValidator { - /** - * Ensure that the client has requested a valid set of scopes. - * - * @param authorizationRequest the AuthorizationRequest to be validated - * @param client the client that is making the request - * @throws InvalidScopeException if a requested scope is invalid - */ - public void validateScope(AuthorizationRequest authorizationRequest, ClientDetails client) throws InvalidScopeException; - - /** - * Ensure that the client has requested a valid set of scopes. - * - * @param tokenRequest the TokenRequest to be validated - * @param client the client that is making the request - * @throws InvalidScopeException if a requested scope is invalid - */ - public void validateScope(TokenRequest tokenRequest, ClientDetails client) throws InvalidScopeException; - + /** + * Ensure that the client has requested a valid set of scopes. + * + * @param authorizationRequest the AuthorizationRequest to be validated + * @param client the client that is making the request + * @throws InvalidScopeException if a requested scope is invalid + */ + public void validateScope(AuthorizationRequest authorizationRequest, ClientDetails client) throws InvalidScopeException; + + /** + * Ensure that the client has requested a valid set of scopes. + * + * @param tokenRequest the TokenRequest to be validated + * @param client the client that is making the request + * @throws InvalidScopeException if a requested scope is invalid + */ + public void validateScope(TokenRequest tokenRequest, ClientDetails client) throws InvalidScopeException; + } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2UserDetailsService.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2UserDetailsService.java index 157663690..5c01932a4 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2UserDetailsService.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/OAuth2UserDetailsService.java @@ -32,32 +32,32 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; * */ public class OAuth2UserDetailsService implements UserDetailsService { - private static final Logger _logger = - LoggerFactory.getLogger(OAuth2UserDetailsService.class); - + private static final Logger _logger = + LoggerFactory.getLogger(OAuth2UserDetailsService.class); + LoginService loginRepository; - + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - UserInfo userInfo; - try { - userInfo = loginRepository.find(username, ""); - } catch (NoSuchClientException e) { - throw new UsernameNotFoundException(e.getMessage(), e); - } - - String onlineTickitId = WebConstants.ONLINE_TICKET_PREFIX + "-" + java.util.UUID.randomUUID().toString().toLowerCase(); - - SignPrincipal principal = new SignPrincipal(userInfo); - Session onlineTicket = new Session(onlineTickitId); - //set OnlineTicket - principal.setSessionId(onlineTicket.getId()); + UserInfo userInfo; + try { + userInfo = loginRepository.find(username, ""); + } catch (NoSuchClientException e) { + throw new UsernameNotFoundException(e.getMessage(), e); + } + + String onlineTickitId = WebConstants.ONLINE_TICKET_PREFIX + "-" + java.util.UUID.randomUUID().toString().toLowerCase(); + + SignPrincipal principal = new SignPrincipal(userInfo); + Session onlineTicket = new Session(onlineTickitId); + //set OnlineTicket + principal.setSessionId(onlineTicket.getId()); List grantedAuthoritys = loginRepository.grantAuthority(userInfo); principal.setAuthenticated(true); for(GrantedAuthority administratorsAuthority : AbstractAuthenticationProvider.grantedAdministratorsAuthoritys) { if(grantedAuthoritys.contains(administratorsAuthority)) { - principal.setRoleAdministrators(true); + principal.setRoleAdministrators(true); _logger.trace("ROLE ADMINISTRATORS Authentication ."); } } @@ -65,12 +65,12 @@ public class OAuth2UserDetailsService implements UserDetailsService { principal.setGrantedAuthorityApps(grantedAuthoritys); - return principal; - } + return principal; + } - public void setLoginRepository(LoginService loginRepository) { - this.loginRepository = loginRepository; - } + public void setLoginRepository(LoginService loginRepository) { + this.loginRepository = loginRepository; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/SecurityContextAccessor.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/SecurityContextAccessor.java index 5ddc9e988..561d783f1 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/SecurityContextAccessor.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/SecurityContextAccessor.java @@ -25,14 +25,14 @@ import org.springframework.security.core.GrantedAuthority; */ public interface SecurityContextAccessor { - /** - * @return true if the current context represents a user - */ - boolean isUser(); + /** + * @return true if the current context represents a user + */ + boolean isUser(); - /** - * Get the current granted authorities (never null) - */ - Set getAuthorities(); + /** + * Get the current granted authorities (never null) + */ + Set getAuthorities(); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/TokenGranter.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/TokenGranter.java index 6484ea10a..ad03b3100 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/TokenGranter.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/TokenGranter.java @@ -27,6 +27,6 @@ import org.dromara.maxkey.authz.oauth2.common.OAuth2AccessToken; */ public interface TokenGranter { - OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest); + OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest); } \ No newline at end of file diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/TokenRequest.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/TokenRequest.java index 323d74545..1278f56c5 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/TokenRequest.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/TokenRequest.java @@ -41,76 +41,76 @@ import org.dromara.maxkey.entity.apps.oauth2.provider.ClientDetails; @SuppressWarnings("serial") public class TokenRequest extends BaseRequest { - private String grantType; + private String grantType; - /** - * Default constructor - */ - protected TokenRequest() { - } + /** + * Default constructor + */ + protected TokenRequest() { + } - /** + /** * Full constructor. Sets this TokenRequest's requestParameters map to an unmodifiable version of the one provided. - * - * @param requestParameters - * @param clientId - * @param scope - * @param grantType - */ - public TokenRequest(Map requestParameters, String clientId, Collection scope, - String grantType) { - setClientId(clientId); - setRequestParameters(requestParameters); - setScope(scope); - this.grantType = grantType; - } + * + * @param requestParameters + * @param clientId + * @param scope + * @param grantType + */ + public TokenRequest(Map requestParameters, String clientId, Collection scope, + String grantType) { + setClientId(clientId); + setRequestParameters(requestParameters); + setScope(scope); + this.grantType = grantType; + } - public String getGrantType() { - return grantType; - } + public String getGrantType() { + return grantType; + } - public void setGrantType(String grantType) { - this.grantType = grantType; - } + public void setGrantType(String grantType) { + this.grantType = grantType; + } - public void setClientId(String clientId) { - super.setClientId(clientId); - } + public void setClientId(String clientId) { + super.setClientId(clientId); + } - /** - * Set the scope value. If the collection contains only a single scope value, this method will parse that value into - * a collection using {@link OAuth2Utils.parseParameterList}. - * - * @see AuthorizationRequest.setScope - * - * @param scope - */ - public void setScope(Collection scope) { - super.setScope(scope); - } + /** + * Set the scope value. If the collection contains only a single scope value, this method will parse that value into + * a collection using {@link OAuth2Utils.parseParameterList}. + * + * @see AuthorizationRequest.setScope + * + * @param scope + */ + public void setScope(Collection scope) { + super.setScope(scope); + } - /** + /** * Set the Request Parameters on this authorization request, which represent the original request parameters and - * should never be changed during processing. The map passed in is wrapped in an unmodifiable map instance. - * - * @see AuthorizationRequest.setRequestParameters - * - * @param requestParameters - */ - public void setRequestParameters(Map requestParameters) { - super.setRequestParameters(requestParameters); - } + * should never be changed during processing. The map passed in is wrapped in an unmodifiable map instance. + * + * @see AuthorizationRequest.setRequestParameters + * + * @param requestParameters + */ + public void setRequestParameters(Map requestParameters) { + super.setRequestParameters(requestParameters); + } - public OAuth2Request createOAuth2Request(ClientDetails client) { - // Remove password if present to prevent leaks - Map requestParameters = getRequestParameters(); - HashMap modifiable = new HashMap(requestParameters); - modifiable.remove("password"); - modifiable.remove("client_secret"); - // Add grant type so it can be retrieved from OAuth2Request - modifiable.put("grant_type", grantType); - return new OAuth2Request(modifiable, client.getClientId(), client.getAuthorities(), true, this.getScope(), - client.getResourceIds(), null, null, null, null, null); - } + public OAuth2Request createOAuth2Request(ClientDetails client) { + // Remove password if present to prevent leaks + Map requestParameters = getRequestParameters(); + HashMap modifiable = new HashMap(requestParameters); + modifiable.remove("password"); + modifiable.remove("client_secret"); + // Add grant type so it can be retrieved from OAuth2Request + modifiable.put("grant_type", grantType); + return new OAuth2Request(modifiable, client.getClientId(), client.getAuthorities(), true, this.getScope(), + client.getResourceIds(), null, null, null, null, null); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/Approval.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/Approval.java index 3d0e723e9..c693b0bb9 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/Approval.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/Approval.java @@ -35,137 +35,137 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize; @JsonInclude(JsonInclude.Include.NON_NULL) public class Approval { - private String userId; + private String userId; - private String clientId; + private String clientId; - private String scope; + private String scope; - public enum ApprovalStatus { - APPROVED, - DENIED; - } + public enum ApprovalStatus { + APPROVED, + DENIED; + } - private ApprovalStatus status; - - private Date expiresAt; + private ApprovalStatus status; + + private Date expiresAt; - private Date lastUpdatedAt; + private Date lastUpdatedAt; - public Approval(String userId, String clientId, String scope, int expiresIn, ApprovalStatus status) { - this(userId, clientId, scope, new Date(), status, new Date()); - Calendar expiresAt = Calendar.getInstance(); - expiresAt.add(Calendar.MILLISECOND, expiresIn); - setExpiresAt(expiresAt.getTime()); - } + public Approval(String userId, String clientId, String scope, int expiresIn, ApprovalStatus status) { + this(userId, clientId, scope, new Date(), status, new Date()); + Calendar expiresAt = Calendar.getInstance(); + expiresAt.add(Calendar.MILLISECOND, expiresIn); + setExpiresAt(expiresAt.getTime()); + } - public Approval(String userId, String clientId, String scope, Date expiresAt, ApprovalStatus status) { - this(userId, clientId, scope, expiresAt, status, new Date()); - } + public Approval(String userId, String clientId, String scope, Date expiresAt, ApprovalStatus status) { + this(userId, clientId, scope, expiresAt, status, new Date()); + } - public Approval(String userId, String clientId, String scope, Date expiresAt, ApprovalStatus status, Date lastUpdatedAt) { - this.userId = userId; - this.clientId = clientId; - this.scope = scope; - this.expiresAt = expiresAt; - this.status = status; - this.lastUpdatedAt = lastUpdatedAt; - } + public Approval(String userId, String clientId, String scope, Date expiresAt, ApprovalStatus status, Date lastUpdatedAt) { + this.userId = userId; + this.clientId = clientId; + this.scope = scope; + this.expiresAt = expiresAt; + this.status = status; + this.lastUpdatedAt = lastUpdatedAt; + } - protected Approval() { } + protected Approval() { } - public String getUserId() { - return userId; - } + public String getUserId() { + return userId; + } - public void setUserId(String userId) { - this.userId = userId == null ? "" : userId; - } + public void setUserId(String userId) { + this.userId = userId == null ? "" : userId; + } - public String getClientId() { - return clientId; - } + public String getClientId() { + return clientId; + } - public void setClientId(String clientId) { - this.clientId = clientId == null ? "" : clientId; - } + public void setClientId(String clientId) { + this.clientId = clientId == null ? "" : clientId; + } - public String getScope() { - return scope; - } + public String getScope() { + return scope; + } - public void setScope(String scope) { - this.scope = scope == null ? "" : scope; - } + public void setScope(String scope) { + this.scope = scope == null ? "" : scope; + } - @JsonSerialize(using = JsonDateSerializer.class) - @JsonInclude(JsonInclude.Include.NON_NULL) - public Date getExpiresAt() { - return expiresAt; - } + @JsonSerialize(using = JsonDateSerializer.class) + @JsonInclude(JsonInclude.Include.NON_NULL) + public Date getExpiresAt() { + return expiresAt; + } - @JsonDeserialize(using = JsonDateDeserializer.class) - public void setExpiresAt(Date expiresAt) { - if (expiresAt == null) { - Calendar thirtyMinFromNow = Calendar.getInstance(); - thirtyMinFromNow.add(Calendar.MINUTE, 30); - expiresAt = thirtyMinFromNow.getTime(); - } - this.expiresAt = expiresAt; - } + @JsonDeserialize(using = JsonDateDeserializer.class) + public void setExpiresAt(Date expiresAt) { + if (expiresAt == null) { + Calendar thirtyMinFromNow = Calendar.getInstance(); + thirtyMinFromNow.add(Calendar.MINUTE, 30); + expiresAt = thirtyMinFromNow.getTime(); + } + this.expiresAt = expiresAt; + } - @JsonSerialize(using = JsonDateSerializer.class) - @JsonInclude(JsonInclude.Include.NON_NULL) - public Date getLastUpdatedAt() { - return lastUpdatedAt; - } + @JsonSerialize(using = JsonDateSerializer.class) + @JsonInclude(JsonInclude.Include.NON_NULL) + public Date getLastUpdatedAt() { + return lastUpdatedAt; + } - @JsonDeserialize(using = JsonDateDeserializer.class) - public void setLastUpdatedAt(Date lastUpdatedAt) { - this.lastUpdatedAt = lastUpdatedAt; - } + @JsonDeserialize(using = JsonDateDeserializer.class) + public void setLastUpdatedAt(Date lastUpdatedAt) { + this.lastUpdatedAt = lastUpdatedAt; + } - @JsonIgnore - public boolean isCurrentlyActive() { - return expiresAt != null && expiresAt.after(new Date()); - } + @JsonIgnore + public boolean isCurrentlyActive() { + return expiresAt != null && expiresAt.after(new Date()); + } - @JsonIgnore - public boolean isApproved() { - return isCurrentlyActive() && status==ApprovalStatus.APPROVED; - } + @JsonIgnore + public boolean isApproved() { + return isCurrentlyActive() && status==ApprovalStatus.APPROVED; + } - public void setStatus(ApprovalStatus status) { - this.status = status; - } + public void setStatus(ApprovalStatus status) { + this.status = status; + } - public ApprovalStatus getStatus() { - return status; - } + public ApprovalStatus getStatus() { + return status; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + userId.hashCode(); - result = prime * result + clientId.hashCode(); - result = prime * result + scope.hashCode(); - result = prime * result + status.hashCode(); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + userId.hashCode(); + result = prime * result + clientId.hashCode(); + result = prime * result + scope.hashCode(); + result = prime * result + status.hashCode(); + return result; + } - @Override - public boolean equals(Object o) { - if (o == null || !(o instanceof Approval)) { - return false; - } - Approval other = (Approval) o; - return userId.equals(other.userId) && clientId.equals(other.clientId) && scope.equals(other.scope) && status == other.status; - } + @Override + public boolean equals(Object o) { + if (o == null || !(o instanceof Approval)) { + return false; + } + Approval other = (Approval) o; + return userId.equals(other.userId) && clientId.equals(other.clientId) && scope.equals(other.scope) && status == other.status; + } - @Override - public String toString() { - return String.format("[%s, %s, %s, %s, %s, %s]", userId, scope, clientId, expiresAt, status.toString(), lastUpdatedAt); - } + @Override + public String toString() { + return String.format("[%s, %s, %s, %s, %s, %s]", userId, scope, clientId, expiresAt, status.toString(), lastUpdatedAt); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/ApprovalStore.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/ApprovalStore.java index 35d5f3ddf..9a776a73f 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/ApprovalStore.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/ApprovalStore.java @@ -25,10 +25,10 @@ import java.util.Collection; */ public interface ApprovalStore { - public boolean addApprovals(Collection approvals); + public boolean addApprovals(Collection approvals); - public boolean revokeApprovals(Collection approvals); + public boolean revokeApprovals(Collection approvals); - public Collection getApprovals(String userId, String clientId); + public Collection getApprovals(String userId, String clientId); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/ApprovalStoreUserApprovalHandler.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/ApprovalStoreUserApprovalHandler.java index 3ada31ffa..bad41a728 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/ApprovalStoreUserApprovalHandler.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/ApprovalStoreUserApprovalHandler.java @@ -47,202 +47,202 @@ import org.springframework.util.Assert; */ public class ApprovalStoreUserApprovalHandler implements UserApprovalHandler, InitializingBean { - private static Log logger = LogFactory.getLog(ApprovalStoreUserApprovalHandler.class); + private static Log logger = LogFactory.getLog(ApprovalStoreUserApprovalHandler.class); - private String scopePrefix = OAuth2Constants.PARAMETER.SCOPE_PREFIX; + private String scopePrefix = OAuth2Constants.PARAMETER.SCOPE_PREFIX; - private ApprovalStore approvalStore; + private ApprovalStore approvalStore; - private int approvalExpirySeconds = -1; + private int approvalExpirySeconds = -1; - private ClientDetailsService clientDetailsService; + private ClientDetailsService clientDetailsService; - /** - * Service to load client details (optional) for auto approval checks. - * - * @param clientDetailsService a client details service - */ - public void setClientDetailsService(ClientDetailsService clientDetailsService) { - this.clientDetailsService = clientDetailsService; - } + /** + * Service to load client details (optional) for auto approval checks. + * + * @param clientDetailsService a client details service + */ + public void setClientDetailsService(ClientDetailsService clientDetailsService) { + this.clientDetailsService = clientDetailsService; + } - /** - * The prefix applied to incoming parameters that signal approval or denial of a scope. - * - * @param scopePrefix the prefix (default {@link OAuth2Utils#SCOPE_PREFIX}) - */ - public void setScopePrefix(String scopePrefix) { - this.scopePrefix = scopePrefix; - } + /** + * The prefix applied to incoming parameters that signal approval or denial of a scope. + * + * @param scopePrefix the prefix (default {@link OAuth2Utils#SCOPE_PREFIX}) + */ + public void setScopePrefix(String scopePrefix) { + this.scopePrefix = scopePrefix; + } - /** - * @param store the approval to set - */ - public void setApprovalStore(ApprovalStore store) { - this.approvalStore = store; - } + /** + * @param store the approval to set + */ + public void setApprovalStore(ApprovalStore store) { + this.approvalStore = store; + } - private OAuth2RequestFactory requestFactory; + private OAuth2RequestFactory requestFactory; - public void setRequestFactory(OAuth2RequestFactory requestFactory) { - this.requestFactory = requestFactory; - } + public void setRequestFactory(OAuth2RequestFactory requestFactory) { + this.requestFactory = requestFactory; + } - public void setApprovalExpiryInSeconds(int approvalExpirySeconds) { - this.approvalExpirySeconds = approvalExpirySeconds; - } + public void setApprovalExpiryInSeconds(int approvalExpirySeconds) { + this.approvalExpirySeconds = approvalExpirySeconds; + } - public void afterPropertiesSet() { - Assert.state(approvalStore != null, "ApprovalStore must be provided"); - Assert.state(requestFactory != null, "OAuth2RequestFactory must be provided"); - } + public void afterPropertiesSet() { + Assert.state(approvalStore != null, "ApprovalStore must be provided"); + Assert.state(requestFactory != null, "OAuth2RequestFactory must be provided"); + } - public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { - return authorizationRequest.isApproved(); - } + public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { + return authorizationRequest.isApproved(); + } - public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, - Authentication userAuthentication) { + public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, + Authentication userAuthentication) { - String clientId = authorizationRequest.getClientId(); - Collection requestedScopes = authorizationRequest.getScope(); - Set approvedScopes = new HashSet(); - Set validUserApprovedScopes = new HashSet(); + String clientId = authorizationRequest.getClientId(); + Collection requestedScopes = authorizationRequest.getScope(); + Set approvedScopes = new HashSet(); + Set validUserApprovedScopes = new HashSet(); - if (clientDetailsService != null) { - try { - ClientDetails client = clientDetailsService.loadClientByClientId(clientId,true); - for (String scope : requestedScopes) { - if (client.isAutoApprove(scope) || client.isAutoApprove("all")) { - approvedScopes.add(scope); - } - } - if (approvedScopes.containsAll(requestedScopes)) { - authorizationRequest.setApproved(true); - return authorizationRequest; - } - } - catch (ClientRegistrationException e) { - logger.warn("Client registration problem prevent autoapproval check for client=" + clientId); - } - } + if (clientDetailsService != null) { + try { + ClientDetails client = clientDetailsService.loadClientByClientId(clientId,true); + for (String scope : requestedScopes) { + if (client.isAutoApprove(scope) || client.isAutoApprove("all")) { + approvedScopes.add(scope); + } + } + if (approvedScopes.containsAll(requestedScopes)) { + authorizationRequest.setApproved(true); + return authorizationRequest; + } + } + catch (ClientRegistrationException e) { + logger.warn("Client registration problem prevent autoapproval check for client=" + clientId); + } + } - if (logger.isDebugEnabled()) { - StringBuilder builder = new StringBuilder("Looking up user approved authorizations for "); - builder.append("client_id=" + clientId); - builder.append(" and username=" + userAuthentication.getName()); - logger.debug(builder.toString()); - } + if (logger.isDebugEnabled()) { + StringBuilder builder = new StringBuilder("Looking up user approved authorizations for "); + builder.append("client_id=" + clientId); + builder.append(" and username=" + userAuthentication.getName()); + logger.debug(builder.toString()); + } - // Find the stored approvals for that user and client - Collection userApprovals = approvalStore.getApprovals(userAuthentication.getName(), clientId); + // Find the stored approvals for that user and client + Collection userApprovals = approvalStore.getApprovals(userAuthentication.getName(), clientId); - // Look at the scopes and see if they have expired - Date today = new Date(); - for (Approval approval : userApprovals) { - if (approval.getExpiresAt().after(today)) { - validUserApprovedScopes.add(approval.getScope()); - if (approval.getStatus() == ApprovalStatus.APPROVED) { - approvedScopes.add(approval.getScope()); - } - } - } + // Look at the scopes and see if they have expired + Date today = new Date(); + for (Approval approval : userApprovals) { + if (approval.getExpiresAt().after(today)) { + validUserApprovedScopes.add(approval.getScope()); + if (approval.getStatus() == ApprovalStatus.APPROVED) { + approvedScopes.add(approval.getScope()); + } + } + } - if (logger.isDebugEnabled()) { - logger.debug("Valid user approved/denied scopes are " + validUserApprovedScopes); - } + if (logger.isDebugEnabled()) { + logger.debug("Valid user approved/denied scopes are " + validUserApprovedScopes); + } - // If the requested scopes have already been acted upon by the user, - // this request is approved - if (validUserApprovedScopes.containsAll(requestedScopes)) { - approvedScopes.retainAll(requestedScopes); - // Set only the scopes that have been approved by the user - authorizationRequest.setScope(approvedScopes); - authorizationRequest.setApproved(true); - } + // If the requested scopes have already been acted upon by the user, + // this request is approved + if (validUserApprovedScopes.containsAll(requestedScopes)) { + approvedScopes.retainAll(requestedScopes); + // Set only the scopes that have been approved by the user + authorizationRequest.setScope(approvedScopes); + authorizationRequest.setApproved(true); + } - return authorizationRequest; + return authorizationRequest; - } + } - private Date computeExpiry() { - Calendar expiresAt = Calendar.getInstance(); - if (approvalExpirySeconds == -1) { // use default of 1 month - expiresAt.add(Calendar.MONTH, 1); - } - else { - expiresAt.add(Calendar.SECOND, approvalExpirySeconds); - } - return expiresAt.getTime(); - } + private Date computeExpiry() { + Calendar expiresAt = Calendar.getInstance(); + if (approvalExpirySeconds == -1) { // use default of 1 month + expiresAt.add(Calendar.MONTH, 1); + } + else { + expiresAt.add(Calendar.SECOND, approvalExpirySeconds); + } + return expiresAt.getTime(); + } - /** - * Requires the authorization request to be explicitly approved, including all individual scopes, and the user to be - * authenticated. A scope that was requested in the authorization request can be approved by sending a request - * parameter scope.<scopename> equal to "true" or "approved" (otherwise it will be assumed to - * have been denied). The {@link ApprovalStore} will be updated to reflect the inputs. - * - * @param authorizationRequest The authorization request. - * @param userAuthentication the current user authentication - * - * @return An approved request if all scopes have been approved by the current user. - */ - public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest, - Authentication userAuthentication) { - // Get the approved scopes - Set requestedScopes = authorizationRequest.getScope(); - Set approvedScopes = new HashSet(); - Set approvals = new HashSet(); + /** + * Requires the authorization request to be explicitly approved, including all individual scopes, and the user to be + * authenticated. A scope that was requested in the authorization request can be approved by sending a request + * parameter scope.<scopename> equal to "true" or "approved" (otherwise it will be assumed to + * have been denied). The {@link ApprovalStore} will be updated to reflect the inputs. + * + * @param authorizationRequest The authorization request. + * @param userAuthentication the current user authentication + * + * @return An approved request if all scopes have been approved by the current user. + */ + public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest, + Authentication userAuthentication) { + // Get the approved scopes + Set requestedScopes = authorizationRequest.getScope(); + Set approvedScopes = new HashSet(); + Set approvals = new HashSet(); - Date expiry = computeExpiry(); + Date expiry = computeExpiry(); - // Store the scopes that have been approved / denied - Map approvalParameters = authorizationRequest.getApprovalParameters(); - for (String requestedScope : requestedScopes) { - String approvalParameter = scopePrefix + requestedScope; - String value = approvalParameters.get(approvalParameter); - value = value == null ? "" : value.toLowerCase(); - if ("true".equals(value) || value.startsWith("approve")) { - approvedScopes.add(requestedScope); - approvals.add(new Approval(userAuthentication.getName(), authorizationRequest.getClientId(), - requestedScope, expiry, ApprovalStatus.APPROVED)); - } - else { - approvals.add(new Approval(userAuthentication.getName(), authorizationRequest.getClientId(), - requestedScope, expiry, ApprovalStatus.DENIED)); - } - } - approvalStore.addApprovals(approvals); + // Store the scopes that have been approved / denied + Map approvalParameters = authorizationRequest.getApprovalParameters(); + for (String requestedScope : requestedScopes) { + String approvalParameter = scopePrefix + requestedScope; + String value = approvalParameters.get(approvalParameter); + value = value == null ? "" : value.toLowerCase(); + if ("true".equals(value) || value.startsWith("approve")) { + approvedScopes.add(requestedScope); + approvals.add(new Approval(userAuthentication.getName(), authorizationRequest.getClientId(), + requestedScope, expiry, ApprovalStatus.APPROVED)); + } + else { + approvals.add(new Approval(userAuthentication.getName(), authorizationRequest.getClientId(), + requestedScope, expiry, ApprovalStatus.DENIED)); + } + } + approvalStore.addApprovals(approvals); - boolean approved; - authorizationRequest.setScope(approvedScopes); - if (approvedScopes.isEmpty() && !requestedScopes.isEmpty()) { - approved = false; - } - else { - approved = true; - } - authorizationRequest.setApproved(approved); - return authorizationRequest; - } + boolean approved; + authorizationRequest.setScope(approvedScopes); + if (approvedScopes.isEmpty() && !requestedScopes.isEmpty()) { + approved = false; + } + else { + approved = true; + } + authorizationRequest.setApproved(approved); + return authorizationRequest; + } - @Override - public Map getUserApprovalRequest(AuthorizationRequest authorizationRequest, - Authentication userAuthentication) { - Map model = new HashMap(); - model.putAll(authorizationRequest.getRequestParameters()); - Map scopes = new LinkedHashMap(); - for (String scope : authorizationRequest.getScope()) { - scopes.put(OAuth2Constants.PARAMETER.SCOPE_PREFIX + scope, "false"); - } - for (Approval approval : approvalStore.getApprovals(userAuthentication.getName(), - authorizationRequest.getClientId())) { - if (authorizationRequest.getScope().contains(approval.getScope())) { - scopes.put(OAuth2Constants.PARAMETER.SCOPE_PREFIX + approval.getScope(), - approval.getStatus() == ApprovalStatus.APPROVED ? "true" : "false"); - } - } - model.put("scopes", scopes); - return model; - } + @Override + public Map getUserApprovalRequest(AuthorizationRequest authorizationRequest, + Authentication userAuthentication) { + Map model = new HashMap(); + model.putAll(authorizationRequest.getRequestParameters()); + Map scopes = new LinkedHashMap(); + for (String scope : authorizationRequest.getScope()) { + scopes.put(OAuth2Constants.PARAMETER.SCOPE_PREFIX + scope, "false"); + } + for (Approval approval : approvalStore.getApprovals(userAuthentication.getName(), + authorizationRequest.getClientId())) { + if (authorizationRequest.getScope().contains(approval.getScope())) { + scopes.put(OAuth2Constants.PARAMETER.SCOPE_PREFIX + approval.getScope(), + approval.getStatus() == ApprovalStatus.APPROVED ? "true" : "false"); + } + } + model.put("scopes", scopes); + return model; + } } \ No newline at end of file diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/DefaultUserApprovalHandler.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/DefaultUserApprovalHandler.java index f256b7b8a..615fb2653 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/DefaultUserApprovalHandler.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/DefaultUserApprovalHandler.java @@ -31,51 +31,51 @@ import org.springframework.security.core.Authentication; */ public class DefaultUserApprovalHandler implements UserApprovalHandler { - private String approvalParameter = OAuth2Constants.PARAMETER.USER_OAUTH_APPROVAL; - - /** - * @param approvalParameter the approvalParameter to set - */ - public void setApprovalParameter(String approvalParameter) { - this.approvalParameter = approvalParameter; - } + private String approvalParameter = OAuth2Constants.PARAMETER.USER_OAUTH_APPROVAL; + + /** + * @param approvalParameter the approvalParameter to set + */ + public void setApprovalParameter(String approvalParameter) { + this.approvalParameter = approvalParameter; + } - /** - * Basic implementation just requires the authorization request to be explicitly approved and the user to be - * authenticated. - * - * @param authorizationRequest The authorization request. - * @param userAuthentication the current user authentication - * - * @return Whether the specified request has been approved by the current user. - */ - public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { - if (authorizationRequest.isApproved()) { - return true; - } - return false; - } + /** + * Basic implementation just requires the authorization request to be explicitly approved and the user to be + * authenticated. + * + * @param authorizationRequest The authorization request. + * @param userAuthentication the current user authentication + * + * @return Whether the specified request has been approved by the current user. + */ + public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { + if (authorizationRequest.isApproved()) { + return true; + } + return false; + } - public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { - return authorizationRequest; - } + public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { + return authorizationRequest; + } - @Override - public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { - Map approvalParameters = authorizationRequest.getApprovalParameters(); - String flag = approvalParameters.get(approvalParameter); - boolean approved = flag != null && flag.toLowerCase().equals("true"); - authorizationRequest.setApproved(approved); - return authorizationRequest; - } - - @Override - public Map getUserApprovalRequest(AuthorizationRequest authorizationRequest, - Authentication userAuthentication) { - Map model = new HashMap(); - // In case of a redirect we might want the request parameters to be included - model.putAll(authorizationRequest.getRequestParameters()); - return model; - } + @Override + public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { + Map approvalParameters = authorizationRequest.getApprovalParameters(); + String flag = approvalParameters.get(approvalParameter); + boolean approved = flag != null && flag.toLowerCase().equals("true"); + authorizationRequest.setApproved(approved); + return authorizationRequest; + } + + @Override + public Map getUserApprovalRequest(AuthorizationRequest authorizationRequest, + Authentication userAuthentication) { + Map model = new HashMap(); + // In case of a redirect we might want the request parameters to be included + model.putAll(authorizationRequest.getRequestParameters()); + return model; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/InMemoryApprovalStore.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/InMemoryApprovalStore.java index 7b03f49bb..42641dce4 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/InMemoryApprovalStore.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/InMemoryApprovalStore.java @@ -28,94 +28,94 @@ import java.util.concurrent.ConcurrentMap; */ public class InMemoryApprovalStore implements ApprovalStore { - private ConcurrentMap> map = new ConcurrentHashMap>(); + private ConcurrentMap> map = new ConcurrentHashMap>(); - @Override - public boolean addApprovals(Collection approvals) { - for (Approval approval : approvals) { - Collection collection = getApprovals(approval); - collection.add(approval); - } - return true; - } + @Override + public boolean addApprovals(Collection approvals) { + for (Approval approval : approvals) { + Collection collection = getApprovals(approval); + collection.add(approval); + } + return true; + } - @Override - public boolean revokeApprovals(Collection approvals) { - boolean success = true; - for (Approval approval : approvals) { - Collection collection = getApprovals(approval); - boolean removed = collection.remove(approval); - if (!removed) { - success = false; - } - } - return success; - } + @Override + public boolean revokeApprovals(Collection approvals) { + boolean success = true; + for (Approval approval : approvals) { + Collection collection = getApprovals(approval); + boolean removed = collection.remove(approval); + if (!removed) { + success = false; + } + } + return success; + } - private Collection getApprovals(Approval approval) { - Key key = new Key(approval.getUserId(), approval.getClientId()); - if (!map.containsKey(key)) { - map.putIfAbsent(key, new HashSet()); - } - return map.get(key); - } + private Collection getApprovals(Approval approval) { + Key key = new Key(approval.getUserId(), approval.getClientId()); + if (!map.containsKey(key)) { + map.putIfAbsent(key, new HashSet()); + } + return map.get(key); + } - @Override - public Collection getApprovals(String userId, String clientId) { - Approval approval = new Approval(); - approval.setUserId(userId); - approval.setClientId(clientId); - return Collections.unmodifiableCollection(getApprovals(approval)); - } - - public void clear() { - map.clear(); - } + @Override + public Collection getApprovals(String userId, String clientId) { + Approval approval = new Approval(); + approval.setUserId(userId); + approval.setClientId(clientId); + return Collections.unmodifiableCollection(getApprovals(approval)); + } + + public void clear() { + map.clear(); + } - private static class Key { + private static class Key { - String userId; + String userId; - String clientId; + String clientId; - public Key(String userId, String clientId) { - this.userId = userId; - this.clientId = clientId; - } + public Key(String userId, String clientId) { + this.userId = userId; + this.clientId = clientId; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((clientId == null) ? 0 : clientId.hashCode()); - result = prime * result + ((userId == null) ? 0 : userId.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((clientId == null) ? 0 : clientId.hashCode()); + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Key other = (Key) obj; - if (clientId == null) { - if (other.clientId != null) - return false; - } - else if (!clientId.equals(other.clientId)) - return false; - if (userId == null) { - if (other.userId != null) - return false; - } - else if (!userId.equals(other.userId)) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Key other = (Key) obj; + if (clientId == null) { + if (other.clientId != null) + return false; + } + else if (!clientId.equals(other.clientId)) + return false; + if (userId == null) { + if (other.userId != null) + return false; + } + else if (!userId.equals(other.userId)) + return false; + return true; + } - } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/JdbcApprovalStore.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/JdbcApprovalStore.java index 804bf4772..f73670aa9 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/JdbcApprovalStore.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/JdbcApprovalStore.java @@ -42,180 +42,180 @@ import org.springframework.util.Assert; */ public class JdbcApprovalStore implements ApprovalStore { - private final JdbcTemplate jdbcTemplate; + private final JdbcTemplate jdbcTemplate; - private final Log logger = LogFactory.getLog(getClass()); + private final Log logger = LogFactory.getLog(getClass()); - private final RowMapper rowMapper = new AuthorizationRowMapper(); - - private static final String TABLE_NAME = "oauth_approvals"; + private final RowMapper rowMapper = new AuthorizationRowMapper(); + + private static final String TABLE_NAME = "oauth_approvals"; - private static final String FIELDS = "expiresAt,status,lastModifiedAt,userId,clientId,scope"; + private static final String FIELDS = "expiresAt,status,lastModifiedAt,userId,clientId,scope"; - private static final String WHERE_KEY = "where userId=? and clientId=?"; + private static final String WHERE_KEY = "where userId=? and clientId=?"; - private static final String WHERE_KEY_AND_SCOPE = WHERE_KEY + " and scope=?"; + private static final String WHERE_KEY_AND_SCOPE = WHERE_KEY + " and scope=?"; - private static final String DEFAULT_ADD_APPROVAL_STATEMENT = String.format("insert into %s ( %s ) values (?,?,?,?,?,?)", TABLE_NAME, - FIELDS); + private static final String DEFAULT_ADD_APPROVAL_STATEMENT = String.format("insert into %s ( %s ) values (?,?,?,?,?,?)", TABLE_NAME, + FIELDS); - private static final String DEFAULT_REFRESH_APPROVAL_STATEMENT = String.format( - "update %s set expiresAt=?, status=?, lastModifiedAt=? " + WHERE_KEY_AND_SCOPE, TABLE_NAME); + private static final String DEFAULT_REFRESH_APPROVAL_STATEMENT = String.format( + "update %s set expiresAt=?, status=?, lastModifiedAt=? " + WHERE_KEY_AND_SCOPE, TABLE_NAME); - private static final String DEFAULT_GET_APPROVAL_SQL = String.format("select %s from %s " + WHERE_KEY, FIELDS, TABLE_NAME); + private static final String DEFAULT_GET_APPROVAL_SQL = String.format("select %s from %s " + WHERE_KEY, FIELDS, TABLE_NAME); - private static final String DEFAULT_DELETE_APPROVAL_SQL = String.format("delete from %s " + WHERE_KEY_AND_SCOPE, - TABLE_NAME); + private static final String DEFAULT_DELETE_APPROVAL_SQL = String.format("delete from %s " + WHERE_KEY_AND_SCOPE, + TABLE_NAME); - private static final String DEFAULT_EXPIRE_APPROVAL_STATEMENT = String.format("update %s set expiresAt = ? " + WHERE_KEY_AND_SCOPE, - TABLE_NAME); + private static final String DEFAULT_EXPIRE_APPROVAL_STATEMENT = String.format("update %s set expiresAt = ? " + WHERE_KEY_AND_SCOPE, + TABLE_NAME); - private String addApprovalStatement = DEFAULT_ADD_APPROVAL_STATEMENT; + private String addApprovalStatement = DEFAULT_ADD_APPROVAL_STATEMENT; - private String refreshApprovalStatement = DEFAULT_REFRESH_APPROVAL_STATEMENT; + private String refreshApprovalStatement = DEFAULT_REFRESH_APPROVAL_STATEMENT; - private String findApprovalStatement = DEFAULT_GET_APPROVAL_SQL; + private String findApprovalStatement = DEFAULT_GET_APPROVAL_SQL; - private String deleteApprovalStatment = DEFAULT_DELETE_APPROVAL_SQL; + private String deleteApprovalStatment = DEFAULT_DELETE_APPROVAL_SQL; - private String expireApprovalStatement = DEFAULT_EXPIRE_APPROVAL_STATEMENT; + private String expireApprovalStatement = DEFAULT_EXPIRE_APPROVAL_STATEMENT; - private boolean handleRevocationsAsExpiry = false; + private boolean handleRevocationsAsExpiry = false; - public JdbcApprovalStore(DataSource dataSource) { - Assert.notNull(dataSource,"DataSource must not null"); - this.jdbcTemplate = new JdbcTemplate(dataSource); - } + public JdbcApprovalStore(DataSource dataSource) { + Assert.notNull(dataSource,"DataSource must not null"); + this.jdbcTemplate = new JdbcTemplate(dataSource); + } - public void setHandleRevocationsAsExpiry(boolean handleRevocationsAsExpiry) { - this.handleRevocationsAsExpiry = handleRevocationsAsExpiry; - } + public void setHandleRevocationsAsExpiry(boolean handleRevocationsAsExpiry) { + this.handleRevocationsAsExpiry = handleRevocationsAsExpiry; + } - public void setAddApprovalStatement(String addApprovalStatement) { - this.addApprovalStatement = addApprovalStatement; - } + public void setAddApprovalStatement(String addApprovalStatement) { + this.addApprovalStatement = addApprovalStatement; + } - public void setFindApprovalStatement(String findApprovalStatement) { - this.findApprovalStatement = findApprovalStatement; - } + public void setFindApprovalStatement(String findApprovalStatement) { + this.findApprovalStatement = findApprovalStatement; + } - public void setDeleteApprovalStatment(String deleteApprovalStatment) { - this.deleteApprovalStatment = deleteApprovalStatment; - } + public void setDeleteApprovalStatment(String deleteApprovalStatment) { + this.deleteApprovalStatment = deleteApprovalStatment; + } - public void setExpireApprovalStatement(String expireApprovalStatement) { - this.expireApprovalStatement = expireApprovalStatement; - } - - public void setRefreshApprovalStatement(String refreshApprovalStatement) { - this.refreshApprovalStatement = refreshApprovalStatement; - } - - @Override - public boolean addApprovals(final Collection approvals) { - logger.debug(String.format("adding approvals: [%s]", approvals)); - boolean success = true; - for (Approval approval : approvals) { - if (!updateApproval(refreshApprovalStatement, approval)) { - if (!updateApproval(addApprovalStatement, approval)) { - success = false; - } - } - } - return success; - } + public void setExpireApprovalStatement(String expireApprovalStatement) { + this.expireApprovalStatement = expireApprovalStatement; + } + + public void setRefreshApprovalStatement(String refreshApprovalStatement) { + this.refreshApprovalStatement = refreshApprovalStatement; + } + + @Override + public boolean addApprovals(final Collection approvals) { + logger.debug(String.format("adding approvals: [%s]", approvals)); + boolean success = true; + for (Approval approval : approvals) { + if (!updateApproval(refreshApprovalStatement, approval)) { + if (!updateApproval(addApprovalStatement, approval)) { + success = false; + } + } + } + return success; + } - @Override - public boolean revokeApprovals(Collection approvals) { - logger.debug(String.format("Revoking approvals: [%s]", approvals)); - boolean success = true; - for (final Approval approval : approvals) { - if (handleRevocationsAsExpiry) { - int refreshed = jdbcTemplate.update(expireApprovalStatement, new PreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps) throws SQLException { - ps.setTimestamp(1, new Timestamp(System.currentTimeMillis())); - ps.setString(2, approval.getUserId()); - ps.setString(3, approval.getClientId()); - ps.setString(4, approval.getScope()); - } - }); - if (refreshed != 1) { - success = false; - } - } - else { - int refreshed = jdbcTemplate.update(deleteApprovalStatment, new PreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps) throws SQLException { - ps.setString(1, approval.getUserId()); - ps.setString(2, approval.getClientId()); - ps.setString(3, approval.getScope()); - } - }); - if (refreshed != 1) { - success = false; - } - } - } - return success; - } + @Override + public boolean revokeApprovals(Collection approvals) { + logger.debug(String.format("Revoking approvals: [%s]", approvals)); + boolean success = true; + for (final Approval approval : approvals) { + if (handleRevocationsAsExpiry) { + int refreshed = jdbcTemplate.update(expireApprovalStatement, new PreparedStatementSetter() { + @Override + public void setValues(PreparedStatement ps) throws SQLException { + ps.setTimestamp(1, new Timestamp(System.currentTimeMillis())); + ps.setString(2, approval.getUserId()); + ps.setString(3, approval.getClientId()); + ps.setString(4, approval.getScope()); + } + }); + if (refreshed != 1) { + success = false; + } + } + else { + int refreshed = jdbcTemplate.update(deleteApprovalStatment, new PreparedStatementSetter() { + @Override + public void setValues(PreparedStatement ps) throws SQLException { + ps.setString(1, approval.getUserId()); + ps.setString(2, approval.getClientId()); + ps.setString(3, approval.getScope()); + } + }); + if (refreshed != 1) { + success = false; + } + } + } + return success; + } - public boolean purgeExpiredApprovals() { - logger.debug("Purging expired approvals from database"); - try { - int deleted = jdbcTemplate.update(deleteApprovalStatment + " where expiresAt <= ?", - new PreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps) throws SQLException { - ps.setTimestamp(1, new Timestamp(new Date().getTime())); - } - }); - logger.debug(deleted + " expired approvals deleted"); - } - catch (DataAccessException ex) { - logger.error("Error purging expired approvals", ex); - return false; - } - return true; - } + public boolean purgeExpiredApprovals() { + logger.debug("Purging expired approvals from database"); + try { + int deleted = jdbcTemplate.update(deleteApprovalStatment + " where expiresAt <= ?", + new PreparedStatementSetter() { + @Override + public void setValues(PreparedStatement ps) throws SQLException { + ps.setTimestamp(1, new Timestamp(new Date().getTime())); + } + }); + logger.debug(deleted + " expired approvals deleted"); + } + catch (DataAccessException ex) { + logger.error("Error purging expired approvals", ex); + return false; + } + return true; + } - @Override - public List getApprovals(String userName, String clientId) { - return jdbcTemplate.query(findApprovalStatement, rowMapper, userName, clientId); - } + @Override + public List getApprovals(String userName, String clientId) { + return jdbcTemplate.query(findApprovalStatement, rowMapper, userName, clientId); + } - private boolean updateApproval(final String sql, final Approval approval) { - logger.debug(String.format("refreshing approval: [%s]", approval)); - int refreshed = jdbcTemplate.update(sql, new PreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps) throws SQLException { - ps.setTimestamp(1, new Timestamp(approval.getExpiresAt().getTime())); - ps.setString(2, (approval.getStatus() == null ? APPROVED : approval.getStatus()).toString()); - ps.setTimestamp(3, new Timestamp(approval.getLastUpdatedAt().getTime())); - ps.setString(4, approval.getUserId()); - ps.setString(5, approval.getClientId()); - ps.setString(6, approval.getScope()); - } - }); - if (refreshed != 1) { - return false; - } - return true; - } + private boolean updateApproval(final String sql, final Approval approval) { + logger.debug(String.format("refreshing approval: [%s]", approval)); + int refreshed = jdbcTemplate.update(sql, new PreparedStatementSetter() { + @Override + public void setValues(PreparedStatement ps) throws SQLException { + ps.setTimestamp(1, new Timestamp(approval.getExpiresAt().getTime())); + ps.setString(2, (approval.getStatus() == null ? APPROVED : approval.getStatus()).toString()); + ps.setTimestamp(3, new Timestamp(approval.getLastUpdatedAt().getTime())); + ps.setString(4, approval.getUserId()); + ps.setString(5, approval.getClientId()); + ps.setString(6, approval.getScope()); + } + }); + if (refreshed != 1) { + return false; + } + return true; + } - private static class AuthorizationRowMapper implements RowMapper { + private static class AuthorizationRowMapper implements RowMapper { - @Override - public Approval mapRow(ResultSet rs, int rowNum) throws SQLException { - String userName = rs.getString(4); - String clientId = rs.getString(5); - String scope = rs.getString(6); - Date expiresAt = rs.getTimestamp(1); - String status = rs.getString(2); - Date lastUpdatedAt = rs.getTimestamp(3); + @Override + public Approval mapRow(ResultSet rs, int rowNum) throws SQLException { + String userName = rs.getString(4); + String clientId = rs.getString(5); + String scope = rs.getString(6); + Date expiresAt = rs.getTimestamp(1); + String status = rs.getString(2); + Date lastUpdatedAt = rs.getTimestamp(3); - return new Approval(userName, clientId, scope, expiresAt, ApprovalStatus.valueOf(status), lastUpdatedAt); - } - } + return new Approval(userName, clientId, scope, expiresAt, ApprovalStatus.valueOf(status), lastUpdatedAt); + } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/TokenApprovalStore.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/TokenApprovalStore.java index c2b6baba2..fbab13a4f 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/TokenApprovalStore.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/TokenApprovalStore.java @@ -40,79 +40,79 @@ import org.slf4j.LoggerFactory; */ public class TokenApprovalStore implements ApprovalStore { - static final Logger _logger = LoggerFactory.getLogger(TokenApprovalStore.class); - - private TokenStore store; + static final Logger _logger = LoggerFactory.getLogger(TokenApprovalStore.class); + + private TokenStore store; - /** - * @param store the token store to set - */ - public void setTokenStore(TokenStore store) { - this.store = store; - } + /** + * @param store the token store to set + */ + public void setTokenStore(TokenStore store) { + this.store = store; + } - /** - * This implementation is a no-op. We assume that the {@link TokenStore} is populated elsewhere, by (for example) a - * token services instance that knows more about granted tokens than we could possibly infer from the approvals. - * - * @see org.dromara.maxkey.authz.oauth2.provider.approval.ApprovalStore#addApprovals(java.util.Collection) - */ - @Override - public boolean addApprovals(Collection approvals) { - _logger.debug("add Approvals..."); - return true; - } + /** + * This implementation is a no-op. We assume that the {@link TokenStore} is populated elsewhere, by (for example) a + * token services instance that knows more about granted tokens than we could possibly infer from the approvals. + * + * @see org.dromara.maxkey.authz.oauth2.provider.approval.ApprovalStore#addApprovals(java.util.Collection) + */ + @Override + public boolean addApprovals(Collection approvals) { + _logger.debug("add Approvals..."); + return true; + } - /** - * Revoke all tokens that match the client and user in the approvals supplied. - * - * @see org.dromara.maxkey.authz.oauth2.provider.approval.ApprovalStore#revokeApprovals(java.util.Collection) - */ - @Override - public boolean revokeApprovals(Collection approvals) { - _logger.debug("revoke Approvals " + approvals); - boolean success = true; - for (Approval approval : approvals) { - Collection tokens = store.findTokensByClientIdAndUserName(approval.getClientId(), approval.getUserId()); - for (OAuth2AccessToken token : tokens) { - OAuth2Authentication authentication = store.readAuthentication(token); - if (authentication != null - && approval.getClientId().equals(authentication.getOAuth2Request().getClientId())) { - store.removeAccessToken(token); - } - } - } - return success; - } + /** + * Revoke all tokens that match the client and user in the approvals supplied. + * + * @see org.dromara.maxkey.authz.oauth2.provider.approval.ApprovalStore#revokeApprovals(java.util.Collection) + */ + @Override + public boolean revokeApprovals(Collection approvals) { + _logger.debug("revoke Approvals " + approvals); + boolean success = true; + for (Approval approval : approvals) { + Collection tokens = store.findTokensByClientIdAndUserName(approval.getClientId(), approval.getUserId()); + for (OAuth2AccessToken token : tokens) { + OAuth2Authentication authentication = store.readAuthentication(token); + if (authentication != null + && approval.getClientId().equals(authentication.getOAuth2Request().getClientId())) { + store.removeAccessToken(token); + } + } + } + return success; + } - /** - * Extract the implied approvals from any tokens associated with the user and client id supplied. - * - * @see org.dromara.maxkey.authz.oauth2.provider.approval.ApprovalStore#getApprovals(java.lang.String, - * java.lang.String) - */ - @Override - public Collection getApprovals(String userId, String clientId) { - _logger.trace("userId " + userId+" , clientId " + clientId); - Collection result = new HashSet(); - Collection tokens = store.findTokensByClientIdAndUserName(clientId, userId); - _logger.trace("tokens Collection " + tokens); - for (OAuth2AccessToken token : tokens) { - _logger.trace("token " + token); - if(token != null) { - OAuth2Authentication authentication = store.readAuthentication(token); - _logger.trace("authentication " + authentication); - if (authentication != null) { - Date expiresAt = token.getExpiration(); - for (String scope : token.getScope()) { - Approval approval = new Approval(userId, clientId, scope, expiresAt, ApprovalStatus.APPROVED); - result.add(approval); - _logger.trace("add approval " + approval); - } - } - } - } - return result; - } + /** + * Extract the implied approvals from any tokens associated with the user and client id supplied. + * + * @see org.dromara.maxkey.authz.oauth2.provider.approval.ApprovalStore#getApprovals(java.lang.String, + * java.lang.String) + */ + @Override + public Collection getApprovals(String userId, String clientId) { + _logger.trace("userId " + userId+" , clientId " + clientId); + Collection result = new HashSet(); + Collection tokens = store.findTokensByClientIdAndUserName(clientId, userId); + _logger.trace("tokens Collection " + tokens); + for (OAuth2AccessToken token : tokens) { + _logger.trace("token " + token); + if(token != null) { + OAuth2Authentication authentication = store.readAuthentication(token); + _logger.trace("authentication " + authentication); + if (authentication != null) { + Date expiresAt = token.getExpiration(); + for (String scope : token.getScope()) { + Approval approval = new Approval(userId, clientId, scope, expiresAt, ApprovalStatus.APPROVED); + result.add(approval); + _logger.trace("add approval " + approval); + } + } + } + } + return result; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/TokenStoreUserApprovalHandler.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/TokenStoreUserApprovalHandler.java index 22593ba7e..ae2b7ebae 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/TokenStoreUserApprovalHandler.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/TokenStoreUserApprovalHandler.java @@ -44,132 +44,132 @@ import org.springframework.util.Assert; */ public class TokenStoreUserApprovalHandler implements UserApprovalHandler, InitializingBean { - private static Log logger = LogFactory.getLog(TokenStoreUserApprovalHandler.class); + private static Log logger = LogFactory.getLog(TokenStoreUserApprovalHandler.class); - private String approvalParameter = OAuth2Constants.PARAMETER.USER_OAUTH_APPROVAL; - - private TokenStore tokenStore; - - private ClientDetailsService clientDetailsService; - - /** - * Service to load client details (optional) for auto approval checks. - * - * @param clientDetailsService a client details service - */ - public void setClientDetailsService(ClientDetailsService clientDetailsService) { - this.clientDetailsService = clientDetailsService; - } + private String approvalParameter = OAuth2Constants.PARAMETER.USER_OAUTH_APPROVAL; + + private TokenStore tokenStore; + + private ClientDetailsService clientDetailsService; + + /** + * Service to load client details (optional) for auto approval checks. + * + * @param clientDetailsService a client details service + */ + public void setClientDetailsService(ClientDetailsService clientDetailsService) { + this.clientDetailsService = clientDetailsService; + } - /** - * @param approvalParameter the approvalParameter to set - */ - public void setApprovalParameter(String approvalParameter) { - this.approvalParameter = approvalParameter; - } + /** + * @param approvalParameter the approvalParameter to set + */ + public void setApprovalParameter(String approvalParameter) { + this.approvalParameter = approvalParameter; + } - /** - * @param tokenStore the token store to set - */ - public void setTokenStore(TokenStore tokenStore) { - this.tokenStore = tokenStore; - } + /** + * @param tokenStore the token store to set + */ + public void setTokenStore(TokenStore tokenStore) { + this.tokenStore = tokenStore; + } - private OAuth2RequestFactory requestFactory; - - public void setRequestFactory(OAuth2RequestFactory requestFactory) { - this.requestFactory = requestFactory; - } - - @Override - public void afterPropertiesSet() { - Assert.state(tokenStore != null, "TokenStore must be provided"); - Assert.state(requestFactory != null, "OAuth2RequestFactory must be provided"); - } - - /** - * Basic implementation just requires the authorization request to be explicitly approved and the user to be - * authenticated. - * - * @param authorizationRequest The authorization request. - * @param userAuthentication the current user authentication - * - * @return Whether the specified request has been approved by the current user. - */ - @Override - public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { - return authorizationRequest.isApproved(); - } + private OAuth2RequestFactory requestFactory; + + public void setRequestFactory(OAuth2RequestFactory requestFactory) { + this.requestFactory = requestFactory; + } + + @Override + public void afterPropertiesSet() { + Assert.state(tokenStore != null, "TokenStore must be provided"); + Assert.state(requestFactory != null, "OAuth2RequestFactory must be provided"); + } + + /** + * Basic implementation just requires the authorization request to be explicitly approved and the user to be + * authenticated. + * + * @param authorizationRequest The authorization request. + * @param userAuthentication the current user authentication + * + * @return Whether the specified request has been approved by the current user. + */ + @Override + public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { + return authorizationRequest.isApproved(); + } - @Override - public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { - - boolean approved = false; - - String clientId = authorizationRequest.getClientId(); - Set scopes = authorizationRequest.getScope(); - if (clientDetailsService!=null) { - try { - ClientDetails client = clientDetailsService.loadClientByClientId(clientId,true); - approved = true; - for (String scope : scopes) { - if (!client.isAutoApprove(scope)) { - approved = false; - } - } - if (approved) { - authorizationRequest.setApproved(true); - return authorizationRequest; - } - } - catch (ClientRegistrationException e) { - logger.warn("Client registration problem prevent autoapproval check for client=" + clientId); - } - } - - OAuth2Request storedOAuth2Request = requestFactory.createOAuth2Request(authorizationRequest); - - OAuth2Authentication authentication = new OAuth2Authentication(storedOAuth2Request, userAuthentication); - if (logger.isDebugEnabled()) { - StringBuilder builder = new StringBuilder("Looking up existing token for "); - builder.append("client_id=" + clientId); - builder.append(", scope=" + scopes); - builder.append(" and username=" + userAuthentication.getName()); - logger.debug(builder.toString()); - } + @Override + public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { + + boolean approved = false; + + String clientId = authorizationRequest.getClientId(); + Set scopes = authorizationRequest.getScope(); + if (clientDetailsService!=null) { + try { + ClientDetails client = clientDetailsService.loadClientByClientId(clientId,true); + approved = true; + for (String scope : scopes) { + if (!client.isAutoApprove(scope)) { + approved = false; + } + } + if (approved) { + authorizationRequest.setApproved(true); + return authorizationRequest; + } + } + catch (ClientRegistrationException e) { + logger.warn("Client registration problem prevent autoapproval check for client=" + clientId); + } + } + + OAuth2Request storedOAuth2Request = requestFactory.createOAuth2Request(authorizationRequest); + + OAuth2Authentication authentication = new OAuth2Authentication(storedOAuth2Request, userAuthentication); + if (logger.isDebugEnabled()) { + StringBuilder builder = new StringBuilder("Looking up existing token for "); + builder.append("client_id=" + clientId); + builder.append(", scope=" + scopes); + builder.append(" and username=" + userAuthentication.getName()); + logger.debug(builder.toString()); + } - OAuth2AccessToken accessToken = tokenStore.getAccessToken(authentication); - logger.debug("Existing access token=" + accessToken); - if (accessToken != null && !accessToken.isExpired()) { - logger.debug("User already approved with token=" + accessToken); - // A token was already granted and is still valid, so this is already approved - approved = true; - } - else { - logger.debug("Checking explicit approval"); - approved = userAuthentication.isAuthenticated() && approved; - } - - authorizationRequest.setApproved(approved); + OAuth2AccessToken accessToken = tokenStore.getAccessToken(authentication); + logger.debug("Existing access token=" + accessToken); + if (accessToken != null && !accessToken.isExpired()) { + logger.debug("User already approved with token=" + accessToken); + // A token was already granted and is still valid, so this is already approved + approved = true; + } + else { + logger.debug("Checking explicit approval"); + approved = userAuthentication.isAuthenticated() && approved; + } + + authorizationRequest.setApproved(approved); - return authorizationRequest; - } + return authorizationRequest; + } - @Override - public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { - Map approvalParameters = authorizationRequest.getApprovalParameters(); - String flag = approvalParameters.get(approvalParameter); - boolean approved = flag != null && flag.toLowerCase().equals("true"); - authorizationRequest.setApproved(approved); - return authorizationRequest; - } + @Override + public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { + Map approvalParameters = authorizationRequest.getApprovalParameters(); + String flag = approvalParameters.get(approvalParameter); + boolean approved = flag != null && flag.toLowerCase().equals("true"); + authorizationRequest.setApproved(approved); + return authorizationRequest; + } - @Override - public Map getUserApprovalRequest(AuthorizationRequest authorizationRequest, - Authentication userAuthentication) { - Map model = new HashMap(); - // In case of a redirect we might want the request parameters to be included - model.putAll(authorizationRequest.getRequestParameters()); - return model; - } + @Override + public Map getUserApprovalRequest(AuthorizationRequest authorizationRequest, + Authentication userAuthentication) { + Map model = new HashMap(); + // In case of a redirect we might want the request parameters to be included + model.putAll(authorizationRequest.getRequestParameters()); + return model; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/UserApprovalHandler.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/UserApprovalHandler.java index 50c47225a..4c8f62c9a 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/UserApprovalHandler.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/UserApprovalHandler.java @@ -31,57 +31,57 @@ import org.springframework.security.core.Authentication; */ public interface UserApprovalHandler { - /** - *

- * Tests whether the specified authorization request has been approved by the current user (if there is one). - *

- * - * @param authorizationRequest the authorization request. - * @param userAuthentication the user authentication for the current user. - * @return true if the request has been approved, false otherwise - */ - boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication); + /** + *

+ * Tests whether the specified authorization request has been approved by the current user (if there is one). + *

+ * + * @param authorizationRequest the authorization request. + * @param userAuthentication the user authentication for the current user. + * @return true if the request has been approved, false otherwise + */ + boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication); - /** - *

- * Provides a hook for allowing requests to be pre-approved (skipping the User Approval Page). Some implementations - * may allow users to store approval decisions so that they only have to approve a site once. This method is called - * in the AuthorizationEndpoint before sending the user to the Approval page. If this method sets - * oAuth2Request.approved to true, the Approval page will be skipped. - *

- * - * @param authorizationRequest the authorization request. - * @param userAuthentication the user authentication - * @return the AuthorizationRequest, modified if necessary - */ - AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, - Authentication userAuthentication); + /** + *

+ * Provides a hook for allowing requests to be pre-approved (skipping the User Approval Page). Some implementations + * may allow users to store approval decisions so that they only have to approve a site once. This method is called + * in the AuthorizationEndpoint before sending the user to the Approval page. If this method sets + * oAuth2Request.approved to true, the Approval page will be skipped. + *

+ * + * @param authorizationRequest the authorization request. + * @param userAuthentication the user authentication + * @return the AuthorizationRequest, modified if necessary + */ + AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, + Authentication userAuthentication); - /** - *

- * Provides an opportunity to update the authorization request before it is checked for approval in cases where the - * incoming approval parameters contain richer information than just true/false (e.g. some scopes are approved, and - * others are rejected), implementations may need to be able to modify the {@link AuthorizationRequest} before a - * token is generated from it. - *

- * - * @param authorizationRequest the authorization request. - * @param userAuthentication the user authentication - * @return the AuthorizationRequest, modified if necessary - */ - AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest, - Authentication userAuthentication); + /** + *

+ * Provides an opportunity to update the authorization request before it is checked for approval in cases where the + * incoming approval parameters contain richer information than just true/false (e.g. some scopes are approved, and + * others are rejected), implementations may need to be able to modify the {@link AuthorizationRequest} before a + * token is generated from it. + *

+ * + * @param authorizationRequest the authorization request. + * @param userAuthentication the user authentication + * @return the AuthorizationRequest, modified if necessary + */ + AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest, + Authentication userAuthentication); - /** - * Generate a request for the authorization server to ask for the user's approval. Typically this will be rendered - * into a view (HTML etc.) to prompt for the approval, so it needs to contain information about the grant (scopes - * and client id for instance). - * - * @param authorizationRequest the authorization request - * @param userAuthentication the user authentication - * @return a model map for rendering to the user to ask for approval - */ - Map getUserApprovalRequest(AuthorizationRequest authorizationRequest, - Authentication userAuthentication); + /** + * Generate a request for the authorization server to ask for the user's approval. Typically this will be rendered + * into a view (HTML etc.) to prompt for the approval, so it needs to contain information about the grant (scopes + * and client id for instance). + * + * @param authorizationRequest the authorization request + * @param userAuthentication the user authentication + * @return a model map for rendering to the user to ask for approval + */ + Map getUserApprovalRequest(AuthorizationRequest authorizationRequest, + Authentication userAuthentication); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/endpoint/OAuth20AccessConfirmationEndpoint.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/endpoint/OAuth20AccessConfirmationEndpoint.java index 492fe80e8..422dbf7f6 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/endpoint/OAuth20AccessConfirmationEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/endpoint/OAuth20AccessConfirmationEndpoint.java @@ -56,8 +56,8 @@ import org.springframework.web.servlet.ModelAndView; */ @Controller public class OAuth20AccessConfirmationEndpoint { - static final Logger _logger = LoggerFactory.getLogger(OAuth20AccessConfirmationEndpoint.class); - + static final Logger _logger = LoggerFactory.getLogger(OAuth20AccessConfirmationEndpoint.class); + @Autowired protected AppsService appsService; @@ -74,13 +74,13 @@ public class OAuth20AccessConfirmationEndpoint { OAuth20UserApprovalHandler oauth20UserApprovalHandler; @Autowired - protected MomentaryService momentaryService; + protected MomentaryService momentaryService; @Autowired protected ApplicationConfig applicationConfig; @Autowired - AuthTokenService authTokenService; + AuthTokenService authTokenService; /** * getAccessConfirmation. @@ -91,36 +91,36 @@ public class OAuth20AccessConfirmationEndpoint { @RequestMapping(OAuth2Constants.ENDPOINT.ENDPOINT_APPROVAL_CONFIRM) public ModelAndView getAccessConfirmation( @RequestParam Map model,@CurrentUser UserInfo currentUser) { - try { - // Map model - AuthorizationRequest clientAuth = - (AuthorizationRequest) momentaryService.get(currentUser.getSessionId(), "authorizationRequest"); - ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId(),true); - model.put("oauth_approval", authTokenService.genRandomJwt()); - model.put("auth_request", clientAuth); - model.put("client", client); - model.put("oauth_version", "oauth 2.0"); - Map scopes = new LinkedHashMap<>(); - for (String scope : clientAuth.getScope()) { - scopes.put(OAuth2Constants.PARAMETER.SCOPE_PREFIX + scope, "false"); - } - 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(), - approval.getStatus() == ApprovalStatus.APPROVED ? "true" : "false"); - } - } - - model.put("scopes", scopes); - - if(!model.containsKey(OAuth2Constants.PARAMETER.APPROVAL_PROMPT)) { - model.put(OAuth2Constants.PARAMETER.APPROVAL_PROMPT, client.getApprovalPrompt()); - } - }catch(Exception e) { - _logger.debug("OAuth Access Confirmation process error." ,e); - } - + try { + // Map model + AuthorizationRequest clientAuth = + (AuthorizationRequest) momentaryService.get(currentUser.getSessionId(), "authorizationRequest"); + ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId(),true); + model.put("oauth_approval", authTokenService.genRandomJwt()); + model.put("auth_request", clientAuth); + model.put("client", client); + model.put("oauth_version", "oauth 2.0"); + Map scopes = new LinkedHashMap<>(); + for (String scope : clientAuth.getScope()) { + scopes.put(OAuth2Constants.PARAMETER.SCOPE_PREFIX + scope, "false"); + } + 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(), + approval.getStatus() == ApprovalStatus.APPROVED ? "true" : "false"); + } + } + + model.put("scopes", scopes); + + if(!model.containsKey(OAuth2Constants.PARAMETER.APPROVAL_PROMPT)) { + model.put(OAuth2Constants.PARAMETER.APPROVAL_PROMPT, client.getApprovalPrompt()); + } + }catch(Exception e) { + _logger.debug("OAuth Access Confirmation process error." ,e); + } + ModelAndView modelAndView = new ModelAndView("authorize/oauth_access_confirmation"); _logger.trace("Confirmation details "); for (Object key : model.keySet()) { @@ -136,50 +136,50 @@ public class OAuth20AccessConfirmationEndpoint { @RequestMapping(OAuth2Constants.ENDPOINT.ENDPOINT_APPROVAL_CONFIRM+"/get/{oauth_approval}") @ResponseBody public Message> getAccess( - @PathVariable("oauth_approval") String oauthApproval, - @CurrentUser UserInfo currentUser) { - Map model = new HashMap<>(); - if(authTokenService.validateJwtToken(oauthApproval)) { - try { - AuthorizationRequest clientAuth = - (AuthorizationRequest) momentaryService.get(currentUser.getSessionId(), "authorizationRequest"); - ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId(),true); + @PathVariable("oauth_approval") String oauthApproval, + @CurrentUser UserInfo currentUser) { + Map model = new HashMap<>(); + if(authTokenService.validateJwtToken(oauthApproval)) { + try { + AuthorizationRequest clientAuth = + (AuthorizationRequest) momentaryService.get(currentUser.getSessionId(), "authorizationRequest"); + ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId(),true); - Apps app = appsService.get(client.getClientId(),true); - app.transIconBase64(); - - model.put("auth_request", clientAuth); - model.put("client", client); - model.put("clientId", clientAuth.getClientId()); - model.put("appName", app.getAppName()); - model.put("iconBase64", app.getIconBase64()); - model.put("oauth_version", "oauth 2.0"); - Map scopes = new LinkedHashMap<>(); - for (String scope : clientAuth.getScope()) { - scopes.put(OAuth2Constants.PARAMETER.SCOPE_PREFIX + scope, "false"); - } - 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(), - approval.getStatus() == ApprovalStatus.APPROVED ? "true" : "false"); - } - } - - model.put("scopes", scopes); - - if(!model.containsKey(OAuth2Constants.PARAMETER.APPROVAL_PROMPT)) { - model.put(OAuth2Constants.PARAMETER.APPROVAL_PROMPT, client.getApprovalPrompt()); - } - }catch(Exception e) { - _logger.debug("OAuth Access Confirmation process error." ,e); - } - - _logger.trace("Confirmation details "); - for (Object key : model.keySet()) { - _logger.trace("key {} = {}" ,key,model.get(key)); - } - } + Apps app = appsService.get(client.getClientId(),true); + app.transIconBase64(); + + model.put("auth_request", clientAuth); + model.put("client", client); + model.put("clientId", clientAuth.getClientId()); + model.put("appName", app.getAppName()); + model.put("iconBase64", app.getIconBase64()); + model.put("oauth_version", "oauth 2.0"); + Map scopes = new LinkedHashMap<>(); + for (String scope : clientAuth.getScope()) { + scopes.put(OAuth2Constants.PARAMETER.SCOPE_PREFIX + scope, "false"); + } + 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(), + approval.getStatus() == ApprovalStatus.APPROVED ? "true" : "false"); + } + } + + model.put("scopes", scopes); + + if(!model.containsKey(OAuth2Constants.PARAMETER.APPROVAL_PROMPT)) { + model.put(OAuth2Constants.PARAMETER.APPROVAL_PROMPT, client.getApprovalPrompt()); + } + }catch(Exception e) { + _logger.debug("OAuth Access Confirmation process error." ,e); + } + + _logger.trace("Confirmation details "); + for (Object key : model.keySet()) { + _logger.trace("key {} = {}" ,key,model.get(key)); + } + } return new Message<>(model); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/endpoint/OAuth20UserApprovalHandler.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/endpoint/OAuth20UserApprovalHandler.java index 21b9399e7..580c229d0 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/endpoint/OAuth20UserApprovalHandler.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/approval/endpoint/OAuth20UserApprovalHandler.java @@ -31,66 +31,66 @@ import org.springframework.security.core.Authentication; */ public class OAuth20UserApprovalHandler extends ApprovalStoreUserApprovalHandler { - private boolean useApprovalStore = true; + private boolean useApprovalStore = true; - private ClientDetailsService clientDetailsService; + private ClientDetailsService clientDetailsService; - /** - * Service to load client details (optional) for auto approval checks. - * - * @param clientDetailsService a client details service - */ - public void setClientDetailsService(ClientDetailsService clientDetailsService) { - this.clientDetailsService = clientDetailsService; - super.setClientDetailsService(clientDetailsService); - } + /** + * Service to load client details (optional) for auto approval checks. + * + * @param clientDetailsService a client details service + */ + public void setClientDetailsService(ClientDetailsService clientDetailsService) { + this.clientDetailsService = clientDetailsService; + super.setClientDetailsService(clientDetailsService); + } - /** - * @param useApprovalStore the useTokenServices to set - */ - public void setUseApprovalStore(boolean useApprovalStore) { - this.useApprovalStore = useApprovalStore; - } + /** + * @param useApprovalStore the useTokenServices to set + */ + public void setUseApprovalStore(boolean useApprovalStore) { + this.useApprovalStore = useApprovalStore; + } - /** - * Allows automatic approval for a white list of clients in the implicit grant case. - * - * @param authorizationRequest The authorization request. - * @param userAuthentication the current user authentication - * - * @return An updated request if it has already been approved by the current user. - */ - @Override - public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, - Authentication userAuthentication) { + /** + * Allows automatic approval for a white list of clients in the implicit grant case. + * + * @param authorizationRequest The authorization request. + * @param userAuthentication the current user authentication + * + * @return An updated request if it has already been approved by the current user. + */ + @Override + public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, + Authentication userAuthentication) { - boolean approved = false; - // If we are allowed to check existing approvals this will short circuit the decision - if (useApprovalStore) { - authorizationRequest = super.checkForPreApproval(authorizationRequest, userAuthentication); - approved = authorizationRequest.isApproved(); - } - else { - if (clientDetailsService != null) { - Collection requestedScopes = authorizationRequest.getScope(); - try { - ClientDetails client = clientDetailsService - .loadClientByClientId(authorizationRequest.getClientId(),true); - for (String scope : requestedScopes) { - if (client.isAutoApprove(scope) || client.isAutoApprove("all")) { - approved = true; - break; - } - } - } - catch (ClientRegistrationException e) { - } - } - } - authorizationRequest.setApproved(approved); + boolean approved = false; + // If we are allowed to check existing approvals this will short circuit the decision + if (useApprovalStore) { + authorizationRequest = super.checkForPreApproval(authorizationRequest, userAuthentication); + approved = authorizationRequest.isApproved(); + } + else { + if (clientDetailsService != null) { + Collection requestedScopes = authorizationRequest.getScope(); + try { + ClientDetails client = clientDetailsService + .loadClientByClientId(authorizationRequest.getClientId(),true); + for (String scope : requestedScopes) { + if (client.isAutoApprove(scope) || client.isAutoApprove("all")) { + approved = true; + break; + } + } + } + catch (ClientRegistrationException e) { + } + } + } + authorizationRequest.setApproved(approved); - return authorizationRequest; + return authorizationRequest; - } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/authentication/BearerTokenExtractor.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/authentication/BearerTokenExtractor.java index cd0b17ce2..1b23058a0 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/authentication/BearerTokenExtractor.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/authentication/BearerTokenExtractor.java @@ -34,60 +34,60 @@ import jakarta.servlet.http.HttpServletRequest; */ public class BearerTokenExtractor implements TokenExtractor { - private static final Log logger = LogFactory.getLog(BearerTokenExtractor.class); + private static final Log logger = LogFactory.getLog(BearerTokenExtractor.class); - @Override - public Authentication extract(HttpServletRequest request) { - String tokenValue = extractToken(request); - if (tokenValue != null) { - PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(tokenValue, ""); - return authentication; - } - return null; - } + @Override + public Authentication extract(HttpServletRequest request) { + String tokenValue = extractToken(request); + if (tokenValue != null) { + PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(tokenValue, ""); + return authentication; + } + return null; + } - protected String extractToken(HttpServletRequest request) { - // first check the header... - String token = extractHeaderToken(request); + protected String extractToken(HttpServletRequest request) { + // first check the header... + String token = extractHeaderToken(request); - // bearer type allows a request parameter as well - if (token == null) { - logger.debug("Token not found in headers. Trying request parameters."); - token = request.getParameter(OAuth2AccessToken.ACCESS_TOKEN); - if (token == null) { - logger.debug("Token not found in request parameters. Not an OAuth2 request."); - }else { - request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, OAuth2AccessToken.BEARER_TYPE); - } - } + // bearer type allows a request parameter as well + if (token == null) { + logger.debug("Token not found in headers. Trying request parameters."); + token = request.getParameter(OAuth2AccessToken.ACCESS_TOKEN); + if (token == null) { + logger.debug("Token not found in request parameters. Not an OAuth2 request."); + }else { + request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, OAuth2AccessToken.BEARER_TYPE); + } + } - return token; - } + return token; + } - /** - * Extract the OAuth bearer token from a header. - * - * @param request The request. - * @return The token, or null if no OAuth authorization header was supplied. - */ - protected String extractHeaderToken(HttpServletRequest request) { - Enumeration headers = request.getHeaders("Authorization"); - while (headers.hasMoreElements()) { // typically there is only one (most servers enforce that) - String value = headers.nextElement(); - if ((value.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) { - String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim(); - // Add this here for the auth details later. Would be better to change the signature of this method. - request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, - value.substring(0, OAuth2AccessToken.BEARER_TYPE.length()).trim()); - int commaIndex = authHeaderValue.indexOf(','); - if (commaIndex > 0) { - authHeaderValue = authHeaderValue.substring(0, commaIndex); - } - return authHeaderValue; - } - } + /** + * Extract the OAuth bearer token from a header. + * + * @param request The request. + * @return The token, or null if no OAuth authorization header was supplied. + */ + protected String extractHeaderToken(HttpServletRequest request) { + Enumeration headers = request.getHeaders("Authorization"); + while (headers.hasMoreElements()) { // typically there is only one (most servers enforce that) + String value = headers.nextElement(); + if ((value.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) { + String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim(); + // Add this here for the auth details later. Would be better to change the signature of this method. + request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, + value.substring(0, OAuth2AccessToken.BEARER_TYPE.length()).trim()); + int commaIndex = authHeaderValue.indexOf(','); + if (commaIndex > 0) { + authHeaderValue = authHeaderValue.substring(0, commaIndex); + } + return authHeaderValue; + } + } - return null; - } + return null; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/authentication/OAuth2AuthenticationDetails.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/authentication/OAuth2AuthenticationDetails.java index d0846abc8..650ecb6ba 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/authentication/OAuth2AuthenticationDetails.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/authentication/OAuth2AuthenticationDetails.java @@ -26,120 +26,120 @@ import jakarta.servlet.http.HttpSession; * */ public class OAuth2AuthenticationDetails implements Serializable { - - private static final long serialVersionUID = -4809832298438307309L; + + private static final long serialVersionUID = -4809832298438307309L; - public static final String ACCESS_TOKEN_VALUE = OAuth2AuthenticationDetails.class.getSimpleName() + ".ACCESS_TOKEN_VALUE"; + public static final String ACCESS_TOKEN_VALUE = OAuth2AuthenticationDetails.class.getSimpleName() + ".ACCESS_TOKEN_VALUE"; - public static final String ACCESS_TOKEN_TYPE = OAuth2AuthenticationDetails.class.getSimpleName() + ".ACCESS_TOKEN_TYPE"; - - private final String remoteAddress; + public static final String ACCESS_TOKEN_TYPE = OAuth2AuthenticationDetails.class.getSimpleName() + ".ACCESS_TOKEN_TYPE"; + + private final String remoteAddress; - private final String sessionId; + private final String sessionId; - private final String tokenValue; + private final String tokenValue; - private final String tokenType; + private final String tokenType; - private final String display; - - private Object decodedDetails; + private final String display; + + private Object decodedDetails; - /** - * Records the access token value and remote address and will also set the session Id if a session already exists - * (it won't create one). - * - * @param request that the authentication request was received from - */ - public OAuth2AuthenticationDetails(HttpServletRequest request) { - this.tokenValue = (String) request.getAttribute(ACCESS_TOKEN_VALUE); - this.tokenType = (String) request.getAttribute(ACCESS_TOKEN_TYPE); - this.remoteAddress = request.getRemoteAddr(); + /** + * Records the access token value and remote address and will also set the session Id if a session already exists + * (it won't create one). + * + * @param request that the authentication request was received from + */ + public OAuth2AuthenticationDetails(HttpServletRequest request) { + this.tokenValue = (String) request.getAttribute(ACCESS_TOKEN_VALUE); + this.tokenType = (String) request.getAttribute(ACCESS_TOKEN_TYPE); + this.remoteAddress = request.getRemoteAddr(); - HttpSession session = request.getSession(false); - this.sessionId = (session != null) ? session.getId() : null; - StringBuilder builder = new StringBuilder(); - if (remoteAddress!=null) { - builder.append("remoteAddress=").append(remoteAddress); - } - if (builder.length()>1) { - builder.append(", "); - } - if (sessionId!=null) { - builder.append("sessionId="); - if (builder.length()>1) { - builder.append(", "); - } - } - - if (tokenType!=null) { - builder.append("tokenType=").append(this.tokenType); - } - if (tokenValue!=null) { - builder.append("tokenValue="); - } - this.display = builder.toString(); - } + HttpSession session = request.getSession(false); + this.sessionId = (session != null) ? session.getId() : null; + StringBuilder builder = new StringBuilder(); + if (remoteAddress!=null) { + builder.append("remoteAddress=").append(remoteAddress); + } + if (builder.length()>1) { + builder.append(", "); + } + if (sessionId!=null) { + builder.append("sessionId="); + if (builder.length()>1) { + builder.append(", "); + } + } + + if (tokenType!=null) { + builder.append("tokenType=").append(this.tokenType); + } + if (tokenValue!=null) { + builder.append("tokenValue="); + } + this.display = builder.toString(); + } - /** - * The access token value used to authenticate the request (normally in an authorization header). - * - * @return the tokenValue used to authenticate the request - */ - public String getTokenValue() { - return tokenValue; - } + /** + * The access token value used to authenticate the request (normally in an authorization header). + * + * @return the tokenValue used to authenticate the request + */ + public String getTokenValue() { + return tokenValue; + } - /** - * The access token type used to authenticate the request (normally in an authorization header). - * - * @return the tokenType used to authenticate the request if known - */ - public String getTokenType() { - return tokenType; - } - - /** - * Indicates the TCP/IP address the authentication request was received from. - * - * @return the address - */ - public String getRemoteAddress() { - return remoteAddress; - } + /** + * The access token type used to authenticate the request (normally in an authorization header). + * + * @return the tokenType used to authenticate the request if known + */ + public String getTokenType() { + return tokenType; + } + + /** + * Indicates the TCP/IP address the authentication request was received from. + * + * @return the address + */ + public String getRemoteAddress() { + return remoteAddress; + } - /** - * Indicates the HttpSession id the authentication request was received from. - * - * @return the session ID - */ - public String getSessionId() { - return sessionId; - } + /** + * Indicates the HttpSession id the authentication request was received from. + * + * @return the session ID + */ + public String getSessionId() { + return sessionId; + } - /** - * The authentication details obtained by decoding the access token - * if available. - * - * @return the decodedDetails if available (default null) - */ - public Object getDecodedDetails() { - return decodedDetails; - } + /** + * The authentication details obtained by decoding the access token + * if available. + * + * @return the decodedDetails if available (default null) + */ + public Object getDecodedDetails() { + return decodedDetails; + } - /** - * The authentication details obtained by decoding the access token - * if available. - * - * @param decodedDetails the decodedDetails to set - */ - public void setDecodedDetails(Object decodedDetails) { - this.decodedDetails = decodedDetails; - } - - @Override - public String toString() { - return display; - } + /** + * The authentication details obtained by decoding the access token + * if available. + * + * @param decodedDetails the decodedDetails to set + */ + public void setDecodedDetails(Object decodedDetails) { + this.decodedDetails = decodedDetails; + } + + @Override + public String toString() { + return display; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/authentication/OAuth2AuthenticationDetailsSource.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/authentication/OAuth2AuthenticationDetailsSource.java index 95001d99a..354355d4b 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/authentication/OAuth2AuthenticationDetailsSource.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/authentication/OAuth2AuthenticationDetailsSource.java @@ -25,10 +25,10 @@ import jakarta.servlet.http.HttpServletRequest; * */ public class OAuth2AuthenticationDetailsSource implements - AuthenticationDetailsSource { + AuthenticationDetailsSource { - public OAuth2AuthenticationDetails buildDetails(HttpServletRequest context) { - return new OAuth2AuthenticationDetails(context); - } + public OAuth2AuthenticationDetails buildDetails(HttpServletRequest context) { + return new OAuth2AuthenticationDetails(context); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/authentication/TokenExtractor.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/authentication/TokenExtractor.java index 803099fa3..5d9e17550 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/authentication/TokenExtractor.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/authentication/TokenExtractor.java @@ -24,12 +24,12 @@ import jakarta.servlet.http.HttpServletRequest; */ public interface TokenExtractor { - /** - * Extract a token value from an incoming request without authentication. - * - * @param request the current ServletRequest - * @return an authentication token whose principal is an access token (or null if there is none) - */ - Authentication extract(HttpServletRequest request); + /** + * Extract a token value from an incoming request without authentication. + * + * @param request the current ServletRequest + * @return an authentication token whose principal is an access token (or null if there is none) + */ + Authentication extract(HttpServletRequest request); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/client/ClientCredentialsTokenGranter.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/client/ClientCredentialsTokenGranter.java index 0451da6f9..ccd1d65a9 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/client/ClientCredentialsTokenGranter.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/client/ClientCredentialsTokenGranter.java @@ -30,30 +30,30 @@ import org.dromara.maxkey.authz.oauth2.provider.token.AuthorizationServerTokenSe */ public class ClientCredentialsTokenGranter extends AbstractTokenGranter { - private static final String GRANT_TYPE = "client_credentials"; - private boolean allowRefresh = false; + private static final String GRANT_TYPE = "client_credentials"; + private boolean allowRefresh = false; - public ClientCredentialsTokenGranter(AuthorizationServerTokenServices tokenServices, - ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) { - super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE); - } - - public void setAllowRefresh(boolean allowRefresh) { - this.allowRefresh = allowRefresh; - } + public ClientCredentialsTokenGranter(AuthorizationServerTokenServices tokenServices, + ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) { + super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE); + } + + public void setAllowRefresh(boolean allowRefresh) { + this.allowRefresh = allowRefresh; + } - @Override - public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) { - OAuth2AccessToken token = super.grant(grantType, tokenRequest); - if (token != null) { - DefaultOAuth2AccessToken norefresh = new DefaultOAuth2AccessToken(token); - // The spec says that client credentials should not be allowed to get a refresh token - if (!allowRefresh) { - norefresh.setRefreshToken(null); - } - token = norefresh; - } - return token; - } + @Override + public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) { + OAuth2AccessToken token = super.grant(grantType, tokenRequest); + if (token != null) { + DefaultOAuth2AccessToken norefresh = new DefaultOAuth2AccessToken(token); + // The spec says that client credentials should not be allowed to get a refresh token + if (!allowRefresh) { + norefresh.setRefreshToken(null); + } + token = norefresh; + } + return token; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/client/ClientDetailsUserDetailsService.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/client/ClientDetailsUserDetailsService.java index 3ce820677..6a496aeac 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/client/ClientDetailsUserDetailsService.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/client/ClientDetailsUserDetailsService.java @@ -28,38 +28,38 @@ import org.springframework.security.crypto.password.PasswordEncoder; */ public class ClientDetailsUserDetailsService implements UserDetailsService { - private final ClientDetailsService clientDetailsService; - private PasswordEncoder passwordEncoder; - - public ClientDetailsUserDetailsService(ClientDetailsService clientDetailsService) { - this.clientDetailsService = clientDetailsService; - } - - /** - * @param passwordEncoder the password encoder to set - */ - public void setPasswordEncoder(PasswordEncoder passwordEncoder) { - this.passwordEncoder = passwordEncoder; - } + private final ClientDetailsService clientDetailsService; + private PasswordEncoder passwordEncoder; + + public ClientDetailsUserDetailsService(ClientDetailsService clientDetailsService) { + this.clientDetailsService = clientDetailsService; + } + + /** + * @param passwordEncoder the password encoder to set + */ + public void setPasswordEncoder(PasswordEncoder passwordEncoder) { + this.passwordEncoder = passwordEncoder; + } - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - ClientDetails clientDetails; - try { - clientDetails = clientDetailsService.loadClientByClientId(username,true); - } catch (NoSuchClientException e) { - throw new UsernameNotFoundException(e.getMessage(), e); - } - - String clientSecret = clientDetails.getClientSecret(); - if (clientSecret== null || clientSecret.trim().length()==0) { - clientSecret = ""; - }else{ - if(passwordEncoder instanceof PasswordReciprocal){ - clientSecret = ((PasswordReciprocal)passwordEncoder).decoder(clientSecret); - } - } - - return new User(username, clientSecret, clientDetails.getAuthorities()); - } + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + ClientDetails clientDetails; + try { + clientDetails = clientDetailsService.loadClientByClientId(username,true); + } catch (NoSuchClientException e) { + throw new UsernameNotFoundException(e.getMessage(), e); + } + + String clientSecret = clientDetails.getClientSecret(); + if (clientSecret== null || clientSecret.trim().length()==0) { + clientSecret = ""; + }else{ + if(passwordEncoder instanceof PasswordReciprocal){ + clientSecret = ((PasswordReciprocal)passwordEncoder).decoder(clientSecret); + } + } + + return new User(username, clientSecret, clientDetails.getAuthorities()); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/client/JdbcClientDetailsService.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/client/JdbcClientDetailsService.java index 1cd784960..b5b80e459 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/client/JdbcClientDetailsService.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/client/JdbcClientDetailsService.java @@ -127,26 +127,26 @@ public class JdbcClientDetailsService implements ClientDetailsService, ClientReg public ClientDetails loadClientByClientId(String clientId,boolean cached) { // cache in memory - ClientDetails details = null; - try { - if(cached) { - details = detailsCache.getIfPresent(clientId); - if(details == null) { - details = jdbcTemplate.queryForObject( - selectClientDetailsSql, - new ClientDetailsRowMapper(), - clientId - ); - detailsCache.put(clientId, details); - } - }else { - details = jdbcTemplate.queryForObject( - selectClientDetailsSql, - new ClientDetailsRowMapper(), - clientId - ); - } - } catch (EmptyResultDataAccessException e) { + ClientDetails details = null; + try { + if(cached) { + details = detailsCache.getIfPresent(clientId); + if(details == null) { + details = jdbcTemplate.queryForObject( + selectClientDetailsSql, + new ClientDetailsRowMapper(), + clientId + ); + detailsCache.put(clientId, details); + } + }else { + details = jdbcTemplate.queryForObject( + selectClientDetailsSql, + new ClientDetailsRowMapper(), + clientId + ); + } + } catch (EmptyResultDataAccessException e) { throw new NoSuchClientException("No client with requested id: " + clientId); } return details; diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/AuthorizationCodeServices.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/AuthorizationCodeServices.java index d052f1a07..6fd139db6 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/AuthorizationCodeServices.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/AuthorizationCodeServices.java @@ -27,22 +27,22 @@ import org.dromara.maxkey.authz.oauth2.provider.OAuth2Authentication; */ public interface AuthorizationCodeServices { - /** - * Create a authorization code for the specified authentications. - * - * @param authentication The authentications to store. - * @return The generated code. - */ - String createAuthorizationCode(OAuth2Authentication authentication); + /** + * Create a authorization code for the specified authentications. + * + * @param authentication The authentications to store. + * @return The generated code. + */ + String createAuthorizationCode(OAuth2Authentication authentication); - /** - * Consume a authorization code. - * - * @param code The authorization code to consume. - * @return The authentications associated with the code. - * @throws InvalidGrantException If the authorization code is invalid or expired. - */ - OAuth2Authentication consumeAuthorizationCode(String code) - throws InvalidGrantException; + /** + * Consume a authorization code. + * + * @param code The authorization code to consume. + * @return The authentications associated with the code. + * @throws InvalidGrantException If the authorization code is invalid or expired. + */ + OAuth2Authentication consumeAuthorizationCode(String code) + throws InvalidGrantException; } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/AuthorizationCodeTokenGranter.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/AuthorizationCodeTokenGranter.java index 5c22f02bf..2143be03c 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/AuthorizationCodeTokenGranter.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/AuthorizationCodeTokenGranter.java @@ -48,120 +48,120 @@ import org.springframework.security.core.Authentication; */ public class AuthorizationCodeTokenGranter extends AbstractTokenGranter { - private static final String GRANT_TYPE = "authorization_code"; + private static final String GRANT_TYPE = "authorization_code"; - private final AuthorizationCodeServices authorizationCodeServices; + private final AuthorizationCodeServices authorizationCodeServices; - public AuthorizationCodeTokenGranter(AuthorizationServerTokenServices tokenServices, - AuthorizationCodeServices authorizationCodeServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) { - super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE); - this.authorizationCodeServices = authorizationCodeServices; - } + public AuthorizationCodeTokenGranter(AuthorizationServerTokenServices tokenServices, + AuthorizationCodeServices authorizationCodeServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) { + super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE); + this.authorizationCodeServices = authorizationCodeServices; + } - @Override - protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { + @Override + protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { - Map parameters = tokenRequest.getRequestParameters(); - String authorizationCode = parameters.get(OAuth2Constants.PARAMETER.CODE); - String redirectUri = parameters.get(OAuth2Constants.PARAMETER.REDIRECT_URI); - String codeVerifier = parameters.get(OAuth2Constants.PARAMETER.CODE_VERIFIER); + Map parameters = tokenRequest.getRequestParameters(); + String authorizationCode = parameters.get(OAuth2Constants.PARAMETER.CODE); + String redirectUri = parameters.get(OAuth2Constants.PARAMETER.REDIRECT_URI); + String codeVerifier = parameters.get(OAuth2Constants.PARAMETER.CODE_VERIFIER); - if (authorizationCode == null) { - throw new InvalidRequestException("An authorization code must be supplied."); - } - //consume AuthorizationCode - logger.trace("consume AuthorizationCode..."); - OAuth2Authentication storedAuth = authorizationCodeServices.consumeAuthorizationCode(authorizationCode); - if (storedAuth == null) { - throw new InvalidGrantException("Invalid authorization code: " + authorizationCode); - } + if (authorizationCode == null) { + throw new InvalidRequestException("An authorization code must be supplied."); + } + //consume AuthorizationCode + logger.trace("consume AuthorizationCode..."); + OAuth2Authentication storedAuth = authorizationCodeServices.consumeAuthorizationCode(authorizationCode); + if (storedAuth == null) { + throw new InvalidGrantException("Invalid authorization code: " + authorizationCode); + } - OAuth2Request pendingOAuth2Request = storedAuth.getOAuth2Request(); - // https://jira.springsource.org/browse/SECOAUTH-333 - // This might be null, if the authorization was done without the redirect_uri parameter - String redirectUriApprovalParameter = - pendingOAuth2Request.getRequestParameters().get( - OAuth2Constants.PARAMETER.REDIRECT_URI); + OAuth2Request pendingOAuth2Request = storedAuth.getOAuth2Request(); + // https://jira.springsource.org/browse/SECOAUTH-333 + // This might be null, if the authorization was done without the redirect_uri parameter + String redirectUriApprovalParameter = + pendingOAuth2Request.getRequestParameters().get( + OAuth2Constants.PARAMETER.REDIRECT_URI); - String pendingClientId = pendingOAuth2Request.getClientId(); - String clientId = tokenRequest.getClientId(); - - /* - * - * add for RedirectUri - * add by Crystal.Sea - */ - Set redirectUris = client.getRegisteredRedirectUri(); - boolean redirectMismatch=false; - //match the stored RedirectUri with request redirectUri parameter - for(String storedRedirectUri : redirectUris){ - if(redirectUri.startsWith(storedRedirectUri)){ - redirectMismatch=true; - } - } - - if ((redirectUri != null || redirectUriApprovalParameter != null) - && !redirectMismatch) { - logger.info("storedAuth redirectUri "+pendingOAuth2Request.getRedirectUri()); - logger.info("redirectUri parameter "+ redirectUri); - logger.info("stored RedirectUri "+ redirectUris); - throw new RedirectMismatchException("Redirect URI mismatch."); - } - /* - if ((redirectUri != null || redirectUriApprovalParameter != null) - && !pendingOAuth2Request.getRedirectUri().equals(redirectUri)) { - logger.info("storedAuth redirectUri "+pendingOAuth2Request.getRedirectUri()); - logger.info("redirectUri "+ redirectUri); - throw new RedirectMismatchException("Redirect URI mismatch."); - }*/ + String pendingClientId = pendingOAuth2Request.getClientId(); + String clientId = tokenRequest.getClientId(); + + /* + * + * add for RedirectUri + * add by Crystal.Sea + */ + Set redirectUris = client.getRegisteredRedirectUri(); + boolean redirectMismatch=false; + //match the stored RedirectUri with request redirectUri parameter + for(String storedRedirectUri : redirectUris){ + if(redirectUri.startsWith(storedRedirectUri)){ + redirectMismatch=true; + } + } + + if ((redirectUri != null || redirectUriApprovalParameter != null) + && !redirectMismatch) { + logger.info("storedAuth redirectUri "+pendingOAuth2Request.getRedirectUri()); + logger.info("redirectUri parameter "+ redirectUri); + logger.info("stored RedirectUri "+ redirectUris); + throw new RedirectMismatchException("Redirect URI mismatch."); + } + /* + if ((redirectUri != null || redirectUriApprovalParameter != null) + && !pendingOAuth2Request.getRedirectUri().equals(redirectUri)) { + logger.info("storedAuth redirectUri "+pendingOAuth2Request.getRedirectUri()); + logger.info("redirectUri "+ redirectUri); + throw new RedirectMismatchException("Redirect URI mismatch."); + }*/ - - if (clientId != null && !clientId.equals(pendingClientId)) { - // just a sanity check. - throw new InvalidClientException("Client ID mismatch"); - } - - //OAuth 2.1 and PKCE Support - logger.debug("client Protocol "+client.getProtocol()+", PKCE Support "+ - (client.getPkce().equalsIgnoreCase(OAuth2Constants.PKCE_TYPE.PKCE_TYPE_YES))); - if(client.getProtocol().equalsIgnoreCase(ConstsProtocols.OAUTH21) - || client.getPkce().equalsIgnoreCase(OAuth2Constants.PKCE_TYPE.PKCE_TYPE_YES)) { - logger.trace("stored CodeChallengeMethod "+ pendingOAuth2Request.getCodeChallengeMethod()); - logger.trace("stored CodeChallenge "+ pendingOAuth2Request.getCodeChallenge()); - logger.trace("stored codeVerifier "+ codeVerifier); - if(StringUtils.isBlank(codeVerifier)) { - throw new OAuth2Exception("code_verifier can not null."); - } - - if(StringUtils.isBlank(pendingOAuth2Request.getCodeChallenge())) { + + if (clientId != null && !clientId.equals(pendingClientId)) { + // just a sanity check. + throw new InvalidClientException("Client ID mismatch"); + } + + //OAuth 2.1 and PKCE Support + logger.debug("client Protocol "+client.getProtocol()+", PKCE Support "+ + (client.getPkce().equalsIgnoreCase(OAuth2Constants.PKCE_TYPE.PKCE_TYPE_YES))); + if(client.getProtocol().equalsIgnoreCase(ConstsProtocols.OAUTH21) + || client.getPkce().equalsIgnoreCase(OAuth2Constants.PKCE_TYPE.PKCE_TYPE_YES)) { + logger.trace("stored CodeChallengeMethod "+ pendingOAuth2Request.getCodeChallengeMethod()); + logger.trace("stored CodeChallenge "+ pendingOAuth2Request.getCodeChallenge()); + logger.trace("stored codeVerifier "+ codeVerifier); + if(StringUtils.isBlank(codeVerifier)) { + throw new OAuth2Exception("code_verifier can not null."); + } + + if(StringUtils.isBlank(pendingOAuth2Request.getCodeChallenge())) { throw new OAuth2Exception("code_challenge can not null."); } - - if(CODE_CHALLENGE_METHOD_TYPE.S256.equalsIgnoreCase(pendingOAuth2Request.getCodeChallengeMethod())) { - codeVerifier = DigestUtils.digestBase64Url(codeVerifier,DigestUtils.Algorithm.SHA256); - } - - if(!codeVerifier.equals(pendingOAuth2Request.getCodeChallenge())) { + + if(CODE_CHALLENGE_METHOD_TYPE.S256.equalsIgnoreCase(pendingOAuth2Request.getCodeChallengeMethod())) { + codeVerifier = DigestUtils.digestBase64Url(codeVerifier,DigestUtils.Algorithm.SHA256); + } + + if(!codeVerifier.equals(pendingOAuth2Request.getCodeChallenge())) { throw new OAuth2Exception("code_verifier not match."); } - } + } - // Secret is not required in the authorization request, so it won't be available - // in the pendingAuthorizationRequest. We do want to check that a secret is provided - // in the token request, but that happens elsewhere. + // Secret is not required in the authorization request, so it won't be available + // in the pendingAuthorizationRequest. We do want to check that a secret is provided + // in the token request, but that happens elsewhere. - Map combinedParameters = new HashMap(pendingOAuth2Request - .getRequestParameters()); - // Combine the parameters adding the new ones last so they override if there are any clashes - combinedParameters.putAll(parameters); - - // Make a new stored request with the combined parameters - OAuth2Request finalStoredOAuth2Request = pendingOAuth2Request.createOAuth2Request(combinedParameters); - - Authentication userAuth = storedAuth.getUserAuthentication(); - - return new OAuth2Authentication(finalStoredOAuth2Request, userAuth); + Map combinedParameters = new HashMap(pendingOAuth2Request + .getRequestParameters()); + // Combine the parameters adding the new ones last so they override if there are any clashes + combinedParameters.putAll(parameters); + + // Make a new stored request with the combined parameters + OAuth2Request finalStoredOAuth2Request = pendingOAuth2Request.createOAuth2Request(combinedParameters); + + Authentication userAuth = storedAuth.getUserAuthentication(); + + return new OAuth2Authentication(finalStoredOAuth2Request, userAuth); - } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/InMemoryAuthorizationCodeServices.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/InMemoryAuthorizationCodeServices.java index 12d4c1142..c970b18e7 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/InMemoryAuthorizationCodeServices.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/InMemoryAuthorizationCodeServices.java @@ -31,20 +31,20 @@ import com.github.benmanes.caffeine.cache.Caffeine; * @author Dave Syer */ public class InMemoryAuthorizationCodeServices extends RandomValueAuthorizationCodeServices { - protected static final Cache authorizationCodeStore = - Caffeine.newBuilder() + protected static final Cache authorizationCodeStore = + Caffeine.newBuilder() .expireAfterWrite(3, TimeUnit.MINUTES) .build(); - @Override - protected void store(String code, OAuth2Authentication authentication) { - authorizationCodeStore.put(code, authentication); - } + @Override + protected void store(String code, OAuth2Authentication authentication) { + authorizationCodeStore.put(code, authentication); + } - @Override - public OAuth2Authentication remove(String code) { - OAuth2Authentication auth = authorizationCodeStore.getIfPresent(code); - authorizationCodeStore.invalidate(code); - return auth; - } + @Override + public OAuth2Authentication remove(String code) { + OAuth2Authentication auth = authorizationCodeStore.getIfPresent(code); + authorizationCodeStore.invalidate(code); + return auth; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/RandomValueAuthorizationCodeServices.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/RandomValueAuthorizationCodeServices.java index 82b75a4c5..11ecaae77 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/RandomValueAuthorizationCodeServices.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/RandomValueAuthorizationCodeServices.java @@ -30,31 +30,31 @@ import org.dromara.maxkey.authz.oauth2.provider.OAuth2Authentication; */ public abstract class RandomValueAuthorizationCodeServices implements AuthorizationCodeServices { - //default Random code Generator - //private RandomValueStringGenerator generator = new RandomValueStringGenerator(); + //default Random code Generator + //private RandomValueStringGenerator generator = new RandomValueStringGenerator(); - protected abstract void store(String code, OAuth2Authentication authentication); + protected abstract void store(String code, OAuth2Authentication authentication); - protected abstract OAuth2Authentication remove(String code); + protected abstract OAuth2Authentication remove(String code); - public String createAuthorizationCode(OAuth2Authentication authentication) { - //String code = generator.generate(); - /* - * replace with uuid random code - * add by Crystal.Sea - */ - String code = UUID.randomUUID().toString(); - store(code, authentication); - return code; - } + public String createAuthorizationCode(OAuth2Authentication authentication) { + //String code = generator.generate(); + /* + * replace with uuid random code + * add by Crystal.Sea + */ + String code = UUID.randomUUID().toString(); + store(code, authentication); + return code; + } - public OAuth2Authentication consumeAuthorizationCode(String code) - throws InvalidGrantException { - OAuth2Authentication auth = this.remove(code); - if (auth == null) { - throw new InvalidGrantException("Invalid authorization code: " + code); - } - return auth; - } + public OAuth2Authentication consumeAuthorizationCode(String code) + throws InvalidGrantException { + OAuth2Authentication auth = this.remove(code); + if (auth == null) { + throw new InvalidGrantException("Invalid authorization code: " + code); + } + return auth; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/RedisAuthorizationCodeServices.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/RedisAuthorizationCodeServices.java index 5c438d73a..eb728a4aa 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/RedisAuthorizationCodeServices.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/code/RedisAuthorizationCodeServices.java @@ -28,38 +28,38 @@ import org.dromara.maxkey.persistence.redis.RedisConnectionFactory; */ public class RedisAuthorizationCodeServices extends RandomValueAuthorizationCodeServices { - RedisConnectionFactory connectionFactory; - - public static String PREFIX="MXK_OAUTH_V20_CODE_"; - - protected int codeValiditySeconds = 60 * 10; //default 10 minutes. - - /** - * @param connectionFactory - */ - public RedisAuthorizationCodeServices(RedisConnectionFactory connectionFactory) { - super(); - this.connectionFactory = connectionFactory; - } + RedisConnectionFactory connectionFactory; + + public static String PREFIX="MXK_OAUTH_V20_CODE_"; + + protected int codeValiditySeconds = 60 * 10; //default 10 minutes. + + /** + * @param connectionFactory + */ + public RedisAuthorizationCodeServices(RedisConnectionFactory connectionFactory) { + super(); + this.connectionFactory = connectionFactory; + } - public void setConnectionFactory(RedisConnectionFactory connectionFactory) { - this.connectionFactory = connectionFactory; - } - - @Override - protected void store(String code, OAuth2Authentication authentication) { - RedisConnection conn=connectionFactory.getConnection(); - conn.setexObject(PREFIX+code,codeValiditySeconds, authentication); - conn.close(); - } - - @Override - public OAuth2Authentication remove(String code) { - RedisConnection conn=connectionFactory.getConnection(); - OAuth2Authentication auth = conn.getObject(PREFIX+code); - conn.delete(PREFIX+code); + public void setConnectionFactory(RedisConnectionFactory connectionFactory) { + this.connectionFactory = connectionFactory; + } + + @Override + protected void store(String code, OAuth2Authentication authentication) { + RedisConnection conn=connectionFactory.getConnection(); + conn.setexObject(PREFIX+code,codeValiditySeconds, authentication); conn.close(); - return auth; - } + } + + @Override + public OAuth2Authentication remove(String code) { + RedisConnection conn=connectionFactory.getConnection(); + OAuth2Authentication auth = conn.getObject(PREFIX+code); + conn.delete(PREFIX+code); + conn.close(); + return auth; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/AbstractEndpoint.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/AbstractEndpoint.java index 85111a151..8454f1412 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/AbstractEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/AbstractEndpoint.java @@ -49,103 +49,103 @@ import org.springframework.util.Assert; */ public class AbstractEndpoint implements InitializingBean { - protected final Log logger = LogFactory.getLog(getClass()); + protected final Log logger = LogFactory.getLog(getClass()); - private TokenGranter tokenGranter; - - @Autowired - @Qualifier("oauth20AuthorizationCodeServices") - protected AuthorizationCodeServices authorizationCodeServices = new InMemoryAuthorizationCodeServices(); - - @Autowired - @Qualifier("oauth20TokenServices") - protected AuthorizationServerTokenServices tokenServices ; - - @Autowired - @Qualifier("oauth20JdbcClientDetailsService") - protected ClientDetailsService clientDetailsService; - - @Autowired - @Qualifier("oAuth2RequestFactory") - protected OAuth2RequestFactory oAuth2RequestFactory; - - @Autowired - @Qualifier("oAuth2RequestFactory") - protected OAuth2RequestFactory defaultOAuth2RequestFactory; + private TokenGranter tokenGranter; + + @Autowired + @Qualifier("oauth20AuthorizationCodeServices") + protected AuthorizationCodeServices authorizationCodeServices = new InMemoryAuthorizationCodeServices(); + + @Autowired + @Qualifier("oauth20TokenServices") + protected AuthorizationServerTokenServices tokenServices ; + + @Autowired + @Qualifier("oauth20JdbcClientDetailsService") + protected ClientDetailsService clientDetailsService; + + @Autowired + @Qualifier("oAuth2RequestFactory") + protected OAuth2RequestFactory oAuth2RequestFactory; + + @Autowired + @Qualifier("oAuth2RequestFactory") + protected OAuth2RequestFactory defaultOAuth2RequestFactory; - @Autowired + @Autowired @Qualifier("oauth20UserAuthenticationManager") - AuthenticationManager authenticationManager; - - @Autowired + AuthenticationManager authenticationManager; + + @Autowired protected AppsService appsService; - - @Autowired + + @Autowired @Qualifier("applicationConfig") protected ApplicationConfig applicationConfig; - - @Autowired - protected MomentaryService momentaryService; - - - public void afterPropertiesSet() throws Exception { - if (tokenGranter == null) { - //ClientDetailsService clientDetails = clientDetailsService(); - //AuthorizationServerTokenServices tokenServices = tokenServices(); - //AuthorizationCodeServices authorizationCodeServices = authorizationCodeServices(); - //OAuth2RequestFactory requestFactory = requestFactory(); + + @Autowired + protected MomentaryService momentaryService; + + + public void afterPropertiesSet() throws Exception { + if (tokenGranter == null) { + //ClientDetailsService clientDetails = clientDetailsService(); + //AuthorizationServerTokenServices tokenServices = tokenServices(); + //AuthorizationCodeServices authorizationCodeServices = authorizationCodeServices(); + //OAuth2RequestFactory requestFactory = requestFactory(); - List tokenGranters = new ArrayList(); - tokenGranters.add(new AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, - clientDetailsService, oAuth2RequestFactory)); - tokenGranters.add(new RefreshTokenGranter(tokenServices, clientDetailsService, oAuth2RequestFactory)); - ImplicitTokenGranter implicit = new ImplicitTokenGranter(tokenServices, clientDetailsService, oAuth2RequestFactory); - tokenGranters.add(implicit); - tokenGranters.add(new ClientCredentialsTokenGranter(tokenServices, clientDetailsService, oAuth2RequestFactory)); - if (authenticationManager != null) { - tokenGranters.add(new ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices, - clientDetailsService, oAuth2RequestFactory)); - } - tokenGranter = new CompositeTokenGranter(tokenGranters); - } - Assert.state(tokenGranter != null, "TokenGranter must be provided"); - Assert.state(clientDetailsService != null, "ClientDetailsService must be provided"); - defaultOAuth2RequestFactory = new DefaultOAuth2RequestFactory(getClientDetailsService()); - if (oAuth2RequestFactory == null) { - oAuth2RequestFactory = defaultOAuth2RequestFactory; - } - } + List tokenGranters = new ArrayList(); + tokenGranters.add(new AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, + clientDetailsService, oAuth2RequestFactory)); + tokenGranters.add(new RefreshTokenGranter(tokenServices, clientDetailsService, oAuth2RequestFactory)); + ImplicitTokenGranter implicit = new ImplicitTokenGranter(tokenServices, clientDetailsService, oAuth2RequestFactory); + tokenGranters.add(implicit); + tokenGranters.add(new ClientCredentialsTokenGranter(tokenServices, clientDetailsService, oAuth2RequestFactory)); + if (authenticationManager != null) { + tokenGranters.add(new ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices, + clientDetailsService, oAuth2RequestFactory)); + } + tokenGranter = new CompositeTokenGranter(tokenGranters); + } + Assert.state(tokenGranter != null, "TokenGranter must be provided"); + Assert.state(clientDetailsService != null, "ClientDetailsService must be provided"); + defaultOAuth2RequestFactory = new DefaultOAuth2RequestFactory(getClientDetailsService()); + if (oAuth2RequestFactory == null) { + oAuth2RequestFactory = defaultOAuth2RequestFactory; + } + } - public void setTokenGranter(TokenGranter tokenGranter) { - this.tokenGranter = tokenGranter; - } + public void setTokenGranter(TokenGranter tokenGranter) { + this.tokenGranter = tokenGranter; + } - protected TokenGranter getTokenGranter() { - return tokenGranter; - } + protected TokenGranter getTokenGranter() { + return tokenGranter; + } - protected OAuth2RequestFactory getOAuth2RequestFactory() { - return oAuth2RequestFactory; - } + protected OAuth2RequestFactory getOAuth2RequestFactory() { + return oAuth2RequestFactory; + } - protected OAuth2RequestFactory getDefaultOAuth2RequestFactory() { - return defaultOAuth2RequestFactory; - } + protected OAuth2RequestFactory getDefaultOAuth2RequestFactory() { + return defaultOAuth2RequestFactory; + } - public void setOAuth2RequestFactory(OAuth2RequestFactory oAuth2RequestFactory) { - this.oAuth2RequestFactory = oAuth2RequestFactory; - } + public void setOAuth2RequestFactory(OAuth2RequestFactory oAuth2RequestFactory) { + this.oAuth2RequestFactory = oAuth2RequestFactory; + } - protected ClientDetailsService getClientDetailsService() { - return clientDetailsService; - } + protected ClientDetailsService getClientDetailsService() { + return clientDetailsService; + } - public void setClientDetailsService(ClientDetailsService clientDetailsService) { - this.clientDetailsService = clientDetailsService; - } + public void setClientDetailsService(ClientDetailsService clientDetailsService) { + this.clientDetailsService = clientDetailsService; + } } \ No newline at end of file diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/AuthorizationEndpoint.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/AuthorizationEndpoint.java index fd016dbfa..f09fec00d 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/AuthorizationEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/AuthorizationEndpoint.java @@ -95,28 +95,28 @@ import jakarta.servlet.http.HttpServletResponse; @Tag(name = "2-1-OAuth v2.0 API文档模块") @Controller public class AuthorizationEndpoint extends AbstractEndpoint { - static final Logger _logger = LoggerFactory.getLogger(AuthorizationEndpoint.class); - - private static final String OAUTH_V20_AUTHORIZATION_URL = "" + OAuth2Constants.ENDPOINT.ENDPOINT_AUTHORIZE + "?client_id=%s&response_type=code&redirect_uri=%s&approval_prompt=auto"; - - private RedirectResolver redirectResolver = new DefaultRedirectResolver(); + static final Logger _logger = LoggerFactory.getLogger(AuthorizationEndpoint.class); + + private static final String OAUTH_V20_AUTHORIZATION_URL = "" + OAuth2Constants.ENDPOINT.ENDPOINT_AUTHORIZE + "?client_id=%s&response_type=code&redirect_uri=%s&approval_prompt=auto"; + + private RedirectResolver redirectResolver = new DefaultRedirectResolver(); - private UserApprovalHandler userApprovalHandler = new DefaultUserApprovalHandler(); + private UserApprovalHandler userApprovalHandler = new DefaultUserApprovalHandler(); - private OAuth2RequestValidator oauth2RequestValidator = new DefaultOAuth2RequestValidator(); + private OAuth2RequestValidator oauth2RequestValidator = new DefaultOAuth2RequestValidator(); - private String userApprovalPage = "forward:" + OAuth2Constants.ENDPOINT.ENDPOINT_APPROVAL_CONFIRM; + private String userApprovalPage = "forward:" + OAuth2Constants.ENDPOINT.ENDPOINT_APPROVAL_CONFIRM; - private String errorPage = "forward:" + OAuth2Constants.ENDPOINT.ENDPOINT_ERROR; - - private Object implicitLock = new Object(); + private String errorPage = "forward:" + OAuth2Constants.ENDPOINT.ENDPOINT_ERROR; + + private Object implicitLock = new Object(); - public void setErrorPage(String errorPage) { - this.errorPage = errorPage; - } + public void setErrorPage(String errorPage) { + this.errorPage = errorPage; + } - @Operation(summary = "OAuth 2.0 认证接口", description = "传递参数应用ID,自动完成跳转认证拼接",method="GET") + @Operation(summary = "OAuth 2.0 认证接口", description = "传递参数应用ID,自动完成跳转认证拼接",method="GET") @GetMapping(value = {OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/{id}"}) public ModelAndView authorize( HttpServletRequest request, @@ -137,408 +137,408 @@ public class AuthorizationEndpoint extends AbstractEndpoint { return WebContext.redirect(authorizationUrl); } - - @Operation(summary = "OAuth 2.0 认证接口", description = "传递参数client_id,response_type,redirect_uri等",method="GET") - @GetMapping(value = { - OAuth2Constants.ENDPOINT.ENDPOINT_AUTHORIZE, - OAuth2Constants.ENDPOINT.ENDPOINT_TENCENT_IOA_AUTHORIZE - }) - public ModelAndView authorize( - Map model, - @RequestParam Map parameters, - @CurrentUser UserInfo currentUser, - SessionStatus sessionStatus) { - - 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. - AuthorizationRequest authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters); + + @Operation(summary = "OAuth 2.0 认证接口", description = "传递参数client_id,response_type,redirect_uri等",method="GET") + @GetMapping(value = { + OAuth2Constants.ENDPOINT.ENDPOINT_AUTHORIZE, + OAuth2Constants.ENDPOINT.ENDPOINT_TENCENT_IOA_AUTHORIZE + }) + public ModelAndView authorize( + Map model, + @RequestParam Map parameters, + @CurrentUser UserInfo currentUser, + SessionStatus sessionStatus) { + + 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. + AuthorizationRequest authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters); - Set responseTypes = authorizationRequest.getResponseTypes(); + Set responseTypes = authorizationRequest.getResponseTypes(); - if (!responseTypes.contains(OAuth2Constants.PARAMETER.TOKEN) && !responseTypes.contains(OAuth2Constants.PARAMETER.CODE)) { - throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes); - } + if (!responseTypes.contains(OAuth2Constants.PARAMETER.TOKEN) && !responseTypes.contains(OAuth2Constants.PARAMETER.CODE)) { + throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes); + } - if (authorizationRequest.getClientId() == null) { - throw new InvalidClientException("A client id must be provided"); - } + if (authorizationRequest.getClientId() == null) { + throw new InvalidClientException("A client id must be provided"); + } - try { + try { - if (!(principal instanceof Authentication) || !((Authentication) principal).isAuthenticated()) { - throw new InsufficientAuthenticationException( - "User must be authenticated with Spring Security before authorization can be completed."); - } + if (!(principal instanceof Authentication) || !((Authentication) principal).isAuthenticated()) { + throw new InsufficientAuthenticationException( + "User must be authenticated with Spring Security before authorization can be completed."); + } - ClientDetails client = getClientDetailsService().loadClientByClientId(authorizationRequest.getClientId(),true); + ClientDetails client = getClientDetailsService().loadClientByClientId(authorizationRequest.getClientId(),true); - // The resolved redirect URI is either the redirect_uri from the parameters or the one from - // clientDetails. Either way we need to store it on the AuthorizationRequest. - String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Constants.PARAMETER.REDIRECT_URI); - //URLDecoder for redirect_uri - redirectUriParameter = URLDecoder.decode(redirectUriParameter,"UTF-8"); - String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client); - if (!StringUtils.hasText(resolvedRedirect)) { - logger.info("Client redirectUri "+resolvedRedirect); - logger.info("Parameter redirectUri "+redirectUriParameter); - - throw new RedirectMismatchException( - "A redirectUri must be either supplied or preconfigured in the ClientDetails"); - } - authorizationRequest.setRedirectUri(resolvedRedirect); + // The resolved redirect URI is either the redirect_uri from the parameters or the one from + // clientDetails. Either way we need to store it on the AuthorizationRequest. + String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Constants.PARAMETER.REDIRECT_URI); + //URLDecoder for redirect_uri + redirectUriParameter = URLDecoder.decode(redirectUriParameter,"UTF-8"); + String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client); + if (!StringUtils.hasText(resolvedRedirect)) { + logger.info("Client redirectUri "+resolvedRedirect); + logger.info("Parameter redirectUri "+redirectUriParameter); + + throw new RedirectMismatchException( + "A redirectUri must be either supplied or preconfigured in the ClientDetails"); + } + authorizationRequest.setRedirectUri(resolvedRedirect); - // We intentionally only validate the parameters requested by the client (ignoring any data that may have - // been added to the request by the manager). - oauth2RequestValidator.validateScope(authorizationRequest, client); + // We intentionally only validate the parameters requested by the client (ignoring any data that may have + // been added to the request by the manager). + oauth2RequestValidator.validateScope(authorizationRequest, client); - // Some systems may allow for approval decisions to be remembered or approved by default. Check for - // such logic here, and set the approved flag on the authorization request accordingly. - authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest, - (Authentication) principal); - // is this call necessary? - boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal); - authorizationRequest.setApproved(approved); + // Some systems may allow for approval decisions to be remembered or approved by default. Check for + // such logic here, and set the approved flag on the authorization request accordingly. + authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest, + (Authentication) principal); + // is this call necessary? + boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal); + authorizationRequest.setApproved(approved); - // Validation is all done, so we can check for auto approval... - if (authorizationRequest.isApproved()) { - if (responseTypes.contains(OAuth2Constants.PARAMETER.TOKEN)) { - return new ModelAndView(getImplicitGrantResponse(authorizationRequest)); - } - if (responseTypes.contains(OAuth2Constants.PARAMETER.CODE)) { - return new ModelAndView(getAuthorizationCodeResponse(authorizationRequest, - (Authentication) principal)); - } - } - Apps app = (Apps)WebContext.getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP); - //session中为空或者id不一致重新加载 + // Validation is all done, so we can check for auto approval... + if (authorizationRequest.isApproved()) { + if (responseTypes.contains(OAuth2Constants.PARAMETER.TOKEN)) { + return new ModelAndView(getImplicitGrantResponse(authorizationRequest)); + } + if (responseTypes.contains(OAuth2Constants.PARAMETER.CODE)) { + return new ModelAndView(getAuthorizationCodeResponse(authorizationRequest, + (Authentication) principal)); + } + } + Apps app = (Apps)WebContext.getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP); + //session中为空或者id不一致重新加载 if (app == null || !app.getId().equalsIgnoreCase(authorizationRequest.getClientId())) { app = appsService.get(authorizationRequest.getClientId()); WebContext.setAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP, app); } - // Place auth request into the model so that it is stored in the session - // for approveOrDeny to use. That way we make sure that auth request comes from the session, - // so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session. + // Place auth request into the model so that it is stored in the session + // for approveOrDeny to use. That way we make sure that auth request comes from the session, + // so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session. momentaryService.put(currentUser.getSessionId(), "authorizationRequest", authorizationRequest); - return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal); + return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal); - }catch(UnsupportedEncodingException e) { - logger.info("URLDecoder Exception ",e); - throw new RuntimeException("URLDecoder UnsupportedEncodingException"); - }catch (RuntimeException e) { - sessionStatus.setComplete(); - throw e; - } + }catch(UnsupportedEncodingException e) { + logger.info("URLDecoder Exception ",e); + throw new RuntimeException("URLDecoder UnsupportedEncodingException"); + }catch (RuntimeException e) { + sessionStatus.setComplete(); + throw e; + } - } + } - //approval must post - @PostMapping(value = {OAuth2Constants.ENDPOINT.ENDPOINT_AUTHORIZE+"/approval"}, params = OAuth2Constants.PARAMETER.USER_OAUTH_APPROVAL) - @ResponseBody - public Message< String> authorizeApproveOrDeny(@RequestParam Map approvalParameters,@CurrentUser UserInfo currentUser) { - Principal principal = (Principal)AuthorizationUtils.getAuthentication(); - if (!(principal instanceof Authentication)) { - throw new InsufficientAuthenticationException( - "User must be authenticated with Spring Security before authorizing an access token."); - } + //approval must post + @PostMapping(value = {OAuth2Constants.ENDPOINT.ENDPOINT_AUTHORIZE+"/approval"}, params = OAuth2Constants.PARAMETER.USER_OAUTH_APPROVAL) + @ResponseBody + public Message< String> authorizeApproveOrDeny(@RequestParam Map approvalParameters,@CurrentUser UserInfo currentUser) { + Principal principal = (Principal)AuthorizationUtils.getAuthentication(); + if (!(principal instanceof Authentication)) { + throw new InsufficientAuthenticationException( + "User must be authenticated with Spring Security before authorizing an access token."); + } - AuthorizationRequest authorizationRequest = (AuthorizationRequest) momentaryService.get(currentUser.getSessionId(), "authorizationRequest"); + AuthorizationRequest authorizationRequest = (AuthorizationRequest) momentaryService.get(currentUser.getSessionId(), "authorizationRequest"); - if (authorizationRequest == null) { - throw new InvalidRequestException("Cannot approve uninitialized authorization request."); - } + if (authorizationRequest == null) { + throw new InvalidRequestException("Cannot approve uninitialized authorization request."); + } - Set responseTypes = authorizationRequest.getResponseTypes(); + Set responseTypes = authorizationRequest.getResponseTypes(); - authorizationRequest.setApprovalParameters(approvalParameters); - authorizationRequest = userApprovalHandler.updateAfterApproval(authorizationRequest,(Authentication) principal); - boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal); - authorizationRequest.setApproved(approved); + authorizationRequest.setApprovalParameters(approvalParameters); + authorizationRequest = userApprovalHandler.updateAfterApproval(authorizationRequest,(Authentication) principal); + boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal); + authorizationRequest.setApproved(approved); - if (authorizationRequest.getRedirectUri() == null) { - throw new InvalidRequestException("Cannot approve request when no redirect URI is provided."); - } + if (authorizationRequest.getRedirectUri() == null) { + throw new InvalidRequestException("Cannot approve request when no redirect URI is provided."); + } - if (!authorizationRequest.isApproved()) { - return new Message<>(Message.FAIL, - getUnsuccessfulRedirect( - authorizationRequest, - new UserDeniedAuthorizationException("User denied access"), - responseTypes.contains(OAuth2Constants.PARAMETER.TOKEN) - ) - ); - } + if (!authorizationRequest.isApproved()) { + return new Message<>(Message.FAIL, + getUnsuccessfulRedirect( + authorizationRequest, + new UserDeniedAuthorizationException("User denied access"), + responseTypes.contains(OAuth2Constants.PARAMETER.TOKEN) + ) + ); + } - if (responseTypes.contains(OAuth2Constants.PARAMETER.TOKEN)) { - return new Message<>(getImplicitGrantResponse(authorizationRequest)); - } + if (responseTypes.contains(OAuth2Constants.PARAMETER.TOKEN)) { + return new Message<>(getImplicitGrantResponse(authorizationRequest)); + } - return new Message<>(getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal)); - } + return new Message<>(getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal)); + } - // We need explicit approval from the user. - private ModelAndView getUserApprovalPageResponse(Map model, - AuthorizationRequest authorizationRequest, Authentication principal) { - logger.debug("Loading user approval page: " + userApprovalPage); - model.putAll(userApprovalHandler.getUserApprovalRequest(authorizationRequest, principal)); - return new ModelAndView(userApprovalPage, model); - } + // We need explicit approval from the user. + private ModelAndView getUserApprovalPageResponse(Map model, + AuthorizationRequest authorizationRequest, Authentication principal) { + logger.debug("Loading user approval page: " + userApprovalPage); + model.putAll(userApprovalHandler.getUserApprovalRequest(authorizationRequest, principal)); + return new ModelAndView(userApprovalPage, model); + } - // We can grant a token and return it with implicit approval. - private String getImplicitGrantResponse(AuthorizationRequest authorizationRequest) { - try { - TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest, "implicit"); - OAuth2Request storedOAuth2Request = getOAuth2RequestFactory().createOAuth2Request(authorizationRequest); + // We can grant a token and return it with implicit approval. + private String getImplicitGrantResponse(AuthorizationRequest authorizationRequest) { + try { + TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest, "implicit"); + OAuth2Request storedOAuth2Request = getOAuth2RequestFactory().createOAuth2Request(authorizationRequest); - OAuth2AccessToken accessToken = getAccessTokenForImplicitGrant(tokenRequest, storedOAuth2Request); - if (accessToken == null) { - throw new UnsupportedResponseTypeException("Unsupported response type: token"); - } - return appendAccessToken(authorizationRequest, accessToken); - } - catch (OAuth2Exception e) { - return getUnsuccessfulRedirect(authorizationRequest, e, true); - } - } + OAuth2AccessToken accessToken = getAccessTokenForImplicitGrant(tokenRequest, storedOAuth2Request); + if (accessToken == null) { + throw new UnsupportedResponseTypeException("Unsupported response type: token"); + } + return appendAccessToken(authorizationRequest, accessToken); + } + catch (OAuth2Exception e) { + return getUnsuccessfulRedirect(authorizationRequest, e, true); + } + } - private OAuth2AccessToken getAccessTokenForImplicitGrant(TokenRequest tokenRequest, - OAuth2Request storedOAuth2Request) { - OAuth2AccessToken accessToken = null; - // These 1 method calls have to be atomic, otherwise the ImplicitGrantService can have a race condition where - // one thread removes the token request before another has a chance to redeem it. - synchronized (this.implicitLock) { - accessToken = getTokenGranter().grant("implicit", new ImplicitTokenRequest(tokenRequest, storedOAuth2Request)); - } - return accessToken; - } - - // Authorization Code Response - private String getAuthorizationCodeResponse(AuthorizationRequest authorizationRequest, Authentication authUser) { - try { - String successfulRedirect = getSuccessfulRedirect( - authorizationRequest, - generateCode(authorizationRequest, authUser) - ); - _logger.debug("successfulRedirect {}" , successfulRedirect); - return successfulRedirect; - } - catch (OAuth2Exception e) { - return getUnsuccessfulRedirect(authorizationRequest, e, false); - } - } + private OAuth2AccessToken getAccessTokenForImplicitGrant(TokenRequest tokenRequest, + OAuth2Request storedOAuth2Request) { + OAuth2AccessToken accessToken = null; + // These 1 method calls have to be atomic, otherwise the ImplicitGrantService can have a race condition where + // one thread removes the token request before another has a chance to redeem it. + synchronized (this.implicitLock) { + accessToken = getTokenGranter().grant("implicit", new ImplicitTokenRequest(tokenRequest, storedOAuth2Request)); + } + return accessToken; + } + + // Authorization Code Response + private String getAuthorizationCodeResponse(AuthorizationRequest authorizationRequest, Authentication authUser) { + try { + String successfulRedirect = getSuccessfulRedirect( + authorizationRequest, + generateCode(authorizationRequest, authUser) + ); + _logger.debug("successfulRedirect {}" , successfulRedirect); + return successfulRedirect; + } + catch (OAuth2Exception e) { + return getUnsuccessfulRedirect(authorizationRequest, e, false); + } + } - private String appendAccessToken(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken) { + private String appendAccessToken(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken) { - Map vars = new HashMap(); + Map vars = new HashMap(); - String requestedRedirect = authorizationRequest.getRedirectUri(); - if (accessToken == null) { - throw new InvalidRequestException("An implicit grant could not be made"); - } - StringBuilder url = new StringBuilder(requestedRedirect); - if (requestedRedirect.contains("#")) { - url.append("&"); - } - else { - url.append("#"); - } + String requestedRedirect = authorizationRequest.getRedirectUri(); + if (accessToken == null) { + throw new InvalidRequestException("An implicit grant could not be made"); + } + StringBuilder url = new StringBuilder(requestedRedirect); + if (requestedRedirect.contains("#")) { + url.append("&"); + } + else { + url.append("#"); + } - url.append(templateUrlVar(OAuth2Constants.PARAMETER.ACCESS_TOKEN)); - url.append("&").append(templateUrlVar(OAuth2Constants.PARAMETER.TOKEN_TYPE)); - vars.put(OAuth2Constants.PARAMETER.ACCESS_TOKEN, accessToken.getValue()); - vars.put(OAuth2Constants.PARAMETER.TOKEN_TYPE, accessToken.getTokenType()); - String state = authorizationRequest.getState(); + url.append(templateUrlVar(OAuth2Constants.PARAMETER.ACCESS_TOKEN)); + url.append("&").append(templateUrlVar(OAuth2Constants.PARAMETER.TOKEN_TYPE)); + vars.put(OAuth2Constants.PARAMETER.ACCESS_TOKEN, accessToken.getValue()); + vars.put(OAuth2Constants.PARAMETER.TOKEN_TYPE, accessToken.getTokenType()); + String state = authorizationRequest.getState(); - if (state != null) { - url.append("&").append(templateUrlVar(OAuth2Constants.PARAMETER.STATE)); - vars.put(OAuth2Constants.PARAMETER.STATE, state); - } - Date expiration = accessToken.getExpiration(); - if (expiration != null) { - long expires_in = (expiration.getTime() - System.currentTimeMillis()) / 1000; - url.append("&").append(templateUrlVar(OAuth2Constants.PARAMETER.EXPIRES_IN)); - vars.put(OAuth2Constants.PARAMETER.EXPIRES_IN, expires_in); - } - String originalScope = authorizationRequest.getRequestParameters().get(OAuth2Constants.PARAMETER.SCOPE); - if (originalScope == null || !OAuth2Utils.parseParameterList(originalScope).equals(accessToken.getScope())) { - url.append("&").append(templateUrlVar(OAuth2Constants.PARAMETER.SCOPE)); - vars.put(OAuth2Constants.PARAMETER.SCOPE, OAuth2Utils.formatParameterList(accessToken.getScope())); - } - Map additionalInformation = accessToken.getAdditionalInformation(); - for (String key : additionalInformation.keySet()) { - Object value = additionalInformation.get(key); - if (value != null) { - url.append("&" + key + "={extra_" + key + "}"); - vars.put("extra_" + key, value); - } - } - UriTemplate template = new UriTemplate(url.toString()); - // Do not include the refresh token (even if there is one) - return template.expand(vars).toString(); - } - - public String templateUrlVar(String parameterName) { - return parameterName + "={" + parameterName + "}"; - } + if (state != null) { + url.append("&").append(templateUrlVar(OAuth2Constants.PARAMETER.STATE)); + vars.put(OAuth2Constants.PARAMETER.STATE, state); + } + Date expiration = accessToken.getExpiration(); + if (expiration != null) { + long expires_in = (expiration.getTime() - System.currentTimeMillis()) / 1000; + url.append("&").append(templateUrlVar(OAuth2Constants.PARAMETER.EXPIRES_IN)); + vars.put(OAuth2Constants.PARAMETER.EXPIRES_IN, expires_in); + } + String originalScope = authorizationRequest.getRequestParameters().get(OAuth2Constants.PARAMETER.SCOPE); + if (originalScope == null || !OAuth2Utils.parseParameterList(originalScope).equals(accessToken.getScope())) { + url.append("&").append(templateUrlVar(OAuth2Constants.PARAMETER.SCOPE)); + vars.put(OAuth2Constants.PARAMETER.SCOPE, OAuth2Utils.formatParameterList(accessToken.getScope())); + } + Map additionalInformation = accessToken.getAdditionalInformation(); + for (String key : additionalInformation.keySet()) { + Object value = additionalInformation.get(key); + if (value != null) { + url.append("&" + key + "={extra_" + key + "}"); + vars.put("extra_" + key, value); + } + } + UriTemplate template = new UriTemplate(url.toString()); + // Do not include the refresh token (even if there is one) + return template.expand(vars).toString(); + } + + public String templateUrlVar(String parameterName) { + return parameterName + "={" + parameterName + "}"; + } - private String generateCode(AuthorizationRequest authorizationRequest, Authentication authentication) - throws AuthenticationException { + private String generateCode(AuthorizationRequest authorizationRequest, Authentication authentication) + throws AuthenticationException { - try { + try { - OAuth2Request storedOAuth2Request = getOAuth2RequestFactory().createOAuth2Request(authorizationRequest); + OAuth2Request storedOAuth2Request = getOAuth2RequestFactory().createOAuth2Request(authorizationRequest); - OAuth2Authentication combinedAuth = new OAuth2Authentication(storedOAuth2Request, authentication); - String code = authorizationCodeServices.createAuthorizationCode(combinedAuth); + OAuth2Authentication combinedAuth = new OAuth2Authentication(storedOAuth2Request, authentication); + String code = authorizationCodeServices.createAuthorizationCode(combinedAuth); - return code; + return code; - } - catch (OAuth2Exception e) { + } + catch (OAuth2Exception e) { - if (authorizationRequest.getState() != null) { - e.addAdditionalInformation(OAuth2Constants.PARAMETER.STATE, authorizationRequest.getState()); - } + if (authorizationRequest.getState() != null) { + e.addAdditionalInformation(OAuth2Constants.PARAMETER.STATE, authorizationRequest.getState()); + } - throw e; + throw e; - } - } - // Successful Redirect - private String getSuccessfulRedirect(AuthorizationRequest authorizationRequest, String authorizationCode) { + } + } + // Successful Redirect + private String getSuccessfulRedirect(AuthorizationRequest authorizationRequest, String authorizationCode) { - if (authorizationCode == null) { - throw new IllegalStateException("No authorization code found in the current request scope."); - } + if (authorizationCode == null) { + throw new IllegalStateException("No authorization code found in the current request scope."); + } - Map query = new LinkedHashMap(); - query.put(OAuth2Constants.PARAMETER.CODE, authorizationCode); + Map query = new LinkedHashMap(); + query.put(OAuth2Constants.PARAMETER.CODE, authorizationCode); - String state = authorizationRequest.getState(); - if (state != null) { - query.put(OAuth2Constants.PARAMETER.STATE, state); - } - - //this is for cas - String service = authorizationRequest.getRequestParameters().get("service"); - if (service != null) { - query.put("service", service); - } + String state = authorizationRequest.getState(); + if (state != null) { + query.put(OAuth2Constants.PARAMETER.STATE, state); + } + + //this is for cas + String service = authorizationRequest.getRequestParameters().get("service"); + if (service != null) { + query.put("service", service); + } - return append(authorizationRequest.getRedirectUri(), query, false); - } + return append(authorizationRequest.getRedirectUri(), query, false); + } - private String getUnsuccessfulRedirect(AuthorizationRequest authorizationRequest, OAuth2Exception failure, - boolean fragment) { + private String getUnsuccessfulRedirect(AuthorizationRequest authorizationRequest, OAuth2Exception failure, + boolean fragment) { - if (authorizationRequest == null || authorizationRequest.getRedirectUri() == null) { - // we have no redirect for the user. very sad. - throw new UnapprovedClientAuthenticationException("Authorization failure, and no redirect URI.", failure); - } + if (authorizationRequest == null || authorizationRequest.getRedirectUri() == null) { + // we have no redirect for the user. very sad. + throw new UnapprovedClientAuthenticationException("Authorization failure, and no redirect URI.", failure); + } - Map query = new LinkedHashMap(); + Map query = new LinkedHashMap(); - query.put("error", failure.getOAuth2ErrorCode()); - query.put("error_description", failure.getMessage()); + query.put("error", failure.getOAuth2ErrorCode()); + query.put("error_description", failure.getMessage()); - if (authorizationRequest.getState() != null) { - query.put(OAuth2Constants.PARAMETER.STATE, authorizationRequest.getState()); - } + if (authorizationRequest.getState() != null) { + query.put(OAuth2Constants.PARAMETER.STATE, authorizationRequest.getState()); + } - if (failure.getAdditionalInformation() != null) { - for (Map.Entry additionalInfo : failure.getAdditionalInformation().entrySet()) { - query.put(additionalInfo.getKey(), additionalInfo.getValue()); - } - } + if (failure.getAdditionalInformation() != null) { + for (Map.Entry additionalInfo : failure.getAdditionalInformation().entrySet()) { + query.put(additionalInfo.getKey(), additionalInfo.getValue()); + } + } - return append(authorizationRequest.getRedirectUri(), query, fragment); + return append(authorizationRequest.getRedirectUri(), query, fragment); - } + } - private String append(String base, Map query, boolean fragment) { - return append(base, query, null, fragment); - } + private String append(String base, Map query, boolean fragment) { + return append(base, query, null, fragment); + } - private String append(String base, Map query, Map keys, boolean fragment) { + private String append(String base, Map query, Map keys, boolean fragment) { - UriComponentsBuilder template = UriComponentsBuilder.newInstance(); - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(base); - URI redirectUri; - try { - // assume it's encoded to start with (if it came in over the wire) - redirectUri = builder.build(true).toUri(); - } - catch (Exception e) { - // ... but allow client registrations to contain hard-coded non-encoded values - redirectUri = builder.build().toUri(); - builder = UriComponentsBuilder.fromUri(redirectUri); - } - template.scheme(redirectUri.getScheme()).port(redirectUri.getPort()).host(redirectUri.getHost()) - .userInfo(redirectUri.getUserInfo()).path(redirectUri.getPath()); - if (StringUtils.hasLength(redirectUri.getFragment())) { - StringBuilder values = new StringBuilder(); - if (redirectUri.getFragment() != null) { - String append = redirectUri.getFragment(); - values.append(append); - } - for (String key : query.keySet()) { - if (values.length() > 0) { - if(values.indexOf("?") == -1) { - values.append("?"); - }else { - values.append("&"); - } - } - String name = key; - if (keys != null && keys.containsKey(key)) { - name = keys.get(key); - } - values.append(name + "={" + key + "}"); - } - if (values.length() > 0) { - template.fragment(values.toString()); - } - UriComponents encoded = template.build().expand(query).encode(); - builder.fragment(encoded.getFragment()); - } - else { - for (String key : query.keySet()) { - String name = key; - if (keys != null && keys.containsKey(key)) { - name = keys.get(key); - } - template.queryParam(name, "{" + key + "}"); - } - template.fragment(redirectUri.getFragment()); - UriComponents encoded = template.build().expand(query).encode(); - builder.query(encoded.getQuery()); - } + UriComponentsBuilder template = UriComponentsBuilder.newInstance(); + UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(base); + URI redirectUri; + try { + // assume it's encoded to start with (if it came in over the wire) + redirectUri = builder.build(true).toUri(); + } + catch (Exception e) { + // ... but allow client registrations to contain hard-coded non-encoded values + redirectUri = builder.build().toUri(); + builder = UriComponentsBuilder.fromUri(redirectUri); + } + template.scheme(redirectUri.getScheme()).port(redirectUri.getPort()).host(redirectUri.getHost()) + .userInfo(redirectUri.getUserInfo()).path(redirectUri.getPath()); + if (StringUtils.hasLength(redirectUri.getFragment())) { + StringBuilder values = new StringBuilder(); + if (redirectUri.getFragment() != null) { + String append = redirectUri.getFragment(); + values.append(append); + } + for (String key : query.keySet()) { + if (values.length() > 0) { + if(values.indexOf("?") == -1) { + values.append("?"); + }else { + values.append("&"); + } + } + String name = key; + if (keys != null && keys.containsKey(key)) { + name = keys.get(key); + } + values.append(name + "={" + key + "}"); + } + if (values.length() > 0) { + template.fragment(values.toString()); + } + UriComponents encoded = template.build().expand(query).encode(); + builder.fragment(encoded.getFragment()); + } + else { + for (String key : query.keySet()) { + String name = key; + if (keys != null && keys.containsKey(key)) { + name = keys.get(key); + } + template.queryParam(name, "{" + key + "}"); + } + template.fragment(redirectUri.getFragment()); + UriComponents encoded = template.build().expand(query).encode(); + builder.query(encoded.getQuery()); + } - return builder.build().toUriString(); + return builder.build().toUriString(); - } - - public void setUserApprovalPage(String userApprovalPage) { - this.userApprovalPage = userApprovalPage; - } + } + + public void setUserApprovalPage(String userApprovalPage) { + this.userApprovalPage = userApprovalPage; + } - public void setAuthorizationCodeServices(AuthorizationCodeServices authorizationCodeServices) { - this.authorizationCodeServices = authorizationCodeServices; - } + public void setAuthorizationCodeServices(AuthorizationCodeServices authorizationCodeServices) { + this.authorizationCodeServices = authorizationCodeServices; + } - public void setRedirectResolver(RedirectResolver redirectResolver) { - this.redirectResolver = redirectResolver; - } + public void setRedirectResolver(RedirectResolver redirectResolver) { + this.redirectResolver = redirectResolver; + } - public void setUserApprovalHandler(UserApprovalHandler userApprovalHandler) { - this.userApprovalHandler = userApprovalHandler; - } + public void setUserApprovalHandler(UserApprovalHandler userApprovalHandler) { + this.userApprovalHandler = userApprovalHandler; + } - public void setOAuth2RequestValidator(OAuth2RequestValidator oauth2RequestValidator) { - this.oauth2RequestValidator = oauth2RequestValidator; - } + public void setOAuth2RequestValidator(OAuth2RequestValidator oauth2RequestValidator) { + this.oauth2RequestValidator = oauth2RequestValidator; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/CheckTokenEndpoint.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/CheckTokenEndpoint.java index c6c5b19a9..b02819d55 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/CheckTokenEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/CheckTokenEndpoint.java @@ -57,46 +57,46 @@ import io.swagger.v3.oas.annotations.tags.Tag; @RestController public class CheckTokenEndpoint { - private ResourceServerTokenServices resourceServerTokenServices; + private ResourceServerTokenServices resourceServerTokenServices; - private AccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter(); + private AccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter(); - protected final Log logger = LogFactory.getLog(getClass()); + protected final Log logger = LogFactory.getLog(getClass()); - public CheckTokenEndpoint(ResourceServerTokenServices resourceServerTokenServices) { - this.resourceServerTokenServices = resourceServerTokenServices; - } - + public CheckTokenEndpoint(ResourceServerTokenServices resourceServerTokenServices) { + this.resourceServerTokenServices = resourceServerTokenServices; + } + - /** - * @param accessTokenConverter the accessTokenConverter to set - */ - public void setAccessTokenConverter(AccessTokenConverter accessTokenConverter) { - this.accessTokenConverter = accessTokenConverter; - } + /** + * @param accessTokenConverter the accessTokenConverter to set + */ + public void setAccessTokenConverter(AccessTokenConverter accessTokenConverter) { + this.accessTokenConverter = accessTokenConverter; + } - @Operation(summary = "OAuth 2.0 token检查接口", description = "传递参数token",method="POST") - @PostMapping(OAuth2Constants.ENDPOINT.ENDPOINT_CHECK_TOKEN) - public Map checkToken(@RequestParam(OAuth2Constants.PARAMETER.TOKEN) String value) { + @Operation(summary = "OAuth 2.0 token检查接口", description = "传递参数token",method="POST") + @PostMapping(OAuth2Constants.ENDPOINT.ENDPOINT_CHECK_TOKEN) + public Map checkToken(@RequestParam(OAuth2Constants.PARAMETER.TOKEN) String value) { - OAuth2AccessToken token = resourceServerTokenServices.readAccessToken(value); - if (token == null) { - throw new InvalidTokenException("Token was not recognised"); - } + OAuth2AccessToken token = resourceServerTokenServices.readAccessToken(value); + if (token == null) { + throw new InvalidTokenException("Token was not recognised"); + } - if (token.isExpired()) { - throw new InvalidTokenException("Token has expired"); - } + if (token.isExpired()) { + throw new InvalidTokenException("Token has expired"); + } - OAuth2Authentication authentication = resourceServerTokenServices.loadAuthentication(token.getValue()); + OAuth2Authentication authentication = resourceServerTokenServices.loadAuthentication(token.getValue()); - Map response = accessTokenConverter.convertAccessToken(token, authentication); + Map response = accessTokenConverter.convertAccessToken(token, authentication); - return response; - } + return response; + } - + } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/DefaultRedirectResolver.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/DefaultRedirectResolver.java index adebe0771..b2b1c4d38 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/DefaultRedirectResolver.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/DefaultRedirectResolver.java @@ -38,125 +38,125 @@ import org.springframework.util.StringUtils; */ public class DefaultRedirectResolver implements RedirectResolver { - private Collection redirectGrantTypes = Arrays.asList("implicit", "authorization_code"); + private Collection redirectGrantTypes = Arrays.asList("implicit", "authorization_code"); - private boolean matchSubdomains = true; + private boolean matchSubdomains = true; - /** - * Flag to indicate that requested URIs will match if they are a subdomain of the registered value. - * - * @param matchSubdomains the flag value to set (deafult true) - */ - public void setMatchSubdomains(boolean matchSubdomains) { - this.matchSubdomains = matchSubdomains; - } + /** + * Flag to indicate that requested URIs will match if they are a subdomain of the registered value. + * + * @param matchSubdomains the flag value to set (deafult true) + */ + public void setMatchSubdomains(boolean matchSubdomains) { + this.matchSubdomains = matchSubdomains; + } - /** - * Grant types that are permitted to have a redirect uri. - * - * @param redirectGrantTypes the redirect grant types to set - */ - public void setRedirectGrantTypes(Collection redirectGrantTypes) { - this.redirectGrantTypes = new HashSet(redirectGrantTypes); - } + /** + * Grant types that are permitted to have a redirect uri. + * + * @param redirectGrantTypes the redirect grant types to set + */ + public void setRedirectGrantTypes(Collection redirectGrantTypes) { + this.redirectGrantTypes = new HashSet(redirectGrantTypes); + } - public String resolveRedirect(String requestedRedirect, ClientDetails client) throws OAuth2Exception { + public String resolveRedirect(String requestedRedirect, ClientDetails client) throws OAuth2Exception { - Set authorizedGrantTypes = client.getAuthorizedGrantTypes(); - if (authorizedGrantTypes.isEmpty()) { - throw new InvalidGrantException("A client must have at least one authorized grant type."); - } - if (!containsRedirectGrantType(authorizedGrantTypes)) { - throw new InvalidGrantException( - "A redirect_uri can only be used by implicit or authorization_code grant types."); - } + Set authorizedGrantTypes = client.getAuthorizedGrantTypes(); + if (authorizedGrantTypes.isEmpty()) { + throw new InvalidGrantException("A client must have at least one authorized grant type."); + } + if (!containsRedirectGrantType(authorizedGrantTypes)) { + throw new InvalidGrantException( + "A redirect_uri can only be used by implicit or authorization_code grant types."); + } - Set redirectUris = client.getRegisteredRedirectUri(); + Set redirectUris = client.getRegisteredRedirectUri(); - if (redirectUris != null && !redirectUris.isEmpty()) { - return obtainMatchingRedirect(redirectUris, requestedRedirect); - } - else if (StringUtils.hasText(requestedRedirect)) { - return requestedRedirect; - } - else { - throw new InvalidRequestException("A redirect_uri must be supplied."); - } + if (redirectUris != null && !redirectUris.isEmpty()) { + return obtainMatchingRedirect(redirectUris, requestedRedirect); + } + else if (StringUtils.hasText(requestedRedirect)) { + return requestedRedirect; + } + else { + throw new InvalidRequestException("A redirect_uri must be supplied."); + } - } + } - /** - * @param grantTypes some grant types - * @return true if the supplied grant types includes one or more of the redirect types - */ - private boolean containsRedirectGrantType(Set grantTypes) { - for (String type : grantTypes) { - if (redirectGrantTypes.contains(type)) { - return true; - } - } - return false; - } + /** + * @param grantTypes some grant types + * @return true if the supplied grant types includes one or more of the redirect types + */ + private boolean containsRedirectGrantType(Set grantTypes) { + for (String type : grantTypes) { + if (redirectGrantTypes.contains(type)) { + return true; + } + } + return false; + } - /** - * Whether the requested redirect URI "matches" the specified redirect URI. For a URL, this implementation tests if - * the user requested redirect starts with the registered redirect, so it would have the same host and root path if - * it is an HTTP URL. - *

- * For other (non-URL) cases, such as for some implicit clients, the redirect_uri must be an exact match. - * - * @param requestedRedirect The requested redirect URI. - * @param redirectUri The registered redirect URI. - * @return Whether the requested redirect URI "matches" the specified redirect URI. - */ - protected boolean redirectMatches(String requestedRedirect, String redirectUri) { - try { - URL req = new URL(requestedRedirect); - URL reg = new URL(redirectUri); + /** + * Whether the requested redirect URI "matches" the specified redirect URI. For a URL, this implementation tests if + * the user requested redirect starts with the registered redirect, so it would have the same host and root path if + * it is an HTTP URL. + *

+ * For other (non-URL) cases, such as for some implicit clients, the redirect_uri must be an exact match. + * + * @param requestedRedirect The requested redirect URI. + * @param redirectUri The registered redirect URI. + * @return Whether the requested redirect URI "matches" the specified redirect URI. + */ + protected boolean redirectMatches(String requestedRedirect, String redirectUri) { + try { + URL req = new URL(requestedRedirect); + URL reg = new URL(redirectUri); - if (reg.getProtocol().equals(req.getProtocol()) && hostMatches(reg.getHost(), req.getHost())) { - return StringUtils.cleanPath(req.getPath()).startsWith(StringUtils.cleanPath(reg.getPath())); - } - } - catch (MalformedURLException e) { - } - return requestedRedirect.equals(redirectUri); - } + if (reg.getProtocol().equals(req.getProtocol()) && hostMatches(reg.getHost(), req.getHost())) { + return StringUtils.cleanPath(req.getPath()).startsWith(StringUtils.cleanPath(reg.getPath())); + } + } + catch (MalformedURLException e) { + } + return requestedRedirect.equals(redirectUri); + } - /** - * Check if host matches the registered value. - * - * @param registered the registered host - * @param requested the requested host - * @return true if they match - */ - protected boolean hostMatches(String registered, String requested) { - if (matchSubdomains) { - return requested.endsWith(registered); - } - return registered.equals(requested); - } + /** + * Check if host matches the registered value. + * + * @param registered the registered host + * @param requested the requested host + * @return true if they match + */ + protected boolean hostMatches(String registered, String requested) { + if (matchSubdomains) { + return requested.endsWith(registered); + } + return registered.equals(requested); + } - /** - * Attempt to match one of the registered URIs to the that of the requested one. - * - * @param redirectUris the set of the registered URIs to try and find a match. This cannot be null or empty. - * @param requestedRedirect the URI used as part of the request - * @return the matching URI - * @throws RedirectMismatchException if no match was found - */ - private String obtainMatchingRedirect(Set redirectUris, String requestedRedirect) { - Assert.notEmpty(redirectUris, "Redirect URIs cannot be empty"); + /** + * Attempt to match one of the registered URIs to the that of the requested one. + * + * @param redirectUris the set of the registered URIs to try and find a match. This cannot be null or empty. + * @param requestedRedirect the URI used as part of the request + * @return the matching URI + * @throws RedirectMismatchException if no match was found + */ + private String obtainMatchingRedirect(Set redirectUris, String requestedRedirect) { + Assert.notEmpty(redirectUris, "Redirect URIs cannot be empty"); - if (redirectUris.size() == 1 && requestedRedirect == null) { - return redirectUris.iterator().next(); - } - for (String redirectUri : redirectUris) { - if (requestedRedirect != null && redirectMatches(requestedRedirect, redirectUri)) { - return requestedRedirect; - } - } - throw new RedirectMismatchException("Invalid redirect: " + requestedRedirect - + " does not match one of the registered values: " + redirectUris.toString()); - } + if (redirectUris.size() == 1 && requestedRedirect == null) { + return redirectUris.iterator().next(); + } + for (String redirectUri : redirectUris) { + if (requestedRedirect != null && redirectMatches(requestedRedirect, redirectUri)) { + return requestedRedirect; + } + } + throw new RedirectMismatchException("Invalid redirect: " + requestedRedirect + + " does not match one of the registered values: " + redirectUris.toString()); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/ExactMatchRedirectResolver.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/ExactMatchRedirectResolver.java index bad934fd5..87c316fd8 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/ExactMatchRedirectResolver.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/ExactMatchRedirectResolver.java @@ -28,16 +28,16 @@ package org.dromara.maxkey.authz.oauth2.provider.endpoint; */ public class ExactMatchRedirectResolver extends DefaultRedirectResolver { - /** - * Whether the requested redirect URI "matches" the specified redirect URI. This implementation tests strict - * equality. - * - * @param requestedRedirect The requested redirect URI. - * @param redirectUri The registered redirect URI. - * @return Whether the requested redirect URI "matches" the specified redirect URI. - */ - protected boolean redirectMatches(String requestedRedirect, String redirectUri) { - return requestedRedirect.equals(redirectUri); - } + /** + * Whether the requested redirect URI "matches" the specified redirect URI. This implementation tests strict + * equality. + * + * @param requestedRedirect The requested redirect URI. + * @param redirectUri The registered redirect URI. + * @return Whether the requested redirect URI "matches" the specified redirect URI. + */ + protected boolean redirectMatches(String requestedRedirect, String redirectUri) { + return requestedRedirect.equals(redirectUri); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/IntrospectEndpoint.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/IntrospectEndpoint.java index 44e148a35..5bdcec646 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/IntrospectEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/IntrospectEndpoint.java @@ -45,118 +45,118 @@ import jakarta.servlet.http.HttpServletResponse; @Tag(name = "2-1-OAuth v2.0 API文档模块") @Controller public class IntrospectEndpoint { - static final Logger _logger = LoggerFactory.getLogger(IntrospectEndpoint.class); - @Autowired - @Qualifier("oauth20JdbcClientDetailsService") - private ClientDetailsService clientDetailsService; - - @Autowired - @Qualifier("oauth20TokenServices") - private DefaultTokenServices oauth20tokenServices; - - @Autowired - ProviderManager oauth20ClientAuthenticationManager; + static final Logger _logger = LoggerFactory.getLogger(IntrospectEndpoint.class); + @Autowired + @Qualifier("oauth20JdbcClientDetailsService") + private ClientDetailsService clientDetailsService; + + @Autowired + @Qualifier("oauth20TokenServices") + private DefaultTokenServices oauth20tokenServices; + + @Autowired + ProviderManager oauth20ClientAuthenticationManager; @Autowired protected HttpResponseAdapter httpResponseAdapter; - + @Operation(summary = "OAuth 2.0 令牌验证接口", description = "请求参数access_token , header Authorization , token ",method="POST,GET") - @RequestMapping(value=OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/introspect", method = {RequestMethod.POST, RequestMethod.GET}) - public void introspect(HttpServletRequest request, HttpServletResponse response) { - String access_token = RequestTokenUtils.resolveAccessToken(request); + @RequestMapping(value=OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/introspect", method = {RequestMethod.POST, RequestMethod.GET}) + public void introspect(HttpServletRequest request, HttpServletResponse response) { + String access_token = RequestTokenUtils.resolveAccessToken(request); _logger.debug("access_token {}" , access_token); - - OAuth2Authentication oAuth2Authentication =null; - Introspection introspection = new Introspection(access_token); - try{ - oAuth2Authentication = oauth20tokenServices.loadAuthentication(access_token); - if(oAuth2Authentication != null) { - String sub = ""; - //userAuthentication not null , is password or code , - if(oAuth2Authentication.getUserAuthentication() != null) { - sub = ((SignPrincipal)oAuth2Authentication.getUserAuthentication().getPrincipal()).getUsername(); - }else { - //client_credentials - sub = oAuth2Authentication.getOAuth2Request().getClientId(); - } - if(StringUtils.isNotBlank(sub)) { - introspection.setSub(sub,true); - } - } - }catch(OAuth2Exception e){ - _logger.error("OAuth2Exception ", e); - } - - httpResponseAdapter.write(response,JsonUtils.gsonToString(introspection),"json"); - } - - public boolean clientAuthenticate(AuthorizationHeader headerCredential) { - if(headerCredential != null){ - UsernamePasswordAuthenticationToken authenticationToken = null; - if(headerCredential.isBasic()) { - if(StringUtils.isNotBlank(headerCredential.getUsername())&& - StringUtils.isNotBlank(headerCredential.getCredential()) - ) { - UsernamePasswordAuthenticationToken authRequest = - new UsernamePasswordAuthenticationToken( - headerCredential.getUsername(), - headerCredential.getCredential()); - authenticationToken = (UsernamePasswordAuthenticationToken)oauth20ClientAuthenticationManager.authenticate(authRequest); - } - } - if(authenticationToken != null && authenticationToken.isAuthenticated()) { - return true; - } - } - return false; + + OAuth2Authentication oAuth2Authentication =null; + Introspection introspection = new Introspection(access_token); + try{ + oAuth2Authentication = oauth20tokenServices.loadAuthentication(access_token); + if(oAuth2Authentication != null) { + String sub = ""; + //userAuthentication not null , is password or code , + if(oAuth2Authentication.getUserAuthentication() != null) { + sub = ((SignPrincipal)oAuth2Authentication.getUserAuthentication().getPrincipal()).getUsername(); + }else { + //client_credentials + sub = oAuth2Authentication.getOAuth2Request().getClientId(); + } + if(StringUtils.isNotBlank(sub)) { + introspection.setSub(sub,true); + } + } + }catch(OAuth2Exception e){ + _logger.error("OAuth2Exception ", e); + } + + httpResponseAdapter.write(response,JsonUtils.gsonToString(introspection),"json"); } - public void setOauth20tokenServices(DefaultTokenServices oauth20tokenServices) { - this.oauth20tokenServices = oauth20tokenServices; - } - - public class Introspection { - - String token; - boolean active; - String sub; + public boolean clientAuthenticate(AuthorizationHeader headerCredential) { + if(headerCredential != null){ + UsernamePasswordAuthenticationToken authenticationToken = null; + if(headerCredential.isBasic()) { + if(StringUtils.isNotBlank(headerCredential.getUsername())&& + StringUtils.isNotBlank(headerCredential.getCredential()) + ) { + UsernamePasswordAuthenticationToken authRequest = + new UsernamePasswordAuthenticationToken( + headerCredential.getUsername(), + headerCredential.getCredential()); + authenticationToken = (UsernamePasswordAuthenticationToken)oauth20ClientAuthenticationManager.authenticate(authRequest); + } + } + if(authenticationToken != null && authenticationToken.isAuthenticated()) { + return true; + } + } + return false; + } + + public void setOauth20tokenServices(DefaultTokenServices oauth20tokenServices) { + this.oauth20tokenServices = oauth20tokenServices; + } + + public class Introspection { + + String token; + boolean active; + String sub; - public String getToken() { - return token; - } + public String getToken() { + return token; + } - public void setToken(String token) { - this.token = token; - } + public void setToken(String token) { + this.token = token; + } - public boolean isActive() { - return active; - } + public boolean isActive() { + return active; + } - public void setActive(boolean active) { - this.active = active; - } + public void setActive(boolean active) { + this.active = active; + } - public String getSub() { - return sub; - } + public String getSub() { + return sub; + } - public void setSub(String sub,boolean active) { - this.sub = sub; - this.active = active; - } + public void setSub(String sub,boolean active) { + this.sub = sub; + this.active = active; + } - public Introspection(String token) { - this.token = token; - this.active = false; - } + public Introspection(String token) { + this.token = token; + this.active = false; + } - public Introspection(String token, boolean active, String sub) { - this.token = token; - this.active = active; - this.sub = sub; - } + public Introspection(String token, boolean active, String sub) { + this.token = token; + this.active = active; + this.sub = sub; + } - } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/OauthJwksEndpoint.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/OauthJwksEndpoint.java index a12ba483f..3d4add93b 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/OauthJwksEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/OauthJwksEndpoint.java @@ -41,70 +41,70 @@ import jakarta.servlet.http.HttpServletResponse; @Tag(name = "2-1-OAuth v2.0 API文档模块") @Controller public class OauthJwksEndpoint extends AbstractEndpoint { - static final Logger _logger = LoggerFactory.getLogger(OauthJwksEndpoint.class); + static final Logger _logger = LoggerFactory.getLogger(OauthJwksEndpoint.class); - @Operation(summary = "OAuth JWk 元数据接口", description = "参数inst_id , client_id",method="GET") - @RequestMapping(value = OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/jwks", - method={RequestMethod.POST, RequestMethod.GET}) - @ResponseBody - public String keysMetadataByParam(HttpServletRequest request , HttpServletResponse response, - @RequestParam(value="inst_id",required = false) String inst_id, - @RequestParam(value="client_id",required = false) String client_id) { - return buildMetadata(request,response,inst_id,client_id,ContentType.JSON); - } - - @Operation(summary = "OAuth JWk 元数据接口", description = "参数instId , clientId",method="GET") - @RequestMapping(value = OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/{instId}/{clientId}/jwks", - method={RequestMethod.POST, RequestMethod.GET}) - @ResponseBody - public String keysMetadatabyPath(HttpServletRequest request , HttpServletResponse response, - @PathVariable(value="instId") String instId, - @PathVariable(value="clientId") String clientId) { - return buildMetadata(request,response,instId,clientId,ContentType.JSON); - } - - @Operation(summary = "OAuth JWk 元数据接口", description = "参数mxk_metadata_clientId",method="GET") - @RequestMapping( - value = "/metadata/oauth/v20/" + WebConstants.MXK_METADATA_PREFIX + "{clientId}.{mediaType}", - method={RequestMethod.POST, RequestMethod.GET}) - @ResponseBody - public String metadata(HttpServletRequest request , HttpServletResponse response, - @PathVariable(value="clientId") String clientId, - @PathVariable(value="mediaType") String mediaType) { - return buildMetadata(request,response,null,clientId,mediaType); - } - - public String buildMetadata(HttpServletRequest request , HttpServletResponse response, - String instId,String clientId,String mediaType){ - ClientDetails clientDetails = null; - try { - clientDetails = getClientDetailsService().loadClientByClientId(clientId,true); - }catch(Exception e) { - _logger.error("getClientDetailsService", e); - } - if(clientDetails != null) { - String jwkSetString = ""; - if(!clientDetails.getSignature().equalsIgnoreCase("none")) { - jwkSetString = clientDetails.getSignatureKey(); - } - if(!clientDetails.getAlgorithm().equalsIgnoreCase("none")) { - if(!StringUtils.hasText(jwkSetString)) { - jwkSetString = clientDetails.getAlgorithmKey(); - }else { - jwkSetString = jwkSetString + "," +clientDetails.getAlgorithmKey(); - } - } - JWKSetKeyStore jwkSetKeyStore = new JWKSetKeyStore("{\"keys\": [" + jwkSetString + "]}"); - - if(StringUtils.hasText(mediaType) && mediaType.equalsIgnoreCase(ContentType.XML)) { - response.setContentType(ContentType.APPLICATION_XML_UTF8); - }else { - response.setContentType(ContentType.APPLICATION_JSON_UTF8); - } - return jwkSetKeyStore.toString(mediaType); - } else { - return clientId + " not exist . \n" + WebContext.version(); - } - } + @Operation(summary = "OAuth JWk 元数据接口", description = "参数inst_id , client_id",method="GET") + @RequestMapping(value = OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/jwks", + method={RequestMethod.POST, RequestMethod.GET}) + @ResponseBody + public String keysMetadataByParam(HttpServletRequest request , HttpServletResponse response, + @RequestParam(value="inst_id",required = false) String inst_id, + @RequestParam(value="client_id",required = false) String client_id) { + return buildMetadata(request,response,inst_id,client_id,ContentType.JSON); + } + + @Operation(summary = "OAuth JWk 元数据接口", description = "参数instId , clientId",method="GET") + @RequestMapping(value = OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/{instId}/{clientId}/jwks", + method={RequestMethod.POST, RequestMethod.GET}) + @ResponseBody + public String keysMetadatabyPath(HttpServletRequest request , HttpServletResponse response, + @PathVariable(value="instId") String instId, + @PathVariable(value="clientId") String clientId) { + return buildMetadata(request,response,instId,clientId,ContentType.JSON); + } + + @Operation(summary = "OAuth JWk 元数据接口", description = "参数mxk_metadata_clientId",method="GET") + @RequestMapping( + value = "/metadata/oauth/v20/" + WebConstants.MXK_METADATA_PREFIX + "{clientId}.{mediaType}", + method={RequestMethod.POST, RequestMethod.GET}) + @ResponseBody + public String metadata(HttpServletRequest request , HttpServletResponse response, + @PathVariable(value="clientId") String clientId, + @PathVariable(value="mediaType") String mediaType) { + return buildMetadata(request,response,null,clientId,mediaType); + } + + public String buildMetadata(HttpServletRequest request , HttpServletResponse response, + String instId,String clientId,String mediaType){ + ClientDetails clientDetails = null; + try { + clientDetails = getClientDetailsService().loadClientByClientId(clientId,true); + }catch(Exception e) { + _logger.error("getClientDetailsService", e); + } + if(clientDetails != null) { + String jwkSetString = ""; + if(!clientDetails.getSignature().equalsIgnoreCase("none")) { + jwkSetString = clientDetails.getSignatureKey(); + } + if(!clientDetails.getAlgorithm().equalsIgnoreCase("none")) { + if(!StringUtils.hasText(jwkSetString)) { + jwkSetString = clientDetails.getAlgorithmKey(); + }else { + jwkSetString = jwkSetString + "," +clientDetails.getAlgorithmKey(); + } + } + JWKSetKeyStore jwkSetKeyStore = new JWKSetKeyStore("{\"keys\": [" + jwkSetString + "]}"); + + if(StringUtils.hasText(mediaType) && mediaType.equalsIgnoreCase(ContentType.XML)) { + response.setContentType(ContentType.APPLICATION_XML_UTF8); + }else { + response.setContentType(ContentType.APPLICATION_JSON_UTF8); + } + return jwkSetKeyStore.toString(mediaType); + } else { + return clientId + " not exist . \n" + WebContext.version(); + } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/TokenEndpoint.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/TokenEndpoint.java index 660a6ff18..5e70122ad 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/TokenEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/TokenEndpoint.java @@ -77,174 +77,174 @@ import io.swagger.v3.oas.annotations.tags.Tag; @Controller public class TokenEndpoint extends AbstractEndpoint { - private OAuth2RequestValidator oAuth2RequestValidator = new DefaultOAuth2RequestValidator(); + private OAuth2RequestValidator oAuth2RequestValidator = new DefaultOAuth2RequestValidator(); - private Set allowedRequestMethods = new HashSet(Arrays.asList(HttpMethod.POST,HttpMethod.GET)); + private Set allowedRequestMethods = new HashSet(Arrays.asList(HttpMethod.POST,HttpMethod.GET)); - /** - * must use HTTP POST Method to get token - * HTTP GET is not Supported - * @param principal - * @param parameters - * @return OAuth2AccessToken Entity - * @throws HttpRequestMethodNotSupportedException - */ - @Operation(summary = "OAuth 2.0 获取AccessToken接口", description = "传递参数token等",method="GET") - @RequestMapping(value = { - OAuth2Constants.ENDPOINT.ENDPOINT_TOKEN, - OAuth2Constants.ENDPOINT.ENDPOINT_TENCENT_IOA_TOKEN - }, - method=RequestMethod.GET) - public ResponseEntity getAccessToken(@RequestParam - Map parameters) throws HttpRequestMethodNotSupportedException { - if (!allowedRequestMethods.contains(HttpMethod.GET)) { - throw new HttpRequestMethodNotSupportedException("GET"); - } - return postAccessToken(parameters); - } - - @Operation(summary = "OAuth 2.0 获取AccessToken接口", description = "传递参数token等",method="POST") - @RequestMapping(value = { - OAuth2Constants.ENDPOINT.ENDPOINT_TOKEN, - OAuth2Constants.ENDPOINT.ENDPOINT_TENCENT_IOA_TOKEN - }, - method=RequestMethod.POST) - public ResponseEntity postAccessToken(@RequestParam - Map parameters) throws HttpRequestMethodNotSupportedException { - // TokenEndpointAuthenticationFilter - OAuth2AccessToken token = null; - try { - Object principal = AuthorizationUtils.getAuthentication(); - - if (!(principal instanceof Authentication)) { - throw new InsufficientAuthenticationException( - "There is no client authentication. Try adding an appropriate authentication."); - } - - String clientId = getClientId((Authentication)principal); - ClientDetails authenticatedClient = getClientDetailsService().loadClientByClientId(clientId,true); - - TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient); - - if (clientId != null && !clientId.equals("")) { - // Only validate the client details if a client authenticated during this - // request. - if (!clientId.equals(tokenRequest.getClientId())) { - // double check to make sure that the client ID in the token request is the same as that in the - // authenticated client - throw new InvalidClientException("Given client ID does not match authenticated client"); - } - } - if (authenticatedClient != null) { - oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient); - } - if (!StringUtils.hasText(tokenRequest.getGrantType())) { - throw new InvalidRequestException("Missing grant type"); - } - if (tokenRequest.getGrantType().equals(OAuth2Constants.PARAMETER.GRANT_TYPE_IMPLICIT)) { - throw new InvalidGrantException("Implicit grant type not supported from token endpoint"); - } - - if (isAuthCodeRequest(parameters)) { - // The scope was requested or determined during the authorization step - if (!tokenRequest.getScope().isEmpty()) { - logger.debug("Clearing scope of incoming token request"); - tokenRequest.setScope(Collections. emptySet()); - } - } - - logger.debug("request parameters " + parameters); - // The scope was requested or determined during the authorization step - /**crystal.sea - * code must uuid format - */ - if (parameters.get(OAuth2Constants.PARAMETER.CODE) != null - &&!StringGenerator.uuidMatches(parameters.get(OAuth2Constants.PARAMETER.CODE))) { - throw new InvalidRequestException("The code is not valid format ."); - } - - if (isRefreshTokenRequest(parameters)) { - // A refresh token has its own default scopes, so we should ignore any added by the factory here. - tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Constants.PARAMETER.SCOPE))); - } - //granter grant access token - token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest); - if (token == null) { - throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType()); - } - }catch(OAuth2Exception oauth2Exception) { - token = new DefaultOAuth2AccessToken(oauth2Exception); - }catch(InsufficientAuthenticationException authenticationException) { - token = new DefaultOAuth2AccessToken(new OAuth2Exception(authenticationException.getMessage())); - } - return getResponse(token); + /** + * must use HTTP POST Method to get token + * HTTP GET is not Supported + * @param principal + * @param parameters + * @return OAuth2AccessToken Entity + * @throws HttpRequestMethodNotSupportedException + */ + @Operation(summary = "OAuth 2.0 获取AccessToken接口", description = "传递参数token等",method="GET") + @RequestMapping(value = { + OAuth2Constants.ENDPOINT.ENDPOINT_TOKEN, + OAuth2Constants.ENDPOINT.ENDPOINT_TENCENT_IOA_TOKEN + }, + method=RequestMethod.GET) + public ResponseEntity getAccessToken(@RequestParam + Map parameters) throws HttpRequestMethodNotSupportedException { + if (!allowedRequestMethods.contains(HttpMethod.GET)) { + throw new HttpRequestMethodNotSupportedException("GET"); + } + return postAccessToken(parameters); + } + + @Operation(summary = "OAuth 2.0 获取AccessToken接口", description = "传递参数token等",method="POST") + @RequestMapping(value = { + OAuth2Constants.ENDPOINT.ENDPOINT_TOKEN, + OAuth2Constants.ENDPOINT.ENDPOINT_TENCENT_IOA_TOKEN + }, + method=RequestMethod.POST) + public ResponseEntity postAccessToken(@RequestParam + Map parameters) throws HttpRequestMethodNotSupportedException { + // TokenEndpointAuthenticationFilter + OAuth2AccessToken token = null; + try { + Object principal = AuthorizationUtils.getAuthentication(); + + if (!(principal instanceof Authentication)) { + throw new InsufficientAuthenticationException( + "There is no client authentication. Try adding an appropriate authentication."); + } + + String clientId = getClientId((Authentication)principal); + ClientDetails authenticatedClient = getClientDetailsService().loadClientByClientId(clientId,true); + + TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient); + + if (clientId != null && !clientId.equals("")) { + // Only validate the client details if a client authenticated during this + // request. + if (!clientId.equals(tokenRequest.getClientId())) { + // double check to make sure that the client ID in the token request is the same as that in the + // authenticated client + throw new InvalidClientException("Given client ID does not match authenticated client"); + } + } + if (authenticatedClient != null) { + oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient); + } + if (!StringUtils.hasText(tokenRequest.getGrantType())) { + throw new InvalidRequestException("Missing grant type"); + } + if (tokenRequest.getGrantType().equals(OAuth2Constants.PARAMETER.GRANT_TYPE_IMPLICIT)) { + throw new InvalidGrantException("Implicit grant type not supported from token endpoint"); + } + + if (isAuthCodeRequest(parameters)) { + // The scope was requested or determined during the authorization step + if (!tokenRequest.getScope().isEmpty()) { + logger.debug("Clearing scope of incoming token request"); + tokenRequest.setScope(Collections. emptySet()); + } + } + + logger.debug("request parameters " + parameters); + // The scope was requested or determined during the authorization step + /**crystal.sea + * code must uuid format + */ + if (parameters.get(OAuth2Constants.PARAMETER.CODE) != null + &&!StringGenerator.uuidMatches(parameters.get(OAuth2Constants.PARAMETER.CODE))) { + throw new InvalidRequestException("The code is not valid format ."); + } + + if (isRefreshTokenRequest(parameters)) { + // A refresh token has its own default scopes, so we should ignore any added by the factory here. + tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Constants.PARAMETER.SCOPE))); + } + //granter grant access token + token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest); + if (token == null) { + throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType()); + } + }catch(OAuth2Exception oauth2Exception) { + token = new DefaultOAuth2AccessToken(oauth2Exception); + }catch(InsufficientAuthenticationException authenticationException) { + token = new DefaultOAuth2AccessToken(new OAuth2Exception(authenticationException.getMessage())); + } + return getResponse(token); - } + } - /** - * @param principal the currently authentication principal - * @return a client id if there is one in the principal - */ - protected String getClientId(Authentication principal) { - Authentication client = (Authentication) principal; - if (!client.isAuthenticated()) { - throw new InsufficientAuthenticationException("The client is not authenticated."); - } - String clientId = client.getPrincipal().toString(); - if (client instanceof OAuth2Authentication) { - // Might be a client and user combined authentication - clientId = ((OAuth2Authentication) client).getOAuth2Request().getClientId(); - } - if (client instanceof UsernamePasswordAuthenticationToken) { - clientId = ((SignPrincipal)client.getPrincipal()).getUsername(); - } - return clientId; - } - - - /** - * @param principal the currently authentication principal - * @return a client id if there is one in the principal - - protected String getClientId(Principal principal) { - Authentication client = (Authentication) principal; - if (!client.isAuthenticated()) { - throw new InsufficientAuthenticationException("The client is not authenticated."); - } - String clientId = client.getName(); - if (client instanceof OAuth2Authentication) { - // Might be a client and user combined authentication - clientId = ((OAuth2Authentication) client).getOAuth2Request().getClientId(); - } - return clientId; - } + /** + * @param principal the currently authentication principal + * @return a client id if there is one in the principal + */ + protected String getClientId(Authentication principal) { + Authentication client = (Authentication) principal; + if (!client.isAuthenticated()) { + throw new InsufficientAuthenticationException("The client is not authenticated."); + } + String clientId = client.getPrincipal().toString(); + if (client instanceof OAuth2Authentication) { + // Might be a client and user combined authentication + clientId = ((OAuth2Authentication) client).getOAuth2Request().getClientId(); + } + if (client instanceof UsernamePasswordAuthenticationToken) { + clientId = ((SignPrincipal)client.getPrincipal()).getUsername(); + } + return clientId; + } + + + /** + * @param principal the currently authentication principal + * @return a client id if there is one in the principal + + protected String getClientId(Principal principal) { + Authentication client = (Authentication) principal; + if (!client.isAuthenticated()) { + throw new InsufficientAuthenticationException("The client is not authenticated."); + } + String clientId = client.getName(); + if (client instanceof OAuth2Authentication) { + // Might be a client and user combined authentication + clientId = ((OAuth2Authentication) client).getOAuth2Request().getClientId(); + } + return clientId; + } */ - private ResponseEntity getResponse(OAuth2AccessToken accessToken) { - HttpHeaders headers = new HttpHeaders(); - headers.set("Cache-Control", "no-store"); - headers.set("Pragma", "no-cache"); - return new ResponseEntity(accessToken, headers, HttpStatus.OK); - } + private ResponseEntity getResponse(OAuth2AccessToken accessToken) { + HttpHeaders headers = new HttpHeaders(); + headers.set("Cache-Control", "no-store"); + headers.set("Pragma", "no-cache"); + return new ResponseEntity(accessToken, headers, HttpStatus.OK); + } - private boolean isRefreshTokenRequest(Map parameters) { - return OAuth2Constants.PARAMETER.GRANT_TYPE_REFRESH_TOKEN.equals(parameters.get(OAuth2Constants.PARAMETER.GRANT_TYPE)) - && parameters.get(OAuth2Constants.PARAMETER.GRANT_TYPE_REFRESH_TOKEN) != null; - } + private boolean isRefreshTokenRequest(Map parameters) { + return OAuth2Constants.PARAMETER.GRANT_TYPE_REFRESH_TOKEN.equals(parameters.get(OAuth2Constants.PARAMETER.GRANT_TYPE)) + && parameters.get(OAuth2Constants.PARAMETER.GRANT_TYPE_REFRESH_TOKEN) != null; + } - private boolean isAuthCodeRequest(Map parameters) { - return OAuth2Constants.PARAMETER.GRANT_TYPE_AUTHORIZATION_CODE.equals(parameters.get(OAuth2Constants.PARAMETER.GRANT_TYPE)) - && parameters.get(OAuth2Constants.PARAMETER.CODE) != null; - } + private boolean isAuthCodeRequest(Map parameters) { + return OAuth2Constants.PARAMETER.GRANT_TYPE_AUTHORIZATION_CODE.equals(parameters.get(OAuth2Constants.PARAMETER.GRANT_TYPE)) + && parameters.get(OAuth2Constants.PARAMETER.CODE) != null; + } - public void setOAuth2RequestValidator(OAuth2RequestValidator oAuth2RequestValidator) { - this.oAuth2RequestValidator = oAuth2RequestValidator; - } + public void setOAuth2RequestValidator(OAuth2RequestValidator oAuth2RequestValidator) { + this.oAuth2RequestValidator = oAuth2RequestValidator; + } - public void setAllowedRequestMethods(Set allowedRequestMethods) { - this.allowedRequestMethods = allowedRequestMethods; - } + public void setAllowedRequestMethods(Set allowedRequestMethods) { + this.allowedRequestMethods = allowedRequestMethods; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/TokenEndpointAuthenticationFilter.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/TokenEndpointAuthenticationFilter.java index 4e28b83c8..096b4a234 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/TokenEndpointAuthenticationFilter.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/TokenEndpointAuthenticationFilter.java @@ -80,276 +80,276 @@ import jakarta.servlet.http.HttpServletResponse; * @author Dave Syer * */ -@WebFilter( filterName = "TokenEndpointAuthenticationFilter", - urlPatterns = { - OAuth2Constants.ENDPOINT.ENDPOINT_TOKEN+"/*", - OAuth2Constants.ENDPOINT.ENDPOINT_TENCENT_IOA_TOKEN+"/*"}) +@WebFilter( filterName = "TokenEndpointAuthenticationFilter", + urlPatterns = { + OAuth2Constants.ENDPOINT.ENDPOINT_TOKEN+"/*", + OAuth2Constants.ENDPOINT.ENDPOINT_TENCENT_IOA_TOKEN+"/*"}) public class TokenEndpointAuthenticationFilter implements Filter { - static final Logger _logger = LoggerFactory.getLogger(TokenEndpointAuthenticationFilter.class); + static final Logger _logger = LoggerFactory.getLogger(TokenEndpointAuthenticationFilter.class); - private AuthenticationDetailsSource authenticationDetailsSource = new WebAuthenticationDetailsSource(); - boolean allowOnlyPost; - - private AuthenticationManager authenticationManager; - - private AuthenticationManager oauth20ClientAuthenticationManager; - - private OAuth2RequestFactory oAuth2RequestFactory; + private AuthenticationDetailsSource authenticationDetailsSource = new WebAuthenticationDetailsSource(); + boolean allowOnlyPost; + + private AuthenticationManager authenticationManager; + + private AuthenticationManager oauth20ClientAuthenticationManager; + + private OAuth2RequestFactory oAuth2RequestFactory; - public TokenEndpointAuthenticationFilter() { + public TokenEndpointAuthenticationFilter() { - } + } - /** - * @param authenticationManager an AuthenticationManager for the incoming request - */ - public TokenEndpointAuthenticationFilter(AuthenticationManager authenticationManager, OAuth2RequestFactory oAuth2RequestFactory) { - super(); - this.authenticationManager = authenticationManager; - this.oAuth2RequestFactory = oAuth2RequestFactory; - } + /** + * @param authenticationManager an AuthenticationManager for the incoming request + */ + public TokenEndpointAuthenticationFilter(AuthenticationManager authenticationManager, OAuth2RequestFactory oAuth2RequestFactory) { + super(); + this.authenticationManager = authenticationManager; + this.oAuth2RequestFactory = oAuth2RequestFactory; + } - /** - * A source of authentication details for requests that result in authentication. - * - * @param authenticationDetailsSource the authenticationDetailsSource to set - */ - public void setAuthenticationDetailsSource( - AuthenticationDetailsSource authenticationDetailsSource) { - this.authenticationDetailsSource = authenticationDetailsSource; - } + /** + * A source of authentication details for requests that result in authentication. + * + * @param authenticationDetailsSource the authenticationDetailsSource to set + */ + public void setAuthenticationDetailsSource( + AuthenticationDetailsSource authenticationDetailsSource) { + this.authenticationDetailsSource = authenticationDetailsSource; + } - public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, - ServletException { - _logger.debug("Authentication TokenEndpoint "); - if(authenticationManager==null) { - authenticationManager= WebContext.getBean("oauth20UserAuthenticationManager",AuthenticationManager.class); - } - if(oAuth2RequestFactory==null) { - oAuth2RequestFactory= WebContext.getBean("oAuth2RequestFactory",OAuth2RequestFactory.class); - } - if(oauth20ClientAuthenticationManager==null) { - oauth20ClientAuthenticationManager = WebContext.getBean("oauth20ClientAuthenticationManager",AuthenticationManager.class); - } - - final boolean debug = _logger.isDebugEnabled(); - final HttpServletRequest request = (HttpServletRequest) req; - final HttpServletResponse response = (HttpServletResponse) res; + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, + ServletException { + _logger.debug("Authentication TokenEndpoint "); + if(authenticationManager==null) { + authenticationManager= WebContext.getBean("oauth20UserAuthenticationManager",AuthenticationManager.class); + } + if(oAuth2RequestFactory==null) { + oAuth2RequestFactory= WebContext.getBean("oAuth2RequestFactory",OAuth2RequestFactory.class); + } + if(oauth20ClientAuthenticationManager==null) { + oauth20ClientAuthenticationManager = WebContext.getBean("oauth20ClientAuthenticationManager",AuthenticationManager.class); + } + + final boolean debug = _logger.isDebugEnabled(); + final HttpServletRequest request = (HttpServletRequest) req; + final HttpServletResponse response = (HttpServletResponse) res; - try { - String grantType = request.getParameter(OAuth2Constants.PARAMETER.GRANT_TYPE); - if (grantType != null && grantType.equals(OAuth2Constants.PARAMETER.GRANT_TYPE_PASSWORD)) { - //password - usernamepassword(request,response); - }else { - Authentication authentication=ClientCredentials(request,response); - _logger.trace("getPrincipal " + authentication.getPrincipal().getClass()); - SignPrincipal auth = null; - if(authentication.getPrincipal() instanceof SignPrincipal) { - //authorization_code - auth = (SignPrincipal)authentication.getPrincipal(); - }else { - //client_credentials - auth =new SignPrincipal((User)authentication.getPrincipal()); - } - auth.setAuthenticated(true); - UsernamePasswordAuthenticationToken simpleUserAuthentication = new UsernamePasswordAuthenticationToken(auth, authentication.getCredentials(), authentication.getAuthorities()); - AuthorizationUtils.setAuthentication(simpleUserAuthentication); - } + try { + String grantType = request.getParameter(OAuth2Constants.PARAMETER.GRANT_TYPE); + if (grantType != null && grantType.equals(OAuth2Constants.PARAMETER.GRANT_TYPE_PASSWORD)) { + //password + usernamepassword(request,response); + }else { + Authentication authentication=ClientCredentials(request,response); + _logger.trace("getPrincipal " + authentication.getPrincipal().getClass()); + SignPrincipal auth = null; + if(authentication.getPrincipal() instanceof SignPrincipal) { + //authorization_code + auth = (SignPrincipal)authentication.getPrincipal(); + }else { + //client_credentials + auth =new SignPrincipal((User)authentication.getPrincipal()); + } + auth.setAuthenticated(true); + UsernamePasswordAuthenticationToken simpleUserAuthentication = new UsernamePasswordAuthenticationToken(auth, authentication.getCredentials(), authentication.getAuthorities()); + AuthorizationUtils.setAuthentication(simpleUserAuthentication); + } - } - catch (AuthenticationException failed) { - SecurityContextHolder.clearContext(); + } + catch (AuthenticationException failed) { + SecurityContextHolder.clearContext(); - if (debug) { - _logger.debug("Authentication request for failed: " + failed); - } + if (debug) { + _logger.debug("Authentication request for failed: " + failed); + } - onUnsuccessfulAuthentication(request, response, failed); + onUnsuccessfulAuthentication(request, response, failed); - return; - } + return; + } - chain.doFilter(request, response); - } + chain.doFilter(request, response); + } - public void usernamepassword(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException { - _logger.debug("Authentication TokenEndpoint "); - - try { - Authentication credentials = extractCredentials(request); - - if (credentials != null) { - _logger.debug("Authentication credentials found for '" + credentials.getName() + "'"); - - Authentication authResult = authenticationManager.authenticate(credentials); - - _logger.debug("Authentication success: " + authResult.getName()); - String clientId = request.getParameter(OAuth2Constants.PARAMETER.CLIENT_ID); - String clientSecret = request.getParameter(OAuth2Constants.PARAMETER.CLIENT_SECRET); - UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId, - clientSecret); - Authentication clientAuth = oauth20ClientAuthenticationManager.authenticate(authRequest); - //Authentication clientAuth = SecurityContextHolder.getContext().getAuthentication(); - if (clientAuth == null) { - throw new BadCredentialsException( - "No client authentication found. Remember to put a filter upstream of the TokenEndpointAuthenticationFilter."); - } - - Map map = getSingleValueMap(request); - map.put(OAuth2Constants.PARAMETER.CLIENT_ID, clientAuth.getName()); - AuthorizationRequest authorizationRequest = oAuth2RequestFactory.createAuthorizationRequest(map); - - authorizationRequest.setScope(getScope(request)); - if (clientAuth.isAuthenticated()) { - // Ensure the OAuth2Authentication is authenticated - authorizationRequest.setApproved(true); - } - - OAuth2Request storedOAuth2Request = oAuth2RequestFactory.createOAuth2Request(authorizationRequest); - - AuthorizationUtils.setAuthentication(new OAuth2Authentication(storedOAuth2Request, authResult)); - - onSuccessfulAuthentication(request, response, authResult); - - } - - } - catch (AuthenticationException failed) { - SecurityContextHolder.clearContext(); - - _logger.debug("Authentication request for failed: " + failed); - - onUnsuccessfulAuthentication(request, response, failed); - - return; - } - } - - public Authentication ClientCredentials(HttpServletRequest request, HttpServletResponse response) - throws AuthenticationException, IOException, ServletException { - if (allowOnlyPost && !"POST".equalsIgnoreCase(request.getMethod())) { - throw new HttpRequestMethodNotSupportedException(request.getMethod(), Arrays.asList("POST","G")); - } + public void usernamepassword(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException { + _logger.debug("Authentication TokenEndpoint "); + + try { + Authentication credentials = extractCredentials(request); + + if (credentials != null) { + _logger.debug("Authentication credentials found for '" + credentials.getName() + "'"); + + Authentication authResult = authenticationManager.authenticate(credentials); + + _logger.debug("Authentication success: " + authResult.getName()); + String clientId = request.getParameter(OAuth2Constants.PARAMETER.CLIENT_ID); + String clientSecret = request.getParameter(OAuth2Constants.PARAMETER.CLIENT_SECRET); + UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId, + clientSecret); + Authentication clientAuth = oauth20ClientAuthenticationManager.authenticate(authRequest); + //Authentication clientAuth = SecurityContextHolder.getContext().getAuthentication(); + if (clientAuth == null) { + throw new BadCredentialsException( + "No client authentication found. Remember to put a filter upstream of the TokenEndpointAuthenticationFilter."); + } + + Map map = getSingleValueMap(request); + map.put(OAuth2Constants.PARAMETER.CLIENT_ID, clientAuth.getName()); + AuthorizationRequest authorizationRequest = oAuth2RequestFactory.createAuthorizationRequest(map); + + authorizationRequest.setScope(getScope(request)); + if (clientAuth.isAuthenticated()) { + // Ensure the OAuth2Authentication is authenticated + authorizationRequest.setApproved(true); + } + + OAuth2Request storedOAuth2Request = oAuth2RequestFactory.createOAuth2Request(authorizationRequest); + + AuthorizationUtils.setAuthentication(new OAuth2Authentication(storedOAuth2Request, authResult)); + + onSuccessfulAuthentication(request, response, authResult); + + } + + } + catch (AuthenticationException failed) { + SecurityContextHolder.clearContext(); + + _logger.debug("Authentication request for failed: " + failed); + + onUnsuccessfulAuthentication(request, response, failed); + + return; + } + } + + public Authentication ClientCredentials(HttpServletRequest request, HttpServletResponse response) + throws AuthenticationException, IOException, ServletException { + if (allowOnlyPost && !"POST".equalsIgnoreCase(request.getMethod())) { + throw new HttpRequestMethodNotSupportedException(request.getMethod(), Arrays.asList("POST","G")); + } - String clientId = request.getParameter(OAuth2Constants.PARAMETER.CLIENT_ID); - String clientSecret = request.getParameter(OAuth2Constants.PARAMETER.CLIENT_SECRET); - if(clientId == null) { - //for header authorization basic - String authorization_bearer =request.getHeader("authorization"); - AuthorizationHeader ahc=AuthorizationHeaderUtils.resolve(authorization_bearer); - clientId =ahc.getUsername(); - clientSecret=ahc.getCredential(); - } - - _logger.trace("clientId "+clientId +" , clientSecret " + clientSecret); + String clientId = request.getParameter(OAuth2Constants.PARAMETER.CLIENT_ID); + String clientSecret = request.getParameter(OAuth2Constants.PARAMETER.CLIENT_SECRET); + if(clientId == null) { + //for header authorization basic + String authorization_bearer =request.getHeader("authorization"); + AuthorizationHeader ahc=AuthorizationHeaderUtils.resolve(authorization_bearer); + clientId =ahc.getUsername(); + clientSecret=ahc.getCredential(); + } + + _logger.trace("clientId "+clientId +" , clientSecret " + clientSecret); - // If the request is already authenticated we can assume that this - // filter is not needed - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication != null && authentication.isAuthenticated()) { - return authentication; - } + // If the request is already authenticated we can assume that this + // filter is not needed + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication != null && authentication.isAuthenticated()) { + return authentication; + } - if (clientId == null) { - throw new BadCredentialsException("No client credentials presented"); - } + if (clientId == null) { + throw new BadCredentialsException("No client credentials presented"); + } - if (clientSecret == null) { - clientSecret = ""; - } + if (clientSecret == null) { + clientSecret = ""; + } - clientId = clientId.trim(); - UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId,clientSecret); + clientId = clientId.trim(); + UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId,clientSecret); - return this.oauth20ClientAuthenticationManager.authenticate(authRequest); - } - - private Map getSingleValueMap(HttpServletRequest request) { - Map map = new HashMap(); - Map parameters = request.getParameterMap(); - for (String key : parameters.keySet()) { - String[] values = parameters.get(key); - map.put(key, values != null && values.length > 0 ? values[0] : null); - } - return map; - } + return this.oauth20ClientAuthenticationManager.authenticate(authRequest); + } + + private Map getSingleValueMap(HttpServletRequest request) { + Map map = new HashMap(); + Map parameters = request.getParameterMap(); + for (String key : parameters.keySet()) { + String[] values = parameters.get(key); + map.put(key, values != null && values.length > 0 ? values[0] : null); + } + return map; + } - protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, - Authentication authResult) throws IOException { - } + protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, + Authentication authResult) throws IOException { + } - protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, - AuthenticationException failed) throws IOException { - } + protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, + AuthenticationException failed) throws IOException { + } - /** - * If the incoming request contains user credentials in headers or parameters then extract them here into an - * Authentication token that can be validated later. This implementation only recognises password grant requests and - * extracts the username and password. - * - * @param request the incoming request, possibly with user credentials - * @return an authentication for validation (or null if there is no further authentication) - */ - protected Authentication extractCredentials(HttpServletRequest request) { - String grantType = request.getParameter(OAuth2Constants.PARAMETER.GRANT_TYPE); - if (grantType != null && grantType.equals(OAuth2Constants.PARAMETER.GRANT_TYPE_PASSWORD)) { - UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken( - request.getParameter("username"), request.getParameter("password")); - result.setDetails(authenticationDetailsSource.buildDetails(request)); - return result; - } - return null; - } + /** + * If the incoming request contains user credentials in headers or parameters then extract them here into an + * Authentication token that can be validated later. This implementation only recognises password grant requests and + * extracts the username and password. + * + * @param request the incoming request, possibly with user credentials + * @return an authentication for validation (or null if there is no further authentication) + */ + protected Authentication extractCredentials(HttpServletRequest request) { + String grantType = request.getParameter(OAuth2Constants.PARAMETER.GRANT_TYPE); + if (grantType != null && grantType.equals(OAuth2Constants.PARAMETER.GRANT_TYPE_PASSWORD)) { + UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken( + request.getParameter("username"), request.getParameter("password")); + result.setDetails(authenticationDetailsSource.buildDetails(request)); + return result; + } + return null; + } - private Set getScope(HttpServletRequest request) { - return OAuth2Utils.parseParameterList(request.getParameter(OAuth2Constants.PARAMETER.SCOPE)); - } - - public void init(FilterConfig filterConfig) throws ServletException { - } + private Set getScope(HttpServletRequest request) { + return OAuth2Utils.parseParameterList(request.getParameter(OAuth2Constants.PARAMETER.SCOPE)); + } + + public void init(FilterConfig filterConfig) throws ServletException { + } - public void destroy() { - } - - - - protected static class ClientCredentialsRequestMatcher implements RequestMatcher { + public void destroy() { + } + + + + protected static class ClientCredentialsRequestMatcher implements RequestMatcher { - private String path; + private String path; - public ClientCredentialsRequestMatcher(String path) { - this.path = path; + public ClientCredentialsRequestMatcher(String path) { + this.path = path; - } + } - @Override - public boolean matches(HttpServletRequest request) { - String uri = request.getRequestURI(); - int pathParamIndex = uri.indexOf(';'); + @Override + public boolean matches(HttpServletRequest request) { + String uri = request.getRequestURI(); + int pathParamIndex = uri.indexOf(';'); - if (pathParamIndex > 0) { - // strip everything after the first semi-colon - uri = uri.substring(0, pathParamIndex); - } + if (pathParamIndex > 0) { + // strip everything after the first semi-colon + uri = uri.substring(0, pathParamIndex); + } - String clientId = request.getParameter(OAuth2Constants.PARAMETER.CLIENT_ID); + String clientId = request.getParameter(OAuth2Constants.PARAMETER.CLIENT_ID); - if (clientId == null) { - // Give basic auth a chance to work instead (it's preferred anyway) - return false; - } + if (clientId == null) { + // Give basic auth a chance to work instead (it's preferred anyway) + return false; + } - if ("".equals(request.getContextPath())) { - return uri.endsWith(path); - } + if ("".equals(request.getContextPath())) { + return uri.endsWith(path); + } - return uri.endsWith(request.getContextPath() + path); - } + return uri.endsWith(request.getContextPath() + path); + } - } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/TokenKeyEndpoint.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/TokenKeyEndpoint.java index 138ba851c..36f6b555a 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/TokenKeyEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/endpoint/TokenKeyEndpoint.java @@ -57,10 +57,10 @@ public class TokenKeyEndpoint { private JwtAccessTokenConverter converter; - public TokenKeyEndpoint(JwtAccessTokenConverter converter) { - super(); - this.converter = converter; - } + public TokenKeyEndpoint(JwtAccessTokenConverter converter) { + super(); + this.converter = converter; + } /** * Get the verification key for the token signatures. The principal has to diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/implicit/ImplicitGrantService.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/implicit/ImplicitGrantService.java index 1bdba2886..7ce4b33e0 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/implicit/ImplicitGrantService.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/implicit/ImplicitGrantService.java @@ -34,20 +34,20 @@ import org.dromara.maxkey.authz.oauth2.provider.TokenRequest; @Deprecated public interface ImplicitGrantService { - /** - * Save an association between an OAuth2Request and a TokenRequest. - * - * @param originalRequest - * @param tokenRequest - */ - public void store(OAuth2Request originalRequest, TokenRequest tokenRequest); - - /** - * Look up and return the OAuth2Request associated with the given TokenRequest. - * - * @param tokenRequest - * @return - */ - public OAuth2Request remove(TokenRequest tokenRequest); - + /** + * Save an association between an OAuth2Request and a TokenRequest. + * + * @param originalRequest + * @param tokenRequest + */ + public void store(OAuth2Request originalRequest, TokenRequest tokenRequest); + + /** + * Look up and return the OAuth2Request associated with the given TokenRequest. + * + * @param tokenRequest + * @return + */ + public OAuth2Request remove(TokenRequest tokenRequest); + } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/implicit/ImplicitTokenGranter.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/implicit/ImplicitTokenGranter.java index deed1a7b2..cd73ed902 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/implicit/ImplicitTokenGranter.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/implicit/ImplicitTokenGranter.java @@ -36,29 +36,29 @@ import org.springframework.util.Assert; */ public class ImplicitTokenGranter extends AbstractTokenGranter { - private static final String GRANT_TYPE = "implicit"; + private static final String GRANT_TYPE = "implicit"; - public ImplicitTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) { - super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE); - } + public ImplicitTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) { + super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE); + } - @Override - protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest clientToken) { + @Override + protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest clientToken) { - Authentication userAuth = SecurityContextHolder.getContext().getAuthentication(); - if (userAuth==null || !userAuth.isAuthenticated()) { - throw new InsufficientAuthenticationException("There is no currently logged in user"); - } - Assert.state(clientToken instanceof ImplicitTokenRequest, "An ImplicitTokenRequest is required here. Caller needs to wrap the TokenRequest."); - - OAuth2Request requestForStorage = ((ImplicitTokenRequest)clientToken).getOAuth2Request(); - - return new OAuth2Authentication(requestForStorage, userAuth); + Authentication userAuth = SecurityContextHolder.getContext().getAuthentication(); + if (userAuth==null || !userAuth.isAuthenticated()) { + throw new InsufficientAuthenticationException("There is no currently logged in user"); + } + Assert.state(clientToken instanceof ImplicitTokenRequest, "An ImplicitTokenRequest is required here. Caller needs to wrap the TokenRequest."); + + OAuth2Request requestForStorage = ((ImplicitTokenRequest)clientToken).getOAuth2Request(); + + return new OAuth2Authentication(requestForStorage, userAuth); - } - - @SuppressWarnings("deprecation") - public void setImplicitGrantService(ImplicitGrantService service) { - } + } + + @SuppressWarnings("deprecation") + public void setImplicitGrantService(ImplicitGrantService service) { + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/implicit/ImplicitTokenRequest.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/implicit/ImplicitTokenRequest.java index e23ecff72..791b444d0 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/implicit/ImplicitTokenRequest.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/implicit/ImplicitTokenRequest.java @@ -25,15 +25,15 @@ import org.dromara.maxkey.authz.oauth2.provider.TokenRequest; @SuppressWarnings("serial") public class ImplicitTokenRequest extends TokenRequest { - private OAuth2Request oauth2Request; + private OAuth2Request oauth2Request; - public ImplicitTokenRequest(TokenRequest tokenRequest, OAuth2Request oauth2Request) { - super(tokenRequest.getRequestParameters(), tokenRequest.getClientId(), tokenRequest.getScope(), tokenRequest.getGrantType()); - this.oauth2Request = oauth2Request; - } + public ImplicitTokenRequest(TokenRequest tokenRequest, OAuth2Request oauth2Request) { + super(tokenRequest.getRequestParameters(), tokenRequest.getClientId(), tokenRequest.getScope(), tokenRequest.getGrantType()); + this.oauth2Request = oauth2Request; + } - public OAuth2Request getOAuth2Request() { - return oauth2Request; - } + public OAuth2Request getOAuth2Request() { + return oauth2Request; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/implicit/InMemoryImplicitGrantService.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/implicit/InMemoryImplicitGrantService.java index d4d5e1c07..007f598c0 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/implicit/InMemoryImplicitGrantService.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/implicit/InMemoryImplicitGrantService.java @@ -31,15 +31,15 @@ import org.dromara.maxkey.authz.oauth2.provider.TokenRequest; @SuppressWarnings("deprecation") public class InMemoryImplicitGrantService implements ImplicitGrantService { - protected final ConcurrentHashMap requestStore = new ConcurrentHashMap(); - - public void store(OAuth2Request originalRequest, TokenRequest tokenRequest) { - this.requestStore.put(tokenRequest, originalRequest); - } + protected final ConcurrentHashMap requestStore = new ConcurrentHashMap(); + + public void store(OAuth2Request originalRequest, TokenRequest tokenRequest) { + this.requestStore.put(tokenRequest, originalRequest); + } - public OAuth2Request remove(TokenRequest tokenRequest) { - OAuth2Request request = this.requestStore.remove(tokenRequest); - return request; - } + public OAuth2Request remove(TokenRequest tokenRequest) { + OAuth2Request request = this.requestStore.remove(tokenRequest); + return request; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/password/ResourceOwnerPasswordTokenGranter.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/password/ResourceOwnerPasswordTokenGranter.java index d1441bf1e..2a4ae69cd 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/password/ResourceOwnerPasswordTokenGranter.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/password/ResourceOwnerPasswordTokenGranter.java @@ -40,42 +40,42 @@ import org.springframework.security.core.Authentication; */ public class ResourceOwnerPasswordTokenGranter extends AbstractTokenGranter { - private static final String GRANT_TYPE = "password"; + private static final String GRANT_TYPE = "password"; - private final AuthenticationManager authenticationManager; + private final AuthenticationManager authenticationManager; - public ResourceOwnerPasswordTokenGranter(AuthenticationManager authenticationManager, - AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) { - super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE); - this.authenticationManager = authenticationManager; - } + public ResourceOwnerPasswordTokenGranter(AuthenticationManager authenticationManager, + AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) { + super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE); + this.authenticationManager = authenticationManager; + } - @Override - protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { + @Override + protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { - Map parameters = new LinkedHashMap(tokenRequest.getRequestParameters()); - String username = parameters.get("username"); - String password = parameters.get("password"); - // Protect from downstream leaks of password - parameters.remove("password"); + Map parameters = new LinkedHashMap(tokenRequest.getRequestParameters()); + String username = parameters.get("username"); + String password = parameters.get("password"); + // Protect from downstream leaks of password + parameters.remove("password"); - Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password); - try { - userAuth = authenticationManager.authenticate(userAuth); - } - catch (AccountStatusException ase) { - //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31) - throw new InvalidGrantException(ase.getMessage()); - } - catch (BadCredentialsException e) { - // If the username/password are wrong the spec says we should send 400/invlid grant - throw new InvalidGrantException(e.getMessage()); - } - if (userAuth == null || !userAuth.isAuthenticated()) { - throw new InvalidGrantException("Could not authenticate user: " + username); - } - - OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest); - return new OAuth2Authentication(storedOAuth2Request, userAuth); - } + Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password); + try { + userAuth = authenticationManager.authenticate(userAuth); + } + catch (AccountStatusException ase) { + //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31) + throw new InvalidGrantException(ase.getMessage()); + } + catch (BadCredentialsException e) { + // If the username/password are wrong the spec says we should send 400/invlid grant + throw new InvalidGrantException(e.getMessage()); + } + if (userAuth == null || !userAuth.isAuthenticated()) { + throw new InvalidGrantException("Could not authenticate user: " + username); + } + + OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest); + return new OAuth2Authentication(storedOAuth2Request, userAuth); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/refresh/RefreshTokenGranter.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/refresh/RefreshTokenGranter.java index acac0da37..d100d7da7 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/refresh/RefreshTokenGranter.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/refresh/RefreshTokenGranter.java @@ -30,16 +30,16 @@ import org.dromara.maxkey.entity.apps.oauth2.provider.ClientDetails; */ public class RefreshTokenGranter extends AbstractTokenGranter { - private static final String GRANT_TYPE = "refresh_token"; + private static final String GRANT_TYPE = "refresh_token"; - public RefreshTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) { - super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE); - } - - @Override - protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) { - String refreshToken = tokenRequest.getRequestParameters().get("refresh_token"); - return getTokenServices().refreshAccessToken(refreshToken, tokenRequest); - } + public RefreshTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) { + super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE); + } + + @Override + protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) { + String refreshToken = tokenRequest.getRequestParameters().get("refresh_token"); + return getTokenServices().refreshAccessToken(refreshToken, tokenRequest); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/request/DefaultOAuth2RequestFactory.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/request/DefaultOAuth2RequestFactory.java index a2061c5e1..9ff3de860 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/request/DefaultOAuth2RequestFactory.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/request/DefaultOAuth2RequestFactory.java @@ -41,126 +41,126 @@ import org.springframework.security.core.authority.AuthorityUtils; */ public class DefaultOAuth2RequestFactory implements OAuth2RequestFactory { - private final ClientDetailsService clientDetailsService; + private final ClientDetailsService clientDetailsService; - private SecurityContextAccessor securityContextAccessor = new DefaultSecurityContextAccessor(); + private SecurityContextAccessor securityContextAccessor = new DefaultSecurityContextAccessor(); - private boolean checkUserScopes = false; + private boolean checkUserScopes = false; - public DefaultOAuth2RequestFactory(ClientDetailsService clientDetailsService) { - this.clientDetailsService = clientDetailsService; - } + public DefaultOAuth2RequestFactory(ClientDetailsService clientDetailsService) { + this.clientDetailsService = clientDetailsService; + } - /** - * @param securityContextAccessor the security context accessor to set - */ - public void setSecurityContextAccessor(SecurityContextAccessor securityContextAccessor) { - this.securityContextAccessor = securityContextAccessor; - } + /** + * @param securityContextAccessor the security context accessor to set + */ + public void setSecurityContextAccessor(SecurityContextAccessor securityContextAccessor) { + this.securityContextAccessor = securityContextAccessor; + } - /** - * Flag to indicate that scopes should be interpreted as valid authorities. No scopes will be granted to a user - * unless they are permitted as a granted authority to that user. - * - * @param checkUserScopes the checkUserScopes to set (default false) - */ - public void setCheckUserScopes(boolean checkUserScopes) { - this.checkUserScopes = checkUserScopes; - } + /** + * Flag to indicate that scopes should be interpreted as valid authorities. No scopes will be granted to a user + * unless they are permitted as a granted authority to that user. + * + * @param checkUserScopes the checkUserScopes to set (default false) + */ + public void setCheckUserScopes(boolean checkUserScopes) { + this.checkUserScopes = checkUserScopes; + } - public AuthorizationRequest createAuthorizationRequest(Map authorizationParameters) { + public AuthorizationRequest createAuthorizationRequest(Map authorizationParameters) { - String clientId = authorizationParameters.get(OAuth2Constants.PARAMETER.CLIENT_ID); - String state = authorizationParameters.get(OAuth2Constants.PARAMETER.STATE); - String redirectUri = authorizationParameters.get(OAuth2Constants.PARAMETER.REDIRECT_URI); - //oauth 2.1 PKCE - String codeChallenge = authorizationParameters.get(OAuth2Constants.PARAMETER.CODE_CHALLENGE); - String codeChallengeMethod = authorizationParameters.get(OAuth2Constants.PARAMETER.CODE_CHALLENGE_METHOD); - Set responseTypes = OAuth2Utils.parseParameterList(authorizationParameters - .get(OAuth2Constants.PARAMETER.RESPONSE_TYPE)); + String clientId = authorizationParameters.get(OAuth2Constants.PARAMETER.CLIENT_ID); + String state = authorizationParameters.get(OAuth2Constants.PARAMETER.STATE); + String redirectUri = authorizationParameters.get(OAuth2Constants.PARAMETER.REDIRECT_URI); + //oauth 2.1 PKCE + String codeChallenge = authorizationParameters.get(OAuth2Constants.PARAMETER.CODE_CHALLENGE); + String codeChallengeMethod = authorizationParameters.get(OAuth2Constants.PARAMETER.CODE_CHALLENGE_METHOD); + Set responseTypes = OAuth2Utils.parseParameterList(authorizationParameters + .get(OAuth2Constants.PARAMETER.RESPONSE_TYPE)); - Set scopes = extractScopes(authorizationParameters, clientId); - - AuthorizationRequest request = new AuthorizationRequest(authorizationParameters, - Collections. emptyMap(), clientId, scopes, null, null, false, state, redirectUri, - responseTypes,codeChallenge,codeChallengeMethod); + Set scopes = extractScopes(authorizationParameters, clientId); + + AuthorizationRequest request = new AuthorizationRequest(authorizationParameters, + Collections. emptyMap(), clientId, scopes, null, null, false, state, redirectUri, + responseTypes,codeChallenge,codeChallengeMethod); - ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId,true); - request.setResourceIdsAndAuthoritiesFromClientDetails(clientDetails); + ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId,true); + request.setResourceIdsAndAuthoritiesFromClientDetails(clientDetails); - return request; + return request; - } + } - public OAuth2Request createOAuth2Request(AuthorizationRequest request) { - return request.createOAuth2Request(); - } + public OAuth2Request createOAuth2Request(AuthorizationRequest request) { + return request.createOAuth2Request(); + } - public TokenRequest createTokenRequest(Map requestParameters, ClientDetails authenticatedClient) { + public TokenRequest createTokenRequest(Map requestParameters, ClientDetails authenticatedClient) { - String clientId = requestParameters.get(OAuth2Constants.PARAMETER.CLIENT_ID); - if (clientId == null) { - // if the clientId wasn't passed in in the map, we add pull it from the authenticated client object - clientId = authenticatedClient.getClientId(); - } - else { - // otherwise, make sure that they match - if (!clientId.equals(authenticatedClient.getClientId())) { - throw new InvalidClientException("Given client ID does not match authenticated client"); - } - } - String grantType = requestParameters.get(OAuth2Constants.PARAMETER.GRANT_TYPE); - if(StringUtils.isBlank(grantType)) { - //default client_credentials - grantType = OAuth2Constants.PARAMETER.GRANT_TYPE_CLIENT_CREDENTIALS; - } + String clientId = requestParameters.get(OAuth2Constants.PARAMETER.CLIENT_ID); + if (clientId == null) { + // if the clientId wasn't passed in in the map, we add pull it from the authenticated client object + clientId = authenticatedClient.getClientId(); + } + else { + // otherwise, make sure that they match + if (!clientId.equals(authenticatedClient.getClientId())) { + throw new InvalidClientException("Given client ID does not match authenticated client"); + } + } + String grantType = requestParameters.get(OAuth2Constants.PARAMETER.GRANT_TYPE); + if(StringUtils.isBlank(grantType)) { + //default client_credentials + grantType = OAuth2Constants.PARAMETER.GRANT_TYPE_CLIENT_CREDENTIALS; + } - Set scopes = extractScopes(requestParameters, clientId); - TokenRequest tokenRequest = new TokenRequest(requestParameters, clientId, scopes, grantType); + Set scopes = extractScopes(requestParameters, clientId); + TokenRequest tokenRequest = new TokenRequest(requestParameters, clientId, scopes, grantType); - return tokenRequest; - } + return tokenRequest; + } - public TokenRequest createTokenRequest(AuthorizationRequest authorizationRequest, String grantType) { - TokenRequest tokenRequest = new TokenRequest(authorizationRequest.getRequestParameters(), - authorizationRequest.getClientId(), authorizationRequest.getScope(), grantType); - return tokenRequest; - } + public TokenRequest createTokenRequest(AuthorizationRequest authorizationRequest, String grantType) { + TokenRequest tokenRequest = new TokenRequest(authorizationRequest.getRequestParameters(), + authorizationRequest.getClientId(), authorizationRequest.getScope(), grantType); + return tokenRequest; + } - public OAuth2Request createOAuth2Request(ClientDetails client, TokenRequest tokenRequest) { - return tokenRequest.createOAuth2Request(client); - } + public OAuth2Request createOAuth2Request(ClientDetails client, TokenRequest tokenRequest) { + return tokenRequest.createOAuth2Request(client); + } - private Set extractScopes(Map requestParameters, String clientId) { - Set scopes = OAuth2Utils.parseParameterList(requestParameters.get(OAuth2Constants.PARAMETER.SCOPE)); - ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId,true); + private Set extractScopes(Map requestParameters, String clientId) { + Set scopes = OAuth2Utils.parseParameterList(requestParameters.get(OAuth2Constants.PARAMETER.SCOPE)); + ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId,true); - if ((scopes == null || scopes.isEmpty())) { - // If no scopes are specified in the incoming data, use the default values registered with the client - // (the spec allows us to choose between this option and rejecting the request completely, so we'll take the - // least obnoxious choice as a default). - scopes = clientDetails.getScope(); - } + if ((scopes == null || scopes.isEmpty())) { + // If no scopes are specified in the incoming data, use the default values registered with the client + // (the spec allows us to choose between this option and rejecting the request completely, so we'll take the + // least obnoxious choice as a default). + scopes = clientDetails.getScope(); + } - if (checkUserScopes) { - scopes = checkUserScopes(scopes, clientDetails); - } - return scopes; - } + if (checkUserScopes) { + scopes = checkUserScopes(scopes, clientDetails); + } + return scopes; + } - private Set checkUserScopes(Set scopes, ClientDetails clientDetails) { - if (!securityContextAccessor.isUser()) { - return scopes; - } - Set result = new LinkedHashSet(); - Set authorities = AuthorityUtils.authorityListToSet(securityContextAccessor.getAuthorities()); - for (String scope : scopes) { - if (authorities.contains(scope) || authorities.contains(scope.toUpperCase()) - || authorities.contains("ROLE_" + scope.toUpperCase())) { - result.add(scope); - } - } - return result; - } + private Set checkUserScopes(Set scopes, ClientDetails clientDetails) { + if (!securityContextAccessor.isUser()) { + return scopes; + } + Set result = new LinkedHashSet(); + Set authorities = AuthorityUtils.authorityListToSet(securityContextAccessor.getAuthorities()); + for (String scope : scopes) { + if (authorities.contains(scope) || authorities.contains(scope.toUpperCase()) + || authorities.contains("ROLE_" + scope.toUpperCase())) { + result.add(scope); + } + } + return result; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/request/DefaultOAuth2RequestValidator.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/request/DefaultOAuth2RequestValidator.java index 3de5ce88a..f0dfdab6c 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/request/DefaultOAuth2RequestValidator.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/request/DefaultOAuth2RequestValidator.java @@ -33,27 +33,27 @@ import org.dromara.maxkey.entity.apps.oauth2.provider.ClientDetails; */ public class DefaultOAuth2RequestValidator implements OAuth2RequestValidator { - public void validateScope(AuthorizationRequest authorizationRequest, ClientDetails client) throws InvalidScopeException { - validateScope(authorizationRequest.getScope(), client.getScope()); - } + public void validateScope(AuthorizationRequest authorizationRequest, ClientDetails client) throws InvalidScopeException { + validateScope(authorizationRequest.getScope(), client.getScope()); + } - public void validateScope(TokenRequest tokenRequest, ClientDetails client) throws InvalidScopeException { - validateScope(tokenRequest.getScope(), client.getScope()); - } - - private void validateScope(Set requestScopes, Set clientScopes) { + public void validateScope(TokenRequest tokenRequest, ClientDetails client) throws InvalidScopeException { + validateScope(tokenRequest.getScope(), client.getScope()); + } + + private void validateScope(Set requestScopes, Set clientScopes) { - if (clientScopes != null && !clientScopes.isEmpty()) { - for (String scope : requestScopes) { - if (!clientScopes.contains(scope)) { - throw new InvalidScopeException("Invalid scope: " + scope, clientScopes); - } - } - } - - if (requestScopes.isEmpty()) { - throw new InvalidScopeException("Empty scope (either the client or the user is not allowed the requested scopes)"); - } - } + if (clientScopes != null && !clientScopes.isEmpty()) { + for (String scope : requestScopes) { + if (!clientScopes.contains(scope)) { + throw new InvalidScopeException("Invalid scope: " + scope, clientScopes); + } + } + } + + if (requestScopes.isEmpty()) { + throw new InvalidScopeException("Empty scope (either the client or the user is not allowed the requested scopes)"); + } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/AbstractTokenGranter.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/AbstractTokenGranter.java index 51e505232..1192418ae 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/AbstractTokenGranter.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/AbstractTokenGranter.java @@ -31,64 +31,64 @@ import org.dromara.maxkey.entity.apps.oauth2.provider.ClientDetails; * */ public abstract class AbstractTokenGranter implements TokenGranter { - - protected final Log logger = LogFactory.getLog(getClass()); + + protected final Log logger = LogFactory.getLog(getClass()); - private final AuthorizationServerTokenServices tokenServices; + private final AuthorizationServerTokenServices tokenServices; - private final ClientDetailsService clientDetailsService; - - private final OAuth2RequestFactory requestFactory; - - private final String grantType; + private final ClientDetailsService clientDetailsService; + + private final OAuth2RequestFactory requestFactory; + + private final String grantType; - protected AbstractTokenGranter(AuthorizationServerTokenServices tokenServices, - ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) { - this.clientDetailsService = clientDetailsService; - this.grantType = grantType; - this.tokenServices = tokenServices; - this.requestFactory = requestFactory; - } + protected AbstractTokenGranter(AuthorizationServerTokenServices tokenServices, + ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) { + this.clientDetailsService = clientDetailsService; + this.grantType = grantType; + this.tokenServices = tokenServices; + this.requestFactory = requestFactory; + } - public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) { + public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) { - if (!this.grantType.equals(grantType)) { - return null; - } - - String clientId = tokenRequest.getClientId(); - ClientDetails client = clientDetailsService.loadClientByClientId(clientId,true); - validateGrantType(grantType, client); - - logger.debug("Getting access token for: " + clientId); + if (!this.grantType.equals(grantType)) { + return null; + } + + String clientId = tokenRequest.getClientId(); + ClientDetails client = clientDetailsService.loadClientByClientId(clientId,true); + validateGrantType(grantType, client); + + logger.debug("Getting access token for: " + clientId); - return getAccessToken(client, tokenRequest); + return getAccessToken(client, tokenRequest); - } + } - protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) { - return tokenServices.createAccessToken(getOAuth2Authentication(client, tokenRequest)); - } + protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) { + return tokenServices.createAccessToken(getOAuth2Authentication(client, tokenRequest)); + } - protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { - OAuth2Request storedOAuth2Request = requestFactory.createOAuth2Request(client, tokenRequest); - return new OAuth2Authentication(storedOAuth2Request, null); - } + protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { + OAuth2Request storedOAuth2Request = requestFactory.createOAuth2Request(client, tokenRequest); + return new OAuth2Authentication(storedOAuth2Request, null); + } - protected void validateGrantType(String grantType, ClientDetails clientDetails) { - Collection authorizedGrantTypes = clientDetails.getAuthorizedGrantTypes(); - if (authorizedGrantTypes != null && !authorizedGrantTypes.isEmpty() - && !authorizedGrantTypes.contains(grantType)) { - throw new InvalidClientException("Unauthorized grant type: " + grantType); - } - } + protected void validateGrantType(String grantType, ClientDetails clientDetails) { + Collection authorizedGrantTypes = clientDetails.getAuthorizedGrantTypes(); + if (authorizedGrantTypes != null && !authorizedGrantTypes.isEmpty() + && !authorizedGrantTypes.contains(grantType)) { + throw new InvalidClientException("Unauthorized grant type: " + grantType); + } + } - protected AuthorizationServerTokenServices getTokenServices() { - return tokenServices; - } - - protected OAuth2RequestFactory getRequestFactory() { - return requestFactory; - } + protected AuthorizationServerTokenServices getTokenServices() { + return tokenServices; + } + + protected OAuth2RequestFactory getRequestFactory() { + return requestFactory; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/AccessTokenConverter.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/AccessTokenConverter.java index 1d1e663ad..77cae8e54 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/AccessTokenConverter.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/AccessTokenConverter.java @@ -42,48 +42,48 @@ import org.dromara.maxkey.authz.oauth2.provider.OAuth2Authentication; */ public interface AccessTokenConverter { - final String AUD = "aud"; + final String AUD = "aud"; - final String CLIENT_ID = "client_id"; + final String CLIENT_ID = "client_id"; - final String EXP = "exp"; + final String EXP = "exp"; - final String JTI = "jti"; - - final String GRANT_TYPE = "grant_type"; + final String JTI = "jti"; + + final String GRANT_TYPE = "grant_type"; - final String ATI = "ati"; + final String ATI = "ati"; - final String SCOPE = OAuth2AccessToken.SCOPE; + final String SCOPE = OAuth2AccessToken.SCOPE; - final String AUTHORITIES = "authorities"; + final String AUTHORITIES = "authorities"; - /** - * @param token an access token - * @param authentication the current OAuth authentication - * - * @return a map representation of the token suitable for a JSON response - * - */ - Map convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication); + /** + * @param token an access token + * @param authentication the current OAuth authentication + * + * @return a map representation of the token suitable for a JSON response + * + */ + Map convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication); - /** - * Recover an access token from the converted value. Half the inverse of - * {@link #convertAccessToken(OAuth2AccessToken, OAuth2Authentication)}. - * - * @param value the token value - * @param map information decoded from an access token - * @return an access token - */ - OAuth2AccessToken extractAccessToken(String value, Map map); + /** + * Recover an access token from the converted value. Half the inverse of + * {@link #convertAccessToken(OAuth2AccessToken, OAuth2Authentication)}. + * + * @param value the token value + * @param map information decoded from an access token + * @return an access token + */ + OAuth2AccessToken extractAccessToken(String value, Map map); - /** - * Recover an {@link OAuth2Authentication} from the converted access token. Half the inverse of - * {@link #convertAccessToken(OAuth2AccessToken, OAuth2Authentication)}. - * - * @param map information decoded from an access token - * @return an authentication representing the client and user (if there is one) - */ - OAuth2Authentication extractAuthentication(Map map); + /** + * Recover an {@link OAuth2Authentication} from the converted access token. Half the inverse of + * {@link #convertAccessToken(OAuth2AccessToken, OAuth2Authentication)}. + * + * @param map information decoded from an access token + * @return an authentication representing the client and user (if there is one) + */ + OAuth2Authentication extractAuthentication(Map map); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/AuthenticationKeyGenerator.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/AuthenticationKeyGenerator.java index 0617b6da3..dd75c16bf 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/AuthenticationKeyGenerator.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/AuthenticationKeyGenerator.java @@ -22,10 +22,10 @@ import org.dromara.maxkey.authz.oauth2.provider.OAuth2Authentication; */ public interface AuthenticationKeyGenerator { - /** - * @param authentication an OAuth2Authentication - * @return a unique key identifying the authentication - */ - String extractKey(OAuth2Authentication authentication); + /** + * @param authentication an OAuth2Authentication + * @return a unique key identifying the authentication + */ + String extractKey(OAuth2Authentication authentication); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/AuthorizationServerTokenServices.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/AuthorizationServerTokenServices.java index 85a3376d3..5fa72f6e0 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/AuthorizationServerTokenServices.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/AuthorizationServerTokenServices.java @@ -27,34 +27,34 @@ import org.springframework.security.core.AuthenticationException; */ public interface AuthorizationServerTokenServices { - /** - * Create an access token associated with the specified credentials. - * @param authentication The credentials associated with the access token. - * @return The access token. - * @throws AuthenticationException If the credentials are inadequate. - */ - OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException; + /** + * Create an access token associated with the specified credentials. + * @param authentication The credentials associated with the access token. + * @return The access token. + * @throws AuthenticationException If the credentials are inadequate. + */ + OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException; - /** - * Refresh an access token. The authorization request should be used for 2 things (at least): to validate that the - * client id of the original access token is the same as the one requesting the refresh, and to narrow the scopes - * (if provided). - * - * @param refreshToken The details about the refresh token. - * @param tokenRequest The incoming token request. - * @return The (new) access token. - * @throws AuthenticationException If the refresh token is invalid or expired. - */ - OAuth2AccessToken refreshAccessToken(String refreshToken, TokenRequest tokenRequest) - throws AuthenticationException; + /** + * Refresh an access token. The authorization request should be used for 2 things (at least): to validate that the + * client id of the original access token is the same as the one requesting the refresh, and to narrow the scopes + * (if provided). + * + * @param refreshToken The details about the refresh token. + * @param tokenRequest The incoming token request. + * @return The (new) access token. + * @throws AuthenticationException If the refresh token is invalid or expired. + */ + OAuth2AccessToken refreshAccessToken(String refreshToken, TokenRequest tokenRequest) + throws AuthenticationException; - /** - * Retrieve an access token stored against the provided authentication key, if it exists. - * - * @param authentication the authentication key for the access token - * - * @return the access token or null if there was none - */ - OAuth2AccessToken getAccessToken(OAuth2Authentication authentication); + /** + * Retrieve an access token stored against the provided authentication key, if it exists. + * + * @param authentication the authentication key for the access token + * + * @return the access token or null if there was none + */ + OAuth2AccessToken getAccessToken(OAuth2Authentication authentication); } \ No newline at end of file diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/ConsumerTokenServices.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/ConsumerTokenServices.java index 901e7e407..8b6161954 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/ConsumerTokenServices.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/ConsumerTokenServices.java @@ -18,7 +18,7 @@ package org.dromara.maxkey.authz.oauth2.provider.token; * */ public interface ConsumerTokenServices { - - boolean revokeToken(String tokenValue); + + boolean revokeToken(String tokenValue); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/DefaultAccessTokenConverter.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/DefaultAccessTokenConverter.java index b74863682..72b2397a8 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/DefaultAccessTokenConverter.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/DefaultAccessTokenConverter.java @@ -54,115 +54,115 @@ import org.springframework.security.core.authority.AuthorityUtils; */ public class DefaultAccessTokenConverter implements AccessTokenConverter { - private UserAuthenticationConverter userTokenConverter = new DefaultUserAuthenticationConverter(); - - private boolean includeGrantType; + private UserAuthenticationConverter userTokenConverter = new DefaultUserAuthenticationConverter(); + + private boolean includeGrantType; - /** - * Converter for the part of the data in the token representing a user. - * - * @param userTokenConverter the userTokenConverter to set - */ - public void setUserTokenConverter(UserAuthenticationConverter userTokenConverter) { - this.userTokenConverter = userTokenConverter; - } + /** + * Converter for the part of the data in the token representing a user. + * + * @param userTokenConverter the userTokenConverter to set + */ + public void setUserTokenConverter(UserAuthenticationConverter userTokenConverter) { + this.userTokenConverter = userTokenConverter; + } - /** - * Flag to indicate the the grant type should be included in the converted token. - * - * @param includeGrantType the flag value (default false) - */ - public void setIncludeGrantType(boolean includeGrantType) { - this.includeGrantType = includeGrantType; - } + /** + * Flag to indicate the the grant type should be included in the converted token. + * + * @param includeGrantType the flag value (default false) + */ + public void setIncludeGrantType(boolean includeGrantType) { + this.includeGrantType = includeGrantType; + } - public Map convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { - Map response = new HashMap(); - OAuth2Request clientToken = authentication.getOAuth2Request(); + public Map convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { + Map response = new HashMap(); + OAuth2Request clientToken = authentication.getOAuth2Request(); - if (!authentication.isClientOnly()) { - response.putAll(userTokenConverter.convertUserAuthentication(authentication.getUserAuthentication())); - } else { - if (clientToken.getAuthorities()!=null && !clientToken.getAuthorities().isEmpty()) { - response.put(UserAuthenticationConverter.AUTHORITIES, - AuthorityUtils.authorityListToSet(clientToken.getAuthorities())); - } - } + if (!authentication.isClientOnly()) { + response.putAll(userTokenConverter.convertUserAuthentication(authentication.getUserAuthentication())); + } else { + if (clientToken.getAuthorities()!=null && !clientToken.getAuthorities().isEmpty()) { + response.put(UserAuthenticationConverter.AUTHORITIES, + AuthorityUtils.authorityListToSet(clientToken.getAuthorities())); + } + } - if (token.getScope()!=null) { - response.put(SCOPE, token.getScope()); - } - if (token.getAdditionalInformation().containsKey(JTI)) { - response.put(JTI, token.getAdditionalInformation().get(JTI)); - } + if (token.getScope()!=null) { + response.put(SCOPE, token.getScope()); + } + if (token.getAdditionalInformation().containsKey(JTI)) { + response.put(JTI, token.getAdditionalInformation().get(JTI)); + } - if (token.getExpiration() != null) { - response.put(EXP, token.getExpiration().getTime() / 1000); - } - - if (includeGrantType && authentication.getOAuth2Request().getGrantType()!=null) { - response.put(GRANT_TYPE, authentication.getOAuth2Request().getGrantType()); - } + if (token.getExpiration() != null) { + response.put(EXP, token.getExpiration().getTime() / 1000); + } + + if (includeGrantType && authentication.getOAuth2Request().getGrantType()!=null) { + response.put(GRANT_TYPE, authentication.getOAuth2Request().getGrantType()); + } - response.putAll(token.getAdditionalInformation()); + response.putAll(token.getAdditionalInformation()); - response.put(CLIENT_ID, clientToken.getClientId()); - if (clientToken.getResourceIds() != null && !clientToken.getResourceIds().isEmpty()) { - response.put(AUD, clientToken.getResourceIds()); - } - - //default - response.put("active", Boolean.TRUE); - - return response; - } + response.put(CLIENT_ID, clientToken.getClientId()); + if (clientToken.getResourceIds() != null && !clientToken.getResourceIds().isEmpty()) { + response.put(AUD, clientToken.getResourceIds()); + } + + //default + response.put("active", Boolean.TRUE); + + return response; + } - public OAuth2AccessToken extractAccessToken(String value, Map map) { - DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(value); - Map info = new HashMap(map); - info.remove(EXP); - info.remove(AUD); - info.remove(CLIENT_ID); - info.remove(SCOPE); - if (map.containsKey(EXP)) { - token.setExpiration(new Date((Long) map.get(EXP) * 1000L)); - } - if (map.containsKey(JTI)) { - info.put(JTI, map.get(JTI)); - } - @SuppressWarnings("unchecked") - Collection scope = (Collection) map.get(SCOPE); - if (scope != null) { - token.setScope(new HashSet(scope)); - } - token.setAdditionalInformation(info); - return token; - } + public OAuth2AccessToken extractAccessToken(String value, Map map) { + DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(value); + Map info = new HashMap(map); + info.remove(EXP); + info.remove(AUD); + info.remove(CLIENT_ID); + info.remove(SCOPE); + if (map.containsKey(EXP)) { + token.setExpiration(new Date((Long) map.get(EXP) * 1000L)); + } + if (map.containsKey(JTI)) { + info.put(JTI, map.get(JTI)); + } + @SuppressWarnings("unchecked") + Collection scope = (Collection) map.get(SCOPE); + if (scope != null) { + token.setScope(new HashSet(scope)); + } + token.setAdditionalInformation(info); + return token; + } - public OAuth2Authentication extractAuthentication(Map map) { - Map parameters = new HashMap(); - @SuppressWarnings("unchecked") - Set scope = new LinkedHashSet(map.containsKey(SCOPE) ? (Collection) map.get(SCOPE) - : Collections.emptySet()); - Authentication user = userTokenConverter.extractAuthentication(map); - String clientId = (String) map.get(CLIENT_ID); - parameters.put(CLIENT_ID, clientId); - if (includeGrantType && map.containsKey(GRANT_TYPE)) { - parameters.put(GRANT_TYPE, (String) map.get(GRANT_TYPE)); - } - @SuppressWarnings("unchecked") - Set resourceIds = new LinkedHashSet(map.containsKey(AUD) ? (Collection) map.get(AUD) - : Collections.emptySet()); - - Collection authorities = null; - if (user==null && map.containsKey(AUTHORITIES)) { - @SuppressWarnings("unchecked") - String[] roles = ((Collection)map.get(AUTHORITIES)).toArray(new String[0]); - authorities = AuthorityUtils.createAuthorityList(roles); - } - OAuth2Request request = new OAuth2Request(parameters, clientId, authorities, true, scope, resourceIds, null, null, - null, null, null); - return new OAuth2Authentication(request, user); - } + public OAuth2Authentication extractAuthentication(Map map) { + Map parameters = new HashMap(); + @SuppressWarnings("unchecked") + Set scope = new LinkedHashSet(map.containsKey(SCOPE) ? (Collection) map.get(SCOPE) + : Collections.emptySet()); + Authentication user = userTokenConverter.extractAuthentication(map); + String clientId = (String) map.get(CLIENT_ID); + parameters.put(CLIENT_ID, clientId); + if (includeGrantType && map.containsKey(GRANT_TYPE)) { + parameters.put(GRANT_TYPE, (String) map.get(GRANT_TYPE)); + } + @SuppressWarnings("unchecked") + Set resourceIds = new LinkedHashSet(map.containsKey(AUD) ? (Collection) map.get(AUD) + : Collections.emptySet()); + + Collection authorities = null; + if (user==null && map.containsKey(AUTHORITIES)) { + @SuppressWarnings("unchecked") + String[] roles = ((Collection)map.get(AUTHORITIES)).toArray(new String[0]); + authorities = AuthorityUtils.createAuthorityList(roles); + } + OAuth2Request request = new OAuth2Request(parameters, clientId, authorities, true, scope, resourceIds, null, null, + null, null, null); + return new OAuth2Authentication(request, user); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/DefaultAuthenticationKeyGenerator.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/DefaultAuthenticationKeyGenerator.java index c58107b79..66693bb03 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/DefaultAuthenticationKeyGenerator.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/DefaultAuthenticationKeyGenerator.java @@ -32,37 +32,37 @@ import org.dromara.maxkey.authz.oauth2.provider.OAuth2Request; */ public class DefaultAuthenticationKeyGenerator implements AuthenticationKeyGenerator { - private static final String CLIENT_ID = "client_id"; + private static final String CLIENT_ID = "client_id"; - private static final String SCOPE = "scope"; + private static final String SCOPE = "scope"; - private static final String USERNAME = "username"; + private static final String USERNAME = "username"; - public String extractKey(OAuth2Authentication authentication) { - Map values = new LinkedHashMap(); - OAuth2Request authorizationRequest = authentication.getOAuth2Request(); - if (!authentication.isClientOnly()) { - values.put(USERNAME, authentication.getName()); - } - values.put(CLIENT_ID, authorizationRequest.getClientId()); - if (authorizationRequest.getScope() != null) { - values.put(SCOPE, OAuth2Utils.formatParameterList(authorizationRequest.getScope())); - } - MessageDigest digest; - try { - digest = MessageDigest.getInstance("MD5"); - } - catch (NoSuchAlgorithmException e) { - throw new IllegalStateException("MD5 algorithm not available. Fatal (should be in the JDK)."); - } + public String extractKey(OAuth2Authentication authentication) { + Map values = new LinkedHashMap(); + OAuth2Request authorizationRequest = authentication.getOAuth2Request(); + if (!authentication.isClientOnly()) { + values.put(USERNAME, authentication.getName()); + } + values.put(CLIENT_ID, authorizationRequest.getClientId()); + if (authorizationRequest.getScope() != null) { + values.put(SCOPE, OAuth2Utils.formatParameterList(authorizationRequest.getScope())); + } + MessageDigest digest; + try { + digest = MessageDigest.getInstance("MD5"); + } + catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("MD5 algorithm not available. Fatal (should be in the JDK)."); + } - try { - byte[] bytes = digest.digest(values.toString().getBytes("UTF-8")); - return String.format("%032x", new BigInteger(1, bytes)); - } - catch (UnsupportedEncodingException e) { - throw new IllegalStateException("UTF-8 encoding not available. Fatal (should be in the JDK)."); - } - } + try { + byte[] bytes = digest.digest(values.toString().getBytes("UTF-8")); + return String.format("%032x", new BigInteger(1, bytes)); + } + catch (UnsupportedEncodingException e) { + throw new IllegalStateException("UTF-8 encoding not available. Fatal (should be in the JDK)."); + } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/DefaultTokenServices.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/DefaultTokenServices.java index 925eb76f1..0e5971602 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/DefaultTokenServices.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/DefaultTokenServices.java @@ -62,416 +62,416 @@ import org.springframework.util.Assert; * @author Dave Syer */ public class DefaultTokenServices implements AuthorizationServerTokenServices, ResourceServerTokenServices, - ConsumerTokenServices, InitializingBean { - static final Logger _logger = LoggerFactory.getLogger(DefaultTokenServices.class); + ConsumerTokenServices, InitializingBean { + static final Logger _logger = LoggerFactory.getLogger(DefaultTokenServices.class); - private int refreshTokenValiditySeconds = 60 * 60 * 24 * 30; // default 30 days. + private int refreshTokenValiditySeconds = 60 * 60 * 24 * 30; // default 30 days. - private int accessTokenValiditySeconds = 60 * 60 * 12; // default 12 hours. + private int accessTokenValiditySeconds = 60 * 60 * 12; // default 12 hours. - private boolean supportRefreshToken = false; + private boolean supportRefreshToken = false; - private boolean reuseRefreshToken = true; + private boolean reuseRefreshToken = true; - private TokenStore tokenStore; + private TokenStore tokenStore; - private ClientDetailsService clientDetailsService; + private ClientDetailsService clientDetailsService; - private TokenEnhancer accessTokenEnhancer; + private TokenEnhancer accessTokenEnhancer; - private AuthenticationManager authenticationManager; - - private AppsService appsService; - - private SessionManager sessionManager; + private AuthenticationManager authenticationManager; + + private AppsService appsService; + + private SessionManager sessionManager; - /** - * Initialize these token services. If no random generator is set, one will be created. - */ - public void afterPropertiesSet() throws Exception { - Assert.notNull(tokenStore, "tokenStore must be set"); - } + /** + * Initialize these token services. If no random generator is set, one will be created. + */ + public void afterPropertiesSet() throws Exception { + Assert.notNull(tokenStore, "tokenStore must be set"); + } private void saveVisited(OAuth2Authentication authentication, OAuth2AccessToken accessToken) { - //存储oauth、oidc等的token,用户退出时清除 - if(authentication.getUserAuthentication().getPrincipal() instanceof SignPrincipal principal) { - _logger.debug("{}({}) , session {} access for logout clear ", - principal.getUsername(),principal.getUserId(),principal.getSessionId()); - String clientId = authentication.getOAuth2Request().getRequestParameters().get(OAuth2Constants.PARAMETER.CLIENT_ID); - _logger.debug("client_id {} token {}",clientId, accessToken); - Apps app = appsService.get(clientId, true); - VisitedDto visited = new VisitedDto(app,principal.getSessionId()); - visited.setToken(accessToken.getValue()); - if (Objects.nonNull(accessToken.getRefreshToken())) { - visited.setRefreshToken(accessToken.getRefreshToken().getValue()); - } - sessionManager.visited(principal.getSessionId(), visited); - } - } + //存储oauth、oidc等的token,用户退出时清除 + if(authentication.getUserAuthentication().getPrincipal() instanceof SignPrincipal principal) { + _logger.debug("{}({}) , session {} access for logout clear ", + principal.getUsername(),principal.getUserId(),principal.getSessionId()); + String clientId = authentication.getOAuth2Request().getRequestParameters().get(OAuth2Constants.PARAMETER.CLIENT_ID); + _logger.debug("client_id {} token {}",clientId, accessToken); + Apps app = appsService.get(clientId, true); + VisitedDto visited = new VisitedDto(app,principal.getSessionId()); + visited.setToken(accessToken.getValue()); + if (Objects.nonNull(accessToken.getRefreshToken())) { + visited.setRefreshToken(accessToken.getRefreshToken().getValue()); + } + sessionManager.visited(principal.getSessionId(), visited); + } + } - @Transactional - public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException { + @Transactional + public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException { - OAuth2AccessToken existingAccessToken = tokenStore.getAccessToken(authentication); - OAuth2RefreshToken refreshToken = null; - if (existingAccessToken != null) { - if (existingAccessToken.isExpired()) { - if (existingAccessToken.getRefreshToken() != null) { - refreshToken = existingAccessToken.getRefreshToken(); - // The token store could remove the refresh token when the - // access token is removed, but we want to - // be sure... - tokenStore.removeRefreshToken(refreshToken); - } - tokenStore.removeAccessToken(existingAccessToken); - } - else { - // Re-store the access token in case the authentication has changed - tokenStore.storeAccessToken(existingAccessToken, authentication); + OAuth2AccessToken existingAccessToken = tokenStore.getAccessToken(authentication); + OAuth2RefreshToken refreshToken = null; + if (existingAccessToken != null) { + if (existingAccessToken.isExpired()) { + if (existingAccessToken.getRefreshToken() != null) { + refreshToken = existingAccessToken.getRefreshToken(); + // The token store could remove the refresh token when the + // access token is removed, but we want to + // be sure... + tokenStore.removeRefreshToken(refreshToken); + } + tokenStore.removeAccessToken(existingAccessToken); + } + else { + // Re-store the access token in case the authentication has changed + tokenStore.storeAccessToken(existingAccessToken, authentication); saveVisited(authentication, existingAccessToken); - return enhancerToken(existingAccessToken, authentication); - } - } + return enhancerToken(existingAccessToken, authentication); + } + } - // Only create a new refresh token if there wasn't an existing one - // associated with an expired access token. - // Clients might be holding existing refresh tokens, so we re-use it in - // the case that the old access token - // expired. - if (refreshToken == null) { - refreshToken = createRefreshToken(authentication); - } - // But the refresh token itself might need to be re-issued if it has - // expired. - else if (refreshToken instanceof ExpiringOAuth2RefreshToken) { - ExpiringOAuth2RefreshToken expiring = (ExpiringOAuth2RefreshToken) refreshToken; - if (System.currentTimeMillis() > expiring.getExpiration().getTime()) { - refreshToken = createRefreshToken(authentication); - } - } + // Only create a new refresh token if there wasn't an existing one + // associated with an expired access token. + // Clients might be holding existing refresh tokens, so we re-use it in + // the case that the old access token + // expired. + if (refreshToken == null) { + refreshToken = createRefreshToken(authentication); + } + // But the refresh token itself might need to be re-issued if it has + // expired. + else if (refreshToken instanceof ExpiringOAuth2RefreshToken) { + ExpiringOAuth2RefreshToken expiring = (ExpiringOAuth2RefreshToken) refreshToken; + if (System.currentTimeMillis() > expiring.getExpiration().getTime()) { + refreshToken = createRefreshToken(authentication); + } + } - OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken); - tokenStore.storeAccessToken(accessToken, authentication); - // In case it was modified - refreshToken = accessToken.getRefreshToken(); - if (refreshToken != null) { - tokenStore.storeRefreshToken(refreshToken, authentication); - } - saveVisited(authentication, accessToken); - return accessToken; + OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken); + tokenStore.storeAccessToken(accessToken, authentication); + // In case it was modified + refreshToken = accessToken.getRefreshToken(); + if (refreshToken != null) { + tokenStore.storeRefreshToken(refreshToken, authentication); + } + saveVisited(authentication, accessToken); + return accessToken; - } + } - @Transactional(noRollbackFor={InvalidTokenException.class, InvalidGrantException.class}) - public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest tokenRequest) - throws AuthenticationException { + @Transactional(noRollbackFor={InvalidTokenException.class, InvalidGrantException.class}) + public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest tokenRequest) + throws AuthenticationException { - if (!supportRefreshToken) { - throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue); - } + if (!supportRefreshToken) { + throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue); + } - OAuth2RefreshToken refreshToken = tokenStore.readRefreshToken(refreshTokenValue); - if (refreshToken == null) { - throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue); - } + OAuth2RefreshToken refreshToken = tokenStore.readRefreshToken(refreshTokenValue); + if (refreshToken == null) { + throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue); + } - OAuth2Authentication authentication = tokenStore.readAuthenticationForRefreshToken(refreshToken); - if (this.authenticationManager != null && !authentication.isClientOnly()) { - // The client has already been authenticated, but the user authentication might be old now, so give it a - // chance to re-authenticate. - Authentication user = new PreAuthenticatedAuthenticationToken(authentication.getUserAuthentication(), "", authentication.getAuthorities()); - user = authenticationManager.authenticate(user); - Object details = authentication.getDetails(); - authentication = new OAuth2Authentication(authentication.getOAuth2Request(), user); - authentication.setDetails(details); - } - String clientId = authentication.getOAuth2Request().getClientId(); - if (clientId == null || !clientId.equals(tokenRequest.getClientId())) { - throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue); - } + OAuth2Authentication authentication = tokenStore.readAuthenticationForRefreshToken(refreshToken); + if (this.authenticationManager != null && !authentication.isClientOnly()) { + // The client has already been authenticated, but the user authentication might be old now, so give it a + // chance to re-authenticate. + Authentication user = new PreAuthenticatedAuthenticationToken(authentication.getUserAuthentication(), "", authentication.getAuthorities()); + user = authenticationManager.authenticate(user); + Object details = authentication.getDetails(); + authentication = new OAuth2Authentication(authentication.getOAuth2Request(), user); + authentication.setDetails(details); + } + String clientId = authentication.getOAuth2Request().getClientId(); + if (clientId == null || !clientId.equals(tokenRequest.getClientId())) { + throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue); + } - // clear out any access tokens already associated with the refresh - // token. - tokenStore.removeAccessTokenUsingRefreshToken(refreshToken); + // clear out any access tokens already associated with the refresh + // token. + tokenStore.removeAccessTokenUsingRefreshToken(refreshToken); - if (isExpired(refreshToken)) { - tokenStore.removeRefreshToken(refreshToken); - throw new InvalidTokenException("Invalid refresh token (expired): " + refreshToken); - } + if (isExpired(refreshToken)) { + tokenStore.removeRefreshToken(refreshToken); + throw new InvalidTokenException("Invalid refresh token (expired): " + refreshToken); + } - authentication = createRefreshedAuthentication(authentication, tokenRequest); + authentication = createRefreshedAuthentication(authentication, tokenRequest); - if (!reuseRefreshToken) { - tokenStore.removeRefreshToken(refreshToken); - refreshToken = createRefreshToken(authentication); - } + if (!reuseRefreshToken) { + tokenStore.removeRefreshToken(refreshToken); + refreshToken = createRefreshToken(authentication); + } - OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken); - tokenStore.storeAccessToken(accessToken, authentication); - if (!reuseRefreshToken) { - tokenStore.storeRefreshToken(refreshToken, authentication); - } - return accessToken; - } + OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken); + tokenStore.storeAccessToken(accessToken, authentication); + if (!reuseRefreshToken) { + tokenStore.storeRefreshToken(refreshToken, authentication); + } + return accessToken; + } - public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) { - return tokenStore.getAccessToken(authentication); - } + public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) { + return tokenStore.getAccessToken(authentication); + } - /** - * Create a refreshed authentication. - * - * @param authentication The authentication. - * @param scope The scope for the refreshed token. - * @return The refreshed authentication. - * @throws InvalidScopeException If the scope requested is invalid or wider than the original scope. - */ - private OAuth2Authentication createRefreshedAuthentication(OAuth2Authentication authentication, TokenRequest request) { - OAuth2Authentication narrowed = authentication; - Set scope = request.getScope(); - OAuth2Request clientAuth = authentication.getOAuth2Request().refresh(request); - if (scope != null && !scope.isEmpty()) { - Set originalScope = clientAuth.getScope(); - if (originalScope == null || !originalScope.containsAll(scope)) { - throw new InvalidScopeException("Unable to narrow the scope of the client authentication to " + scope - + ".", originalScope); - } - else { - clientAuth = clientAuth.narrowScope(scope); - } - } - narrowed = new OAuth2Authentication(clientAuth, authentication.getUserAuthentication()); - return narrowed; - } + /** + * Create a refreshed authentication. + * + * @param authentication The authentication. + * @param scope The scope for the refreshed token. + * @return The refreshed authentication. + * @throws InvalidScopeException If the scope requested is invalid or wider than the original scope. + */ + private OAuth2Authentication createRefreshedAuthentication(OAuth2Authentication authentication, TokenRequest request) { + OAuth2Authentication narrowed = authentication; + Set scope = request.getScope(); + OAuth2Request clientAuth = authentication.getOAuth2Request().refresh(request); + if (scope != null && !scope.isEmpty()) { + Set originalScope = clientAuth.getScope(); + if (originalScope == null || !originalScope.containsAll(scope)) { + throw new InvalidScopeException("Unable to narrow the scope of the client authentication to " + scope + + ".", originalScope); + } + else { + clientAuth = clientAuth.narrowScope(scope); + } + } + narrowed = new OAuth2Authentication(clientAuth, authentication.getUserAuthentication()); + return narrowed; + } - protected boolean isExpired(OAuth2RefreshToken refreshToken) { - if (refreshToken instanceof ExpiringOAuth2RefreshToken) { - ExpiringOAuth2RefreshToken expiringToken = (ExpiringOAuth2RefreshToken) refreshToken; - return expiringToken.getExpiration() == null - || System.currentTimeMillis() > expiringToken.getExpiration().getTime(); - } - return false; - } + protected boolean isExpired(OAuth2RefreshToken refreshToken) { + if (refreshToken instanceof ExpiringOAuth2RefreshToken) { + ExpiringOAuth2RefreshToken expiringToken = (ExpiringOAuth2RefreshToken) refreshToken; + return expiringToken.getExpiration() == null + || System.currentTimeMillis() > expiringToken.getExpiration().getTime(); + } + return false; + } - public OAuth2AccessToken readAccessToken(String accessToken) { - return tokenStore.readAccessToken(accessToken); - } + public OAuth2AccessToken readAccessToken(String accessToken) { + return tokenStore.readAccessToken(accessToken); + } - public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException, - InvalidTokenException { - OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue); - if (accessToken == null) { - throw new InvalidTokenException("Invalid access token: " + accessTokenValue); - } - else if (accessToken.isExpired()) { - tokenStore.removeAccessToken(accessToken); - throw new InvalidTokenException("Access token expired: " + accessTokenValue); - } + public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException, + InvalidTokenException { + OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue); + if (accessToken == null) { + throw new InvalidTokenException("Invalid access token: " + accessTokenValue); + } + else if (accessToken.isExpired()) { + tokenStore.removeAccessToken(accessToken); + throw new InvalidTokenException("Access token expired: " + accessTokenValue); + } - OAuth2Authentication result = tokenStore.readAuthentication(accessToken); - if (result == null) { - // in case of race condition - throw new InvalidTokenException("Invalid access token: " + accessTokenValue); - } - - if (clientDetailsService != null) { - String clientId = result.getOAuth2Request().getClientId(); - try { - clientDetailsService.loadClientByClientId(clientId,true); - } - catch (ClientRegistrationException e) { - throw new InvalidTokenException("Client not valid: " + clientId, e); - } - } - return result; - } + OAuth2Authentication result = tokenStore.readAuthentication(accessToken); + if (result == null) { + // in case of race condition + throw new InvalidTokenException("Invalid access token: " + accessTokenValue); + } + + if (clientDetailsService != null) { + String clientId = result.getOAuth2Request().getClientId(); + try { + clientDetailsService.loadClientByClientId(clientId,true); + } + catch (ClientRegistrationException e) { + throw new InvalidTokenException("Client not valid: " + clientId, e); + } + } + return result; + } - public String getClientId(String tokenValue) { - OAuth2Authentication authentication = tokenStore.readAuthentication(tokenValue); - if (authentication == null) { - throw new InvalidTokenException("Invalid access token: " + tokenValue); - } - OAuth2Request clientAuth = authentication.getOAuth2Request(); - if (clientAuth == null) { - throw new InvalidTokenException("Invalid access token (no client id): " + tokenValue); - } - return clientAuth.getClientId(); - } + public String getClientId(String tokenValue) { + OAuth2Authentication authentication = tokenStore.readAuthentication(tokenValue); + if (authentication == null) { + throw new InvalidTokenException("Invalid access token: " + tokenValue); + } + OAuth2Request clientAuth = authentication.getOAuth2Request(); + if (clientAuth == null) { + throw new InvalidTokenException("Invalid access token (no client id): " + tokenValue); + } + return clientAuth.getClientId(); + } - public boolean revokeToken(String tokenValue) { - OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue); - if (accessToken == null) { - return false; - } - if (accessToken.getRefreshToken() != null) { - tokenStore.removeRefreshToken(accessToken.getRefreshToken()); - } - tokenStore.removeAccessToken(accessToken); - return true; - } + public boolean revokeToken(String tokenValue) { + OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue); + if (accessToken == null) { + return false; + } + if (accessToken.getRefreshToken() != null) { + tokenStore.removeRefreshToken(accessToken.getRefreshToken()); + } + tokenStore.removeAccessToken(accessToken); + return true; + } - private OAuth2RefreshToken createRefreshToken(OAuth2Authentication authentication) { - if (!isSupportRefreshToken(authentication.getOAuth2Request())) { - return null; - } - int validitySeconds = getRefreshTokenValiditySeconds(authentication.getOAuth2Request()); - String value = UUID.randomUUID().toString(); - if (validitySeconds > 0) { - return new DefaultExpiringOAuth2RefreshToken(value, new Date(System.currentTimeMillis() - + (validitySeconds * 1000L))); - } - return new DefaultOAuth2RefreshToken(value); - } + private OAuth2RefreshToken createRefreshToken(OAuth2Authentication authentication) { + if (!isSupportRefreshToken(authentication.getOAuth2Request())) { + return null; + } + int validitySeconds = getRefreshTokenValiditySeconds(authentication.getOAuth2Request()); + String value = UUID.randomUUID().toString(); + if (validitySeconds > 0) { + return new DefaultExpiringOAuth2RefreshToken(value, new Date(System.currentTimeMillis() + + (validitySeconds * 1000L))); + } + return new DefaultOAuth2RefreshToken(value); + } - private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) { - DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(UUID.randomUUID().toString()); - int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request()); - if (validitySeconds > 0) { - token.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L))); - } - token.setRefreshToken(refreshToken); - token.setScope(authentication.getOAuth2Request().getScope()); + private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) { + DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(UUID.randomUUID().toString()); + int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request()); + if (validitySeconds > 0) { + token.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L))); + } + token.setRefreshToken(refreshToken); + token.setScope(authentication.getOAuth2Request().getScope()); - return enhancerToken(token, authentication); - } - - private OAuth2AccessToken enhancerToken(OAuth2AccessToken token , OAuth2Authentication authentication) { - return accessTokenEnhancer != null ? accessTokenEnhancer.enhance(token, authentication) : token; - } + return enhancerToken(token, authentication); + } + + private OAuth2AccessToken enhancerToken(OAuth2AccessToken token , OAuth2Authentication authentication) { + return accessTokenEnhancer != null ? accessTokenEnhancer.enhance(token, authentication) : token; + } - /** - * The access token validity period in seconds - * - * @param authorizationRequest the current authorization request - * @return the access token validity period in seconds - */ - protected int getAccessTokenValiditySeconds(OAuth2Request clientAuth) { - if (clientDetailsService != null) { - ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId(),true); - Integer validity = client.getAccessTokenValiditySeconds(); - if (validity != null) { - return validity; - } - } - return accessTokenValiditySeconds; - } + /** + * The access token validity period in seconds + * + * @param authorizationRequest the current authorization request + * @return the access token validity period in seconds + */ + protected int getAccessTokenValiditySeconds(OAuth2Request clientAuth) { + if (clientDetailsService != null) { + ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId(),true); + Integer validity = client.getAccessTokenValiditySeconds(); + if (validity != null) { + return validity; + } + } + return accessTokenValiditySeconds; + } - /** - * The refresh token validity period in seconds - * - * @param authorizationRequest the current authorization request - * @return the refresh token validity period in seconds - */ - protected int getRefreshTokenValiditySeconds(OAuth2Request clientAuth) { - if (clientDetailsService != null) { - ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId(),true); - Integer validity = client.getRefreshTokenValiditySeconds(); - if (validity != null) { - return validity; - } - } - return refreshTokenValiditySeconds; - } + /** + * The refresh token validity period in seconds + * + * @param authorizationRequest the current authorization request + * @return the refresh token validity period in seconds + */ + protected int getRefreshTokenValiditySeconds(OAuth2Request clientAuth) { + if (clientDetailsService != null) { + ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId(),true); + Integer validity = client.getRefreshTokenValiditySeconds(); + if (validity != null) { + return validity; + } + } + return refreshTokenValiditySeconds; + } - /** - * Is a refresh token supported for this client (or the global setting if - * {@link #setClientDetailsService(ClientDetailsService) clientDetailsService} is not set. - * - * @param authorizationRequest the current authorization request - * @return boolean to indicate if refresh token is supported - */ - protected boolean isSupportRefreshToken(OAuth2Request clientAuth) { - if (clientDetailsService != null) { - ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId(),true); - return client.getAuthorizedGrantTypes().contains("refresh_token"); - } - return this.supportRefreshToken; - } + /** + * Is a refresh token supported for this client (or the global setting if + * {@link #setClientDetailsService(ClientDetailsService) clientDetailsService} is not set. + * + * @param authorizationRequest the current authorization request + * @return boolean to indicate if refresh token is supported + */ + protected boolean isSupportRefreshToken(OAuth2Request clientAuth) { + if (clientDetailsService != null) { + ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId(),true); + return client.getAuthorizedGrantTypes().contains("refresh_token"); + } + return this.supportRefreshToken; + } - /** - * An access token enhancer that will be applied to a new token before it is saved in the token store. - * - * @param accessTokenEnhancer the access token enhancer to set - */ - public void setTokenEnhancer(TokenEnhancer accessTokenEnhancer) { - this.accessTokenEnhancer = accessTokenEnhancer; - } + /** + * An access token enhancer that will be applied to a new token before it is saved in the token store. + * + * @param accessTokenEnhancer the access token enhancer to set + */ + public void setTokenEnhancer(TokenEnhancer accessTokenEnhancer) { + this.accessTokenEnhancer = accessTokenEnhancer; + } - /** - * The validity (in seconds) of the refresh token. If less than or equal to zero then the tokens will be - * non-expiring. - * - * @param refreshTokenValiditySeconds The validity (in seconds) of the refresh token. - */ - public void setRefreshTokenValiditySeconds(int refreshTokenValiditySeconds) { - this.refreshTokenValiditySeconds = refreshTokenValiditySeconds; - } + /** + * The validity (in seconds) of the refresh token. If less than or equal to zero then the tokens will be + * non-expiring. + * + * @param refreshTokenValiditySeconds The validity (in seconds) of the refresh token. + */ + public void setRefreshTokenValiditySeconds(int refreshTokenValiditySeconds) { + this.refreshTokenValiditySeconds = refreshTokenValiditySeconds; + } - /** - * The default validity (in seconds) of the access token. Zero or negative for non-expiring tokens. If a client - * details service is set the validity period will be read from he client, defaulting to this value if not defined - * by the client. - * - * @param accessTokenValiditySeconds The validity (in seconds) of the access token. - */ - public void setAccessTokenValiditySeconds(int accessTokenValiditySeconds) { - this.accessTokenValiditySeconds = accessTokenValiditySeconds; - } + /** + * The default validity (in seconds) of the access token. Zero or negative for non-expiring tokens. If a client + * details service is set the validity period will be read from he client, defaulting to this value if not defined + * by the client. + * + * @param accessTokenValiditySeconds The validity (in seconds) of the access token. + */ + public void setAccessTokenValiditySeconds(int accessTokenValiditySeconds) { + this.accessTokenValiditySeconds = accessTokenValiditySeconds; + } - /** - * Whether to support the refresh token. - * - * @param supportRefreshToken Whether to support the refresh token. - */ - public void setSupportRefreshToken(boolean supportRefreshToken) { - this.supportRefreshToken = supportRefreshToken; - } + /** + * Whether to support the refresh token. + * + * @param supportRefreshToken Whether to support the refresh token. + */ + public void setSupportRefreshToken(boolean supportRefreshToken) { + this.supportRefreshToken = supportRefreshToken; + } - /** - * Whether to reuse refresh tokens (until expired). - * - * @param reuseRefreshToken Whether to reuse refresh tokens (until expired). - */ - public void setReuseRefreshToken(boolean reuseRefreshToken) { - this.reuseRefreshToken = reuseRefreshToken; - } + /** + * Whether to reuse refresh tokens (until expired). + * + * @param reuseRefreshToken Whether to reuse refresh tokens (until expired). + */ + public void setReuseRefreshToken(boolean reuseRefreshToken) { + this.reuseRefreshToken = reuseRefreshToken; + } - /** - * The persistence strategy for token storage. - * - * @param tokenStore the store for access and refresh tokens. - */ - public void setTokenStore(TokenStore tokenStore) { - this.tokenStore = tokenStore; - } + /** + * The persistence strategy for token storage. + * + * @param tokenStore the store for access and refresh tokens. + */ + public void setTokenStore(TokenStore tokenStore) { + this.tokenStore = tokenStore; + } - /** - * An authentication manager that will be used (if provided) to check the user authentication when a token is - * refreshed. - * - * @param authenticationManager the authenticationManager to set - */ - public void setAuthenticationManager(AuthenticationManager authenticationManager) { - this.authenticationManager = authenticationManager; - } + /** + * An authentication manager that will be used (if provided) to check the user authentication when a token is + * refreshed. + * + * @param authenticationManager the authenticationManager to set + */ + public void setAuthenticationManager(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } - /** - * The client details service to use for looking up clients (if necessary). Optional if the access token expiry is - * set globally via {@link #setAccessTokenValiditySeconds(int)}. - * - * @param clientDetailsService the client details service - */ - public void setClientDetailsService(ClientDetailsService clientDetailsService) { - this.clientDetailsService = clientDetailsService; - } + /** + * The client details service to use for looking up clients (if necessary). Optional if the access token expiry is + * set globally via {@link #setAccessTokenValiditySeconds(int)}. + * + * @param clientDetailsService the client details service + */ + public void setClientDetailsService(ClientDetailsService clientDetailsService) { + this.clientDetailsService = clientDetailsService; + } - public void setAppsService(AppsService appsService) { - this.appsService = appsService; - } + public void setAppsService(AppsService appsService) { + this.appsService = appsService; + } - public void setSessionManager(SessionManager sessionManager) { - this.sessionManager = sessionManager; - } + public void setSessionManager(SessionManager sessionManager) { + this.sessionManager = sessionManager; + } - + } \ No newline at end of file diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/DefaultUserAuthenticationConverter.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/DefaultUserAuthenticationConverter.java index 0e2462428..ed904e7b3 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/DefaultUserAuthenticationConverter.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/DefaultUserAuthenticationConverter.java @@ -51,66 +51,66 @@ import org.springframework.util.StringUtils; */ public class DefaultUserAuthenticationConverter implements UserAuthenticationConverter { - private Collection defaultAuthorities; + private Collection defaultAuthorities; - private UserDetailsService userDetailsService; + private UserDetailsService userDetailsService; - /** - * Optional {@link UserDetailsService} to use when extracting an {@link Authentication} from the incoming map. - * - * @param userDetailsService the userDetailsService to set - */ - public void setUserDetailsService(UserDetailsService userDetailsService) { - this.userDetailsService = userDetailsService; - } - - /** - * Default value for authorities if an Authentication is being created and the input has no data for authorities. - * Note that unless this property is set, the default Authentication created by {@link #extractAuthentication(Map)} - * will be unauthenticated. - * - * @param defaultAuthorities the defaultAuthorities to set. Default null. - */ - public void setDefaultAuthorities(String[] defaultAuthorities) { - this.defaultAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils - .arrayToCommaDelimitedString(defaultAuthorities)); - } + /** + * Optional {@link UserDetailsService} to use when extracting an {@link Authentication} from the incoming map. + * + * @param userDetailsService the userDetailsService to set + */ + public void setUserDetailsService(UserDetailsService userDetailsService) { + this.userDetailsService = userDetailsService; + } + + /** + * Default value for authorities if an Authentication is being created and the input has no data for authorities. + * Note that unless this property is set, the default Authentication created by {@link #extractAuthentication(Map)} + * will be unauthenticated. + * + * @param defaultAuthorities the defaultAuthorities to set. Default null. + */ + public void setDefaultAuthorities(String[] defaultAuthorities) { + this.defaultAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils + .arrayToCommaDelimitedString(defaultAuthorities)); + } - public Map convertUserAuthentication(Authentication authentication) { - Map response = new LinkedHashMap(); - response.put(USERNAME, authentication.getName()); - if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) { - response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities())); - } - return response; - } + public Map convertUserAuthentication(Authentication authentication) { + Map response = new LinkedHashMap(); + response.put(USERNAME, authentication.getName()); + if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) { + response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities())); + } + return response; + } - public Authentication extractAuthentication(Map map) { - if (map.containsKey(USERNAME)) { - Object principal = map.get(USERNAME); - Collection authorities = getAuthorities(map); - if (userDetailsService != null) { - UserDetails user = userDetailsService.loadUserByUsername((String) map.get(USERNAME)); - authorities = user.getAuthorities(); - principal = user; - } - return new UsernamePasswordAuthenticationToken(principal, "N/A", authorities); - } - return null; - } + public Authentication extractAuthentication(Map map) { + if (map.containsKey(USERNAME)) { + Object principal = map.get(USERNAME); + Collection authorities = getAuthorities(map); + if (userDetailsService != null) { + UserDetails user = userDetailsService.loadUserByUsername((String) map.get(USERNAME)); + authorities = user.getAuthorities(); + principal = user; + } + return new UsernamePasswordAuthenticationToken(principal, "N/A", authorities); + } + return null; + } - private Collection getAuthorities(Map map) { - if (!map.containsKey(AUTHORITIES)) { - return defaultAuthorities; - } - Object authorities = map.get(AUTHORITIES); - if (authorities instanceof String) { - return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities); - } - if (authorities instanceof Collection) { - return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils - .collectionToCommaDelimitedString((Collection) authorities)); - } - throw new IllegalArgumentException("Authorities must be either a String or a Collection"); - } + private Collection getAuthorities(Map map) { + if (!map.containsKey(AUTHORITIES)) { + return defaultAuthorities; + } + Object authorities = map.get(AUTHORITIES); + if (authorities instanceof String) { + return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities); + } + if (authorities instanceof Collection) { + return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils + .collectionToCommaDelimitedString((Collection) authorities)); + } + throw new IllegalArgumentException("Authorities must be either a String or a Collection"); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/RemoteTokenServices.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/RemoteTokenServices.java index 968028096..8cdac0e61 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/RemoteTokenServices.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/RemoteTokenServices.java @@ -63,94 +63,94 @@ import org.springframework.web.client.RestTemplate; */ public class RemoteTokenServices implements ResourceServerTokenServices { - protected final Log logger = LogFactory.getLog(getClass()); + protected final Log logger = LogFactory.getLog(getClass()); - private RestOperations restTemplate; + private RestOperations restTemplate; - private String checkTokenEndpointUrl; + private String checkTokenEndpointUrl; - private String clientId; + private String clientId; - private String clientSecret; + private String clientSecret; - private AccessTokenConverter tokenConverter = new DefaultAccessTokenConverter(); + private AccessTokenConverter tokenConverter = new DefaultAccessTokenConverter(); - public RemoteTokenServices() { - restTemplate = new RestTemplate(); - ((RestTemplate) restTemplate).setErrorHandler(new DefaultResponseErrorHandler() { - @Override - // Ignore 400 - public void handleError(ClientHttpResponse response) throws IOException { - if (response.getStatusCode().value() != 400) { - super.handleError(response); - } - } - }); - } + public RemoteTokenServices() { + restTemplate = new RestTemplate(); + ((RestTemplate) restTemplate).setErrorHandler(new DefaultResponseErrorHandler() { + @Override + // Ignore 400 + public void handleError(ClientHttpResponse response) throws IOException { + if (response.getStatusCode().value() != 400) { + super.handleError(response); + } + } + }); + } - public void setRestTemplate(RestOperations restTemplate) { - this.restTemplate = restTemplate; - } + public void setRestTemplate(RestOperations restTemplate) { + this.restTemplate = restTemplate; + } - public void setCheckTokenEndpointUrl(String checkTokenEndpointUrl) { - this.checkTokenEndpointUrl = checkTokenEndpointUrl; - } + public void setCheckTokenEndpointUrl(String checkTokenEndpointUrl) { + this.checkTokenEndpointUrl = checkTokenEndpointUrl; + } - public void setClientId(String clientId) { - this.clientId = clientId; - } + public void setClientId(String clientId) { + this.clientId = clientId; + } - public void setClientSecret(String clientSecret) { - this.clientSecret = clientSecret; - } + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } - public void setAccessTokenConverter(AccessTokenConverter accessTokenConverter) { - this.tokenConverter = accessTokenConverter; - } + public void setAccessTokenConverter(AccessTokenConverter accessTokenConverter) { + this.tokenConverter = accessTokenConverter; + } - @Override - public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException { + @Override + public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException { - MultiValueMap formData = new LinkedMultiValueMap(); - formData.add("token", accessToken); - HttpHeaders headers = new HttpHeaders(); - headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret)); - Map map = postForMap(checkTokenEndpointUrl, formData, headers); + MultiValueMap formData = new LinkedMultiValueMap(); + formData.add("token", accessToken); + HttpHeaders headers = new HttpHeaders(); + headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret)); + Map map = postForMap(checkTokenEndpointUrl, formData, headers); - if (map.containsKey("error")) { - logger.debug("check_token returned error: " + map.get("error")); - throw new InvalidTokenException(accessToken); - } + if (map.containsKey("error")) { + logger.debug("check_token returned error: " + map.get("error")); + throw new InvalidTokenException(accessToken); + } - Assert.state(map.containsKey("client_id"), "Client id must be present in response from auth server"); - return tokenConverter.extractAuthentication(map); - } + Assert.state(map.containsKey("client_id"), "Client id must be present in response from auth server"); + return tokenConverter.extractAuthentication(map); + } - @Override - public OAuth2AccessToken readAccessToken(String accessToken) { - throw new UnsupportedOperationException("Not supported: read access token"); - } + @Override + public OAuth2AccessToken readAccessToken(String accessToken) { + throw new UnsupportedOperationException("Not supported: read access token"); + } - private String getAuthorizationHeader(String clientId, String clientSecret) { - String creds = String.format("%s:%s", clientId, clientSecret); - try { - return "Basic " + new String(Base64.getEncoder().encodeToString(creds.getBytes("UTF-8"))); - } - catch (UnsupportedEncodingException e) { - throw new IllegalStateException("Could not convert String"); - } - } + private String getAuthorizationHeader(String clientId, String clientSecret) { + String creds = String.format("%s:%s", clientId, clientSecret); + try { + return "Basic " + new String(Base64.getEncoder().encodeToString(creds.getBytes("UTF-8"))); + } + catch (UnsupportedEncodingException e) { + throw new IllegalStateException("Could not convert String"); + } + } - private Map postForMap(String path, MultiValueMap formData, HttpHeaders headers) { - if (headers.getContentType() == null) { - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - } - @SuppressWarnings("rawtypes") - Map map = restTemplate.exchange(path, HttpMethod.POST, - new HttpEntity>(formData, headers), Map.class).getBody(); - @SuppressWarnings("unchecked") - Map result = map; - return result; - } + private Map postForMap(String path, MultiValueMap formData, HttpHeaders headers) { + if (headers.getContentType() == null) { + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + } + @SuppressWarnings("rawtypes") + Map map = restTemplate.exchange(path, HttpMethod.POST, + new HttpEntity>(formData, headers), Map.class).getBody(); + @SuppressWarnings("unchecked") + Map result = map; + return result; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/ResourceServerTokenServices.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/ResourceServerTokenServices.java index 40b513ada..f9525a695 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/ResourceServerTokenServices.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/ResourceServerTokenServices.java @@ -24,22 +24,22 @@ import org.springframework.security.core.AuthenticationException; public interface ResourceServerTokenServices { - /** - * Load the credentials for the specified access token. - * - * @param accessToken The access token value. - * @return The authentication for the access token. - * @throws AuthenticationException If the access token is expired - * @throws InvalidTokenException if the token isn't valid - */ - OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException; + /** + * Load the credentials for the specified access token. + * + * @param accessToken The access token value. + * @return The authentication for the access token. + * @throws AuthenticationException If the access token is expired + * @throws InvalidTokenException if the token isn't valid + */ + OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException; - /** - * Retrieve the full access token details from just the value. - * - * @param accessToken the token value - * @return the full access token with client id etc. - */ - OAuth2AccessToken readAccessToken(String accessToken); + /** + * Retrieve the full access token details from just the value. + * + * @param accessToken the token value + * @return the full access token with client id etc. + */ + OAuth2AccessToken readAccessToken(String accessToken); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/TokenEnhancer.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/TokenEnhancer.java index b0f930cd9..64f55f34c 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/TokenEnhancer.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/TokenEnhancer.java @@ -24,14 +24,14 @@ import org.dromara.maxkey.authz.oauth2.provider.OAuth2Authentication; */ public interface TokenEnhancer { - /** - * Provides an opportunity for customization of an access token (e.g. through its additional information map) during - * the process of creating a new token for use by a client. - * - * @param accessToken the current access token with its expiration and refresh token - * @param authentication the current authentication including client and user details - * @return a new token enhanced with additional information - */ - OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication); + /** + * Provides an opportunity for customization of an access token (e.g. through its additional information map) during + * the process of creating a new token for use by a client. + * + * @param accessToken the current access token with its expiration and refresh token + * @param authentication the current authentication including client and user details + * @return a new token enhanced with additional information + */ + OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/TokenEnhancerChain.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/TokenEnhancerChain.java index 2a9a3beaa..2c6ed584b 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/TokenEnhancerChain.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/TokenEnhancerChain.java @@ -26,27 +26,27 @@ import org.dromara.maxkey.authz.oauth2.provider.OAuth2Authentication; */ public class TokenEnhancerChain implements TokenEnhancer { - private List delegates = Collections.emptyList(); + private List delegates = Collections.emptyList(); - /** - * @param delegates the delegates to set - */ - public void setTokenEnhancers(List delegates) { - this.delegates = delegates; - } + /** + * @param delegates the delegates to set + */ + public void setTokenEnhancers(List delegates) { + this.delegates = delegates; + } - /** - * Loop over the {@link #setTokenEnhancers(List) delegates} passing the result into the next member of the chain. - * - * @see org.dromara.maxkey.authz.oauth2.provider.token.TokenEnhancer#enhance(org.dromara.maxkey.authz.oauth2.common.OAuth2AccessToken, - * org.dromara.maxkey.authz.oauth2.provider.OAuth2Authentication) - */ - public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { - OAuth2AccessToken result = accessToken; - for (TokenEnhancer enhancer : delegates) { - result = enhancer.enhance(result, authentication); - } - return result; - } + /** + * Loop over the {@link #setTokenEnhancers(List) delegates} passing the result into the next member of the chain. + * + * @see org.dromara.maxkey.authz.oauth2.provider.token.TokenEnhancer#enhance(org.dromara.maxkey.authz.oauth2.common.OAuth2AccessToken, + * org.dromara.maxkey.authz.oauth2.provider.OAuth2Authentication) + */ + public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { + OAuth2AccessToken result = accessToken; + for (TokenEnhancer enhancer : delegates) { + result = enhancer.enhance(result, authentication); + } + return result; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/TokenStore.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/TokenStore.java index 4231ed3d7..08c38ed59 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/TokenStore.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/TokenStore.java @@ -28,103 +28,103 @@ import org.dromara.maxkey.authz.oauth2.provider.OAuth2Authentication; */ public interface TokenStore { - /** - * Read the authentication stored under the specified token value. - * - * @param token The token value under which the authentication is stored. - * @return The authentication, or null if none. - */ - OAuth2Authentication readAuthentication(OAuth2AccessToken token); + /** + * Read the authentication stored under the specified token value. + * + * @param token The token value under which the authentication is stored. + * @return The authentication, or null if none. + */ + OAuth2Authentication readAuthentication(OAuth2AccessToken token); - /** - * Read the authentication stored under the specified token value. - * - * @param token The token value under which the authentication is stored. - * @return The authentication, or null if none. - */ - OAuth2Authentication readAuthentication(String token); + /** + * Read the authentication stored under the specified token value. + * + * @param token The token value under which the authentication is stored. + * @return The authentication, or null if none. + */ + OAuth2Authentication readAuthentication(String token); - /** - * Store an access token. - * - * @param token The token to store. - * @param authentication The authentication associated with the token. - */ - void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication); + /** + * Store an access token. + * + * @param token The token to store. + * @param authentication The authentication associated with the token. + */ + void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication); - /** - * Read an access token from the store. - * - * @param tokenValue The token value. - * @return The access token to read. - */ - OAuth2AccessToken readAccessToken(String tokenValue); + /** + * Read an access token from the store. + * + * @param tokenValue The token value. + * @return The access token to read. + */ + OAuth2AccessToken readAccessToken(String tokenValue); - /** - * Remove an access token from the database. - * - * @param token The token to remove from the database. - */ - void removeAccessToken(OAuth2AccessToken token); + /** + * Remove an access token from the database. + * + * @param token The token to remove from the database. + */ + void removeAccessToken(OAuth2AccessToken token); - /** - * Store the specified refresh token in the database. - * - * @param refreshToken The refresh token to store. - * @param authentication The authentication associated with the refresh token. - */ - void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication); + /** + * Store the specified refresh token in the database. + * + * @param refreshToken The refresh token to store. + * @param authentication The authentication associated with the refresh token. + */ + void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication); - /** - * Read a refresh token from the store. - * - * @param tokenValue The value of the token to read. - * @return The token. - */ - OAuth2RefreshToken readRefreshToken(String tokenValue); + /** + * Read a refresh token from the store. + * + * @param tokenValue The value of the token to read. + * @return The token. + */ + OAuth2RefreshToken readRefreshToken(String tokenValue); - /** - * @param token a refresh token - * @return the authentication originally used to grant the refresh token - */ - OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token); + /** + * @param token a refresh token + * @return the authentication originally used to grant the refresh token + */ + OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token); - /** - * Remove a refresh token from the database. - * - * @param token The token to remove from the database. - */ - void removeRefreshToken(OAuth2RefreshToken token); + /** + * Remove a refresh token from the database. + * + * @param token The token to remove from the database. + */ + void removeRefreshToken(OAuth2RefreshToken token); - /** - * Remove an access token using a refresh token. This functionality is necessary so refresh tokens can't be used to - * create an unlimited number of access tokens. - * - * @param refreshToken The refresh token. - */ - void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken); + /** + * Remove an access token using a refresh token. This functionality is necessary so refresh tokens can't be used to + * create an unlimited number of access tokens. + * + * @param refreshToken The refresh token. + */ + void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken); - /** - * Retrieve an access token stored against the provided authentication key, if it exists. - * - * @param authentication the authentication key for the access token - * - * @return the access token or null if there was none - */ - OAuth2AccessToken getAccessToken(OAuth2Authentication authentication); + /** + * Retrieve an access token stored against the provided authentication key, if it exists. + * + * @param authentication the authentication key for the access token + * + * @return the access token or null if there was none + */ + OAuth2AccessToken getAccessToken(OAuth2Authentication authentication); - /** - * @param clientId the client id to search - * @param userName the user name to search - * @return a collection of access tokens - */ - Collection findTokensByClientIdAndUserName(String clientId, String userName); + /** + * @param clientId the client id to search + * @param userName the user name to search + * @return a collection of access tokens + */ + Collection findTokensByClientIdAndUserName(String clientId, String userName); - /** - * @param userName the user name to search - * @param clientId the client id to search - * @return a collection of access tokens - */ - Collection findTokensByClientId(String clientId); + /** + * @param userName the user name to search + * @param clientId the client id to search + * @return a collection of access tokens + */ + Collection findTokensByClientId(String clientId); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/UserAuthenticationConverter.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/UserAuthenticationConverter.java index 035083cc0..71c6b6771 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/UserAuthenticationConverter.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/UserAuthenticationConverter.java @@ -42,24 +42,24 @@ import org.springframework.security.core.Authentication; */ public interface UserAuthenticationConverter { - final String AUTHORITIES = "authorities"; + final String AUTHORITIES = "authorities"; - final String USERNAME = "user_name"; + final String USERNAME = "user_name"; - /** - * Extract information about the user to be used in an access token (i.e. for resource servers). - * - * @param userAuthentication an authentication representing a user - * @return a map of key values representing the unique information about the user - */ - Map convertUserAuthentication(Authentication userAuthentication); + /** + * Extract information about the user to be used in an access token (i.e. for resource servers). + * + * @param userAuthentication an authentication representing a user + * @return a map of key values representing the unique information about the user + */ + Map convertUserAuthentication(Authentication userAuthentication); - /** - * Inverse of {@link #convertUserAuthentication(Authentication)}. Extracts an Authentication from a map. - * - * @param map a map of user information - * @return an Authentication representing the user or null if there is none - */ - Authentication extractAuthentication(Map map); + /** + * Inverse of {@link #convertUserAuthentication(Authentication)}. Extracts an Authentication from a map. + * + * @param map a map of user information + * @return an Authentication representing the user or null if there is none + */ + Authentication extractAuthentication(Map map); } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/store/InMemoryTokenStore.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/store/InMemoryTokenStore.java index 12295dc16..f729b4ea5 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/store/InMemoryTokenStore.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/store/InMemoryTokenStore.java @@ -44,272 +44,272 @@ import org.springframework.util.Assert; */ public class InMemoryTokenStore implements TokenStore { - private static final int DEFAULT_FLUSH_INTERVAL = 1000; + private static final int DEFAULT_FLUSH_INTERVAL = 1000; - private final ConcurrentHashMap accessTokenStore = new ConcurrentHashMap(); + private final ConcurrentHashMap accessTokenStore = new ConcurrentHashMap(); - private final ConcurrentHashMap authenticationToAccessTokenStore = new ConcurrentHashMap(); + private final ConcurrentHashMap authenticationToAccessTokenStore = new ConcurrentHashMap(); - private final ConcurrentHashMap> userNameToAccessTokenStore = new ConcurrentHashMap>(); + private final ConcurrentHashMap> userNameToAccessTokenStore = new ConcurrentHashMap>(); - private final ConcurrentHashMap> clientIdToAccessTokenStore = new ConcurrentHashMap>(); + private final ConcurrentHashMap> clientIdToAccessTokenStore = new ConcurrentHashMap>(); - private final ConcurrentHashMap refreshTokenStore = new ConcurrentHashMap(); + private final ConcurrentHashMap refreshTokenStore = new ConcurrentHashMap(); - private final ConcurrentHashMap accessTokenToRefreshTokenStore = new ConcurrentHashMap(); + private final ConcurrentHashMap accessTokenToRefreshTokenStore = new ConcurrentHashMap(); - private final ConcurrentHashMap authenticationStore = new ConcurrentHashMap(); + private final ConcurrentHashMap authenticationStore = new ConcurrentHashMap(); - private final ConcurrentHashMap refreshTokenAuthenticationStore = new ConcurrentHashMap(); + private final ConcurrentHashMap refreshTokenAuthenticationStore = new ConcurrentHashMap(); - private final ConcurrentHashMap refreshTokenToAccessTokenStore = new ConcurrentHashMap(); + private final ConcurrentHashMap refreshTokenToAccessTokenStore = new ConcurrentHashMap(); - private final DelayQueue expiryQueue = new DelayQueue(); + private final DelayQueue expiryQueue = new DelayQueue(); - private final ConcurrentHashMap expiryMap = new ConcurrentHashMap(); + private final ConcurrentHashMap expiryMap = new ConcurrentHashMap(); - private int flushInterval = DEFAULT_FLUSH_INTERVAL; + private int flushInterval = DEFAULT_FLUSH_INTERVAL; - private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator(); + private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator(); - private AtomicInteger flushCounter = new AtomicInteger(0); + private AtomicInteger flushCounter = new AtomicInteger(0); - /** - * The number of tokens to store before flushing expired tokens. Defaults to 1000. - * - * @param flushInterval the interval to set - */ - public void setFlushInterval(int flushInterval) { - this.flushInterval = flushInterval; - } + /** + * The number of tokens to store before flushing expired tokens. Defaults to 1000. + * + * @param flushInterval the interval to set + */ + public void setFlushInterval(int flushInterval) { + this.flushInterval = flushInterval; + } - /** - * The interval (count of token inserts) between flushing expired tokens. - * - * @return the flushInterval the flush interval - */ - public int getFlushInterval() { - return flushInterval; - } + /** + * The interval (count of token inserts) between flushing expired tokens. + * + * @return the flushInterval the flush interval + */ + public int getFlushInterval() { + return flushInterval; + } - /** - * Convenience method for super admin users to remove all tokens (useful for testing, not really in production) - */ - public void clear() { - accessTokenStore.clear(); - authenticationToAccessTokenStore.clear(); - clientIdToAccessTokenStore.clear(); - refreshTokenStore.clear(); - accessTokenToRefreshTokenStore.clear(); - authenticationStore.clear(); - refreshTokenAuthenticationStore.clear(); - refreshTokenToAccessTokenStore.clear(); - expiryQueue.clear(); - } + /** + * Convenience method for super admin users to remove all tokens (useful for testing, not really in production) + */ + public void clear() { + accessTokenStore.clear(); + authenticationToAccessTokenStore.clear(); + clientIdToAccessTokenStore.clear(); + refreshTokenStore.clear(); + accessTokenToRefreshTokenStore.clear(); + authenticationStore.clear(); + refreshTokenAuthenticationStore.clear(); + refreshTokenToAccessTokenStore.clear(); + expiryQueue.clear(); + } - public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) { - this.authenticationKeyGenerator = authenticationKeyGenerator; - } + public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) { + this.authenticationKeyGenerator = authenticationKeyGenerator; + } - public int getAccessTokenCount() { - Assert.state(accessTokenStore.isEmpty() || accessTokenStore.size() >= accessTokenToRefreshTokenStore.size(), - "Too many refresh tokens"); - Assert.state(accessTokenStore.size() == authenticationToAccessTokenStore.size(), - "Inconsistent token store state"); - Assert.state(accessTokenStore.size() <= authenticationStore.size(), "Inconsistent authentication store state"); - return accessTokenStore.size(); - } + public int getAccessTokenCount() { + Assert.state(accessTokenStore.isEmpty() || accessTokenStore.size() >= accessTokenToRefreshTokenStore.size(), + "Too many refresh tokens"); + Assert.state(accessTokenStore.size() == authenticationToAccessTokenStore.size(), + "Inconsistent token store state"); + Assert.state(accessTokenStore.size() <= authenticationStore.size(), "Inconsistent authentication store state"); + return accessTokenStore.size(); + } - public int getRefreshTokenCount() { - Assert.state(refreshTokenStore.size() == refreshTokenToAccessTokenStore.size(), - "Inconsistent refresh token store state"); - return accessTokenStore.size(); - } + public int getRefreshTokenCount() { + Assert.state(refreshTokenStore.size() == refreshTokenToAccessTokenStore.size(), + "Inconsistent refresh token store state"); + return accessTokenStore.size(); + } - public int getExpiryTokenCount() { - return expiryQueue.size(); - } + public int getExpiryTokenCount() { + return expiryQueue.size(); + } - public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) { - String key = authenticationKeyGenerator.extractKey(authentication); - OAuth2AccessToken accessToken = authenticationToAccessTokenStore.get(key); - if (accessToken != null - && !key.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) { - // Keep the stores consistent (maybe the same user is represented by this authentication but the details - // have changed) - storeAccessToken(accessToken, authentication); - } - return accessToken; - } + public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) { + String key = authenticationKeyGenerator.extractKey(authentication); + OAuth2AccessToken accessToken = authenticationToAccessTokenStore.get(key); + if (accessToken != null + && !key.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) { + // Keep the stores consistent (maybe the same user is represented by this authentication but the details + // have changed) + storeAccessToken(accessToken, authentication); + } + return accessToken; + } - public OAuth2Authentication readAuthentication(OAuth2AccessToken token) { - return readAuthentication(token.getValue()); - } + public OAuth2Authentication readAuthentication(OAuth2AccessToken token) { + return readAuthentication(token.getValue()); + } - public OAuth2Authentication readAuthentication(String token) { - return this.authenticationStore.get(token); - } + public OAuth2Authentication readAuthentication(String token) { + return this.authenticationStore.get(token); + } - public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) { - return readAuthenticationForRefreshToken(token.getValue()); - } + public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) { + return readAuthenticationForRefreshToken(token.getValue()); + } - public OAuth2Authentication readAuthenticationForRefreshToken(String token) { - return this.refreshTokenAuthenticationStore.get(token); - } + public OAuth2Authentication readAuthenticationForRefreshToken(String token) { + return this.refreshTokenAuthenticationStore.get(token); + } - public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { - if (this.flushCounter.incrementAndGet() >= this.flushInterval) { - flush(); - this.flushCounter.set(0); - } - this.accessTokenStore.put(token.getValue(), token); - this.authenticationStore.put(token.getValue(), authentication); - this.authenticationToAccessTokenStore.put(authenticationKeyGenerator.extractKey(authentication), token); - if (!authentication.isClientOnly()) { - addToCollection(this.userNameToAccessTokenStore, getApprovalKey(authentication), token); - } - addToCollection(this.clientIdToAccessTokenStore, authentication.getOAuth2Request().getClientId(), token); - if (token.getExpiration() != null) { - TokenExpiry expiry = new TokenExpiry(token.getValue(), token.getExpiration()); - // Remove existing expiry for this token if present - expiryQueue.remove(expiryMap.put(token.getValue(), expiry)); - this.expiryQueue.put(expiry); - } - if (token.getRefreshToken() != null && token.getRefreshToken().getValue() != null) { - this.refreshTokenToAccessTokenStore.put(token.getRefreshToken().getValue(), token.getValue()); - this.accessTokenToRefreshTokenStore.put(token.getValue(), token.getRefreshToken().getValue()); - } - } + public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { + if (this.flushCounter.incrementAndGet() >= this.flushInterval) { + flush(); + this.flushCounter.set(0); + } + this.accessTokenStore.put(token.getValue(), token); + this.authenticationStore.put(token.getValue(), authentication); + this.authenticationToAccessTokenStore.put(authenticationKeyGenerator.extractKey(authentication), token); + if (!authentication.isClientOnly()) { + addToCollection(this.userNameToAccessTokenStore, getApprovalKey(authentication), token); + } + addToCollection(this.clientIdToAccessTokenStore, authentication.getOAuth2Request().getClientId(), token); + if (token.getExpiration() != null) { + TokenExpiry expiry = new TokenExpiry(token.getValue(), token.getExpiration()); + // Remove existing expiry for this token if present + expiryQueue.remove(expiryMap.put(token.getValue(), expiry)); + this.expiryQueue.put(expiry); + } + if (token.getRefreshToken() != null && token.getRefreshToken().getValue() != null) { + this.refreshTokenToAccessTokenStore.put(token.getRefreshToken().getValue(), token.getValue()); + this.accessTokenToRefreshTokenStore.put(token.getValue(), token.getRefreshToken().getValue()); + } + } - private String getApprovalKey(OAuth2Authentication authentication) { - String userName = authentication.getUserAuthentication() == null ? "" : authentication.getUserAuthentication() - .getName(); - return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName); - } + private String getApprovalKey(OAuth2Authentication authentication) { + String userName = authentication.getUserAuthentication() == null ? "" : authentication.getUserAuthentication() + .getName(); + return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName); + } - private String getApprovalKey(String clientId, String userName) { - return clientId + (userName==null ? "" : ":" + userName); - } + private String getApprovalKey(String clientId, String userName) { + return clientId + (userName==null ? "" : ":" + userName); + } - private void addToCollection(ConcurrentHashMap> store, String key, - OAuth2AccessToken token) { - if (!store.containsKey(key)) { - synchronized (store) { - if (!store.containsKey(key)) { - store.put(key, new HashSet()); - } - } - } - store.get(key).add(token); - } + private void addToCollection(ConcurrentHashMap> store, String key, + OAuth2AccessToken token) { + if (!store.containsKey(key)) { + synchronized (store) { + if (!store.containsKey(key)) { + store.put(key, new HashSet()); + } + } + } + store.get(key).add(token); + } - public void removeAccessToken(OAuth2AccessToken accessToken) { - removeAccessToken(accessToken.getValue()); - } + public void removeAccessToken(OAuth2AccessToken accessToken) { + removeAccessToken(accessToken.getValue()); + } - public OAuth2AccessToken readAccessToken(String tokenValue) { - return this.accessTokenStore.get(tokenValue); - } + public OAuth2AccessToken readAccessToken(String tokenValue) { + return this.accessTokenStore.get(tokenValue); + } - public void removeAccessToken(String tokenValue) { - OAuth2AccessToken removed = this.accessTokenStore.remove(tokenValue); - this.accessTokenToRefreshTokenStore.remove(tokenValue); - // Don't remove the refresh token - it's up to the caller to do that - OAuth2Authentication authentication = this.authenticationStore.remove(tokenValue); - if (authentication != null) { - this.authenticationToAccessTokenStore.remove(authenticationKeyGenerator.extractKey(authentication)); - Collection tokens; - tokens = this.userNameToAccessTokenStore.get(authentication.getName()); - if (tokens != null) { - tokens.remove(removed); - } - String clientId = authentication.getOAuth2Request().getClientId(); - tokens = this.clientIdToAccessTokenStore.get(clientId); - if (tokens != null) { - tokens.remove(removed); - } - this.authenticationToAccessTokenStore.remove(authenticationKeyGenerator.extractKey(authentication)); - } - } + public void removeAccessToken(String tokenValue) { + OAuth2AccessToken removed = this.accessTokenStore.remove(tokenValue); + this.accessTokenToRefreshTokenStore.remove(tokenValue); + // Don't remove the refresh token - it's up to the caller to do that + OAuth2Authentication authentication = this.authenticationStore.remove(tokenValue); + if (authentication != null) { + this.authenticationToAccessTokenStore.remove(authenticationKeyGenerator.extractKey(authentication)); + Collection tokens; + tokens = this.userNameToAccessTokenStore.get(authentication.getName()); + if (tokens != null) { + tokens.remove(removed); + } + String clientId = authentication.getOAuth2Request().getClientId(); + tokens = this.clientIdToAccessTokenStore.get(clientId); + if (tokens != null) { + tokens.remove(removed); + } + this.authenticationToAccessTokenStore.remove(authenticationKeyGenerator.extractKey(authentication)); + } + } - public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) { - this.refreshTokenStore.put(refreshToken.getValue(), refreshToken); - this.refreshTokenAuthenticationStore.put(refreshToken.getValue(), authentication); - } + public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) { + this.refreshTokenStore.put(refreshToken.getValue(), refreshToken); + this.refreshTokenAuthenticationStore.put(refreshToken.getValue(), authentication); + } - public OAuth2RefreshToken readRefreshToken(String tokenValue) { - return this.refreshTokenStore.get(tokenValue); - } + public OAuth2RefreshToken readRefreshToken(String tokenValue) { + return this.refreshTokenStore.get(tokenValue); + } - public void removeRefreshToken(OAuth2RefreshToken refreshToken) { - removeRefreshToken(refreshToken.getValue()); - } + public void removeRefreshToken(OAuth2RefreshToken refreshToken) { + removeRefreshToken(refreshToken.getValue()); + } - public void removeRefreshToken(String tokenValue) { - this.refreshTokenStore.remove(tokenValue); - this.refreshTokenAuthenticationStore.remove(tokenValue); - this.refreshTokenToAccessTokenStore.remove(tokenValue); - } + public void removeRefreshToken(String tokenValue) { + this.refreshTokenStore.remove(tokenValue); + this.refreshTokenAuthenticationStore.remove(tokenValue); + this.refreshTokenToAccessTokenStore.remove(tokenValue); + } - public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) { - removeAccessTokenUsingRefreshToken(refreshToken.getValue()); - } + public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) { + removeAccessTokenUsingRefreshToken(refreshToken.getValue()); + } - private void removeAccessTokenUsingRefreshToken(String refreshToken) { - String accessToken = this.refreshTokenToAccessTokenStore.remove(refreshToken); - if (accessToken != null) { - removeAccessToken(accessToken); - } - } + private void removeAccessTokenUsingRefreshToken(String refreshToken) { + String accessToken = this.refreshTokenToAccessTokenStore.remove(refreshToken); + if (accessToken != null) { + removeAccessToken(accessToken); + } + } - public Collection findTokensByClientIdAndUserName(String clientId, String userName) { - Collection result = userNameToAccessTokenStore.get(getApprovalKey(clientId, userName)); - return result != null ? Collections. unmodifiableCollection(result) : Collections - . emptySet(); - } + public Collection findTokensByClientIdAndUserName(String clientId, String userName) { + Collection result = userNameToAccessTokenStore.get(getApprovalKey(clientId, userName)); + return result != null ? Collections. unmodifiableCollection(result) : Collections + . emptySet(); + } - public Collection findTokensByClientId(String clientId) { - Collection result = clientIdToAccessTokenStore.get(clientId); - return result != null ? Collections. unmodifiableCollection(result) : Collections - . emptySet(); - } + public Collection findTokensByClientId(String clientId) { + Collection result = clientIdToAccessTokenStore.get(clientId); + return result != null ? Collections. unmodifiableCollection(result) : Collections + . emptySet(); + } - private void flush() { - TokenExpiry expiry = expiryQueue.poll(); - while (expiry != null) { - removeAccessToken(expiry.getValue()); - expiry = expiryQueue.poll(); - } - } + private void flush() { + TokenExpiry expiry = expiryQueue.poll(); + while (expiry != null) { + removeAccessToken(expiry.getValue()); + expiry = expiryQueue.poll(); + } + } - private static class TokenExpiry implements Delayed { + private static class TokenExpiry implements Delayed { - private final long expiry; + private final long expiry; - private final String value; + private final String value; - public TokenExpiry(String value, Date date) { - this.value = value; - this.expiry = date.getTime(); - } + public TokenExpiry(String value, Date date) { + this.value = value; + this.expiry = date.getTime(); + } - public int compareTo(Delayed other) { - if (this == other) { - return 0; - } - long diff = getDelay(TimeUnit.MILLISECONDS) - other.getDelay(TimeUnit.MILLISECONDS); - return (diff == 0 ? 0 : ((diff < 0) ? -1 : 1)); - } + public int compareTo(Delayed other) { + if (this == other) { + return 0; + } + long diff = getDelay(TimeUnit.MILLISECONDS) - other.getDelay(TimeUnit.MILLISECONDS); + return (diff == 0 ? 0 : ((diff < 0) ? -1 : 1)); + } - public long getDelay(TimeUnit unit) { - return expiry - System.currentTimeMillis(); - } + public long getDelay(TimeUnit unit) { + return expiry - System.currentTimeMillis(); + } - public String getValue() { - return value; - } + public String getValue() { + return value; + } - } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/store/JwtTokenStore.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/store/JwtTokenStore.java index 73dd1cd4e..7433f1960 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/store/JwtTokenStore.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/store/JwtTokenStore.java @@ -42,139 +42,139 @@ import org.springframework.security.core.Authentication; */ public class JwtTokenStore implements TokenStore { - private JwtAccessTokenConverter jwtTokenEnhancer; + private JwtAccessTokenConverter jwtTokenEnhancer; - private ApprovalStore approvalStore; + private ApprovalStore approvalStore; - /** - * Create a JwtTokenStore with this token enhancer (should be shared with the DefaultTokenServices if used). - * - * @param jwtTokenEnhancer - */ - public JwtTokenStore(JwtAccessTokenConverter jwtTokenEnhancer) { - this.jwtTokenEnhancer = jwtTokenEnhancer; - } + /** + * Create a JwtTokenStore with this token enhancer (should be shared with the DefaultTokenServices if used). + * + * @param jwtTokenEnhancer + */ + public JwtTokenStore(JwtAccessTokenConverter jwtTokenEnhancer) { + this.jwtTokenEnhancer = jwtTokenEnhancer; + } - /** - * ApprovalStore to be used to validate and restrict refresh tokens. - * - * @param approvalStore the approvalStore to set - */ - public void setApprovalStore(ApprovalStore approvalStore) { - this.approvalStore = approvalStore; - } + /** + * ApprovalStore to be used to validate and restrict refresh tokens. + * + * @param approvalStore the approvalStore to set + */ + public void setApprovalStore(ApprovalStore approvalStore) { + this.approvalStore = approvalStore; + } - @Override - public OAuth2Authentication readAuthentication(OAuth2AccessToken token) { - return readAuthentication(token.getValue()); - } + @Override + public OAuth2Authentication readAuthentication(OAuth2AccessToken token) { + return readAuthentication(token.getValue()); + } - @Override - public OAuth2Authentication readAuthentication(String token) { - return jwtTokenEnhancer.extractAuthentication(jwtTokenEnhancer.decode(token)); - } + @Override + public OAuth2Authentication readAuthentication(String token) { + return jwtTokenEnhancer.extractAuthentication(jwtTokenEnhancer.decode(token)); + } - @Override - public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { - } + @Override + public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { + } - @Override - public OAuth2AccessToken readAccessToken(String tokenValue) { - return jwtTokenEnhancer.extractAccessToken(tokenValue, jwtTokenEnhancer.decode(tokenValue)); - } + @Override + public OAuth2AccessToken readAccessToken(String tokenValue) { + return jwtTokenEnhancer.extractAccessToken(tokenValue, jwtTokenEnhancer.decode(tokenValue)); + } - @Override - public void removeAccessToken(OAuth2AccessToken token) { - if (approvalStore != null) { - OAuth2Authentication auth = readAuthentication(token); - String clientId = auth.getOAuth2Request().getClientId(); - Authentication user = auth.getUserAuthentication(); - if (user != null) { - Collection approvals = new ArrayList(); - for (String scope : auth.getOAuth2Request().getScope()) { - approvals.add(new Approval(user.getName(), clientId, scope, new Date(), ApprovalStatus.APPROVED)); - } - approvalStore.revokeApprovals(approvals); - } - } - } + @Override + public void removeAccessToken(OAuth2AccessToken token) { + if (approvalStore != null) { + OAuth2Authentication auth = readAuthentication(token); + String clientId = auth.getOAuth2Request().getClientId(); + Authentication user = auth.getUserAuthentication(); + if (user != null) { + Collection approvals = new ArrayList(); + for (String scope : auth.getOAuth2Request().getScope()) { + approvals.add(new Approval(user.getName(), clientId, scope, new Date(), ApprovalStatus.APPROVED)); + } + approvalStore.revokeApprovals(approvals); + } + } + } - @Override - public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) { - } + @Override + public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) { + } - @Override - public OAuth2RefreshToken readRefreshToken(String tokenValue) { - OAuth2AccessToken encodedRefreshToken = readAccessToken(tokenValue); - ExpiringOAuth2RefreshToken refreshToken = new DefaultExpiringOAuth2RefreshToken(encodedRefreshToken.getValue(), - encodedRefreshToken.getExpiration()); - if (approvalStore != null) { - OAuth2Authentication authentication = readAuthentication(tokenValue); - if (authentication.getUserAuthentication() != null) { - String userId = authentication.getUserAuthentication().getName(); - String clientId = authentication.getOAuth2Request().getClientId(); - Collection approvals = approvalStore.getApprovals(userId, clientId); - Collection approvedScopes = new HashSet(); - for (Approval approval : approvals) { - if (approval.isApproved()) { - approvedScopes.add(approval.getScope()); - } - } - if (!approvedScopes.containsAll(authentication.getOAuth2Request().getScope())) { - return null; - } - } - } - return refreshToken; - } + @Override + public OAuth2RefreshToken readRefreshToken(String tokenValue) { + OAuth2AccessToken encodedRefreshToken = readAccessToken(tokenValue); + ExpiringOAuth2RefreshToken refreshToken = new DefaultExpiringOAuth2RefreshToken(encodedRefreshToken.getValue(), + encodedRefreshToken.getExpiration()); + if (approvalStore != null) { + OAuth2Authentication authentication = readAuthentication(tokenValue); + if (authentication.getUserAuthentication() != null) { + String userId = authentication.getUserAuthentication().getName(); + String clientId = authentication.getOAuth2Request().getClientId(); + Collection approvals = approvalStore.getApprovals(userId, clientId); + Collection approvedScopes = new HashSet(); + for (Approval approval : approvals) { + if (approval.isApproved()) { + approvedScopes.add(approval.getScope()); + } + } + if (!approvedScopes.containsAll(authentication.getOAuth2Request().getScope())) { + return null; + } + } + } + return refreshToken; + } - @Override - public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) { - return readAuthentication(token.getValue()); - } + @Override + public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) { + return readAuthentication(token.getValue()); + } - @Override - public void removeRefreshToken(OAuth2RefreshToken token) { - remove(token.getValue()); - } + @Override + public void removeRefreshToken(OAuth2RefreshToken token) { + remove(token.getValue()); + } - @Override - public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) { - removeRefreshToken(refreshToken); - } + @Override + public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) { + removeRefreshToken(refreshToken); + } - @Override - public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) { - // We don't want to accidentally issue a token, and we have no way to reconstruct the refresh token - return null; - } + @Override + public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) { + // We don't want to accidentally issue a token, and we have no way to reconstruct the refresh token + return null; + } - @Override - public Collection findTokensByClientIdAndUserName(String clientId, String userName) { - return Collections.emptySet(); - } + @Override + public Collection findTokensByClientIdAndUserName(String clientId, String userName) { + return Collections.emptySet(); + } - @Override - public Collection findTokensByClientId(String clientId) { - return Collections.emptySet(); - } + @Override + public Collection findTokensByClientId(String clientId) { + return Collections.emptySet(); + } - public void setTokenEnhancer(JwtAccessTokenConverter tokenEnhancer) { - this.jwtTokenEnhancer = tokenEnhancer; - } + public void setTokenEnhancer(JwtAccessTokenConverter tokenEnhancer) { + this.jwtTokenEnhancer = tokenEnhancer; + } - private void remove(String token) { - if (approvalStore != null) { - OAuth2Authentication auth = readAuthentication(token); - String clientId = auth.getOAuth2Request().getClientId(); - Authentication user = auth.getUserAuthentication(); - if (user != null) { - Collection approvals = new ArrayList(); - for (String scope : auth.getOAuth2Request().getScope()) { - approvals.add(new Approval(user.getName(), clientId, scope, new Date(), ApprovalStatus.APPROVED)); - } - approvalStore.revokeApprovals(approvals); - } - } - } + private void remove(String token) { + if (approvalStore != null) { + OAuth2Authentication auth = readAuthentication(token); + String clientId = auth.getOAuth2Request().getClientId(); + Authentication user = auth.getUserAuthentication(); + if (user != null) { + Collection approvals = new ArrayList(); + for (String scope : auth.getOAuth2Request().getScope()) { + approvals.add(new Approval(user.getName(), clientId, scope, new Date(), ApprovalStatus.APPROVED)); + } + approvalStore.revokeApprovals(approvals); + } + } + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/store/KeyStoreKeyFactory.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/store/KeyStoreKeyFactory.java index a7331dc13..45b1cc86b 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/store/KeyStoreKeyFactory.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/store/KeyStoreKeyFactory.java @@ -30,41 +30,41 @@ import org.springframework.core.io.Resource; */ public class KeyStoreKeyFactory { - private Resource resource; + private Resource resource; - private char[] password; + private char[] password; - private KeyStore store; + private KeyStore store; - private Object lock = new Object(); + private Object lock = new Object(); - public KeyStoreKeyFactory(Resource resource, char[] password) { - this.resource = resource; - this.password = password; - } + public KeyStoreKeyFactory(Resource resource, char[] password) { + this.resource = resource; + this.password = password; + } - public KeyPair getKeyPair(String alias) { - return getKeyPair(alias, password); - } + public KeyPair getKeyPair(String alias) { + return getKeyPair(alias, password); + } - public KeyPair getKeyPair(String alias, char[] password) { - try { - synchronized (lock) { - if (store == null) { - synchronized (lock) { - store = KeyStore.getInstance("jks"); - store.load(resource.getInputStream(), this.password); - } - } - } - RSAPrivateCrtKey key = (RSAPrivateCrtKey) store.getKey(alias, password); - RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent()); - PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(spec); - return new KeyPair(publicKey, key); - } - catch (Exception e) { - throw new IllegalStateException("Cannot load keys from store: " + resource, e); - } - } + public KeyPair getKeyPair(String alias, char[] password) { + try { + synchronized (lock) { + if (store == null) { + synchronized (lock) { + store = KeyStore.getInstance("jks"); + store.load(resource.getInputStream(), this.password); + } + } + } + RSAPrivateCrtKey key = (RSAPrivateCrtKey) store.getKey(alias, password); + RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent()); + PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(spec); + return new KeyPair(publicKey, key); + } + catch (Exception e) { + throw new IllegalStateException("Cannot load keys from store: " + resource, e); + } + } } \ No newline at end of file diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/store/RedisTokenStore.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/store/RedisTokenStore.java index 76dd2ed8b..49b277cce 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/store/RedisTokenStore.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/token/store/RedisTokenStore.java @@ -42,341 +42,341 @@ import java.util.Date; * @author efenderbosch */ public class RedisTokenStore implements TokenStore { - static final Logger _logger = LoggerFactory.getLogger(RedisTokenStore.class); - - private static final String PREFIX = "MXK_OAUTH_V20_"; - - private static final String ACCESS = PREFIX + "ACCESS_"; - private static final String AUTH_TO_ACCESS = PREFIX + "AUTH_TO_ACCESS_"; - private static final String AUTH = PREFIX + "AUTH_"; - private static final String REFRESH_AUTH = PREFIX + "REFRESH_AUTH_"; - private static final String ACCESS_TO_REFRESH = PREFIX + "ACCESS_TO_REFRESH_"; - private static final String REFRESH = PREFIX + "REFRESH_"; - private static final String REFRESH_TO_ACCESS = PREFIX + "REFRESH_TO_ACCESS_"; - private static final String CLIENT_ID_TO_ACCESS = PREFIX + "CLIENT_ID_TO_ACCESS_"; - private static final String UNAME_TO_ACCESS = PREFIX + "UNAME_TO_ACCESS_"; + static final Logger _logger = LoggerFactory.getLogger(RedisTokenStore.class); + + private static final String PREFIX = "MXK_OAUTH_V20_"; + + private static final String ACCESS = PREFIX + "ACCESS_"; + private static final String AUTH_TO_ACCESS = PREFIX + "AUTH_TO_ACCESS_"; + private static final String AUTH = PREFIX + "AUTH_"; + private static final String REFRESH_AUTH = PREFIX + "REFRESH_AUTH_"; + private static final String ACCESS_TO_REFRESH = PREFIX + "ACCESS_TO_REFRESH_"; + private static final String REFRESH = PREFIX + "REFRESH_"; + private static final String REFRESH_TO_ACCESS = PREFIX + "REFRESH_TO_ACCESS_"; + private static final String CLIENT_ID_TO_ACCESS = PREFIX + "CLIENT_ID_TO_ACCESS_"; + private static final String UNAME_TO_ACCESS = PREFIX + "UNAME_TO_ACCESS_"; - private final RedisConnectionFactory connectionFactory; - private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator(); - - + private final RedisConnectionFactory connectionFactory; + private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator(); + + - public RedisTokenStore(RedisConnectionFactory connectionFactory) { - this.connectionFactory = connectionFactory; - } + public RedisTokenStore(RedisConnectionFactory connectionFactory) { + this.connectionFactory = connectionFactory; + } - public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) { - this.authenticationKeyGenerator = authenticationKeyGenerator; - } + public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) { + this.authenticationKeyGenerator = authenticationKeyGenerator; + } - private RedisConnection getConnection() { - return connectionFactory.getConnection(); - } + private RedisConnection getConnection() { + return connectionFactory.getConnection(); + } - @Override - public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) { - String key = authenticationKeyGenerator.extractKey(authentication); - String serializedKey = (AUTH_TO_ACCESS + key); - RedisConnection conn = getConnection(); - try { - OAuth2AccessToken accessToken =conn.getObject(serializedKey); - if (accessToken != null - && !key.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) { - // Keep the stores consistent (maybe the same user is - // represented by this authentication but the details have - // changed) - storeAccessToken(accessToken, authentication); - } - return accessToken; - } finally { - conn.close(); - } - } + @Override + public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) { + String key = authenticationKeyGenerator.extractKey(authentication); + String serializedKey = (AUTH_TO_ACCESS + key); + RedisConnection conn = getConnection(); + try { + OAuth2AccessToken accessToken =conn.getObject(serializedKey); + if (accessToken != null + && !key.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) { + // Keep the stores consistent (maybe the same user is + // represented by this authentication but the details have + // changed) + storeAccessToken(accessToken, authentication); + } + return accessToken; + } finally { + conn.close(); + } + } - @Override - public OAuth2Authentication readAuthentication(OAuth2AccessToken token) { - return readAuthentication(token.getValue()); - } + @Override + public OAuth2Authentication readAuthentication(OAuth2AccessToken token) { + return readAuthentication(token.getValue()); + } - @Override - public OAuth2Authentication readAuthentication(String token) { - _logger.trace("read Authentication by token " + token + " , token key " + AUTH + token); - RedisConnection conn = getConnection(); - try { - OAuth2Authentication auth = conn.getObject(AUTH + token); - return auth; - } finally { - conn.close(); - } - } + @Override + public OAuth2Authentication readAuthentication(String token) { + _logger.trace("read Authentication by token " + token + " , token key " + AUTH + token); + RedisConnection conn = getConnection(); + try { + OAuth2Authentication auth = conn.getObject(AUTH + token); + return auth; + } finally { + conn.close(); + } + } - @Override - public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) { - return readAuthenticationForRefreshToken(token.getValue()); - } + @Override + public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) { + return readAuthenticationForRefreshToken(token.getValue()); + } - public OAuth2Authentication readAuthenticationForRefreshToken(String token) { - RedisConnection conn = getConnection(); - try { - OAuth2Authentication auth = conn.getObject(REFRESH_AUTH + token); - return auth; - } finally { - conn.close(); - } - } + public OAuth2Authentication readAuthenticationForRefreshToken(String token) { + RedisConnection conn = getConnection(); + try { + OAuth2Authentication auth = conn.getObject(REFRESH_AUTH + token); + return auth; + } finally { + conn.close(); + } + } - @Override - public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { - String accessKey = (ACCESS + token.getValue()); - String authKey = (AUTH + token.getValue()); - String authToAccessKey = (AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication)); - String approvalKey = (UNAME_TO_ACCESS + getApprovalKey(authentication)); - String clientId = (CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId()); - _logger.trace("accessKey " + accessKey); - _logger.trace("authKey " + authKey); - _logger.trace("authToAccessKey " + authToAccessKey); - _logger.trace("approvalKey " + approvalKey); - _logger.trace("clientId " + clientId); + @Override + public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { + String accessKey = (ACCESS + token.getValue()); + String authKey = (AUTH + token.getValue()); + String authToAccessKey = (AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication)); + String approvalKey = (UNAME_TO_ACCESS + getApprovalKey(authentication)); + String clientId = (CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId()); + _logger.trace("accessKey " + accessKey); + _logger.trace("authKey " + authKey); + _logger.trace("authToAccessKey " + authToAccessKey); + _logger.trace("approvalKey " + approvalKey); + _logger.trace("clientId " + clientId); - RedisConnection conn = getConnection(); - try { - conn.openPipeline(); - conn.setObject(accessKey, token); - conn.setObject(authKey, authentication); - conn.setObject(authToAccessKey, token); - if (!authentication.isClientOnly()) { - conn.rPush(approvalKey, token); - } - conn.rPush(clientId, token); - if (token.getExpiration() != null) { - int seconds = token.getExpiresIn(); - conn.expire(accessKey, seconds); - conn.expire(authKey, seconds); - conn.expire(authToAccessKey, seconds); - conn.expire(clientId, seconds); - conn.expire(approvalKey, seconds); - } - OAuth2RefreshToken refreshToken = token.getRefreshToken(); - if (refreshToken != null && refreshToken.getValue() != null) { - String refresh = (token.getRefreshToken().getValue()); - String auth = (token.getValue()); - String refreshToAccessKey = (REFRESH_TO_ACCESS + token.getRefreshToken().getValue()); - _logger.trace("refreshToAccessKey " + refreshToAccessKey); - conn.set(refreshToAccessKey, auth); - String accessToRefreshKey = (ACCESS_TO_REFRESH + token.getValue()); - _logger.trace("accessToRefreshKey " + accessToRefreshKey); - conn.set(accessToRefreshKey, refresh); - if (refreshToken instanceof ExpiringOAuth2RefreshToken) { - ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken; - Date expiration = expiringRefreshToken.getExpiration(); - if (expiration != null) { - int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L) - .intValue(); - conn.expire(refreshToAccessKey, seconds); - conn.expire(accessToRefreshKey, seconds); - } - } - } - conn.closePipeline(); - } finally { - conn.close(); - } - } + RedisConnection conn = getConnection(); + try { + conn.openPipeline(); + conn.setObject(accessKey, token); + conn.setObject(authKey, authentication); + conn.setObject(authToAccessKey, token); + if (!authentication.isClientOnly()) { + conn.rPush(approvalKey, token); + } + conn.rPush(clientId, token); + if (token.getExpiration() != null) { + int seconds = token.getExpiresIn(); + conn.expire(accessKey, seconds); + conn.expire(authKey, seconds); + conn.expire(authToAccessKey, seconds); + conn.expire(clientId, seconds); + conn.expire(approvalKey, seconds); + } + OAuth2RefreshToken refreshToken = token.getRefreshToken(); + if (refreshToken != null && refreshToken.getValue() != null) { + String refresh = (token.getRefreshToken().getValue()); + String auth = (token.getValue()); + String refreshToAccessKey = (REFRESH_TO_ACCESS + token.getRefreshToken().getValue()); + _logger.trace("refreshToAccessKey " + refreshToAccessKey); + conn.set(refreshToAccessKey, auth); + String accessToRefreshKey = (ACCESS_TO_REFRESH + token.getValue()); + _logger.trace("accessToRefreshKey " + accessToRefreshKey); + conn.set(accessToRefreshKey, refresh); + if (refreshToken instanceof ExpiringOAuth2RefreshToken) { + ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken; + Date expiration = expiringRefreshToken.getExpiration(); + if (expiration != null) { + int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L) + .intValue(); + conn.expire(refreshToAccessKey, seconds); + conn.expire(accessToRefreshKey, seconds); + } + } + } + conn.closePipeline(); + } finally { + conn.close(); + } + } - private static String getApprovalKey(OAuth2Authentication authentication) { - String userName = authentication.getUserAuthentication() == null ? "" - : authentication.getUserAuthentication().getName(); - return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName); - } + private static String getApprovalKey(OAuth2Authentication authentication) { + String userName = authentication.getUserAuthentication() == null ? "" + : authentication.getUserAuthentication().getName(); + return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName); + } - private static String getApprovalKey(String clientId, String userName) { - return clientId + (userName == null ? "" : "_" + userName); - } + private static String getApprovalKey(String clientId, String userName) { + return clientId + (userName == null ? "" : "_" + userName); + } - @Override - public void removeAccessToken(OAuth2AccessToken accessToken) { - removeAccessToken(accessToken.getValue()); - } + @Override + public void removeAccessToken(OAuth2AccessToken accessToken) { + removeAccessToken(accessToken.getValue()); + } - @Override - public OAuth2AccessToken readAccessToken(String tokenValue) { - RedisConnection conn = getConnection(); - try { - String key = (ACCESS + tokenValue); - OAuth2AccessToken accessToken = conn.getObject(key); - return accessToken; - } finally { - conn.close(); - } - } + @Override + public OAuth2AccessToken readAccessToken(String tokenValue) { + RedisConnection conn = getConnection(); + try { + String key = (ACCESS + tokenValue); + OAuth2AccessToken accessToken = conn.getObject(key); + return accessToken; + } finally { + conn.close(); + } + } - public void removeAccessToken(String tokenValue) { - String accessKey = (ACCESS + tokenValue); - String authKey = (AUTH + tokenValue); - String accessToRefreshKey = (ACCESS_TO_REFRESH + tokenValue); - RedisConnection conn = getConnection(); - try { - conn.openPipeline(); - conn.getPipeline().get(accessKey); - conn.getPipeline().get(authKey); - conn.getPipeline().del(accessKey); - conn.getPipeline().del(accessToRefreshKey); - //Don't remove the refresh token - it's up to the caller to do that - conn.getPipeline().del(authKey); - List results = conn.closePipeline(); - String access = (String) results.get(0); - String auth = (String) results.get(1); - OAuth2Authentication authentication = ObjectTransformer.deserialize(auth); - if (authentication != null) { - String key = authenticationKeyGenerator.extractKey(authentication); - String authToAccessKey = (AUTH_TO_ACCESS + key); - String unameKey = (UNAME_TO_ACCESS + getApprovalKey(authentication)); - String clientId = (CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId()); - conn.openPipeline(); - conn.delete(authToAccessKey); - conn.lRem(unameKey, 1, access); - conn.lRem(clientId, 1, access); - conn.delete(ACCESS + key); - conn.closePipeline(); - } - } finally { - conn.close(); - } - } + public void removeAccessToken(String tokenValue) { + String accessKey = (ACCESS + tokenValue); + String authKey = (AUTH + tokenValue); + String accessToRefreshKey = (ACCESS_TO_REFRESH + tokenValue); + RedisConnection conn = getConnection(); + try { + conn.openPipeline(); + conn.getPipeline().get(accessKey); + conn.getPipeline().get(authKey); + conn.getPipeline().del(accessKey); + conn.getPipeline().del(accessToRefreshKey); + //Don't remove the refresh token - it's up to the caller to do that + conn.getPipeline().del(authKey); + List results = conn.closePipeline(); + String access = (String) results.get(0); + String auth = (String) results.get(1); + OAuth2Authentication authentication = ObjectTransformer.deserialize(auth); + if (authentication != null) { + String key = authenticationKeyGenerator.extractKey(authentication); + String authToAccessKey = (AUTH_TO_ACCESS + key); + String unameKey = (UNAME_TO_ACCESS + getApprovalKey(authentication)); + String clientId = (CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId()); + conn.openPipeline(); + conn.delete(authToAccessKey); + conn.lRem(unameKey, 1, access); + conn.lRem(clientId, 1, access); + conn.delete(ACCESS + key); + conn.closePipeline(); + } + } finally { + conn.close(); + } + } - @Override - public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) { - String refreshKey = (REFRESH + refreshToken.getValue()); - String refreshAuthKey = (REFRESH_AUTH + refreshToken.getValue()); - RedisConnection conn = getConnection(); - try { - conn.openPipeline(); - conn.setObject(refreshKey, refreshToken); - conn.setObject(refreshAuthKey, authentication); - - if (refreshToken instanceof ExpiringOAuth2RefreshToken) { - ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken; - Date expiration = expiringRefreshToken.getExpiration(); - if (expiration != null) { - int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L) - .intValue(); - conn.expire(refreshKey, seconds); - conn.expire(refreshAuthKey, seconds); - } - } - conn.closePipeline(); - } finally { - conn.close(); - } - } + @Override + public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) { + String refreshKey = (REFRESH + refreshToken.getValue()); + String refreshAuthKey = (REFRESH_AUTH + refreshToken.getValue()); + RedisConnection conn = getConnection(); + try { + conn.openPipeline(); + conn.setObject(refreshKey, refreshToken); + conn.setObject(refreshAuthKey, authentication); + + if (refreshToken instanceof ExpiringOAuth2RefreshToken) { + ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken; + Date expiration = expiringRefreshToken.getExpiration(); + if (expiration != null) { + int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L) + .intValue(); + conn.expire(refreshKey, seconds); + conn.expire(refreshAuthKey, seconds); + } + } + conn.closePipeline(); + } finally { + conn.close(); + } + } - @Override - public OAuth2RefreshToken readRefreshToken(String tokenValue) { - String key = (REFRESH + tokenValue); - RedisConnection conn = getConnection(); - try { - OAuth2RefreshToken refreshToken = conn.getObject(key); - conn.close(); - return refreshToken; - } finally { - conn.close(); - } - } + @Override + public OAuth2RefreshToken readRefreshToken(String tokenValue) { + String key = (REFRESH + tokenValue); + RedisConnection conn = getConnection(); + try { + OAuth2RefreshToken refreshToken = conn.getObject(key); + conn.close(); + return refreshToken; + } finally { + conn.close(); + } + } - @Override - public void removeRefreshToken(OAuth2RefreshToken refreshToken) { - removeRefreshToken(refreshToken.getValue()); - } + @Override + public void removeRefreshToken(OAuth2RefreshToken refreshToken) { + removeRefreshToken(refreshToken.getValue()); + } - public void removeRefreshToken(String tokenValue) { - String refreshKey = (REFRESH + tokenValue); - String refreshAuthKey = (REFRESH_AUTH + tokenValue); - String refresh2AccessKey = (REFRESH_TO_ACCESS + tokenValue); - String access2RefreshKey = (ACCESS_TO_REFRESH + tokenValue); - RedisConnection conn = getConnection(); - try { - conn.openPipeline(); - conn.delete(refreshKey); - conn.delete(refreshAuthKey); - conn.delete(refresh2AccessKey); - conn.delete(access2RefreshKey); - conn.closePipeline(); - } finally { - conn.close(); - } - } + public void removeRefreshToken(String tokenValue) { + String refreshKey = (REFRESH + tokenValue); + String refreshAuthKey = (REFRESH_AUTH + tokenValue); + String refresh2AccessKey = (REFRESH_TO_ACCESS + tokenValue); + String access2RefreshKey = (ACCESS_TO_REFRESH + tokenValue); + RedisConnection conn = getConnection(); + try { + conn.openPipeline(); + conn.delete(refreshKey); + conn.delete(refreshAuthKey); + conn.delete(refresh2AccessKey); + conn.delete(access2RefreshKey); + conn.closePipeline(); + } finally { + conn.close(); + } + } - @Override - public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) { - removeAccessTokenUsingRefreshToken(refreshToken.getValue()); - } + @Override + public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) { + removeAccessTokenUsingRefreshToken(refreshToken.getValue()); + } - private void removeAccessTokenUsingRefreshToken(String refreshToken) { - String key = (REFRESH_TO_ACCESS + refreshToken); - List results = null; - RedisConnection conn = getConnection(); - try { - conn.openPipeline(); - conn.getPipeline().get(key); - conn.getPipeline().del(key); - results = conn.closePipeline(); - } finally { - conn.close(); - } - if (results == null) { - return; - } - String accessToken = (String) results.get(0); - //String accessToken = ObjectTransformer.deserialize(bytes); - if (accessToken != null) { - removeAccessToken(accessToken); - } - - } + private void removeAccessTokenUsingRefreshToken(String refreshToken) { + String key = (REFRESH_TO_ACCESS + refreshToken); + List results = null; + RedisConnection conn = getConnection(); + try { + conn.openPipeline(); + conn.getPipeline().get(key); + conn.getPipeline().del(key); + results = conn.closePipeline(); + } finally { + conn.close(); + } + if (results == null) { + return; + } + String accessToken = (String) results.get(0); + //String accessToken = ObjectTransformer.deserialize(bytes); + if (accessToken != null) { + removeAccessToken(accessToken); + } + + } - @Override - public Collection findTokensByClientIdAndUserName(String clientId, String userName) { - String approvalKey = (UNAME_TO_ACCESS + getApprovalKey(clientId, userName)); - _logger.trace("approvalKey " + approvalKey); - List stringList = null; - RedisConnection conn = getConnection(); - try { - stringList = conn.lRange(approvalKey, 0, -1); - } finally { - conn.close(); - } - if (stringList == null || stringList.size() == 0) { - return Collections. emptySet(); - } - List accessTokens = new ArrayList(stringList.size()); - for (String str : stringList) { - //accessToken may expired - OAuth2AccessToken accessToken = conn.getObject(str); - accessTokens.add(accessToken); - } - return Collections. unmodifiableCollection(accessTokens); - } + @Override + public Collection findTokensByClientIdAndUserName(String clientId, String userName) { + String approvalKey = (UNAME_TO_ACCESS + getApprovalKey(clientId, userName)); + _logger.trace("approvalKey " + approvalKey); + List stringList = null; + RedisConnection conn = getConnection(); + try { + stringList = conn.lRange(approvalKey, 0, -1); + } finally { + conn.close(); + } + if (stringList == null || stringList.size() == 0) { + return Collections. emptySet(); + } + List accessTokens = new ArrayList(stringList.size()); + for (String str : stringList) { + //accessToken may expired + OAuth2AccessToken accessToken = conn.getObject(str); + accessTokens.add(accessToken); + } + return Collections. unmodifiableCollection(accessTokens); + } - @Override - public Collection findTokensByClientId(String clientId) { - String key = (CLIENT_ID_TO_ACCESS + clientId); - _logger.trace("TokensByClientId " + key); - List stringList = null; - RedisConnection conn = getConnection(); - try { - stringList = conn.lRange(key, 0, -1); - } finally { - conn.close(); - } - if (stringList == null || stringList.size() == 0) { - return Collections. emptySet(); - } - List accessTokens = new ArrayList(stringList.size()); - for (String str : stringList) { - OAuth2AccessToken accessToken = conn.getObject(str); - accessTokens.add(accessToken); - } - return Collections. unmodifiableCollection(accessTokens); - } + @Override + public Collection findTokensByClientId(String clientId) { + String key = (CLIENT_ID_TO_ACCESS + clientId); + _logger.trace("TokensByClientId " + key); + List stringList = null; + RedisConnection conn = getConnection(); + try { + stringList = conn.lRange(key, 0, -1); + } finally { + conn.close(); + } + if (stringList == null || stringList.size() == 0) { + return Collections. emptySet(); + } + List accessTokens = new ArrayList(stringList.size()); + for (String str : stringList) { + OAuth2AccessToken accessToken = conn.getObject(str); + accessTokens.add(accessToken); + } + return Collections. unmodifiableCollection(accessTokens); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/userinfo/endpoint/OAuthDefaultUserInfoAdapter.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/userinfo/endpoint/OAuthDefaultUserInfoAdapter.java index 46dd05f39..a188f4f36 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/userinfo/endpoint/OAuthDefaultUserInfoAdapter.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/userinfo/endpoint/OAuthDefaultUserInfoAdapter.java @@ -28,56 +28,56 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OAuthDefaultUserInfoAdapter extends AbstractAuthorizeAdapter { - static final Logger _logger = LoggerFactory.getLogger(OAuthDefaultUserInfoAdapter.class); - ClientDetails clientDetails; - - public OAuthDefaultUserInfoAdapter() {} + static final Logger _logger = LoggerFactory.getLogger(OAuthDefaultUserInfoAdapter.class); + ClientDetails clientDetails; + + public OAuthDefaultUserInfoAdapter() {} - public OAuthDefaultUserInfoAdapter(ClientDetails clientDetails) { - this.clientDetails = clientDetails; - } + public OAuthDefaultUserInfoAdapter(ClientDetails clientDetails) { + this.clientDetails = clientDetails; + } - @Override - public Object generateInfo() { - String subject = AbstractAuthorizeAdapter.getValueByUserAttr(userInfo, clientDetails.getSubject()); - _logger.debug("userId : {} , username : {} , displayName : {} , subject : {}" , - userInfo.getId(), - userInfo.getUsername(), - userInfo.getDisplayName(), - subject); - - HashMap beanMap = new HashMap(); - beanMap.put("randomId",(new StringGenerator()).uuidGenerate()); - beanMap.put("userId", userInfo.getId()); - //for spring security oauth2 - beanMap.put("user", subject); - beanMap.put("username", subject); - - beanMap.put("displayName", userInfo.getDisplayName()); - beanMap.put("employeeNumber", userInfo.getEmployeeNumber()); - beanMap.put("email", userInfo.getEmail()); - beanMap.put("mobile", userInfo.getMobile()); - beanMap.put("realname", userInfo.getDisplayName()); - beanMap.put("birthday", userInfo.getBirthDate()); - beanMap.put("departmentId", userInfo.getDepartmentId()); - beanMap.put("department", userInfo.getDepartment()); - beanMap.put("createdate", userInfo.getCreatedDate()); - beanMap.put("title", userInfo.getJobTitle()); - beanMap.put("state", userInfo.getWorkRegion()); - beanMap.put("gender", userInfo.getGender()); - beanMap.put("institution", userInfo.getInstId()); - beanMap.put(WebConstants.ONLINE_TICKET_NAME, principal.getSessionId()); - - String info= JsonUtils.toString(beanMap); - - return info; - } + @Override + public Object generateInfo() { + String subject = AbstractAuthorizeAdapter.getValueByUserAttr(userInfo, clientDetails.getSubject()); + _logger.debug("userId : {} , username : {} , displayName : {} , subject : {}" , + userInfo.getId(), + userInfo.getUsername(), + userInfo.getDisplayName(), + subject); + + HashMap beanMap = new HashMap(); + beanMap.put("randomId",(new StringGenerator()).uuidGenerate()); + beanMap.put("userId", userInfo.getId()); + //for spring security oauth2 + beanMap.put("user", subject); + beanMap.put("username", subject); + + beanMap.put("displayName", userInfo.getDisplayName()); + beanMap.put("employeeNumber", userInfo.getEmployeeNumber()); + beanMap.put("email", userInfo.getEmail()); + beanMap.put("mobile", userInfo.getMobile()); + beanMap.put("realname", userInfo.getDisplayName()); + beanMap.put("birthday", userInfo.getBirthDate()); + beanMap.put("departmentId", userInfo.getDepartmentId()); + beanMap.put("department", userInfo.getDepartment()); + beanMap.put("createdate", userInfo.getCreatedDate()); + beanMap.put("title", userInfo.getJobTitle()); + beanMap.put("state", userInfo.getWorkRegion()); + beanMap.put("gender", userInfo.getGender()); + beanMap.put("institution", userInfo.getInstId()); + beanMap.put(WebConstants.ONLINE_TICKET_NAME, principal.getSessionId()); + + String info= JsonUtils.toString(beanMap); + + return info; + } - public ClientDetails getClientDetails() { - return clientDetails; - } + public ClientDetails getClientDetails() { + return clientDetails; + } - public void setClientDetails(ClientDetails clientDetails) { - this.clientDetails = clientDetails; - } + public void setClientDetails(ClientDetails clientDetails) { + this.clientDetails = clientDetails; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/userinfo/endpoint/UserInfoEndpoint.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/userinfo/endpoint/UserInfoEndpoint.java index ed6c4b407..75989e66b 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/userinfo/endpoint/UserInfoEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/userinfo/endpoint/UserInfoEndpoint.java @@ -54,90 +54,90 @@ import jakarta.servlet.http.HttpServletResponse; @Tag(name = "2-1-OAuth v2.0 API文档模块") @Controller public class UserInfoEndpoint { - static final Logger _logger = LoggerFactory.getLogger(UserInfoEndpoint.class); - @Autowired - @Qualifier("oauth20JdbcClientDetailsService") - private ClientDetailsService clientDetailsService; - - @Autowired - @Qualifier("oauth20TokenServices") - private DefaultTokenServices oauth20tokenServices; - - @Autowired - private UserInfoService userInfoService; - - @Autowired - protected AppsService appsService; + static final Logger _logger = LoggerFactory.getLogger(UserInfoEndpoint.class); + @Autowired + @Qualifier("oauth20JdbcClientDetailsService") + private ClientDetailsService clientDetailsService; + + @Autowired + @Qualifier("oauth20TokenServices") + private DefaultTokenServices oauth20tokenServices; + + @Autowired + private UserInfoService userInfoService; + + @Autowired + protected AppsService appsService; @Autowired protected HttpResponseAdapter httpResponseAdapter; - + @Operation(summary = "OAuth 2.0 用户信息接口", description = "请求参数access_token , header Authorization , token ",method="GET") - @RequestMapping(value=OAuth2Constants.ENDPOINT.ENDPOINT_USERINFO, method={RequestMethod.POST, RequestMethod.GET}) - public void apiV20UserInfo(HttpServletRequest request, HttpServletResponse response) { - String access_token = RequestTokenUtils.resolveAccessToken(request); - _logger.debug("access_token {}" , access_token); - if (!StringGenerator.uuidMatches(access_token)) { - httpResponseAdapter.write(response,JsonUtils.gsonToString(accessTokenFormatError(access_token)),"json"); - } - - OAuth2Authentication oAuth2Authentication =null; - try{ - oAuth2Authentication = oauth20tokenServices.loadAuthentication(access_token); - - String client_id= oAuth2Authentication.getOAuth2Request().getClientId(); - ClientDetails clientDetails = - clientDetailsService.loadClientByClientId(client_id,true); - - Apps app = appsService.get(client_id); - - AbstractAuthorizeAdapter adapter; - if(ConstsBoolean.isTrue(app.getIsAdapter())){ - adapter =(AbstractAuthorizeAdapter)Instance.newInstance(app.getAdapter()); - try { - BeanUtils.setProperty(adapter, "clientDetails", clientDetails); - } catch (IllegalAccessException | InvocationTargetException e) { - _logger.error("setProperty error . ", e); - } - }else{ - adapter =(AbstractAuthorizeAdapter)new OAuthDefaultUserInfoAdapter(clientDetails); - } - adapter.setPrincipal((SignPrincipal)oAuth2Authentication.getUserAuthentication().getPrincipal()); - adapter.setApp(app); - - Object jsonData = adapter.generateInfo(); - httpResponseAdapter.write(response,jsonData.toString(),"json"); - }catch(OAuth2Exception e){ - HashMapauthzException=new HashMap(); - authzException.put(OAuth2Exception.ERROR, e.getOAuth2ErrorCode()); - authzException.put(OAuth2Exception.DESCRIPTION,e.getMessage()); - httpResponseAdapter.write(response,JsonUtils.gsonToString(authzException),"json"); - } - } - - public HashMap accessTokenFormatError(String access_token){ - HashMapatfe=new HashMap(); - atfe.put(OAuth2Exception.ERROR, "token Format Invalid"); - atfe.put(OAuth2Exception.DESCRIPTION, "access Token Format Invalid , access_token : "+access_token); - - return atfe; - } + @RequestMapping(value=OAuth2Constants.ENDPOINT.ENDPOINT_USERINFO, method={RequestMethod.POST, RequestMethod.GET}) + public void apiV20UserInfo(HttpServletRequest request, HttpServletResponse response) { + String access_token = RequestTokenUtils.resolveAccessToken(request); + _logger.debug("access_token {}" , access_token); + if (!StringGenerator.uuidMatches(access_token)) { + httpResponseAdapter.write(response,JsonUtils.gsonToString(accessTokenFormatError(access_token)),"json"); + } + + OAuth2Authentication oAuth2Authentication =null; + try{ + oAuth2Authentication = oauth20tokenServices.loadAuthentication(access_token); + + String client_id= oAuth2Authentication.getOAuth2Request().getClientId(); + ClientDetails clientDetails = + clientDetailsService.loadClientByClientId(client_id,true); + + Apps app = appsService.get(client_id); + + AbstractAuthorizeAdapter adapter; + if(ConstsBoolean.isTrue(app.getIsAdapter())){ + adapter =(AbstractAuthorizeAdapter)Instance.newInstance(app.getAdapter()); + try { + BeanUtils.setProperty(adapter, "clientDetails", clientDetails); + } catch (IllegalAccessException | InvocationTargetException e) { + _logger.error("setProperty error . ", e); + } + }else{ + adapter =(AbstractAuthorizeAdapter)new OAuthDefaultUserInfoAdapter(clientDetails); + } + adapter.setPrincipal((SignPrincipal)oAuth2Authentication.getUserAuthentication().getPrincipal()); + adapter.setApp(app); + + Object jsonData = adapter.generateInfo(); + httpResponseAdapter.write(response,jsonData.toString(),"json"); + }catch(OAuth2Exception e){ + HashMapauthzException=new HashMap(); + authzException.put(OAuth2Exception.ERROR, e.getOAuth2ErrorCode()); + authzException.put(OAuth2Exception.DESCRIPTION,e.getMessage()); + httpResponseAdapter.write(response,JsonUtils.gsonToString(authzException),"json"); + } + } + + public HashMap accessTokenFormatError(String access_token){ + HashMapatfe=new HashMap(); + atfe.put(OAuth2Exception.ERROR, "token Format Invalid"); + atfe.put(OAuth2Exception.DESCRIPTION, "access Token Format Invalid , access_token : "+access_token); + + return atfe; + } - public UserInfo queryUserInfo(String userId){ - _logger.debug("userId : "+userId); - UserInfo userInfo = (UserInfo) userInfoService.findByUsername(userId); - return userInfo; - } + public UserInfo queryUserInfo(String userId){ + _logger.debug("userId : "+userId); + UserInfo userInfo = (UserInfo) userInfoService.findByUsername(userId); + return userInfo; + } - public void setOauth20tokenServices(DefaultTokenServices oauth20tokenServices) { - this.oauth20tokenServices = oauth20tokenServices; - } - + public void setOauth20tokenServices(DefaultTokenServices oauth20tokenServices) { + this.oauth20tokenServices = oauth20tokenServices; + } + - public void setUserInfoService(UserInfoService userInfoService) { - this.userInfoService = userInfoService; - } + public void setUserInfoService(UserInfoService userInfoService) { + this.userInfoService = userInfoService; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/userinfo/endpoint/UserInfoOIDCEndpoint.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/userinfo/endpoint/UserInfoOIDCEndpoint.java index 826c7de9e..dc3961fed 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/userinfo/endpoint/UserInfoOIDCEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/userinfo/endpoint/UserInfoOIDCEndpoint.java @@ -74,229 +74,229 @@ import com.nimbusds.jwt.SignedJWT; @Tag(name = "2-1-OAuth v2.0 API文档模块") @Controller public class UserInfoOIDCEndpoint { - static final Logger _logger = LoggerFactory.getLogger(UserInfoOIDCEndpoint.class); - @Autowired - @Qualifier("oauth20JdbcClientDetailsService") - private ClientDetailsService clientDetailsService; - - @Autowired - @Qualifier("oauth20TokenServices") - private DefaultTokenServices oauth20tokenServices; - - - @Autowired - private UserInfoService userInfoService; - - @Autowired - protected AppsService appsService; - - OAuthDefaultUserInfoAdapter defaultOAuthUserInfoAdapter=new OAuthDefaultUserInfoAdapter(); - + static final Logger _logger = LoggerFactory.getLogger(UserInfoOIDCEndpoint.class); + @Autowired + @Qualifier("oauth20JdbcClientDetailsService") + private ClientDetailsService clientDetailsService; + + @Autowired + @Qualifier("oauth20TokenServices") + private DefaultTokenServices oauth20tokenServices; + + + @Autowired + private UserInfoService userInfoService; + + @Autowired + protected AppsService appsService; + + OAuthDefaultUserInfoAdapter defaultOAuthUserInfoAdapter=new OAuthDefaultUserInfoAdapter(); + @Autowired protected HttpResponseAdapter httpResponseAdapter; - + @Operation(summary = "OIDC 用户信息接口", description = "请求参数access_token , header Authorization , token ",method="GET") - @RequestMapping(value=OAuth2Constants.ENDPOINT.ENDPOINT_OPENID_CONNECT_USERINFO, method={RequestMethod.POST, RequestMethod.GET}) - @ResponseBody - public String connect10aUserInfo(HttpServletRequest request, - HttpServletResponse response) { - String access_token = RequestTokenUtils.resolveAccessToken(request); - _logger.debug("access_token {}" , access_token); - if (!StringGenerator.uuidMatches(access_token)) { - return JsonUtils.gsonToString(accessTokenFormatError(access_token)); - } - - String principal = ""; - OAuth2Authentication oAuth2Authentication = null; - try{ - oAuth2Authentication = oauth20tokenServices.loadAuthentication(access_token); - - principal=((SignPrincipal)oAuth2Authentication.getPrincipal()).getUsername(); - - Setscopes = oAuth2Authentication.getOAuth2Request().getScope(); - ClientDetails clientDetails = - clientDetailsService.loadClientByClientId(oAuth2Authentication.getOAuth2Request().getClientId(),true); - - UserInfo userInfo = queryUserInfo(principal); - String userJson = ""; - Builder jwtClaimsSetBuilder= new JWTClaimsSet.Builder(); - - SignPrincipal oauthPrincipal = (SignPrincipal)oAuth2Authentication.getUserAuthentication().getPrincipal(); - - String subject = AbstractAuthorizeAdapter.getValueByUserAttr(userInfo, clientDetails.getSubject()); - _logger.debug("userId : {} , username : {} , displayName : {} , subject : {}" , - userInfo.getId(), - userInfo.getUsername(), - userInfo.getDisplayName(), - subject); - - jwtClaimsSetBuilder.claim("sub", subject); - jwtClaimsSetBuilder.claim("institution", userInfo.getInstId()); - jwtClaimsSetBuilder.claim(WebConstants.ONLINE_TICKET_NAME, oauthPrincipal.getSessionId()); - - if(scopes.contains("profile")){ - jwtClaimsSetBuilder.claim("userId", userInfo.getId()); - jwtClaimsSetBuilder.claim("user", userInfo.getUsername()); - jwtClaimsSetBuilder.claim("name", userInfo.getDisplayName()); - jwtClaimsSetBuilder.claim("preferred_username", userInfo.getDisplayName()); - jwtClaimsSetBuilder.claim("given_name", userInfo.getGivenName()); - jwtClaimsSetBuilder.claim("family_name", userInfo.getFamilyName()); - jwtClaimsSetBuilder.claim("middle_name", userInfo.getMiddleName()); - jwtClaimsSetBuilder.claim("nickname", userInfo.getNickName()); - jwtClaimsSetBuilder.claim("profile", "profile"); - jwtClaimsSetBuilder.claim("picture", "picture"); - //jwtClaimsSetBuilder.claim("website", userInfo.getWebSite()); - jwtClaimsSetBuilder.claim("displayName", userInfo.getDisplayName()); - - jwtClaimsSetBuilder.claim("departmentId", userInfo.getDepartmentId()); - jwtClaimsSetBuilder.claim("department", userInfo.getDepartment()); - - String gender; - switch(userInfo.getGender()){ - case UserInfo.GENDER.MALE : - gender="male";break; - case UserInfo.GENDER.FEMALE : - gender="female";break; - default: - gender="unknown"; - } - jwtClaimsSetBuilder.claim("gender", gender); - jwtClaimsSetBuilder.claim("zoneinfo", userInfo.getTimeZone()); - jwtClaimsSetBuilder.claim("locale", userInfo.getLocale()); - jwtClaimsSetBuilder.claim("updated_time", userInfo.getModifiedDate()); - jwtClaimsSetBuilder.claim("birthdate", userInfo.getBirthDate()); - } - - if(scopes.contains("email")){ - jwtClaimsSetBuilder.claim("email", userInfo.getWorkEmail()); - jwtClaimsSetBuilder.claim("email_verified", false); - } - - if(scopes.contains("phone")){ - jwtClaimsSetBuilder.claim("phone_number", userInfo.getWorkPhoneNumber()); - jwtClaimsSetBuilder.claim("phone_number_verified", false); - } - - if(scopes.contains("address")){ - HashMap addressFields = new HashMap(); - addressFields.put("country", userInfo.getWorkCountry()); - addressFields.put("region", userInfo.getWorkRegion()); - addressFields.put("locality", userInfo.getWorkLocality()); - addressFields.put("street_address", userInfo.getWorkStreetAddress()); - addressFields.put("formatted", userInfo.getWorkAddressFormatted()); - addressFields.put("postal_code", userInfo.getWorkPostalCode()); - - jwtClaimsSetBuilder.claim("address", addressFields); - } - - jwtClaimsSetBuilder - .jwtID(UUID.randomUUID().toString())// set a random NONCE in the middle of it - .audience(Arrays.asList(clientDetails.getClientId())) - .issueTime(new Date()) - .expirationTime(new Date(new Date().getTime() + clientDetails.getAccessTokenValiditySeconds() * 1000)); - - //default ContentType - response.setContentType(ContentType.APPLICATION_JWT_UTF8); - - JWTClaimsSet userInfoJWTClaims = jwtClaimsSetBuilder.build(); - JWT userInfoJWT=null; - - if(clientDetails.getUserInfoResponse().equalsIgnoreCase("NORMAL")) { - response.setContentType(ContentType.APPLICATION_JSON_UTF8); - userJson = userInfoJWTClaims.toString(); - }else if (StringUtils.isNotBlank(clientDetails.getSignature()) - && !clientDetails.getSignature().equalsIgnoreCase("none") - && clientDetails.getUserInfoResponse().equalsIgnoreCase("ENCRYPTION")) { - //需要签名 signed ID token - DefaultJwtSigningAndValidationService jwtSignerService = null; - try { - jwtSignerService = new DefaultJwtSigningAndValidationService( - clientDetails.getSignatureKey(), - clientDetails.getClientId() + "_sig", - clientDetails.getSignature()); - }catch(Exception e) { - _logger.error("Couldn't create Jwt Signing Service",e); - } - - JWSAlgorithm signingAlg = jwtSignerService.getDefaultSigningAlgorithm(); - userInfoJWTClaims = new JWTClaimsSet - .Builder(userInfoJWTClaims) - .claim("kid", jwtSignerService.getDefaultSignerKeyId()) - .build(); + @RequestMapping(value=OAuth2Constants.ENDPOINT.ENDPOINT_OPENID_CONNECT_USERINFO, method={RequestMethod.POST, RequestMethod.GET}) + @ResponseBody + public String connect10aUserInfo(HttpServletRequest request, + HttpServletResponse response) { + String access_token = RequestTokenUtils.resolveAccessToken(request); + _logger.debug("access_token {}" , access_token); + if (!StringGenerator.uuidMatches(access_token)) { + return JsonUtils.gsonToString(accessTokenFormatError(access_token)); + } + + String principal = ""; + OAuth2Authentication oAuth2Authentication = null; + try{ + oAuth2Authentication = oauth20tokenServices.loadAuthentication(access_token); + + principal=((SignPrincipal)oAuth2Authentication.getPrincipal()).getUsername(); + + Setscopes = oAuth2Authentication.getOAuth2Request().getScope(); + ClientDetails clientDetails = + clientDetailsService.loadClientByClientId(oAuth2Authentication.getOAuth2Request().getClientId(),true); + + UserInfo userInfo = queryUserInfo(principal); + String userJson = ""; + Builder jwtClaimsSetBuilder= new JWTClaimsSet.Builder(); + + SignPrincipal oauthPrincipal = (SignPrincipal)oAuth2Authentication.getUserAuthentication().getPrincipal(); + + String subject = AbstractAuthorizeAdapter.getValueByUserAttr(userInfo, clientDetails.getSubject()); + _logger.debug("userId : {} , username : {} , displayName : {} , subject : {}" , + userInfo.getId(), + userInfo.getUsername(), + userInfo.getDisplayName(), + subject); + + jwtClaimsSetBuilder.claim("sub", subject); + jwtClaimsSetBuilder.claim("institution", userInfo.getInstId()); + jwtClaimsSetBuilder.claim(WebConstants.ONLINE_TICKET_NAME, oauthPrincipal.getSessionId()); + + if(scopes.contains("profile")){ + jwtClaimsSetBuilder.claim("userId", userInfo.getId()); + jwtClaimsSetBuilder.claim("user", userInfo.getUsername()); + jwtClaimsSetBuilder.claim("name", userInfo.getDisplayName()); + jwtClaimsSetBuilder.claim("preferred_username", userInfo.getDisplayName()); + jwtClaimsSetBuilder.claim("given_name", userInfo.getGivenName()); + jwtClaimsSetBuilder.claim("family_name", userInfo.getFamilyName()); + jwtClaimsSetBuilder.claim("middle_name", userInfo.getMiddleName()); + jwtClaimsSetBuilder.claim("nickname", userInfo.getNickName()); + jwtClaimsSetBuilder.claim("profile", "profile"); + jwtClaimsSetBuilder.claim("picture", "picture"); + //jwtClaimsSetBuilder.claim("website", userInfo.getWebSite()); + jwtClaimsSetBuilder.claim("displayName", userInfo.getDisplayName()); + + jwtClaimsSetBuilder.claim("departmentId", userInfo.getDepartmentId()); + jwtClaimsSetBuilder.claim("department", userInfo.getDepartment()); + + String gender; + switch(userInfo.getGender()){ + case UserInfo.GENDER.MALE : + gender="male";break; + case UserInfo.GENDER.FEMALE : + gender="female";break; + default: + gender="unknown"; + } + jwtClaimsSetBuilder.claim("gender", gender); + jwtClaimsSetBuilder.claim("zoneinfo", userInfo.getTimeZone()); + jwtClaimsSetBuilder.claim("locale", userInfo.getLocale()); + jwtClaimsSetBuilder.claim("updated_time", userInfo.getModifiedDate()); + jwtClaimsSetBuilder.claim("birthdate", userInfo.getBirthDate()); + } + + if(scopes.contains("email")){ + jwtClaimsSetBuilder.claim("email", userInfo.getWorkEmail()); + jwtClaimsSetBuilder.claim("email_verified", false); + } + + if(scopes.contains("phone")){ + jwtClaimsSetBuilder.claim("phone_number", userInfo.getWorkPhoneNumber()); + jwtClaimsSetBuilder.claim("phone_number_verified", false); + } + + if(scopes.contains("address")){ + HashMap addressFields = new HashMap(); + addressFields.put("country", userInfo.getWorkCountry()); + addressFields.put("region", userInfo.getWorkRegion()); + addressFields.put("locality", userInfo.getWorkLocality()); + addressFields.put("street_address", userInfo.getWorkStreetAddress()); + addressFields.put("formatted", userInfo.getWorkAddressFormatted()); + addressFields.put("postal_code", userInfo.getWorkPostalCode()); + + jwtClaimsSetBuilder.claim("address", addressFields); + } + + jwtClaimsSetBuilder + .jwtID(UUID.randomUUID().toString())// set a random NONCE in the middle of it + .audience(Arrays.asList(clientDetails.getClientId())) + .issueTime(new Date()) + .expirationTime(new Date(new Date().getTime() + clientDetails.getAccessTokenValiditySeconds() * 1000)); + + //default ContentType + response.setContentType(ContentType.APPLICATION_JWT_UTF8); + + JWTClaimsSet userInfoJWTClaims = jwtClaimsSetBuilder.build(); + JWT userInfoJWT=null; + + if(clientDetails.getUserInfoResponse().equalsIgnoreCase("NORMAL")) { + response.setContentType(ContentType.APPLICATION_JSON_UTF8); + userJson = userInfoJWTClaims.toString(); + }else if (StringUtils.isNotBlank(clientDetails.getSignature()) + && !clientDetails.getSignature().equalsIgnoreCase("none") + && clientDetails.getUserInfoResponse().equalsIgnoreCase("ENCRYPTION")) { + //需要签名 signed ID token + DefaultJwtSigningAndValidationService jwtSignerService = null; + try { + jwtSignerService = new DefaultJwtSigningAndValidationService( + clientDetails.getSignatureKey(), + clientDetails.getClientId() + "_sig", + clientDetails.getSignature()); + }catch(Exception e) { + _logger.error("Couldn't create Jwt Signing Service",e); + } + + JWSAlgorithm signingAlg = jwtSignerService.getDefaultSigningAlgorithm(); + userInfoJWTClaims = new JWTClaimsSet + .Builder(userInfoJWTClaims) + .claim("kid", jwtSignerService.getDefaultSignerKeyId()) + .build(); - userInfoJWT = new SignedJWT(new JWSHeader(signingAlg), userInfoJWTClaims); - // sign it with the server's key - jwtSignerService.signJwt((SignedJWT) userInfoJWT); - - userJson = userInfoJWT.serialize(); - }else if (StringUtils.isNotBlank(clientDetails.getAlgorithm()) - && !clientDetails.getAlgorithm().equalsIgnoreCase("none") - && clientDetails.getUserInfoResponse().equalsIgnoreCase("SIGNING") - ) { - // 需要加密 - try { - DefaultJwtEncryptionAndDecryptionService jwtEncryptionService = - new DefaultJwtEncryptionAndDecryptionService( - clientDetails.getAlgorithmKey(), - clientDetails.getClientId() + "_enc", - clientDetails.getAlgorithm()); - - Payload payload = userInfoJWTClaims.toPayload(); - - // Example Request JWT encrypted with RSA-OAEP-256 and 128-bit AES/GCM - //JWEHeader jweHeader = new JWEHeader(JWEAlgorithm.RSA1_5, EncryptionMethod.A128GCM); - JWEHeader jweHeader = new JWEHeader( - jwtEncryptionService.getDefaultAlgorithm(clientDetails.getAlgorithm()), - jwtEncryptionService.parseEncryptionMethod(clientDetails.getEncryptionMethod())); - - JWEObject jweObject = new JWEObject( - new JWEHeader.Builder(jweHeader) - .contentType("JWT") // required to indicate nested JWT - .build(), - payload); - - jwtEncryptionService.encryptJwt(jweObject); - userJson = jweObject.serialize(); - } catch (NoSuchAlgorithmException | InvalidKeySpecException | JOSEException e) { - _logger.error("Couldn't create Jwt Encryption Exception", e); - } - }else { - //不需要加密和签名 unsigned ID token + userInfoJWT = new SignedJWT(new JWSHeader(signingAlg), userInfoJWTClaims); + // sign it with the server's key + jwtSignerService.signJwt((SignedJWT) userInfoJWT); + + userJson = userInfoJWT.serialize(); + }else if (StringUtils.isNotBlank(clientDetails.getAlgorithm()) + && !clientDetails.getAlgorithm().equalsIgnoreCase("none") + && clientDetails.getUserInfoResponse().equalsIgnoreCase("SIGNING") + ) { + // 需要加密 + try { + DefaultJwtEncryptionAndDecryptionService jwtEncryptionService = + new DefaultJwtEncryptionAndDecryptionService( + clientDetails.getAlgorithmKey(), + clientDetails.getClientId() + "_enc", + clientDetails.getAlgorithm()); + + Payload payload = userInfoJWTClaims.toPayload(); + + // Example Request JWT encrypted with RSA-OAEP-256 and 128-bit AES/GCM + //JWEHeader jweHeader = new JWEHeader(JWEAlgorithm.RSA1_5, EncryptionMethod.A128GCM); + JWEHeader jweHeader = new JWEHeader( + jwtEncryptionService.getDefaultAlgorithm(clientDetails.getAlgorithm()), + jwtEncryptionService.parseEncryptionMethod(clientDetails.getEncryptionMethod())); + + JWEObject jweObject = new JWEObject( + new JWEHeader.Builder(jweHeader) + .contentType("JWT") // required to indicate nested JWT + .build(), + payload); + + jwtEncryptionService.encryptJwt(jweObject); + userJson = jweObject.serialize(); + } catch (NoSuchAlgorithmException | InvalidKeySpecException | JOSEException e) { + _logger.error("Couldn't create Jwt Encryption Exception", e); + } + }else { + //不需要加密和签名 unsigned ID token userInfoJWT = new PlainJWT(userInfoJWTClaims); userJson = userInfoJWT.serialize(); } - - _logger.trace("OpenID Connect Response {}",userJson); - return userJson; - - }catch(OAuth2Exception e){ - HashMapauthzException=new HashMap(); - authzException.put(OAuth2Exception.ERROR, e.getOAuth2ErrorCode()); - authzException.put(OAuth2Exception.DESCRIPTION,e.getMessage()); - return JsonUtils.toString(authzException); - } - } - - public HashMap accessTokenFormatError(String access_token){ - HashMapatfe=new HashMap(); - atfe.put(OAuth2Exception.ERROR, "token Format Invalid"); - atfe.put(OAuth2Exception.DESCRIPTION, "access Token Format Invalid , access_token : "+access_token); - - return atfe; - } + + _logger.trace("OpenID Connect Response {}",userJson); + return userJson; + + }catch(OAuth2Exception e){ + HashMapauthzException=new HashMap(); + authzException.put(OAuth2Exception.ERROR, e.getOAuth2ErrorCode()); + authzException.put(OAuth2Exception.DESCRIPTION,e.getMessage()); + return JsonUtils.toString(authzException); + } + } + + public HashMap accessTokenFormatError(String access_token){ + HashMapatfe=new HashMap(); + atfe.put(OAuth2Exception.ERROR, "token Format Invalid"); + atfe.put(OAuth2Exception.DESCRIPTION, "access Token Format Invalid , access_token : "+access_token); + + return atfe; + } - public UserInfo queryUserInfo(String userId){ - return (UserInfo) userInfoService.findByUsername(userId); - } + public UserInfo queryUserInfo(String userId){ + return (UserInfo) userInfoService.findByUsername(userId); + } - public void setOauth20tokenServices(DefaultTokenServices oauth20tokenServices) { - this.oauth20tokenServices = oauth20tokenServices; - } - + public void setOauth20tokenServices(DefaultTokenServices oauth20tokenServices) { + this.oauth20tokenServices = oauth20tokenServices; + } + - public void setUserInfoService(UserInfoService userInfoService) { - this.userInfoService = userInfoService; - } + public void setUserInfoService(UserInfoService userInfoService) { + this.userInfoService = userInfoService; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/wellknown/OauthServerConfiguration.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/wellknown/OauthServerConfiguration.java index 259a90436..32a6ef3aa 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/wellknown/OauthServerConfiguration.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/wellknown/OauthServerConfiguration.java @@ -20,242 +20,242 @@ package org.dromara.maxkey.authz.oauth2.provider.wellknown; import java.util.Set; public class OauthServerConfiguration { - String client_id; - String issuer; - String authorization_endpoint; - String token_endpoint; - String userinfo_endpoint; - String registration_endpoint; - String jwks_uri; - Set code_challenge_methods_supported; - - Set response_types_supported; - Set response_modes_supported; - Set grant_types_supported; - Set subject_types_supported; - Set id_token_signing_alg_values_supported; + String client_id; + String issuer; + String authorization_endpoint; + String token_endpoint; + String userinfo_endpoint; + String registration_endpoint; + String jwks_uri; + Set code_challenge_methods_supported; + + Set response_types_supported; + Set response_modes_supported; + Set grant_types_supported; + Set subject_types_supported; + Set id_token_signing_alg_values_supported; - Set scopes_supported; - Set token_endpoint_auth_methods_supported; - Set claims_supported; - String introspection_endpoint; - Set introspection_endpoint_auth_methods_supported; - String revocation_endpoint; - Set revocation_endpoint_auth_methods_supported; - String end_session_endpoint; - boolean request_parameter_supported; - Set request_object_signing_alg_values_supported; - Set backchannel_token_delivery_modes_supported; - Set backchannel_authentication_request_signing_alg_values_supported; + Set scopes_supported; + Set token_endpoint_auth_methods_supported; + Set claims_supported; + String introspection_endpoint; + Set introspection_endpoint_auth_methods_supported; + String revocation_endpoint; + Set revocation_endpoint_auth_methods_supported; + String end_session_endpoint; + boolean request_parameter_supported; + Set request_object_signing_alg_values_supported; + Set backchannel_token_delivery_modes_supported; + Set backchannel_authentication_request_signing_alg_values_supported; - - public String getClient_id() { - return client_id; - } + + public String getClient_id() { + return client_id; + } - public void setClient_id(String client_id) { - this.client_id = client_id; - } + public void setClient_id(String client_id) { + this.client_id = client_id; + } - public String getIssuer() { - return issuer; - } + public String getIssuer() { + return issuer; + } - public void setIssuer(String issuer) { - this.issuer = issuer; - } + public void setIssuer(String issuer) { + this.issuer = issuer; + } - public String getAuthorization_endpoint() { - return authorization_endpoint; - } + public String getAuthorization_endpoint() { + return authorization_endpoint; + } - public void setAuthorization_endpoint(String authorization_endpoint) { - this.authorization_endpoint = authorization_endpoint; - } + public void setAuthorization_endpoint(String authorization_endpoint) { + this.authorization_endpoint = authorization_endpoint; + } - public Set getCode_challenge_methods_supported() { - return code_challenge_methods_supported; - } + public Set getCode_challenge_methods_supported() { + return code_challenge_methods_supported; + } - public void setCode_challenge_methods_supported(Set code_challenge_methods_supported) { - this.code_challenge_methods_supported = code_challenge_methods_supported; - } + public void setCode_challenge_methods_supported(Set code_challenge_methods_supported) { + this.code_challenge_methods_supported = code_challenge_methods_supported; + } - public String getToken_endpoint() { - return token_endpoint; - } + public String getToken_endpoint() { + return token_endpoint; + } - public void setToken_endpoint(String token_endpoint) { - this.token_endpoint = token_endpoint; - } + public void setToken_endpoint(String token_endpoint) { + this.token_endpoint = token_endpoint; + } - public String getUserinfo_endpoint() { - return userinfo_endpoint; - } + public String getUserinfo_endpoint() { + return userinfo_endpoint; + } - public void setUserinfo_endpoint(String userinfo_endpoint) { - this.userinfo_endpoint = userinfo_endpoint; - } + public void setUserinfo_endpoint(String userinfo_endpoint) { + this.userinfo_endpoint = userinfo_endpoint; + } - public String getRegistration_endpoint() { - return registration_endpoint; - } + public String getRegistration_endpoint() { + return registration_endpoint; + } - public void setRegistration_endpoint(String registration_endpoint) { - this.registration_endpoint = registration_endpoint; - } + public void setRegistration_endpoint(String registration_endpoint) { + this.registration_endpoint = registration_endpoint; + } - public String getJwks_uri() { - return jwks_uri; - } + public String getJwks_uri() { + return jwks_uri; + } - public void setJwks_uri(String jwks_uri) { - this.jwks_uri = jwks_uri; - } + public void setJwks_uri(String jwks_uri) { + this.jwks_uri = jwks_uri; + } - public Set getResponse_types_supported() { - return response_types_supported; - } + public Set getResponse_types_supported() { + return response_types_supported; + } - public void setResponse_types_supported(Set response_types_supported) { - this.response_types_supported = response_types_supported; - } + public void setResponse_types_supported(Set response_types_supported) { + this.response_types_supported = response_types_supported; + } - public Set getResponse_modes_supported() { - return response_modes_supported; - } + public Set getResponse_modes_supported() { + return response_modes_supported; + } - public void setResponse_modes_supported(Set response_modes_supported) { - this.response_modes_supported = response_modes_supported; - } + public void setResponse_modes_supported(Set response_modes_supported) { + this.response_modes_supported = response_modes_supported; + } - public Set getGrant_types_supported() { - return grant_types_supported; - } + public Set getGrant_types_supported() { + return grant_types_supported; + } - public void setGrant_types_supported(Set grant_types_supported) { - this.grant_types_supported = grant_types_supported; - } + public void setGrant_types_supported(Set grant_types_supported) { + this.grant_types_supported = grant_types_supported; + } - public Set getSubject_types_supported() { - return subject_types_supported; - } + public Set getSubject_types_supported() { + return subject_types_supported; + } - public void setSubject_types_supported(Set subject_types_supported) { - this.subject_types_supported = subject_types_supported; - } + public void setSubject_types_supported(Set subject_types_supported) { + this.subject_types_supported = subject_types_supported; + } - public Set getId_token_signing_alg_values_supported() { - return id_token_signing_alg_values_supported; - } + public Set getId_token_signing_alg_values_supported() { + return id_token_signing_alg_values_supported; + } - public void setId_token_signing_alg_values_supported(Set id_token_signing_alg_values_supported) { - this.id_token_signing_alg_values_supported = id_token_signing_alg_values_supported; - } + public void setId_token_signing_alg_values_supported(Set id_token_signing_alg_values_supported) { + this.id_token_signing_alg_values_supported = id_token_signing_alg_values_supported; + } - public Set getScopes_supported() { - return scopes_supported; - } + public Set getScopes_supported() { + return scopes_supported; + } - public void setScopes_supported(Set scopes_supported) { - this.scopes_supported = scopes_supported; - } + public void setScopes_supported(Set scopes_supported) { + this.scopes_supported = scopes_supported; + } - public Set getToken_endpoint_auth_methods_supported() { - return token_endpoint_auth_methods_supported; - } + public Set getToken_endpoint_auth_methods_supported() { + return token_endpoint_auth_methods_supported; + } - public void setToken_endpoint_auth_methods_supported(Set token_endpoint_auth_methods_supported) { - this.token_endpoint_auth_methods_supported = token_endpoint_auth_methods_supported; - } + public void setToken_endpoint_auth_methods_supported(Set token_endpoint_auth_methods_supported) { + this.token_endpoint_auth_methods_supported = token_endpoint_auth_methods_supported; + } - public Set getClaims_supported() { - return claims_supported; - } + public Set getClaims_supported() { + return claims_supported; + } - public void setClaims_supported(Set claims_supported) { - this.claims_supported = claims_supported; - } + public void setClaims_supported(Set claims_supported) { + this.claims_supported = claims_supported; + } - public String getIntrospection_endpoint() { - return introspection_endpoint; - } + public String getIntrospection_endpoint() { + return introspection_endpoint; + } - public void setIntrospection_endpoint(String introspection_endpoint) { - this.introspection_endpoint = introspection_endpoint; - } + public void setIntrospection_endpoint(String introspection_endpoint) { + this.introspection_endpoint = introspection_endpoint; + } - public Set getIntrospection_endpoint_auth_methods_supported() { - return introspection_endpoint_auth_methods_supported; - } + public Set getIntrospection_endpoint_auth_methods_supported() { + return introspection_endpoint_auth_methods_supported; + } - public void setIntrospection_endpoint_auth_methods_supported( - Set introspection_endpoint_auth_methods_supported) { - this.introspection_endpoint_auth_methods_supported = introspection_endpoint_auth_methods_supported; - } + public void setIntrospection_endpoint_auth_methods_supported( + Set introspection_endpoint_auth_methods_supported) { + this.introspection_endpoint_auth_methods_supported = introspection_endpoint_auth_methods_supported; + } - public String getRevocation_endpoint() { - return revocation_endpoint; - } + public String getRevocation_endpoint() { + return revocation_endpoint; + } - public void setRevocation_endpoint(String revocation_endpoint) { - this.revocation_endpoint = revocation_endpoint; - } + public void setRevocation_endpoint(String revocation_endpoint) { + this.revocation_endpoint = revocation_endpoint; + } - public Set getRevocation_endpoint_auth_methods_supported() { - return revocation_endpoint_auth_methods_supported; - } + public Set getRevocation_endpoint_auth_methods_supported() { + return revocation_endpoint_auth_methods_supported; + } - public void setRevocation_endpoint_auth_methods_supported( - Set revocation_endpoint_auth_methods_supported) { - this.revocation_endpoint_auth_methods_supported = revocation_endpoint_auth_methods_supported; - } + public void setRevocation_endpoint_auth_methods_supported( + Set revocation_endpoint_auth_methods_supported) { + this.revocation_endpoint_auth_methods_supported = revocation_endpoint_auth_methods_supported; + } - public String getEnd_session_endpoint() { - return end_session_endpoint; - } + public String getEnd_session_endpoint() { + return end_session_endpoint; + } - public void setEnd_session_endpoint(String end_session_endpoint) { - this.end_session_endpoint = end_session_endpoint; - } + public void setEnd_session_endpoint(String end_session_endpoint) { + this.end_session_endpoint = end_session_endpoint; + } - public boolean isRequest_parameter_supported() { - return request_parameter_supported; - } + public boolean isRequest_parameter_supported() { + return request_parameter_supported; + } - public void setRequest_parameter_supported(boolean request_parameter_supported) { - this.request_parameter_supported = request_parameter_supported; - } + public void setRequest_parameter_supported(boolean request_parameter_supported) { + this.request_parameter_supported = request_parameter_supported; + } - public Set getRequest_object_signing_alg_values_supported() { - return request_object_signing_alg_values_supported; - } + public Set getRequest_object_signing_alg_values_supported() { + return request_object_signing_alg_values_supported; + } - public void setRequest_object_signing_alg_values_supported( - Set request_object_signing_alg_values_supported) { - this.request_object_signing_alg_values_supported = request_object_signing_alg_values_supported; - } + public void setRequest_object_signing_alg_values_supported( + Set request_object_signing_alg_values_supported) { + this.request_object_signing_alg_values_supported = request_object_signing_alg_values_supported; + } - public Set getBackchannel_token_delivery_modes_supported() { - return backchannel_token_delivery_modes_supported; - } + public Set getBackchannel_token_delivery_modes_supported() { + return backchannel_token_delivery_modes_supported; + } - public void setBackchannel_token_delivery_modes_supported( - Set backchannel_token_delivery_modes_supported) { - this.backchannel_token_delivery_modes_supported = backchannel_token_delivery_modes_supported; - } + public void setBackchannel_token_delivery_modes_supported( + Set backchannel_token_delivery_modes_supported) { + this.backchannel_token_delivery_modes_supported = backchannel_token_delivery_modes_supported; + } - public Set getBackchannel_authentication_request_signing_alg_values_supported() { - return backchannel_authentication_request_signing_alg_values_supported; - } + public Set getBackchannel_authentication_request_signing_alg_values_supported() { + return backchannel_authentication_request_signing_alg_values_supported; + } - public void setBackchannel_authentication_request_signing_alg_values_supported( - Set backchannel_authentication_request_signing_alg_values_supported) { - this.backchannel_authentication_request_signing_alg_values_supported = backchannel_authentication_request_signing_alg_values_supported; - } + public void setBackchannel_authentication_request_signing_alg_values_supported( + Set backchannel_authentication_request_signing_alg_values_supported) { + this.backchannel_authentication_request_signing_alg_values_supported = backchannel_authentication_request_signing_alg_values_supported; + } - public OauthServerConfiguration() { - super(); - } + public OauthServerConfiguration() { + super(); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/wellknown/OpenidConfiguration.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/wellknown/OpenidConfiguration.java index 3a7c812fb..3475f08c1 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/wellknown/OpenidConfiguration.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/wellknown/OpenidConfiguration.java @@ -20,232 +20,232 @@ package org.dromara.maxkey.authz.oauth2.provider.wellknown; import java.util.Set; public class OpenidConfiguration { - String client_id; - String issuer; - String authorization_endpoint; - String token_endpoint; - String userinfo_endpoint; - String registration_endpoint; - String jwks_uri; - Set response_types_supported; - Set response_modes_supported; - Set grant_types_supported; - Set subject_types_supported; - Set id_token_signing_alg_values_supported; + String client_id; + String issuer; + String authorization_endpoint; + String token_endpoint; + String userinfo_endpoint; + String registration_endpoint; + String jwks_uri; + Set response_types_supported; + Set response_modes_supported; + Set grant_types_supported; + Set subject_types_supported; + Set id_token_signing_alg_values_supported; - Set scopes_supported; - Set token_endpoint_auth_methods_supported; - Set claims_supported; - String introspection_endpoint; - Set introspection_endpoint_auth_methods_supported; - String revocation_endpoint; - Set revocation_endpoint_auth_methods_supported; - String end_session_endpoint; - boolean request_parameter_supported; - Set request_object_signing_alg_values_supported; - Set backchannel_token_delivery_modes_supported; - Set backchannel_authentication_request_signing_alg_values_supported; + Set scopes_supported; + Set token_endpoint_auth_methods_supported; + Set claims_supported; + String introspection_endpoint; + Set introspection_endpoint_auth_methods_supported; + String revocation_endpoint; + Set revocation_endpoint_auth_methods_supported; + String end_session_endpoint; + boolean request_parameter_supported; + Set request_object_signing_alg_values_supported; + Set backchannel_token_delivery_modes_supported; + Set backchannel_authentication_request_signing_alg_values_supported; - - public String getClient_id() { - return client_id; - } + + public String getClient_id() { + return client_id; + } - public void setClient_id(String client_id) { - this.client_id = client_id; - } + public void setClient_id(String client_id) { + this.client_id = client_id; + } - public String getIssuer() { - return issuer; - } + public String getIssuer() { + return issuer; + } - public void setIssuer(String issuer) { - this.issuer = issuer; - } + public void setIssuer(String issuer) { + this.issuer = issuer; + } - public String getAuthorization_endpoint() { - return authorization_endpoint; - } + public String getAuthorization_endpoint() { + return authorization_endpoint; + } - public void setAuthorization_endpoint(String authorization_endpoint) { - this.authorization_endpoint = authorization_endpoint; - } + public void setAuthorization_endpoint(String authorization_endpoint) { + this.authorization_endpoint = authorization_endpoint; + } - public String getToken_endpoint() { - return token_endpoint; - } + public String getToken_endpoint() { + return token_endpoint; + } - public void setToken_endpoint(String token_endpoint) { - this.token_endpoint = token_endpoint; - } + public void setToken_endpoint(String token_endpoint) { + this.token_endpoint = token_endpoint; + } - public String getUserinfo_endpoint() { - return userinfo_endpoint; - } + public String getUserinfo_endpoint() { + return userinfo_endpoint; + } - public void setUserinfo_endpoint(String userinfo_endpoint) { - this.userinfo_endpoint = userinfo_endpoint; - } + public void setUserinfo_endpoint(String userinfo_endpoint) { + this.userinfo_endpoint = userinfo_endpoint; + } - public String getRegistration_endpoint() { - return registration_endpoint; - } + public String getRegistration_endpoint() { + return registration_endpoint; + } - public void setRegistration_endpoint(String registration_endpoint) { - this.registration_endpoint = registration_endpoint; - } + public void setRegistration_endpoint(String registration_endpoint) { + this.registration_endpoint = registration_endpoint; + } - public String getJwks_uri() { - return jwks_uri; - } + public String getJwks_uri() { + return jwks_uri; + } - public void setJwks_uri(String jwks_uri) { - this.jwks_uri = jwks_uri; - } + public void setJwks_uri(String jwks_uri) { + this.jwks_uri = jwks_uri; + } - public Set getResponse_types_supported() { - return response_types_supported; - } + public Set getResponse_types_supported() { + return response_types_supported; + } - public void setResponse_types_supported(Set response_types_supported) { - this.response_types_supported = response_types_supported; - } + public void setResponse_types_supported(Set response_types_supported) { + this.response_types_supported = response_types_supported; + } - public Set getResponse_modes_supported() { - return response_modes_supported; - } + public Set getResponse_modes_supported() { + return response_modes_supported; + } - public void setResponse_modes_supported(Set response_modes_supported) { - this.response_modes_supported = response_modes_supported; - } + public void setResponse_modes_supported(Set response_modes_supported) { + this.response_modes_supported = response_modes_supported; + } - public Set getGrant_types_supported() { - return grant_types_supported; - } + public Set getGrant_types_supported() { + return grant_types_supported; + } - public void setGrant_types_supported(Set grant_types_supported) { - this.grant_types_supported = grant_types_supported; - } + public void setGrant_types_supported(Set grant_types_supported) { + this.grant_types_supported = grant_types_supported; + } - public Set getSubject_types_supported() { - return subject_types_supported; - } + public Set getSubject_types_supported() { + return subject_types_supported; + } - public void setSubject_types_supported(Set subject_types_supported) { - this.subject_types_supported = subject_types_supported; - } + public void setSubject_types_supported(Set subject_types_supported) { + this.subject_types_supported = subject_types_supported; + } - public Set getId_token_signing_alg_values_supported() { - return id_token_signing_alg_values_supported; - } + public Set getId_token_signing_alg_values_supported() { + return id_token_signing_alg_values_supported; + } - public void setId_token_signing_alg_values_supported(Set id_token_signing_alg_values_supported) { - this.id_token_signing_alg_values_supported = id_token_signing_alg_values_supported; - } + public void setId_token_signing_alg_values_supported(Set id_token_signing_alg_values_supported) { + this.id_token_signing_alg_values_supported = id_token_signing_alg_values_supported; + } - public Set getScopes_supported() { - return scopes_supported; - } + public Set getScopes_supported() { + return scopes_supported; + } - public void setScopes_supported(Set scopes_supported) { - this.scopes_supported = scopes_supported; - } + public void setScopes_supported(Set scopes_supported) { + this.scopes_supported = scopes_supported; + } - public Set getToken_endpoint_auth_methods_supported() { - return token_endpoint_auth_methods_supported; - } + public Set getToken_endpoint_auth_methods_supported() { + return token_endpoint_auth_methods_supported; + } - public void setToken_endpoint_auth_methods_supported(Set token_endpoint_auth_methods_supported) { - this.token_endpoint_auth_methods_supported = token_endpoint_auth_methods_supported; - } + public void setToken_endpoint_auth_methods_supported(Set token_endpoint_auth_methods_supported) { + this.token_endpoint_auth_methods_supported = token_endpoint_auth_methods_supported; + } - public Set getClaims_supported() { - return claims_supported; - } + public Set getClaims_supported() { + return claims_supported; + } - public void setClaims_supported(Set claims_supported) { - this.claims_supported = claims_supported; - } + public void setClaims_supported(Set claims_supported) { + this.claims_supported = claims_supported; + } - public String getIntrospection_endpoint() { - return introspection_endpoint; - } + public String getIntrospection_endpoint() { + return introspection_endpoint; + } - public void setIntrospection_endpoint(String introspection_endpoint) { - this.introspection_endpoint = introspection_endpoint; - } + public void setIntrospection_endpoint(String introspection_endpoint) { + this.introspection_endpoint = introspection_endpoint; + } - public Set getIntrospection_endpoint_auth_methods_supported() { - return introspection_endpoint_auth_methods_supported; - } + public Set getIntrospection_endpoint_auth_methods_supported() { + return introspection_endpoint_auth_methods_supported; + } - public void setIntrospection_endpoint_auth_methods_supported( - Set introspection_endpoint_auth_methods_supported) { - this.introspection_endpoint_auth_methods_supported = introspection_endpoint_auth_methods_supported; - } + public void setIntrospection_endpoint_auth_methods_supported( + Set introspection_endpoint_auth_methods_supported) { + this.introspection_endpoint_auth_methods_supported = introspection_endpoint_auth_methods_supported; + } - public String getRevocation_endpoint() { - return revocation_endpoint; - } + public String getRevocation_endpoint() { + return revocation_endpoint; + } - public void setRevocation_endpoint(String revocation_endpoint) { - this.revocation_endpoint = revocation_endpoint; - } + public void setRevocation_endpoint(String revocation_endpoint) { + this.revocation_endpoint = revocation_endpoint; + } - public Set getRevocation_endpoint_auth_methods_supported() { - return revocation_endpoint_auth_methods_supported; - } + public Set getRevocation_endpoint_auth_methods_supported() { + return revocation_endpoint_auth_methods_supported; + } - public void setRevocation_endpoint_auth_methods_supported( - Set revocation_endpoint_auth_methods_supported) { - this.revocation_endpoint_auth_methods_supported = revocation_endpoint_auth_methods_supported; - } + public void setRevocation_endpoint_auth_methods_supported( + Set revocation_endpoint_auth_methods_supported) { + this.revocation_endpoint_auth_methods_supported = revocation_endpoint_auth_methods_supported; + } - public String getEnd_session_endpoint() { - return end_session_endpoint; - } + public String getEnd_session_endpoint() { + return end_session_endpoint; + } - public void setEnd_session_endpoint(String end_session_endpoint) { - this.end_session_endpoint = end_session_endpoint; - } + public void setEnd_session_endpoint(String end_session_endpoint) { + this.end_session_endpoint = end_session_endpoint; + } - public boolean isRequest_parameter_supported() { - return request_parameter_supported; - } + public boolean isRequest_parameter_supported() { + return request_parameter_supported; + } - public void setRequest_parameter_supported(boolean request_parameter_supported) { - this.request_parameter_supported = request_parameter_supported; - } + public void setRequest_parameter_supported(boolean request_parameter_supported) { + this.request_parameter_supported = request_parameter_supported; + } - public Set getRequest_object_signing_alg_values_supported() { - return request_object_signing_alg_values_supported; - } + public Set getRequest_object_signing_alg_values_supported() { + return request_object_signing_alg_values_supported; + } - public void setRequest_object_signing_alg_values_supported( - Set request_object_signing_alg_values_supported) { - this.request_object_signing_alg_values_supported = request_object_signing_alg_values_supported; - } + public void setRequest_object_signing_alg_values_supported( + Set request_object_signing_alg_values_supported) { + this.request_object_signing_alg_values_supported = request_object_signing_alg_values_supported; + } - public Set getBackchannel_token_delivery_modes_supported() { - return backchannel_token_delivery_modes_supported; - } + public Set getBackchannel_token_delivery_modes_supported() { + return backchannel_token_delivery_modes_supported; + } - public void setBackchannel_token_delivery_modes_supported( - Set backchannel_token_delivery_modes_supported) { - this.backchannel_token_delivery_modes_supported = backchannel_token_delivery_modes_supported; - } + public void setBackchannel_token_delivery_modes_supported( + Set backchannel_token_delivery_modes_supported) { + this.backchannel_token_delivery_modes_supported = backchannel_token_delivery_modes_supported; + } - public Set getBackchannel_authentication_request_signing_alg_values_supported() { - return backchannel_authentication_request_signing_alg_values_supported; - } + public Set getBackchannel_authentication_request_signing_alg_values_supported() { + return backchannel_authentication_request_signing_alg_values_supported; + } - public void setBackchannel_authentication_request_signing_alg_values_supported( - Set backchannel_authentication_request_signing_alg_values_supported) { - this.backchannel_authentication_request_signing_alg_values_supported = backchannel_authentication_request_signing_alg_values_supported; - } + public void setBackchannel_authentication_request_signing_alg_values_supported( + Set backchannel_authentication_request_signing_alg_values_supported) { + this.backchannel_authentication_request_signing_alg_values_supported = backchannel_authentication_request_signing_alg_values_supported; + } - public OpenidConfiguration() { - super(); - } + public OpenidConfiguration() { + super(); + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/wellknown/endpoint/OauthAuthorizationServerEndpoint.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/wellknown/endpoint/OauthAuthorizationServerEndpoint.java index 1ff481729..efc15f136 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/wellknown/endpoint/OauthAuthorizationServerEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/wellknown/endpoint/OauthAuthorizationServerEndpoint.java @@ -41,238 +41,238 @@ import io.swagger.v3.oas.annotations.tags.Tag; @Tag(name = "2-1-OAuth v2.0 API文档模块") @Controller public class OauthAuthorizationServerEndpoint extends AbstractEndpoint { - static final Logger _logger = LoggerFactory.getLogger(OauthAuthorizationServerEndpoint.class); - - @Operation(summary = "OAuth v2 metadata 元数据接口", description = "参数client_id",method="GET,POST") - @RequestMapping(value = {OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/.well-known/oauth-authorization-server"}, - produces = "application/json", - method={RequestMethod.POST, RequestMethod.GET}) - @ResponseBody - public OauthServerConfiguration configurationByParam( - @RequestParam(value = "inst_id", required = false) String inst_id, - @RequestParam(value = "client_id", required = false) String client_id) { - return configurationMetadata( inst_id,client_id,"RequestParam"); - } - - @Operation(summary = "OAuth v2 metadata 元数据接口", description = "参数instId,client_id",method="GET,POST") - @RequestMapping(value = {OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/{instId}/{clientId}/.well-known/oauth-authorization-server"}, - produces = "application/json", - method={RequestMethod.POST, RequestMethod.GET}) - @ResponseBody - public OauthServerConfiguration configurationByPath( - @PathVariable("instId") String instId, - @PathVariable(value = "clientId", required = false) String clientId) { - return configurationMetadata(instId,clientId,"PathVariable"); - } - - public OauthServerConfiguration configurationMetadata(String instId,String clientId,String param) { - _logger.debug("instId {} , client_id {}" , instId ,clientId); - - String baseUrl = WebContext.getContextPath(true); - - ClientDetails clientDetails = null; - - if(StringUtils.isNotBlank(clientId)) { - try { - clientDetails = getClientDetailsService().loadClientByClientId(clientId,true); - }catch(Exception e) { - _logger.error("getClientDetailsService", e); - } - } - - OauthServerConfiguration oauthConfig = new OauthServerConfiguration(); - oauthConfig.setRequest_parameter_supported(true); - oauthConfig.setAuthorization_endpoint(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/authorize"); - oauthConfig.setToken_endpoint(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/token"); - oauthConfig.setIntrospection_endpoint(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/introspect"); - oauthConfig.setUserinfo_endpoint(baseUrl + "/api/oauth/v20/me"); - oauthConfig.setEnd_session_endpoint(baseUrl + "/force/logout"); - - Set code_challenge_methods_supported = new HashSet(); - code_challenge_methods_supported.add("S256"); - oauthConfig.setCode_challenge_methods_supported(code_challenge_methods_supported); - - if(clientDetails != null) { - oauthConfig.setClient_id(clientId); - if(param.equals("RequestParam")){ - StringBuffer jwksUri = new StringBuffer(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/jwks"); - jwksUri.append("?"); - jwksUri.append("client_id").append("=").append(clientDetails.getClientId()); - if(StringUtils.isNotBlank(instId)) { - jwksUri.append("&").append("inst_id").append("=").append(instId); - } - oauthConfig.setJwks_uri(jwksUri.toString()); - }else { - oauthConfig.setJwks_uri(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/"+instId+"/"+clientId+"/jwks"); - } + static final Logger _logger = LoggerFactory.getLogger(OauthAuthorizationServerEndpoint.class); + + @Operation(summary = "OAuth v2 metadata 元数据接口", description = "参数client_id",method="GET,POST") + @RequestMapping(value = {OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/.well-known/oauth-authorization-server"}, + produces = "application/json", + method={RequestMethod.POST, RequestMethod.GET}) + @ResponseBody + public OauthServerConfiguration configurationByParam( + @RequestParam(value = "inst_id", required = false) String inst_id, + @RequestParam(value = "client_id", required = false) String client_id) { + return configurationMetadata( inst_id,client_id,"RequestParam"); + } + + @Operation(summary = "OAuth v2 metadata 元数据接口", description = "参数instId,client_id",method="GET,POST") + @RequestMapping(value = {OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/{instId}/{clientId}/.well-known/oauth-authorization-server"}, + produces = "application/json", + method={RequestMethod.POST, RequestMethod.GET}) + @ResponseBody + public OauthServerConfiguration configurationByPath( + @PathVariable("instId") String instId, + @PathVariable(value = "clientId", required = false) String clientId) { + return configurationMetadata(instId,clientId,"PathVariable"); + } + + public OauthServerConfiguration configurationMetadata(String instId,String clientId,String param) { + _logger.debug("instId {} , client_id {}" , instId ,clientId); + + String baseUrl = WebContext.getContextPath(true); + + ClientDetails clientDetails = null; + + if(StringUtils.isNotBlank(clientId)) { + try { + clientDetails = getClientDetailsService().loadClientByClientId(clientId,true); + }catch(Exception e) { + _logger.error("getClientDetailsService", e); + } + } + + OauthServerConfiguration oauthConfig = new OauthServerConfiguration(); + oauthConfig.setRequest_parameter_supported(true); + oauthConfig.setAuthorization_endpoint(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/authorize"); + oauthConfig.setToken_endpoint(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/token"); + oauthConfig.setIntrospection_endpoint(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/introspect"); + oauthConfig.setUserinfo_endpoint(baseUrl + "/api/oauth/v20/me"); + oauthConfig.setEnd_session_endpoint(baseUrl + "/force/logout"); + + Set code_challenge_methods_supported = new HashSet(); + code_challenge_methods_supported.add("S256"); + oauthConfig.setCode_challenge_methods_supported(code_challenge_methods_supported); + + if(clientDetails != null) { + oauthConfig.setClient_id(clientId); + if(param.equals("RequestParam")){ + StringBuffer jwksUri = new StringBuffer(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/jwks"); + jwksUri.append("?"); + jwksUri.append("client_id").append("=").append(clientDetails.getClientId()); + if(StringUtils.isNotBlank(instId)) { + jwksUri.append("&").append("inst_id").append("=").append(instId); + } + oauthConfig.setJwks_uri(jwksUri.toString()); + }else { + oauthConfig.setJwks_uri(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/"+instId+"/"+clientId+"/jwks"); + } - Set introspection_endpoint_auth_methods_supported = new HashSet(); - introspection_endpoint_auth_methods_supported.add("client_secret_basic"); - oauthConfig.setIntrospection_endpoint_auth_methods_supported(introspection_endpoint_auth_methods_supported); - - oauthConfig.setIssuer(clientDetails.getIssuer()); - Set response_types_supported =clientDetails.getAuthorizedGrantTypes(); - if(response_types_supported.contains("authorization_code")) { - response_types_supported.add("code"); - } - oauthConfig.setResponse_types_supported(response_types_supported); - - Set response_modes_supported = new HashSet(); - response_modes_supported.add("query"); - response_modes_supported.add("form_post"); - oauthConfig.setResponse_modes_supported(response_modes_supported); - - oauthConfig.setGrant_types_supported(clientDetails.getAuthorizedGrantTypes()); - oauthConfig.setClaims_supported(clientDetails.getScope()); - - - Set id_token_signing_alg_values_supported = new HashSet(); - id_token_signing_alg_values_supported.add(clientDetails.getSignature().toUpperCase()); - oauthConfig.setId_token_signing_alg_values_supported(id_token_signing_alg_values_supported); - - oauthConfig.setScopes_supported(clientDetails.getScope()); - - Set token_endpoint_auth_methods_supported = new HashSet(); - token_endpoint_auth_methods_supported.add("client_secret_basic"); - token_endpoint_auth_methods_supported.add("client_secret_post"); - token_endpoint_auth_methods_supported.add("none"); - oauthConfig.setToken_endpoint_auth_methods_supported(token_endpoint_auth_methods_supported); - - Set claims_supported = new HashSet(); - claims_supported.add("iss"); - claims_supported.add("sub"); - claims_supported.add("aud"); - claims_supported.add("iat"); - claims_supported.add("exp"); - claims_supported.add("jti"); - claims_supported.add("auth_time"); - - claims_supported.add("institution"); - claims_supported.add("online_ticket"); - - claims_supported.add("userId"); - claims_supported.add("user"); - claims_supported.add("name"); - claims_supported.add("preferred_username"); - claims_supported.add("given_name"); - claims_supported.add("family_name"); - claims_supported.add("middle_name"); - claims_supported.add("nickname"); - claims_supported.add("displayName"); - claims_supported.add("departmentId"); - claims_supported.add("department"); - claims_supported.add("gender"); - claims_supported.add("zoneinfo"); - claims_supported.add("locale"); - claims_supported.add("updated_time"); - claims_supported.add("birthdate"); - - claims_supported.add("email"); - claims_supported.add("email_verified"); - - claims_supported.add("phone_number"); - claims_supported.add("phone_number_verified"); - - claims_supported.add("address"); - claims_supported.add("country"); - claims_supported.add("region"); - claims_supported.add("locality"); - claims_supported.add("street_address"); - claims_supported.add("formatted"); - claims_supported.add("postal_code"); - - oauthConfig.setClaims_supported(claims_supported); - }else { - oauthConfig.setClient_id(clientId); - oauthConfig.setJwks_uri(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/jwks"); - - Set introspection_endpoint_auth_methods_supported = new HashSet(); - introspection_endpoint_auth_methods_supported.add("client_secret_basic"); - oauthConfig.setIntrospection_endpoint_auth_methods_supported(introspection_endpoint_auth_methods_supported); - - oauthConfig.setIssuer(baseUrl + "/maxkey"); - Set response_types_supported = new HashSet(); - response_types_supported.add("code"); - response_types_supported.add("authorization_code"); - response_types_supported.add("code id_token"); - response_types_supported.add("id_token"); - oauthConfig.setResponse_types_supported(response_types_supported); - - Set response_modes_supported = new HashSet(); - response_modes_supported.add("query"); - response_modes_supported.add("form_post"); - oauthConfig.setResponse_modes_supported(response_modes_supported); - - Set grant_types_supported = new HashSet(); - grant_types_supported.add("authorization_code"); - grant_types_supported.add("refresh_token"); - grant_types_supported.add("password"); - grant_types_supported.add("client_credentials"); - oauthConfig.setGrant_types_supported(grant_types_supported); - - Set id_token_signing_alg_values_supported = new HashSet(); - id_token_signing_alg_values_supported.add("RS256"); - oauthConfig.setId_token_signing_alg_values_supported(id_token_signing_alg_values_supported); - - Set scopes_supported = new HashSet(); - scopes_supported.add("openid"); - scopes_supported.add("email"); - scopes_supported.add("profile"); - scopes_supported.add("address"); - scopes_supported.add("phone"); - oauthConfig.setScopes_supported(scopes_supported); - - Set token_endpoint_auth_methods_supported = new HashSet(); - token_endpoint_auth_methods_supported.add("client_secret_basic"); - token_endpoint_auth_methods_supported.add("client_secret_post"); - token_endpoint_auth_methods_supported.add("none"); - oauthConfig.setToken_endpoint_auth_methods_supported(token_endpoint_auth_methods_supported); - - Set claims_supported = new HashSet(); - claims_supported.add("iss"); - claims_supported.add("sub"); - claims_supported.add("aud"); - claims_supported.add("iat"); - claims_supported.add("exp"); - claims_supported.add("jti"); - claims_supported.add("auth_time"); - - claims_supported.add("institution"); - claims_supported.add("online_ticket"); - - claims_supported.add("userId"); - claims_supported.add("user"); - claims_supported.add("name"); - claims_supported.add("preferred_username"); - claims_supported.add("given_name"); - claims_supported.add("family_name"); - claims_supported.add("middle_name"); - claims_supported.add("nickname"); - claims_supported.add("displayName"); - claims_supported.add("departmentId"); - claims_supported.add("department"); - claims_supported.add("gender"); - claims_supported.add("zoneinfo"); - claims_supported.add("locale"); - claims_supported.add("updated_time"); - claims_supported.add("birthdate"); - - claims_supported.add("email"); - claims_supported.add("email_verified"); - - claims_supported.add("phone_number"); - claims_supported.add("phone_number_verified"); - - claims_supported.add("address"); - claims_supported.add("country"); - claims_supported.add("region"); - claims_supported.add("locality"); - claims_supported.add("street_address"); - claims_supported.add("formatted"); - claims_supported.add("postal_code"); - - oauthConfig.setClaims_supported(claims_supported); - } - return oauthConfig; - } + Set introspection_endpoint_auth_methods_supported = new HashSet(); + introspection_endpoint_auth_methods_supported.add("client_secret_basic"); + oauthConfig.setIntrospection_endpoint_auth_methods_supported(introspection_endpoint_auth_methods_supported); + + oauthConfig.setIssuer(clientDetails.getIssuer()); + Set response_types_supported =clientDetails.getAuthorizedGrantTypes(); + if(response_types_supported.contains("authorization_code")) { + response_types_supported.add("code"); + } + oauthConfig.setResponse_types_supported(response_types_supported); + + Set response_modes_supported = new HashSet(); + response_modes_supported.add("query"); + response_modes_supported.add("form_post"); + oauthConfig.setResponse_modes_supported(response_modes_supported); + + oauthConfig.setGrant_types_supported(clientDetails.getAuthorizedGrantTypes()); + oauthConfig.setClaims_supported(clientDetails.getScope()); + + + Set id_token_signing_alg_values_supported = new HashSet(); + id_token_signing_alg_values_supported.add(clientDetails.getSignature().toUpperCase()); + oauthConfig.setId_token_signing_alg_values_supported(id_token_signing_alg_values_supported); + + oauthConfig.setScopes_supported(clientDetails.getScope()); + + Set token_endpoint_auth_methods_supported = new HashSet(); + token_endpoint_auth_methods_supported.add("client_secret_basic"); + token_endpoint_auth_methods_supported.add("client_secret_post"); + token_endpoint_auth_methods_supported.add("none"); + oauthConfig.setToken_endpoint_auth_methods_supported(token_endpoint_auth_methods_supported); + + Set claims_supported = new HashSet(); + claims_supported.add("iss"); + claims_supported.add("sub"); + claims_supported.add("aud"); + claims_supported.add("iat"); + claims_supported.add("exp"); + claims_supported.add("jti"); + claims_supported.add("auth_time"); + + claims_supported.add("institution"); + claims_supported.add("online_ticket"); + + claims_supported.add("userId"); + claims_supported.add("user"); + claims_supported.add("name"); + claims_supported.add("preferred_username"); + claims_supported.add("given_name"); + claims_supported.add("family_name"); + claims_supported.add("middle_name"); + claims_supported.add("nickname"); + claims_supported.add("displayName"); + claims_supported.add("departmentId"); + claims_supported.add("department"); + claims_supported.add("gender"); + claims_supported.add("zoneinfo"); + claims_supported.add("locale"); + claims_supported.add("updated_time"); + claims_supported.add("birthdate"); + + claims_supported.add("email"); + claims_supported.add("email_verified"); + + claims_supported.add("phone_number"); + claims_supported.add("phone_number_verified"); + + claims_supported.add("address"); + claims_supported.add("country"); + claims_supported.add("region"); + claims_supported.add("locality"); + claims_supported.add("street_address"); + claims_supported.add("formatted"); + claims_supported.add("postal_code"); + + oauthConfig.setClaims_supported(claims_supported); + }else { + oauthConfig.setClient_id(clientId); + oauthConfig.setJwks_uri(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/jwks"); + + Set introspection_endpoint_auth_methods_supported = new HashSet(); + introspection_endpoint_auth_methods_supported.add("client_secret_basic"); + oauthConfig.setIntrospection_endpoint_auth_methods_supported(introspection_endpoint_auth_methods_supported); + + oauthConfig.setIssuer(baseUrl + "/maxkey"); + Set response_types_supported = new HashSet(); + response_types_supported.add("code"); + response_types_supported.add("authorization_code"); + response_types_supported.add("code id_token"); + response_types_supported.add("id_token"); + oauthConfig.setResponse_types_supported(response_types_supported); + + Set response_modes_supported = new HashSet(); + response_modes_supported.add("query"); + response_modes_supported.add("form_post"); + oauthConfig.setResponse_modes_supported(response_modes_supported); + + Set grant_types_supported = new HashSet(); + grant_types_supported.add("authorization_code"); + grant_types_supported.add("refresh_token"); + grant_types_supported.add("password"); + grant_types_supported.add("client_credentials"); + oauthConfig.setGrant_types_supported(grant_types_supported); + + Set id_token_signing_alg_values_supported = new HashSet(); + id_token_signing_alg_values_supported.add("RS256"); + oauthConfig.setId_token_signing_alg_values_supported(id_token_signing_alg_values_supported); + + Set scopes_supported = new HashSet(); + scopes_supported.add("openid"); + scopes_supported.add("email"); + scopes_supported.add("profile"); + scopes_supported.add("address"); + scopes_supported.add("phone"); + oauthConfig.setScopes_supported(scopes_supported); + + Set token_endpoint_auth_methods_supported = new HashSet(); + token_endpoint_auth_methods_supported.add("client_secret_basic"); + token_endpoint_auth_methods_supported.add("client_secret_post"); + token_endpoint_auth_methods_supported.add("none"); + oauthConfig.setToken_endpoint_auth_methods_supported(token_endpoint_auth_methods_supported); + + Set claims_supported = new HashSet(); + claims_supported.add("iss"); + claims_supported.add("sub"); + claims_supported.add("aud"); + claims_supported.add("iat"); + claims_supported.add("exp"); + claims_supported.add("jti"); + claims_supported.add("auth_time"); + + claims_supported.add("institution"); + claims_supported.add("online_ticket"); + + claims_supported.add("userId"); + claims_supported.add("user"); + claims_supported.add("name"); + claims_supported.add("preferred_username"); + claims_supported.add("given_name"); + claims_supported.add("family_name"); + claims_supported.add("middle_name"); + claims_supported.add("nickname"); + claims_supported.add("displayName"); + claims_supported.add("departmentId"); + claims_supported.add("department"); + claims_supported.add("gender"); + claims_supported.add("zoneinfo"); + claims_supported.add("locale"); + claims_supported.add("updated_time"); + claims_supported.add("birthdate"); + + claims_supported.add("email"); + claims_supported.add("email_verified"); + + claims_supported.add("phone_number"); + claims_supported.add("phone_number_verified"); + + claims_supported.add("address"); + claims_supported.add("country"); + claims_supported.add("region"); + claims_supported.add("locality"); + claims_supported.add("street_address"); + claims_supported.add("formatted"); + claims_supported.add("postal_code"); + + oauthConfig.setClaims_supported(claims_supported); + } + return oauthConfig; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/wellknown/endpoint/OpenidConfigurationEndpoint.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/wellknown/endpoint/OpenidConfigurationEndpoint.java index 21f8c99ab..92327e8bc 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/wellknown/endpoint/OpenidConfigurationEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oauth2/provider/wellknown/endpoint/OpenidConfigurationEndpoint.java @@ -36,239 +36,239 @@ import java.util.Set; @Tag(name = "2-1-OAuth v2.0 API文档模块") @Controller public class OpenidConfigurationEndpoint extends AbstractEndpoint { - static final Logger _logger = LoggerFactory.getLogger(OpenidConfigurationEndpoint.class); - + static final Logger _logger = LoggerFactory.getLogger(OpenidConfigurationEndpoint.class); + - @Operation(summary = "OpenID Connect metadata 元数据接口", description = "参数inst_id,client_id",method="GET,POST") - @RequestMapping(value = {OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/.well-known/openid-configuration"}, - produces = "application/json", - method={RequestMethod.POST, RequestMethod.GET}) - @ResponseBody - public OpenidConfiguration configurationByParam( - @RequestParam(value = "inst_id", required = false) String inst_id, - @RequestParam(value = "client_id", required = false) String client_id) { - _logger.debug("Configuration By Param"); - return configurationMetadata(inst_id,client_id,"RequestParam"); - } - - @Operation(summary = "OpenID Connect metadata 元数据接口", description = "参数Path",method="GET,POST") - @RequestMapping(value = {OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/{instId}/{clientId}/.well-known/openid-configuration"}, - produces = "application/json", - method={RequestMethod.POST, RequestMethod.GET}) - @ResponseBody - public OpenidConfiguration configurationByPath( - @PathVariable("instId") String instId , - @PathVariable(value = "clientId") String clientId) { - _logger.debug("Configuration By Path"); - return configurationMetadata(instId,clientId,"PathVariable"); - } - - public OpenidConfiguration configurationMetadata(String instId,String clientId,String param) { - _logger.debug("instId {} , client_id {}" , instId ,clientId); - - String baseUrl = WebContext.getContextPath(true); - - ClientDetails clientDetails = null; - - if(StringUtils.isNotBlank(clientId)) { - try { - clientDetails = getClientDetailsService().loadClientByClientId(clientId,true); - }catch(Exception e) { - _logger.error("getClientDetailsService", e); - } - } - - OpenidConfiguration openidConfig = new OpenidConfiguration(); - openidConfig.setRequest_parameter_supported(true); - openidConfig.setAuthorization_endpoint(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/authorize"); - openidConfig.setToken_endpoint(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/token"); - openidConfig.setIntrospection_endpoint(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/introspect"); - openidConfig.setUserinfo_endpoint(baseUrl + "/api/connect/v10/userinfo"); - openidConfig.setEnd_session_endpoint(baseUrl + "/force/logout"); - - if(clientDetails != null) { - openidConfig.setClient_id(clientId); - if(param.equals("RequestParam")){ - StringBuffer jwksUri = new StringBuffer(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/jwks"); - jwksUri.append("?"); - jwksUri.append("client_id").append("=").append(clientDetails.getClientId()); - if(StringUtils.isNotBlank(instId)) { - jwksUri.append("&").append("inst_id").append("=").append(instId); - } - openidConfig.setJwks_uri(jwksUri.toString()); - }else { - openidConfig.setJwks_uri(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/"+instId+"/"+clientId+"/jwks"); - } - - Set introspection_endpoint_auth_methods_supported = new HashSet(); - introspection_endpoint_auth_methods_supported.add("client_secret_basic"); - openidConfig.setIntrospection_endpoint_auth_methods_supported(introspection_endpoint_auth_methods_supported); - - openidConfig.setIssuer(clientDetails.getIssuer()); - Set response_types_supported =clientDetails.getAuthorizedGrantTypes(); - if(response_types_supported.contains("authorization_code")) { - response_types_supported.add("code"); - } - openidConfig.setResponse_types_supported(response_types_supported); - - Set response_modes_supported = new HashSet(); - response_modes_supported.add("query"); - response_modes_supported.add("form_post"); - openidConfig.setResponse_modes_supported(response_modes_supported); - - openidConfig.setGrant_types_supported(clientDetails.getAuthorizedGrantTypes()); - openidConfig.setClaims_supported(clientDetails.getScope()); - - - Set id_token_signing_alg_values_supported = new HashSet(); - id_token_signing_alg_values_supported.add(clientDetails.getSignature().toUpperCase()); - openidConfig.setId_token_signing_alg_values_supported(id_token_signing_alg_values_supported); - - openidConfig.setScopes_supported(clientDetails.getScope()); - - Set token_endpoint_auth_methods_supported = new HashSet(); - token_endpoint_auth_methods_supported.add("client_secret_basic"); - token_endpoint_auth_methods_supported.add("client_secret_post"); - token_endpoint_auth_methods_supported.add("none"); - openidConfig.setToken_endpoint_auth_methods_supported(token_endpoint_auth_methods_supported); - - Set claims_supported = new HashSet(); - claims_supported.add("iss"); - claims_supported.add("sub"); - claims_supported.add("aud"); - claims_supported.add("iat"); - claims_supported.add("exp"); - claims_supported.add("jti"); - claims_supported.add("auth_time"); - - claims_supported.add("institution"); - claims_supported.add("online_ticket"); - - claims_supported.add("userId"); - claims_supported.add("user"); - claims_supported.add("name"); - claims_supported.add("preferred_username"); - claims_supported.add("given_name"); - claims_supported.add("family_name"); - claims_supported.add("middle_name"); - claims_supported.add("nickname"); - claims_supported.add("displayName"); - claims_supported.add("departmentId"); - claims_supported.add("department"); - claims_supported.add("gender"); - claims_supported.add("zoneinfo"); - claims_supported.add("locale"); - claims_supported.add("updated_time"); - claims_supported.add("birthdate"); - - claims_supported.add("email"); - claims_supported.add("email_verified"); - - claims_supported.add("phone_number"); - claims_supported.add("phone_number_verified"); - - claims_supported.add("address"); - claims_supported.add("country"); - claims_supported.add("region"); - claims_supported.add("locality"); - claims_supported.add("street_address"); - claims_supported.add("formatted"); - claims_supported.add("postal_code"); - - openidConfig.setClaims_supported(claims_supported); - }else { - openidConfig.setClient_id(clientId); - openidConfig.setJwks_uri(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/jwks"); - - Set introspection_endpoint_auth_methods_supported = new HashSet(); - introspection_endpoint_auth_methods_supported.add("client_secret_basic"); - openidConfig.setIntrospection_endpoint_auth_methods_supported(introspection_endpoint_auth_methods_supported); - - openidConfig.setIssuer(baseUrl + "/maxkey"); - Set response_types_supported = new HashSet(); - response_types_supported.add("code"); - response_types_supported.add("authorization_code"); - response_types_supported.add("code id_token"); - response_types_supported.add("id_token"); - openidConfig.setResponse_types_supported(response_types_supported); - - Set response_modes_supported = new HashSet(); - response_modes_supported.add("query"); - response_modes_supported.add("form_post"); - openidConfig.setResponse_modes_supported(response_modes_supported); - - Set grant_types_supported = new HashSet(); - grant_types_supported.add("authorization_code"); - grant_types_supported.add("refresh_token"); - grant_types_supported.add("password"); - grant_types_supported.add("client_credentials"); - openidConfig.setGrant_types_supported(grant_types_supported); - - Set id_token_signing_alg_values_supported = new HashSet(); - id_token_signing_alg_values_supported.add("RS256"); - openidConfig.setId_token_signing_alg_values_supported(id_token_signing_alg_values_supported); - - Set scopes_supported = new HashSet(); - scopes_supported.add("openid"); - scopes_supported.add("email"); - scopes_supported.add("profile"); - scopes_supported.add("address"); - scopes_supported.add("phone"); - openidConfig.setScopes_supported(scopes_supported); - - Set token_endpoint_auth_methods_supported = new HashSet(); - token_endpoint_auth_methods_supported.add("client_secret_basic"); - token_endpoint_auth_methods_supported.add("client_secret_post"); - token_endpoint_auth_methods_supported.add("none"); - openidConfig.setToken_endpoint_auth_methods_supported(token_endpoint_auth_methods_supported); - - Set claims_supported = new HashSet(); - claims_supported.add("iss"); - claims_supported.add("sub"); - claims_supported.add("aud"); - claims_supported.add("iat"); - claims_supported.add("exp"); - claims_supported.add("jti"); - claims_supported.add("auth_time"); - - claims_supported.add("institution"); - claims_supported.add("online_ticket"); - - claims_supported.add("userId"); - claims_supported.add("user"); - claims_supported.add("name"); - claims_supported.add("preferred_username"); - claims_supported.add("given_name"); - claims_supported.add("family_name"); - claims_supported.add("middle_name"); - claims_supported.add("nickname"); - claims_supported.add("displayName"); - claims_supported.add("departmentId"); - claims_supported.add("department"); - claims_supported.add("gender"); - claims_supported.add("zoneinfo"); - claims_supported.add("locale"); - claims_supported.add("updated_time"); - claims_supported.add("birthdate"); - - claims_supported.add("email"); - claims_supported.add("email_verified"); - - claims_supported.add("phone_number"); - claims_supported.add("phone_number_verified"); - - claims_supported.add("address"); - claims_supported.add("country"); - claims_supported.add("region"); - claims_supported.add("locality"); - claims_supported.add("street_address"); - claims_supported.add("formatted"); - claims_supported.add("postal_code"); - - openidConfig.setClaims_supported(claims_supported); - } + @Operation(summary = "OpenID Connect metadata 元数据接口", description = "参数inst_id,client_id",method="GET,POST") + @RequestMapping(value = {OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/.well-known/openid-configuration"}, + produces = "application/json", + method={RequestMethod.POST, RequestMethod.GET}) + @ResponseBody + public OpenidConfiguration configurationByParam( + @RequestParam(value = "inst_id", required = false) String inst_id, + @RequestParam(value = "client_id", required = false) String client_id) { + _logger.debug("Configuration By Param"); + return configurationMetadata(inst_id,client_id,"RequestParam"); + } + + @Operation(summary = "OpenID Connect metadata 元数据接口", description = "参数Path",method="GET,POST") + @RequestMapping(value = {OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/{instId}/{clientId}/.well-known/openid-configuration"}, + produces = "application/json", + method={RequestMethod.POST, RequestMethod.GET}) + @ResponseBody + public OpenidConfiguration configurationByPath( + @PathVariable("instId") String instId , + @PathVariable(value = "clientId") String clientId) { + _logger.debug("Configuration By Path"); + return configurationMetadata(instId,clientId,"PathVariable"); + } + + public OpenidConfiguration configurationMetadata(String instId,String clientId,String param) { + _logger.debug("instId {} , client_id {}" , instId ,clientId); + + String baseUrl = WebContext.getContextPath(true); + + ClientDetails clientDetails = null; + + if(StringUtils.isNotBlank(clientId)) { + try { + clientDetails = getClientDetailsService().loadClientByClientId(clientId,true); + }catch(Exception e) { + _logger.error("getClientDetailsService", e); + } + } + + OpenidConfiguration openidConfig = new OpenidConfiguration(); + openidConfig.setRequest_parameter_supported(true); + openidConfig.setAuthorization_endpoint(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/authorize"); + openidConfig.setToken_endpoint(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/token"); + openidConfig.setIntrospection_endpoint(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/introspect"); + openidConfig.setUserinfo_endpoint(baseUrl + "/api/connect/v10/userinfo"); + openidConfig.setEnd_session_endpoint(baseUrl + "/force/logout"); + + if(clientDetails != null) { + openidConfig.setClient_id(clientId); + if(param.equals("RequestParam")){ + StringBuffer jwksUri = new StringBuffer(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/jwks"); + jwksUri.append("?"); + jwksUri.append("client_id").append("=").append(clientDetails.getClientId()); + if(StringUtils.isNotBlank(instId)) { + jwksUri.append("&").append("inst_id").append("=").append(instId); + } + openidConfig.setJwks_uri(jwksUri.toString()); + }else { + openidConfig.setJwks_uri(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/"+instId+"/"+clientId+"/jwks"); + } + + Set introspection_endpoint_auth_methods_supported = new HashSet(); + introspection_endpoint_auth_methods_supported.add("client_secret_basic"); + openidConfig.setIntrospection_endpoint_auth_methods_supported(introspection_endpoint_auth_methods_supported); + + openidConfig.setIssuer(clientDetails.getIssuer()); + Set response_types_supported =clientDetails.getAuthorizedGrantTypes(); + if(response_types_supported.contains("authorization_code")) { + response_types_supported.add("code"); + } + openidConfig.setResponse_types_supported(response_types_supported); + + Set response_modes_supported = new HashSet(); + response_modes_supported.add("query"); + response_modes_supported.add("form_post"); + openidConfig.setResponse_modes_supported(response_modes_supported); + + openidConfig.setGrant_types_supported(clientDetails.getAuthorizedGrantTypes()); + openidConfig.setClaims_supported(clientDetails.getScope()); + + + Set id_token_signing_alg_values_supported = new HashSet(); + id_token_signing_alg_values_supported.add(clientDetails.getSignature().toUpperCase()); + openidConfig.setId_token_signing_alg_values_supported(id_token_signing_alg_values_supported); + + openidConfig.setScopes_supported(clientDetails.getScope()); + + Set token_endpoint_auth_methods_supported = new HashSet(); + token_endpoint_auth_methods_supported.add("client_secret_basic"); + token_endpoint_auth_methods_supported.add("client_secret_post"); + token_endpoint_auth_methods_supported.add("none"); + openidConfig.setToken_endpoint_auth_methods_supported(token_endpoint_auth_methods_supported); + + Set claims_supported = new HashSet(); + claims_supported.add("iss"); + claims_supported.add("sub"); + claims_supported.add("aud"); + claims_supported.add("iat"); + claims_supported.add("exp"); + claims_supported.add("jti"); + claims_supported.add("auth_time"); + + claims_supported.add("institution"); + claims_supported.add("online_ticket"); + + claims_supported.add("userId"); + claims_supported.add("user"); + claims_supported.add("name"); + claims_supported.add("preferred_username"); + claims_supported.add("given_name"); + claims_supported.add("family_name"); + claims_supported.add("middle_name"); + claims_supported.add("nickname"); + claims_supported.add("displayName"); + claims_supported.add("departmentId"); + claims_supported.add("department"); + claims_supported.add("gender"); + claims_supported.add("zoneinfo"); + claims_supported.add("locale"); + claims_supported.add("updated_time"); + claims_supported.add("birthdate"); + + claims_supported.add("email"); + claims_supported.add("email_verified"); + + claims_supported.add("phone_number"); + claims_supported.add("phone_number_verified"); + + claims_supported.add("address"); + claims_supported.add("country"); + claims_supported.add("region"); + claims_supported.add("locality"); + claims_supported.add("street_address"); + claims_supported.add("formatted"); + claims_supported.add("postal_code"); + + openidConfig.setClaims_supported(claims_supported); + }else { + openidConfig.setClient_id(clientId); + openidConfig.setJwks_uri(baseUrl + OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/jwks"); + + Set introspection_endpoint_auth_methods_supported = new HashSet(); + introspection_endpoint_auth_methods_supported.add("client_secret_basic"); + openidConfig.setIntrospection_endpoint_auth_methods_supported(introspection_endpoint_auth_methods_supported); + + openidConfig.setIssuer(baseUrl + "/maxkey"); + Set response_types_supported = new HashSet(); + response_types_supported.add("code"); + response_types_supported.add("authorization_code"); + response_types_supported.add("code id_token"); + response_types_supported.add("id_token"); + openidConfig.setResponse_types_supported(response_types_supported); + + Set response_modes_supported = new HashSet(); + response_modes_supported.add("query"); + response_modes_supported.add("form_post"); + openidConfig.setResponse_modes_supported(response_modes_supported); + + Set grant_types_supported = new HashSet(); + grant_types_supported.add("authorization_code"); + grant_types_supported.add("refresh_token"); + grant_types_supported.add("password"); + grant_types_supported.add("client_credentials"); + openidConfig.setGrant_types_supported(grant_types_supported); + + Set id_token_signing_alg_values_supported = new HashSet(); + id_token_signing_alg_values_supported.add("RS256"); + openidConfig.setId_token_signing_alg_values_supported(id_token_signing_alg_values_supported); + + Set scopes_supported = new HashSet(); + scopes_supported.add("openid"); + scopes_supported.add("email"); + scopes_supported.add("profile"); + scopes_supported.add("address"); + scopes_supported.add("phone"); + openidConfig.setScopes_supported(scopes_supported); + + Set token_endpoint_auth_methods_supported = new HashSet(); + token_endpoint_auth_methods_supported.add("client_secret_basic"); + token_endpoint_auth_methods_supported.add("client_secret_post"); + token_endpoint_auth_methods_supported.add("none"); + openidConfig.setToken_endpoint_auth_methods_supported(token_endpoint_auth_methods_supported); + + Set claims_supported = new HashSet(); + claims_supported.add("iss"); + claims_supported.add("sub"); + claims_supported.add("aud"); + claims_supported.add("iat"); + claims_supported.add("exp"); + claims_supported.add("jti"); + claims_supported.add("auth_time"); + + claims_supported.add("institution"); + claims_supported.add("online_ticket"); + + claims_supported.add("userId"); + claims_supported.add("user"); + claims_supported.add("name"); + claims_supported.add("preferred_username"); + claims_supported.add("given_name"); + claims_supported.add("family_name"); + claims_supported.add("middle_name"); + claims_supported.add("nickname"); + claims_supported.add("displayName"); + claims_supported.add("departmentId"); + claims_supported.add("department"); + claims_supported.add("gender"); + claims_supported.add("zoneinfo"); + claims_supported.add("locale"); + claims_supported.add("updated_time"); + claims_supported.add("birthdate"); + + claims_supported.add("email"); + claims_supported.add("email_verified"); + + claims_supported.add("phone_number"); + claims_supported.add("phone_number_verified"); + + claims_supported.add("address"); + claims_supported.add("country"); + claims_supported.add("region"); + claims_supported.add("locality"); + claims_supported.add("street_address"); + claims_supported.add("formatted"); + claims_supported.add("postal_code"); + + openidConfig.setClaims_supported(claims_supported); + } - return openidConfig; - } + return openidConfig; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oidc/idtoken/IdTokenHashUtils.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oidc/idtoken/IdTokenHashUtils.java index 01a9d44d2..6a70b5ab6 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oidc/idtoken/IdTokenHashUtils.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oidc/idtoken/IdTokenHashUtils.java @@ -37,74 +37,74 @@ import com.nimbusds.jwt.JWT; */ public class IdTokenHashUtils { - private static Logger logger = LoggerFactory.getLogger(IdTokenHashUtils.class); + private static Logger logger = LoggerFactory.getLogger(IdTokenHashUtils.class); - /** - * Compute the SHA hash of an authorization code - * - * @param signingAlg - * @param code - * @return - */ - public static Base64URL getCodeHash(JWSAlgorithm signingAlg, String code) { - return getHash(signingAlg, code.getBytes()); - } + /** + * Compute the SHA hash of an authorization code + * + * @param signingAlg + * @param code + * @return + */ + public static Base64URL getCodeHash(JWSAlgorithm signingAlg, String code) { + return getHash(signingAlg, code.getBytes()); + } - /** - * Compute the SHA hash of a token - * - * @param signingAlg - * @param token - * @return - */ - public static Base64URL getAccessTokenHash(JWSAlgorithm signingAlg, JWT jwt) { + /** + * Compute the SHA hash of a token + * + * @param signingAlg + * @param token + * @return + */ + public static Base64URL getAccessTokenHash(JWSAlgorithm signingAlg, JWT jwt) { - byte[] tokenBytes = jwt.serialize().getBytes(); + byte[] tokenBytes = jwt.serialize().getBytes(); - return getHash(signingAlg, tokenBytes); + return getHash(signingAlg, tokenBytes); - } + } - public static Base64URL getHash(JWSAlgorithm signingAlg, byte[] bytes) { + public static Base64URL getHash(JWSAlgorithm signingAlg, byte[] bytes) { - //Switch based on the given signing algorithm - use SHA-xxx with the same 'xxx' bitnumber - //as the JWSAlgorithm to hash the token. - String hashAlg = null; + //Switch based on the given signing algorithm - use SHA-xxx with the same 'xxx' bitnumber + //as the JWSAlgorithm to hash the token. + String hashAlg = null; - if (signingAlg.equals(JWSAlgorithm.HS256) || signingAlg.equals(JWSAlgorithm.ES256) || signingAlg.equals(JWSAlgorithm.RS256)) { - hashAlg = "SHA-256"; - } + if (signingAlg.equals(JWSAlgorithm.HS256) || signingAlg.equals(JWSAlgorithm.ES256) || signingAlg.equals(JWSAlgorithm.RS256)) { + hashAlg = "SHA-256"; + } - else if (signingAlg.equals(JWSAlgorithm.ES384) || signingAlg.equals(JWSAlgorithm.HS384) || signingAlg.equals(JWSAlgorithm.RS384)) { - hashAlg = "SHA-384"; - } + else if (signingAlg.equals(JWSAlgorithm.ES384) || signingAlg.equals(JWSAlgorithm.HS384) || signingAlg.equals(JWSAlgorithm.RS384)) { + hashAlg = "SHA-384"; + } - else if (signingAlg.equals(JWSAlgorithm.ES512) || signingAlg.equals(JWSAlgorithm.HS512) || signingAlg.equals(JWSAlgorithm.RS512)) { - hashAlg = "SHA-512"; - } + else if (signingAlg.equals(JWSAlgorithm.ES512) || signingAlg.equals(JWSAlgorithm.HS512) || signingAlg.equals(JWSAlgorithm.RS512)) { + hashAlg = "SHA-512"; + } - if (hashAlg != null) { + if (hashAlg != null) { - try { - MessageDigest hasher = MessageDigest.getInstance(hashAlg); - hasher.reset(); - hasher.update(bytes); + try { + MessageDigest hasher = MessageDigest.getInstance(hashAlg); + hasher.reset(); + hasher.update(bytes); - byte[] hashBytes = hasher.digest(); - byte[] hashBytesLeftHalf = Arrays.copyOf(hashBytes, hashBytes.length / 2); - Base64URL encodedHash = Base64URL.encode(hashBytesLeftHalf); + byte[] hashBytes = hasher.digest(); + byte[] hashBytesLeftHalf = Arrays.copyOf(hashBytes, hashBytes.length / 2); + Base64URL encodedHash = Base64URL.encode(hashBytesLeftHalf); - return encodedHash; + return encodedHash; - } catch (NoSuchAlgorithmException e) { + } catch (NoSuchAlgorithmException e) { - logger.error("No such algorithm error: ", e); + logger.error("No such algorithm error: ", e); - } + } - } + } - return null; - } + return null; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oidc/idtoken/OIDCIdTokenEnhancer.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oidc/idtoken/OIDCIdTokenEnhancer.java index 9eaeed2c2..1b02ad180 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oidc/idtoken/OIDCIdTokenEnhancer.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/authz/oidc/idtoken/OIDCIdTokenEnhancer.java @@ -61,147 +61,147 @@ import com.nimbusds.jwt.SignedJWT; * */ public class OIDCIdTokenEnhancer implements TokenEnhancer { - private static final Logger _logger = LoggerFactory.getLogger(OIDCIdTokenEnhancer.class); - - public static final String ID_TOKEN_SCOPE="openid"; + private static final Logger _logger = LoggerFactory.getLogger(OIDCIdTokenEnhancer.class); + + public static final String ID_TOKEN_SCOPE="openid"; - private OIDCProviderMetadata providerMetadata; - - private ClientDetailsService clientDetailsService; + private OIDCProviderMetadata providerMetadata; + + private ClientDetailsService clientDetailsService; - public void setProviderMetadata(OIDCProviderMetadata providerMetadata) { - this.providerMetadata = providerMetadata; - } + public void setProviderMetadata(OIDCProviderMetadata providerMetadata) { + this.providerMetadata = providerMetadata; + } - public void setClientDetailsService(ClientDetailsService clientDetailsService) { - this.clientDetailsService = clientDetailsService; - } + public void setClientDetailsService(ClientDetailsService clientDetailsService) { + this.clientDetailsService = clientDetailsService; + } - @Override - public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { - OAuth2Request request=authentication.getOAuth2Request(); - if (request.getScope().contains(ID_TOKEN_SCOPE)) {//Enhance for OpenID Connect - ClientDetails clientDetails = - clientDetailsService.loadClientByClientId(authentication.getOAuth2Request().getClientId(),true); - - DefaultJwtSigningAndValidationService jwtSignerService = null; - JWSAlgorithm signingAlg = null; - String signerKeyId = clientDetails.getClientId() + "_sig"; - try {//jwtSignerService - if (StringUtils.isNotBlank(clientDetails.getSignature()) && !clientDetails.getSignature().equalsIgnoreCase("none")) { - jwtSignerService = new DefaultJwtSigningAndValidationService( - clientDetails.getSignatureKey(), - signerKeyId, - clientDetails.getSignature() - ); + @Override + public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { + OAuth2Request request=authentication.getOAuth2Request(); + if (request.getScope().contains(ID_TOKEN_SCOPE)) {//Enhance for OpenID Connect + ClientDetails clientDetails = + clientDetailsService.loadClientByClientId(authentication.getOAuth2Request().getClientId(),true); + + DefaultJwtSigningAndValidationService jwtSignerService = null; + JWSAlgorithm signingAlg = null; + String signerKeyId = clientDetails.getClientId() + "_sig"; + try {//jwtSignerService + if (StringUtils.isNotBlank(clientDetails.getSignature()) && !clientDetails.getSignature().equalsIgnoreCase("none")) { + jwtSignerService = new DefaultJwtSigningAndValidationService( + clientDetails.getSignatureKey(), + signerKeyId, + clientDetails.getSignature() + ); - signingAlg = jwtSignerService.getDefaultSigningAlgorithm(); - } - }catch(Exception e) { - _logger.error("Couldn't create Jwt Signing Service",e); - } - - JWTClaimsSet.Builder builder=new JWTClaimsSet.Builder(); - builder.subject(authentication.getName()) - .expirationTime(accessToken.getExpiration()) - .issuer(clientDetails.getIssuer()) - .issueTime(new Date()) - .audience(Arrays.asList(authentication.getOAuth2Request().getClientId())) - .jwtID(UUID.randomUUID().toString()); - - /** - * https://self-issued.me - * @see http://openid.net/specs/openid-connect-core-1_0.html#SelfIssuedDiscovery - * 7. Self-Issued OpenID Provider - */ - if(clientDetails.getIssuer()!=null - && jwtSignerService != null - && clientDetails.getIssuer().equalsIgnoreCase("https://self-issued.me") - ){ - builder.claim("sub_jwk", jwtSignerService.getAllPublicKeys().get(signerKeyId)); - } - - // if the auth time claim was explicitly requested OR if the client always wants the auth time, put it in - 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 =new DateTime(AuthorizationUtils.getUserInfo().getLastLoginTime()); - builder.claim("auth_time", loginDate.getMillis()/1000); - } - - String nonce = request.getRequestParameters().get("nonce"); - _logger.debug("getRequestParameters nonce {}",nonce); - if (!Strings.isNullOrEmpty(nonce)) { - builder.claim("nonce", nonce); - } - //add at_hash - if(jwtSignerService != null) { - SignedJWT signed = new SignedJWT(new JWSHeader(signingAlg), builder.build()); - Set responseTypes = request.getResponseTypes(); - - if (responseTypes.contains("token")) { - // calculate the token hash - Base64URL at_hash = IdTokenHashUtils.getAccessTokenHash(signingAlg, signed); - builder.claim("at_hash", at_hash); - } - _logger.debug("idClaims {}",builder.build()); - } - String idTokenString = ""; - if (StringUtils.isNotBlank(clientDetails.getSignature()) - && !clientDetails.getSignature().equalsIgnoreCase("none")) { - try { - builder.claim("kid", signerKeyId); - // signed ID token - JWSHeader jwsHeader = new JWSHeader.Builder(signingAlg).keyID(signerKeyId).build(); - JWT idToken = new SignedJWT(jwsHeader, builder.build()); - // sign it with the server's key - jwtSignerService.signJwt((SignedJWT) idToken); - idTokenString = idToken.serialize(); - _logger.debug("idToken {}",idTokenString); - }catch(Exception e) { - _logger.error("Couldn't create Jwt Signing Exception",e); - } - }else if (StringUtils.isNotBlank(clientDetails.getAlgorithm()) - && !clientDetails.getAlgorithm().equalsIgnoreCase("none")) { - try { - String encryptionKeyId = clientDetails.getClientId() + "_enc"; - DefaultJwtEncryptionAndDecryptionService jwtEncryptionService = - new DefaultJwtEncryptionAndDecryptionService( - clientDetails.getAlgorithmKey(), - encryptionKeyId, - clientDetails.getAlgorithm() - ); - Payload payload = builder.build().toPayload(); - // Example Request JWT encrypted with RSA-OAEP-256 and 128-bit AES/GCM - //JWEHeader jweHeader = new JWEHeader(JWEAlgorithm.RSA1_5, EncryptionMethod.A128GCM); - JWEHeader jweHeader = new JWEHeader( - jwtEncryptionService.getDefaultAlgorithm(clientDetails.getAlgorithm()), - jwtEncryptionService.parseEncryptionMethod(clientDetails.getEncryptionMethod()) - ); - JWEObject jweObject = new JWEObject( - new JWEHeader.Builder(jweHeader) - .contentType("JWT") // required to indicate nested JWT - .keyID(encryptionKeyId) - .build(), - payload); - - jwtEncryptionService.encryptJwt(jweObject); - idTokenString = jweObject.serialize(); - } catch (NoSuchAlgorithmException | InvalidKeySpecException | JOSEException e) { - _logger.error("Couldn't create Jwt Encryption Exception", e); - } - }else { - //not need a PlainJWT idToken - //JWT idToken = new PlainJWT(builder.build()); - //idTokenString = idToken.serialize(); - } - - accessToken = new DefaultOAuth2AccessToken(accessToken); - if(StringUtils.isNotBlank(idTokenString)){ - accessToken.getAdditionalInformation().put("id_token", idTokenString); - } - } - return accessToken; - } + signingAlg = jwtSignerService.getDefaultSigningAlgorithm(); + } + }catch(Exception e) { + _logger.error("Couldn't create Jwt Signing Service",e); + } + + JWTClaimsSet.Builder builder=new JWTClaimsSet.Builder(); + builder.subject(authentication.getName()) + .expirationTime(accessToken.getExpiration()) + .issuer(clientDetails.getIssuer()) + .issueTime(new Date()) + .audience(Arrays.asList(authentication.getOAuth2Request().getClientId())) + .jwtID(UUID.randomUUID().toString()); + + /** + * https://self-issued.me + * @see http://openid.net/specs/openid-connect-core-1_0.html#SelfIssuedDiscovery + * 7. Self-Issued OpenID Provider + */ + if(clientDetails.getIssuer()!=null + && jwtSignerService != null + && clientDetails.getIssuer().equalsIgnoreCase("https://self-issued.me") + ){ + builder.claim("sub_jwk", jwtSignerService.getAllPublicKeys().get(signerKeyId)); + } + + // if the auth time claim was explicitly requested OR if the client always wants the auth time, put it in + 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 =new DateTime(AuthorizationUtils.getUserInfo().getLastLoginTime()); + builder.claim("auth_time", loginDate.getMillis()/1000); + } + + String nonce = request.getRequestParameters().get("nonce"); + _logger.debug("getRequestParameters nonce {}",nonce); + if (!Strings.isNullOrEmpty(nonce)) { + builder.claim("nonce", nonce); + } + //add at_hash + if(jwtSignerService != null) { + SignedJWT signed = new SignedJWT(new JWSHeader(signingAlg), builder.build()); + Set responseTypes = request.getResponseTypes(); + + if (responseTypes.contains("token")) { + // calculate the token hash + Base64URL at_hash = IdTokenHashUtils.getAccessTokenHash(signingAlg, signed); + builder.claim("at_hash", at_hash); + } + _logger.debug("idClaims {}",builder.build()); + } + String idTokenString = ""; + if (StringUtils.isNotBlank(clientDetails.getSignature()) + && !clientDetails.getSignature().equalsIgnoreCase("none")) { + try { + builder.claim("kid", signerKeyId); + // signed ID token + JWSHeader jwsHeader = new JWSHeader.Builder(signingAlg).keyID(signerKeyId).build(); + JWT idToken = new SignedJWT(jwsHeader, builder.build()); + // sign it with the server's key + jwtSignerService.signJwt((SignedJWT) idToken); + idTokenString = idToken.serialize(); + _logger.debug("idToken {}",idTokenString); + }catch(Exception e) { + _logger.error("Couldn't create Jwt Signing Exception",e); + } + }else if (StringUtils.isNotBlank(clientDetails.getAlgorithm()) + && !clientDetails.getAlgorithm().equalsIgnoreCase("none")) { + try { + String encryptionKeyId = clientDetails.getClientId() + "_enc"; + DefaultJwtEncryptionAndDecryptionService jwtEncryptionService = + new DefaultJwtEncryptionAndDecryptionService( + clientDetails.getAlgorithmKey(), + encryptionKeyId, + clientDetails.getAlgorithm() + ); + Payload payload = builder.build().toPayload(); + // Example Request JWT encrypted with RSA-OAEP-256 and 128-bit AES/GCM + //JWEHeader jweHeader = new JWEHeader(JWEAlgorithm.RSA1_5, EncryptionMethod.A128GCM); + JWEHeader jweHeader = new JWEHeader( + jwtEncryptionService.getDefaultAlgorithm(clientDetails.getAlgorithm()), + jwtEncryptionService.parseEncryptionMethod(clientDetails.getEncryptionMethod()) + ); + JWEObject jweObject = new JWEObject( + new JWEHeader.Builder(jweHeader) + .contentType("JWT") // required to indicate nested JWT + .keyID(encryptionKeyId) + .build(), + payload); + + jwtEncryptionService.encryptJwt(jweObject); + idTokenString = jweObject.serialize(); + } catch (NoSuchAlgorithmException | InvalidKeySpecException | JOSEException e) { + _logger.error("Couldn't create Jwt Encryption Exception", e); + } + }else { + //not need a PlainJWT idToken + //JWT idToken = new PlainJWT(builder.build()); + //idTokenString = idToken.serialize(); + } + + accessToken = new DefaultOAuth2AccessToken(accessToken); + if(StringUtils.isNotBlank(idTokenString)){ + accessToken.getAdditionalInformation().put("id_token", idTokenString); + } + } + return accessToken; + } } diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/autoconfigure/Oauth20AutoConfiguration.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/autoconfigure/Oauth20AutoConfiguration.java index cb1e89d87..0ba5dce3b 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/autoconfigure/Oauth20AutoConfiguration.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/dromara/maxkey/autoconfigure/Oauth20AutoConfiguration.java @@ -85,8 +85,8 @@ public class Oauth20AutoConfiguration implements InitializingBean { FilterRegistrationBean registration = new FilterRegistrationBean<>(); registration.setFilter(new TokenEndpointAuthenticationFilter()); registration.addUrlPatterns( - OAuth2Constants.ENDPOINT.ENDPOINT_TOKEN + "/*", - OAuth2Constants.ENDPOINT.ENDPOINT_TENCENT_IOA_TOKEN + "/*"); + OAuth2Constants.ENDPOINT.ENDPOINT_TOKEN + "/*", + OAuth2Constants.ENDPOINT.ENDPOINT_TENCENT_IOA_TOKEN + "/*"); registration.setName("TokenEndpointAuthenticationFilter"); registration.setOrder(1); return registration; @@ -203,7 +203,7 @@ public class Oauth20AutoConfiguration implements InitializingBean { authorizationCodeServices = new RedisAuthorizationCodeServices(redisConnFactory); _logger.debug("RedisAuthorizationCodeServices"); }else { - authorizationCodeServices = new InMemoryAuthorizationCodeServices(); + authorizationCodeServices = new InMemoryAuthorizationCodeServices(); _logger.debug("InMemoryAuthorizationCodeServices"); } return authorizationCodeServices; @@ -224,7 +224,7 @@ public class Oauth20AutoConfiguration implements InitializingBean { tokenStore = new RedisTokenStore(redisConnFactory); _logger.debug("RedisTokenStore"); }else { - tokenStore = new InMemoryTokenStore(); + tokenStore = new InMemoryTokenStore(); _logger.debug("InMemoryTokenStore"); } return tokenStore; diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/AuthnRequestInfo.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/AuthnRequestInfo.java index cf7652a7c..d1e0c8fc1 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/AuthnRequestInfo.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/AuthnRequestInfo.java @@ -23,41 +23,41 @@ import org.apache.commons.lang.builder.ToStringBuilder; public class AuthnRequestInfo implements Serializable { - /** - * - */ - private static final long serialVersionUID = 9115030955516039900L; - private final String assertionConumerURL; - private final String authnRequestID; - - public AuthnRequestInfo(String assertionConumerURL, String authnRequestID) { - super(); - this.assertionConumerURL = assertionConumerURL; - this.authnRequestID = authnRequestID; - } - - public AuthnRequestInfo() { - super(); - this.assertionConumerURL = ""; - this.authnRequestID = null; - } - - public String getAssertionConumerURL() { - return assertionConumerURL; - } - - - public String getAuthnRequestID() { - return authnRequestID; - } + /** + * + */ + private static final long serialVersionUID = 9115030955516039900L; + private final String assertionConumerURL; + private final String authnRequestID; + + public AuthnRequestInfo(String assertionConumerURL, String authnRequestID) { + super(); + this.assertionConumerURL = assertionConumerURL; + this.authnRequestID = authnRequestID; + } + + public AuthnRequestInfo() { + super(); + this.assertionConumerURL = ""; + this.authnRequestID = null; + } + + public String getAssertionConumerURL() { + return assertionConumerURL; + } + + + public String getAuthnRequestID() { + return authnRequestID; + } - @Override - public String toString() { - return new ToStringBuilder(this). - append("assertionConumerURL", assertionConumerURL). - append("authnRequestID",authnRequestID). - toString(); - } - - + @Override + public String toString() { + return new ToStringBuilder(this). + append("assertionConumerURL", assertionConumerURL). + append("authnRequestID",authnRequestID). + toString(); + } + + } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/EndpointGenerator.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/EndpointGenerator.java index cc4dc96f2..9f249fd81 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/EndpointGenerator.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/EndpointGenerator.java @@ -29,35 +29,35 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class EndpointGenerator { - private static final Logger logger = LoggerFactory.getLogger(EndpointGenerator.class); - - public Endpoint generateEndpoint( String location) { - logger.debug("end point location: {}", location); - Endpoint samlEndpoint = new AssertionConsumerServiceBuilder().buildObject(); - + private static final Logger logger = LoggerFactory.getLogger(EndpointGenerator.class); + + public Endpoint generateEndpoint( String location) { + logger.debug("end point location: {}", location); + Endpoint samlEndpoint = new AssertionConsumerServiceBuilder().buildObject(); + samlEndpoint.setLocation(location); return samlEndpoint; - } - - public Endpoint generateEndpoint( String location,String responseLocation, QName service) { - logger.debug("end point service: {}", service); - logger.debug("end point location: {}", location); - logger.debug("end point responseLocation: {}", responseLocation); - Endpoint samlEndpoint; - if(null==service){ - service = AssertionConsumerService.DEFAULT_ELEMENT_NAME; - } - samlEndpoint = new AssertionConsumerServiceBuilder().buildObject(service); - + } + + public Endpoint generateEndpoint( String location,String responseLocation, QName service) { + logger.debug("end point service: {}", service); + logger.debug("end point location: {}", location); + logger.debug("end point responseLocation: {}", responseLocation); + Endpoint samlEndpoint; + if(null==service){ + service = AssertionConsumerService.DEFAULT_ELEMENT_NAME; + } + samlEndpoint = new AssertionConsumerServiceBuilder().buildObject(service); + samlEndpoint.setLocation(location); //this does not have to be set if( StringUtils.isNotEmpty(responseLocation)){ - samlEndpoint.setResponseLocation(responseLocation); + samlEndpoint.setResponseLocation(responseLocation); } return samlEndpoint; - } + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/SecurityPolicyDelegate.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/SecurityPolicyDelegate.java index 5d7c04f81..82909cc89 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/SecurityPolicyDelegate.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/SecurityPolicyDelegate.java @@ -28,32 +28,32 @@ import org.opensaml.ws.security.provider.BasicSecurityPolicy; public class SecurityPolicyDelegate implements SecurityPolicy { - private final BasicSecurityPolicy basicSecurityPolicy; - - - public SecurityPolicyDelegate() { - super(); - basicSecurityPolicy = new BasicSecurityPolicy(); - } - - public SecurityPolicyDelegate(List securityPolicyRules) { - super(); - basicSecurityPolicy = new BasicSecurityPolicy(); - basicSecurityPolicy.getPolicyRules().addAll(securityPolicyRules); - } - - public void addSecurityPolicy(SecurityPolicyRule securityPolicyRule){ - basicSecurityPolicy.getPolicyRules().add(securityPolicyRule); - } + private final BasicSecurityPolicy basicSecurityPolicy; + + + public SecurityPolicyDelegate() { + super(); + basicSecurityPolicy = new BasicSecurityPolicy(); + } + + public SecurityPolicyDelegate(List securityPolicyRules) { + super(); + basicSecurityPolicy = new BasicSecurityPolicy(); + basicSecurityPolicy.getPolicyRules().addAll(securityPolicyRules); + } + + public void addSecurityPolicy(SecurityPolicyRule securityPolicyRule){ + basicSecurityPolicy.getPolicyRules().add(securityPolicyRule); + } - @Override - public void evaluate(MessageContext messageContext) throws SecurityPolicyException { - basicSecurityPolicy.evaluate(messageContext); - } + @Override + public void evaluate(MessageContext messageContext) throws SecurityPolicyException { + basicSecurityPolicy.evaluate(messageContext); + } - @Override - public List getPolicyRules() { - return basicSecurityPolicy.getPolicyRules(); - } + @Override + public List getPolicyRules() { + return basicSecurityPolicy.getPolicyRules(); + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/SignatureSecurityPolicyRule.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/SignatureSecurityPolicyRule.java index 591083fd5..d988528e0 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/SignatureSecurityPolicyRule.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/SignatureSecurityPolicyRule.java @@ -48,80 +48,80 @@ import org.springframework.beans.factory.InitializingBean; */ public class SignatureSecurityPolicyRule implements InitializingBean, SecurityPolicyRule { - private static final Logger logger = LoggerFactory.getLogger(SignatureSecurityPolicyRule.class); - - private final CredentialResolver credentialResolver; - private final SAMLSignatureProfileValidator samlSignatureProfileValidator; - ExplicitKeySignatureTrustEngine trustEngine; - - public SignatureSecurityPolicyRule(CredentialResolver credentialResolver, SAMLSignatureProfileValidator samlSignatureProfileValidator) { - super(); - this.credentialResolver = credentialResolver; - this.samlSignatureProfileValidator = samlSignatureProfileValidator; - } + private static final Logger logger = LoggerFactory.getLogger(SignatureSecurityPolicyRule.class); + + private final CredentialResolver credentialResolver; + private final SAMLSignatureProfileValidator samlSignatureProfileValidator; + ExplicitKeySignatureTrustEngine trustEngine; + + public SignatureSecurityPolicyRule(CredentialResolver credentialResolver, SAMLSignatureProfileValidator samlSignatureProfileValidator) { + super(); + this.credentialResolver = credentialResolver; + this.samlSignatureProfileValidator = samlSignatureProfileValidator; + } - @Override - public void afterPropertiesSet() throws Exception { + @Override + public void afterPropertiesSet() throws Exception { - KeyInfoCredentialResolver keyInfoCredResolver = - Configuration.getGlobalSecurityConfiguration().getDefaultKeyInfoCredentialResolver(); + KeyInfoCredentialResolver keyInfoCredResolver = + Configuration.getGlobalSecurityConfiguration().getDefaultKeyInfoCredentialResolver(); - trustEngine = new ExplicitKeySignatureTrustEngine(credentialResolver,keyInfoCredResolver); - } + trustEngine = new ExplicitKeySignatureTrustEngine(credentialResolver,keyInfoCredResolver); + } - public void loadTrustEngine(){ - KeyInfoCredentialResolver keyInfoCredResolver = - Configuration.getGlobalSecurityConfiguration().getDefaultKeyInfoCredentialResolver(); + public void loadTrustEngine(){ + KeyInfoCredentialResolver keyInfoCredResolver = + Configuration.getGlobalSecurityConfiguration().getDefaultKeyInfoCredentialResolver(); - trustEngine = new ExplicitKeySignatureTrustEngine(credentialResolver,keyInfoCredResolver); - } - - @Override - public void evaluate(MessageContext messageContext) throws SecurityPolicyException { - - logger.debug("evaluating signature of {}", messageContext); - - if(!( messageContext.getInboundMessage() instanceof SignableSAMLObject)) { - throw new SecurityPolicyException("Inbound Message is not a SignableSAMLObject"); - } - - SignableSAMLObject samlMessage = (SignableSAMLObject) messageContext.getInboundMessage(); - //POST NEED Signed,but some is not - if( !samlMessage.isSigned()) { - logger.debug("evaluating signature POST NEED Signed,but some is not."); - throw new SecurityPolicyException("InboundMessage was not signed."); - } - - checkSignatureProfile(samlMessage); + trustEngine = new ExplicitKeySignatureTrustEngine(credentialResolver,keyInfoCredResolver); + } + + @Override + public void evaluate(MessageContext messageContext) throws SecurityPolicyException { + + logger.debug("evaluating signature of {}", messageContext); + + if(!( messageContext.getInboundMessage() instanceof SignableSAMLObject)) { + throw new SecurityPolicyException("Inbound Message is not a SignableSAMLObject"); + } + + SignableSAMLObject samlMessage = (SignableSAMLObject) messageContext.getInboundMessage(); + //POST NEED Signed,but some is not + if( !samlMessage.isSigned()) { + logger.debug("evaluating signature POST NEED Signed,but some is not."); + throw new SecurityPolicyException("InboundMessage was not signed."); + } + + checkSignatureProfile(samlMessage); - checkMessageSignature(messageContext, samlMessage); - - } + checkMessageSignature(messageContext, samlMessage); + + } - private void checkMessageSignature(MessageContext messageContext,SignableSAMLObject samlMessage) throws SecurityPolicyException { - CriteriaSet criteriaSet = new CriteriaSet(); - logger.debug("Inbound issuer is {}", messageContext.getInboundMessageIssuer()); - //https://localhost-dev-ed.my.salesforce.com - criteriaSet.add( new EntityIDCriteria(messageContext.getInboundMessageIssuer())); - //criteriaSet.add( new EntityIDCriteria("https://localhost-dev-ed.my.salesforce.com")); - criteriaSet.add( new UsageCriteria(UsageType.SIGNING) ); + private void checkMessageSignature(MessageContext messageContext,SignableSAMLObject samlMessage) throws SecurityPolicyException { + CriteriaSet criteriaSet = new CriteriaSet(); + logger.debug("Inbound issuer is {}", messageContext.getInboundMessageIssuer()); + //https://localhost-dev-ed.my.salesforce.com + criteriaSet.add( new EntityIDCriteria(messageContext.getInboundMessageIssuer())); + //criteriaSet.add( new EntityIDCriteria("https://localhost-dev-ed.my.salesforce.com")); + criteriaSet.add( new UsageCriteria(UsageType.SIGNING) ); - try { - if (!trustEngine.validate( samlMessage.getSignature(), criteriaSet)) { - throw new SecurityPolicyException("Signature was either invalid or signing key could not be established as trusted"); - } - } catch (SecurityException se) { - // System.out.println("Error evaluating the signature"+se.toString()); - throw new SecurityPolicyException("Error evaluating the signature",se); - } - } + try { + if (!trustEngine.validate( samlMessage.getSignature(), criteriaSet)) { + throw new SecurityPolicyException("Signature was either invalid or signing key could not be established as trusted"); + } + } catch (SecurityException se) { + // System.out.println("Error evaluating the signature"+se.toString()); + throw new SecurityPolicyException("Error evaluating the signature",se); + } + } - private void checkSignatureProfile(SignableSAMLObject samlMessage)throws SecurityPolicyException { - try { - samlSignatureProfileValidator.validate(samlMessage.getSignature()); - } catch (ValidationException ve) { - - throw new SecurityPolicyException("Signature did not conform to SAML Signature profile",ve); - } - } + private void checkSignatureProfile(SignableSAMLObject samlMessage)throws SecurityPolicyException { + try { + samlSignatureProfileValidator.validate(samlMessage.getSignature()); + } catch (ValidationException ve) { + + throw new SecurityPolicyException("Signature did not conform to SAML Signature profile",ve); + } + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/TrustResolver.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/TrustResolver.java index 7dfbf3f4b..820b67a16 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/TrustResolver.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/common/TrustResolver.java @@ -36,73 +36,73 @@ import org.opensaml.xml.security.credential.KeyStoreCredentialResolver; */ public class TrustResolver { - KeyStoreCredentialResolver keyStoreCredentialResolver; - SignatureSecurityPolicyRule signatureSecurityPolicyRule; - StaticSecurityPolicyResolver staticSecurityPolicyResolver; - String binding; + KeyStoreCredentialResolver keyStoreCredentialResolver; + SignatureSecurityPolicyRule signatureSecurityPolicyRule; + StaticSecurityPolicyResolver staticSecurityPolicyResolver; + String binding; - public TrustResolver() { - super(); - } - - public KeyStoreCredentialResolver buildKeyStoreCredentialResolver(KeyStore trustKeyStore, String key, String password){ - Map passwords = new HashMap(); - passwords.put(key, password); + public TrustResolver() { + super(); + } + + public KeyStoreCredentialResolver buildKeyStoreCredentialResolver(KeyStore trustKeyStore, String key, String password){ + Map passwords = new HashMap(); + passwords.put(key, password); - keyStoreCredentialResolver = new KeyStoreCredentialResolver(trustKeyStore, passwords); - - return keyStoreCredentialResolver; - } + keyStoreCredentialResolver = new KeyStoreCredentialResolver(trustKeyStore, passwords); + + return keyStoreCredentialResolver; + } - public TrustResolver(KeyStore trustKeyStore, String issuing, String password) { - super(); - buildKeyStoreCredentialResolver(trustKeyStore, issuing, password); - initPolicyRule(); - } + public TrustResolver(KeyStore trustKeyStore, String issuing, String password) { + super(); + buildKeyStoreCredentialResolver(trustKeyStore, issuing, password); + initPolicyRule(); + } - public TrustResolver(KeyStore trustKeyStore, String issuing, - String password, IssueInstantRule issueInstantRule, - MessageReplayRule messageReplayRule,String binding) { - super(); - - this.binding=binding; - buildKeyStoreCredentialResolver(trustKeyStore, issuing, password); - - initPolicyRule(); - - SecurityPolicyDelegate securityPolicyDelegate = new SecurityPolicyDelegate(); - if(binding.equalsIgnoreCase("post")){ - securityPolicyDelegate.addSecurityPolicy(signatureSecurityPolicyRule); - } - securityPolicyDelegate.addSecurityPolicy(issueInstantRule); - securityPolicyDelegate.addSecurityPolicy(messageReplayRule); - staticSecurityPolicyResolver = new StaticSecurityPolicyResolver(securityPolicyDelegate); - } - - public void initPolicyRule(){ - signatureSecurityPolicyRule = new SignatureSecurityPolicyRule(keyStoreCredentialResolver, new SAMLSignatureProfileValidator()); - signatureSecurityPolicyRule.loadTrustEngine(); - } + public TrustResolver(KeyStore trustKeyStore, String issuing, + String password, IssueInstantRule issueInstantRule, + MessageReplayRule messageReplayRule,String binding) { + super(); + + this.binding=binding; + buildKeyStoreCredentialResolver(trustKeyStore, issuing, password); + + initPolicyRule(); + + SecurityPolicyDelegate securityPolicyDelegate = new SecurityPolicyDelegate(); + if(binding.equalsIgnoreCase("post")){ + securityPolicyDelegate.addSecurityPolicy(signatureSecurityPolicyRule); + } + securityPolicyDelegate.addSecurityPolicy(issueInstantRule); + securityPolicyDelegate.addSecurityPolicy(messageReplayRule); + staticSecurityPolicyResolver = new StaticSecurityPolicyResolver(securityPolicyDelegate); + } + + public void initPolicyRule(){ + signatureSecurityPolicyRule = new SignatureSecurityPolicyRule(keyStoreCredentialResolver, new SAMLSignatureProfileValidator()); + signatureSecurityPolicyRule.loadTrustEngine(); + } - public void loadStaticSecurityPolicyResolver( - IssueInstantRule issueInstantRule, - MessageReplayRule messageReplayRule) { - SecurityPolicyDelegate securityPolicyDelegate = new SecurityPolicyDelegate(); - if(binding.equalsIgnoreCase("post")){ - securityPolicyDelegate.addSecurityPolicy(signatureSecurityPolicyRule); - } - securityPolicyDelegate.addSecurityPolicy(issueInstantRule); - securityPolicyDelegate.addSecurityPolicy(messageReplayRule); + public void loadStaticSecurityPolicyResolver( + IssueInstantRule issueInstantRule, + MessageReplayRule messageReplayRule) { + SecurityPolicyDelegate securityPolicyDelegate = new SecurityPolicyDelegate(); + if(binding.equalsIgnoreCase("post")){ + securityPolicyDelegate.addSecurityPolicy(signatureSecurityPolicyRule); + } + securityPolicyDelegate.addSecurityPolicy(issueInstantRule); + securityPolicyDelegate.addSecurityPolicy(messageReplayRule); - staticSecurityPolicyResolver = new StaticSecurityPolicyResolver(securityPolicyDelegate); - } + staticSecurityPolicyResolver = new StaticSecurityPolicyResolver(securityPolicyDelegate); + } - public KeyStoreCredentialResolver getKeyStoreCredentialResolver() { - return keyStoreCredentialResolver; - } + public KeyStoreCredentialResolver getKeyStoreCredentialResolver() { + return keyStoreCredentialResolver; + } - public StaticSecurityPolicyResolver getStaticSecurityPolicyResolver() { - return staticSecurityPolicyResolver; - } + public StaticSecurityPolicyResolver getStaticSecurityPolicyResolver() { + return staticSecurityPolicyResolver; + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/service/IDService.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/service/IDService.java index b86da3432..7420e1fa6 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/service/IDService.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/service/IDService.java @@ -22,7 +22,7 @@ import java.util.UUID; public class IDService { - public String generateID() { - return "MXK_" + UUID.randomUUID().toString(); - } + public String generateID() { + return "MXK_" + UUID.randomUUID().toString(); + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/service/TimeService.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/service/TimeService.java index abcb2cab8..d37d9c3d5 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/service/TimeService.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml/service/TimeService.java @@ -23,8 +23,8 @@ import org.joda.time.DateTime; public class TimeService { - public DateTime getCurrentDateTime() { - return new DateTime(); - } - + public DateTime getCurrentDateTime() { + return new DateTime(); + } + } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/BindingAdapter.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/BindingAdapter.java index b02913a2c..bf4ad65ff 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/BindingAdapter.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/BindingAdapter.java @@ -37,22 +37,22 @@ import jakarta.servlet.http.HttpServletResponse; */ public interface BindingAdapter { - public void sendSAMLMessage(SignableSAMLObject samlMessage, Endpoint endpoint, HttpServletRequest request, HttpServletResponse response) throws MessageEncodingException; - - public void setSecurityPolicyResolver(SecurityPolicyResolver securityPolicyResolver); - - public void setExtractBindingAdapter(ExtractBindingAdapter extractBindingAdapter); - - public void setAuthnRequestInfo(AuthnRequestInfo authnRequestInfo); - - public void setRelayState(String relayState); - - public AppsSAML20Details getSaml20Details(); - - public AuthnRequestInfo getAuthnRequestInfo(); - - public Credential getSigningCredential(); - - public Credential getSpSigningCredential(); - + public void sendSAMLMessage(SignableSAMLObject samlMessage, Endpoint endpoint, HttpServletRequest request, HttpServletResponse response) throws MessageEncodingException; + + public void setSecurityPolicyResolver(SecurityPolicyResolver securityPolicyResolver); + + public void setExtractBindingAdapter(ExtractBindingAdapter extractBindingAdapter); + + public void setAuthnRequestInfo(AuthnRequestInfo authnRequestInfo); + + public void setRelayState(String relayState); + + public AppsSAML20Details getSaml20Details(); + + public AuthnRequestInfo getAuthnRequestInfo(); + + public Credential getSigningCredential(); + + public Credential getSpSigningCredential(); + } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/ExtractBindingAdapter.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/ExtractBindingAdapter.java index 47f2e9bb3..c145084db 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/ExtractBindingAdapter.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/ExtractBindingAdapter.java @@ -38,20 +38,20 @@ import jakarta.servlet.http.HttpServletRequest; */ public interface ExtractBindingAdapter { - @SuppressWarnings("rawtypes") - public SAMLMessageContext extractSAMLMessageContext(HttpServletRequest request) throws MessageDecodingException, SecurityException; + @SuppressWarnings("rawtypes") + public SAMLMessageContext extractSAMLMessageContext(HttpServletRequest request) throws MessageDecodingException, SecurityException; - public String extractSAMLMessage(HttpServletRequest request); - - public void setSecurityPolicyResolver(SecurityPolicyResolver securityPolicyResolver); - - public void buildSecurityPolicyResolver(KeyStore trustKeyStore); - - public void setSaml20Detail(AppsSAML20Details saml20Detail); - - public AppsSAML20Details getSaml20Detail(); - - public KeyStoreLoader getKeyStoreLoader(); - - public CredentialResolver getCredentialResolver(); + public String extractSAMLMessage(HttpServletRequest request); + + public void setSecurityPolicyResolver(SecurityPolicyResolver securityPolicyResolver); + + public void buildSecurityPolicyResolver(KeyStore trustKeyStore); + + public void setSaml20Detail(AppsSAML20Details saml20Detail); + + public AppsSAML20Details getSaml20Detail(); + + public KeyStoreLoader getKeyStoreLoader(); + + public CredentialResolver getCredentialResolver(); } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/decoder/OpenHTTPPostDecoder.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/decoder/OpenHTTPPostDecoder.java index 56360e420..a781f5055 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/decoder/OpenHTTPPostDecoder.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/decoder/OpenHTTPPostDecoder.java @@ -110,15 +110,15 @@ public class OpenHTTPPostDecoder extends HTTPPostDecoder { if (!(inTransport instanceof HttpServletRequestAdapter)) { throw new MessageDecodingException("Message context InTransport instance was an unsupported type"); } - HttpServletRequest httpRequest = - ((HttpServletRequestAdapter) inTransport).getWrappedRequest(); + HttpServletRequest httpRequest = + ((HttpServletRequestAdapter) inTransport).getWrappedRequest(); - String requestUrl = UrlUtils.buildFullRequestUrl(httpRequest); - if(requestUrl.indexOf("?") > -1) { - return requestUrl.substring(0, requestUrl.indexOf("?")); - }else { - return requestUrl; - } + String requestUrl = UrlUtils.buildFullRequestUrl(httpRequest); + if(requestUrl.indexOf("?") > -1) { + return requestUrl.substring(0, requestUrl.indexOf("?")); + }else { + return requestUrl; + } } /** diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/decoder/OpenHTTPPostSimpleSignDecoder.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/decoder/OpenHTTPPostSimpleSignDecoder.java index 244ec631b..56e0ee1c6 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/decoder/OpenHTTPPostSimpleSignDecoder.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/decoder/OpenHTTPPostSimpleSignDecoder.java @@ -31,112 +31,112 @@ import org.springframework.security.web.util.UrlUtils; import jakarta.servlet.http.HttpServletRequest; public class OpenHTTPPostSimpleSignDecoder extends HTTPPostSimpleSignDecoder { - private final Logger log = LoggerFactory.getLogger(OpenHTTPPostSimpleSignDecoder.class); + private final Logger log = LoggerFactory.getLogger(OpenHTTPPostSimpleSignDecoder.class); - private String receiverEndpoint; + private String receiverEndpoint; - public OpenHTTPPostSimpleSignDecoder() { - super(); - } + public OpenHTTPPostSimpleSignDecoder() { + super(); + } - public OpenHTTPPostSimpleSignDecoder(ParserPool pool) { - super(pool); - } + public OpenHTTPPostSimpleSignDecoder(ParserPool pool) { + super(pool); + } - /** - * Check the validity of the SAML protocol message receiver endpoint against - * requirements indicated in the message. - * - * @param messageContext - * current message context - * - * @throws SecurityException - * thrown if the message Destination attribute is invalid with - * respect to the receiver's endpoint - * @throws MessageDecodingException - * thrown if there is a problem decoding and processing the - * message Destination or receiver endpoint information - */ - - @Override - @SuppressWarnings("rawtypes") - protected void checkEndpointURI(SAMLMessageContext messageContext) - throws SecurityException, MessageDecodingException { + /** + * Check the validity of the SAML protocol message receiver endpoint against + * requirements indicated in the message. + * + * @param messageContext + * current message context + * + * @throws SecurityException + * thrown if the message Destination attribute is invalid with + * respect to the receiver's endpoint + * @throws MessageDecodingException + * thrown if there is a problem decoding and processing the + * message Destination or receiver endpoint information + */ + + @Override + @SuppressWarnings("rawtypes") + protected void checkEndpointURI(SAMLMessageContext messageContext) + throws SecurityException, MessageDecodingException { - log.debug("Checking SAML message intended destination endpoint against receiver endpoint"); + log.debug("Checking SAML message intended destination endpoint against receiver endpoint"); - String messageDestination = DatatypeHelper - .safeTrimOrNullString(getIntendedDestinationEndpointURI(messageContext)); + String messageDestination = DatatypeHelper + .safeTrimOrNullString(getIntendedDestinationEndpointURI(messageContext)); - boolean bindingRequires = isIntendedDestinationEndpointURIRequired(messageContext); + boolean bindingRequires = isIntendedDestinationEndpointURIRequired(messageContext); - if (messageDestination == null) { - if (bindingRequires) { - log.error("SAML message intended destination endpoint URI required by binding was empty"); - throw new SecurityException("SAML message intended destination (required by binding) was not present"); - } else { - log.debug("SAML message intended destination endpoint in message was empty, not required by binding, skipping"); - return; - } - } + if (messageDestination == null) { + if (bindingRequires) { + log.error("SAML message intended destination endpoint URI required by binding was empty"); + throw new SecurityException("SAML message intended destination (required by binding) was not present"); + } else { + log.debug("SAML message intended destination endpoint in message was empty, not required by binding, skipping"); + return; + } + } - String receiverEndpoint = DatatypeHelper.safeTrimOrNullString(getActualReceiverEndpointURI(messageContext)); + String receiverEndpoint = DatatypeHelper.safeTrimOrNullString(getActualReceiverEndpointURI(messageContext)); - log.debug("Intended message destination endpoint: {}",messageDestination); - log.debug("Actual message receiver endpoint: {}", receiverEndpoint); + log.debug("Intended message destination endpoint: {}",messageDestination); + log.debug("Actual message receiver endpoint: {}", receiverEndpoint); - // 协议头统一(http或https,需要和destination统一) - if (messageDestination.indexOf("/") != -1 - && receiverEndpoint.indexOf("/") != -1) { - if (!messageDestination.substring(0,messageDestination.indexOf("/")) - .equalsIgnoreCase(receiverEndpoint.substring(0,receiverEndpoint.indexOf("/")))) { - - receiverEndpoint = messageDestination.substring(0,messageDestination.indexOf("/")) - + receiverEndpoint.substring(receiverEndpoint.indexOf("/")); - } - } - boolean matched = compareEndpointURIs(messageDestination, - receiverEndpoint); - if (!matched) { - log.error("SAML message intended destination endpoint '{}' did not match the recipient endpoint '{}'", - messageDestination, receiverEndpoint); - throw new SecurityException("SAML message intended destination endpoint did not match recipient endpoint"); - } else { - log.debug("SAML message intended destination endpoint matched recipient endpoint"); - } - } + // 协议头统一(http或https,需要和destination统一) + if (messageDestination.indexOf("/") != -1 + && receiverEndpoint.indexOf("/") != -1) { + if (!messageDestination.substring(0,messageDestination.indexOf("/")) + .equalsIgnoreCase(receiverEndpoint.substring(0,receiverEndpoint.indexOf("/")))) { + + receiverEndpoint = messageDestination.substring(0,messageDestination.indexOf("/")) + + receiverEndpoint.substring(receiverEndpoint.indexOf("/")); + } + } + boolean matched = compareEndpointURIs(messageDestination, + receiverEndpoint); + if (!matched) { + log.error("SAML message intended destination endpoint '{}' did not match the recipient endpoint '{}'", + messageDestination, receiverEndpoint); + throw new SecurityException("SAML message intended destination endpoint did not match recipient endpoint"); + } else { + log.debug("SAML message intended destination endpoint matched recipient endpoint"); + } + } - @Override - @SuppressWarnings("rawtypes") - protected String getActualReceiverEndpointURI( - SAMLMessageContext messageContext) throws MessageDecodingException { - InTransport inTransport = messageContext.getInboundMessageTransport(); - if (!(inTransport instanceof HttpServletRequestAdapter)) { - throw new MessageDecodingException("Message context InTransport instance was an unsupported type"); - } - HttpServletRequest httpRequest = - ((HttpServletRequestAdapter) inTransport).getWrappedRequest(); + @Override + @SuppressWarnings("rawtypes") + protected String getActualReceiverEndpointURI( + SAMLMessageContext messageContext) throws MessageDecodingException { + InTransport inTransport = messageContext.getInboundMessageTransport(); + if (!(inTransport instanceof HttpServletRequestAdapter)) { + throw new MessageDecodingException("Message context InTransport instance was an unsupported type"); + } + HttpServletRequest httpRequest = + ((HttpServletRequestAdapter) inTransport).getWrappedRequest(); - String requestUrl = UrlUtils.buildFullRequestUrl(httpRequest); - if(requestUrl.indexOf("?") > -1) { - return requestUrl.substring(0, requestUrl.indexOf("?")); - }else { - return requestUrl; - } - } + String requestUrl = UrlUtils.buildFullRequestUrl(httpRequest); + if(requestUrl.indexOf("?") > -1) { + return requestUrl.substring(0, requestUrl.indexOf("?")); + }else { + return requestUrl; + } + } - /** - * @param receiverEndpoint - * the receiverEndpoint to set - */ - public void setReceiverEndpoint(String receiverEndpoint) { - this.receiverEndpoint = receiverEndpoint; - } + /** + * @param receiverEndpoint + * the receiverEndpoint to set + */ + public void setReceiverEndpoint(String receiverEndpoint) { + this.receiverEndpoint = receiverEndpoint; + } - /** - * @return the receiverEndpoint - */ - public String getReceiverEndpoint() { - return receiverEndpoint; - } + /** + * @return the receiverEndpoint + */ + public String getReceiverEndpoint() { + return receiverEndpoint; + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/decoder/OpenHTTPRedirectDecoder.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/decoder/OpenHTTPRedirectDecoder.java index 0496c87d6..2425a76cb 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/decoder/OpenHTTPRedirectDecoder.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/decoder/OpenHTTPRedirectDecoder.java @@ -31,118 +31,118 @@ import org.springframework.security.web.util.UrlUtils; import jakarta.servlet.http.HttpServletRequest; public class OpenHTTPRedirectDecoder extends HTTPRedirectDeflateDecoder { - private final Logger log = LoggerFactory.getLogger(OpenHTTPRedirectDecoder.class); + private final Logger log = LoggerFactory.getLogger(OpenHTTPRedirectDecoder.class); - private String receiverEndpoint; + private String receiverEndpoint; - public OpenHTTPRedirectDecoder() { - super(); - } + public OpenHTTPRedirectDecoder() { + super(); + } - public OpenHTTPRedirectDecoder(ParserPool pool) { - super(pool); - } + public OpenHTTPRedirectDecoder(ParserPool pool) { + super(pool); + } - /** - * Check the validity of the SAML protocol message receiver endpoint against - * requirements indicated in the message. - * - * @param messageContext - * current message context - * - * @throws SecurityException - * thrown if the message Destination attribute is invalid with - * respect to the receiver's endpoint - * @throws MessageDecodingException - * thrown if there is a problem decoding and processing the - * message Destination or receiver endpoint information - */ - - @Override - @SuppressWarnings("rawtypes") - protected void checkEndpointURI(SAMLMessageContext messageContext)throws SecurityException, MessageDecodingException { + /** + * Check the validity of the SAML protocol message receiver endpoint against + * requirements indicated in the message. + * + * @param messageContext + * current message context + * + * @throws SecurityException + * thrown if the message Destination attribute is invalid with + * respect to the receiver's endpoint + * @throws MessageDecodingException + * thrown if there is a problem decoding and processing the + * message Destination or receiver endpoint information + */ + + @Override + @SuppressWarnings("rawtypes") + protected void checkEndpointURI(SAMLMessageContext messageContext)throws SecurityException, MessageDecodingException { - log.debug("Checking SAML message intended destination endpoint against receiver endpoint"); + log.debug("Checking SAML message intended destination endpoint against receiver endpoint"); - String messageDestination = DatatypeHelper - .safeTrimOrNullString(getIntendedDestinationEndpointURI(messageContext)); + String messageDestination = DatatypeHelper + .safeTrimOrNullString(getIntendedDestinationEndpointURI(messageContext)); - boolean bindingRequires = isIntendedDestinationEndpointURIRequired(messageContext); + boolean bindingRequires = isIntendedDestinationEndpointURIRequired(messageContext); - if (messageDestination == null) { - if (bindingRequires) { - log.error("SAML message intended destination endpoint URI required by binding was empty"); - throw new SecurityException( - "SAML message intended destination (required by binding) was not present"); - } else { - log.debug("SAML message intended destination endpoint in message was empty, not required by binding, skipping"); - return; - } - } + if (messageDestination == null) { + if (bindingRequires) { + log.error("SAML message intended destination endpoint URI required by binding was empty"); + throw new SecurityException( + "SAML message intended destination (required by binding) was not present"); + } else { + log.debug("SAML message intended destination endpoint in message was empty, not required by binding, skipping"); + return; + } + } - String receiverEndpoint = DatatypeHelper - .safeTrimOrNullString(getActualReceiverEndpointURI(messageContext)); + String receiverEndpoint = DatatypeHelper + .safeTrimOrNullString(getActualReceiverEndpointURI(messageContext)); - log.debug("Intended message destination endpoint: {}",messageDestination); - log.debug("Actual message receiver endpoint: {}", receiverEndpoint); + log.debug("Intended message destination endpoint: {}",messageDestination); + log.debug("Actual message receiver endpoint: {}", receiverEndpoint); - // 协议头统一(http或https,需要和destination统一) - if (messageDestination.indexOf("/") != -1 - && receiverEndpoint.indexOf("/") != -1) { - if (!messageDestination.substring(0, - messageDestination.indexOf("/")) - .equalsIgnoreCase( - receiverEndpoint.substring(0, - receiverEndpoint.indexOf("/")))) { - receiverEndpoint = messageDestination.substring(0, - messageDestination.indexOf("/")) - + receiverEndpoint.substring(receiverEndpoint - .indexOf("/")); - } - } - boolean matched = compareEndpointURIs(messageDestination, - receiverEndpoint); - if (!matched) { - log.error( - "SAML message intended destination endpoint '{}' did not match the recipient endpoint '{}'", - messageDestination, receiverEndpoint); - throw new SecurityException( - "SAML message intended destination endpoint did not match recipient endpoint"); - } else { - log.debug("SAML message intended destination endpoint matched recipient endpoint"); - } - } + // 协议头统一(http或https,需要和destination统一) + if (messageDestination.indexOf("/") != -1 + && receiverEndpoint.indexOf("/") != -1) { + if (!messageDestination.substring(0, + messageDestination.indexOf("/")) + .equalsIgnoreCase( + receiverEndpoint.substring(0, + receiverEndpoint.indexOf("/")))) { + receiverEndpoint = messageDestination.substring(0, + messageDestination.indexOf("/")) + + receiverEndpoint.substring(receiverEndpoint + .indexOf("/")); + } + } + boolean matched = compareEndpointURIs(messageDestination, + receiverEndpoint); + if (!matched) { + log.error( + "SAML message intended destination endpoint '{}' did not match the recipient endpoint '{}'", + messageDestination, receiverEndpoint); + throw new SecurityException( + "SAML message intended destination endpoint did not match recipient endpoint"); + } else { + log.debug("SAML message intended destination endpoint matched recipient endpoint"); + } + } - @Override - @SuppressWarnings("rawtypes") - protected String getActualReceiverEndpointURI(SAMLMessageContext messageContext) throws MessageDecodingException { - InTransport inTransport = messageContext.getInboundMessageTransport(); - if (!(inTransport instanceof HttpServletRequestAdapter)) { - throw new MessageDecodingException( - "Message context InTransport instance was an unsupported type"); - } - HttpServletRequest httpRequest = - ((HttpServletRequestAdapter) inTransport).getWrappedRequest(); - String requestUrl = UrlUtils.buildFullRequestUrl(httpRequest); - if(requestUrl.indexOf("?") > -1) { - return requestUrl.substring(0, requestUrl.indexOf("?")); - }else { - return requestUrl; - } - } + @Override + @SuppressWarnings("rawtypes") + protected String getActualReceiverEndpointURI(SAMLMessageContext messageContext) throws MessageDecodingException { + InTransport inTransport = messageContext.getInboundMessageTransport(); + if (!(inTransport instanceof HttpServletRequestAdapter)) { + throw new MessageDecodingException( + "Message context InTransport instance was an unsupported type"); + } + HttpServletRequest httpRequest = + ((HttpServletRequestAdapter) inTransport).getWrappedRequest(); + String requestUrl = UrlUtils.buildFullRequestUrl(httpRequest); + if(requestUrl.indexOf("?") > -1) { + return requestUrl.substring(0, requestUrl.indexOf("?")); + }else { + return requestUrl; + } + } - /** - * @param receiverEndpoint - * the receiverEndpoint to set - */ - public void setReceiverEndpoint(String receiverEndpoint) { - this.receiverEndpoint = receiverEndpoint; - } + /** + * @param receiverEndpoint + * the receiverEndpoint to set + */ + public void setReceiverEndpoint(String receiverEndpoint) { + this.receiverEndpoint = receiverEndpoint; + } - /** - * @return the receiverEndpoint - */ - public String getReceiverEndpoint() { - return receiverEndpoint; - } + /** + * @return the receiverEndpoint + */ + public String getReceiverEndpoint() { + return receiverEndpoint; + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/impl/ExtractPostBindingAdapter.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/impl/ExtractPostBindingAdapter.java index f95de84c7..0f4554eb8 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/impl/ExtractPostBindingAdapter.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/impl/ExtractPostBindingAdapter.java @@ -42,154 +42,154 @@ import org.springframework.beans.factory.InitializingBean; import jakarta.servlet.http.HttpServletRequest; public class ExtractPostBindingAdapter implements ExtractBindingAdapter, InitializingBean{ - private static final Logger _logger = LoggerFactory.getLogger(ExtractPostBindingAdapter.class); - - static final String SAML_REQUEST_POST_PARAM_NAME = "SAMLRequest"; - static final String SAML_RESPONSE_POST_PARAM_NAME = "SAMLResponse"; + private static final Logger _logger = LoggerFactory.getLogger(ExtractPostBindingAdapter.class); + + static final String SAML_REQUEST_POST_PARAM_NAME = "SAMLRequest"; + static final String SAML_RESPONSE_POST_PARAM_NAME = "SAMLResponse"; - protected SAMLMessageDecoder decoder; - protected String issuingEntityName; - protected SecurityPolicyResolver securityPolicyResolver; - - protected IssueInstantRule issueInstantRule; - protected MessageReplayRule messageReplayRule; - - protected KeyStoreLoader keyStoreLoader; - protected CredentialResolver credentialResolver; - - protected AppsSAML20Details saml20Detail; - - - public ExtractPostBindingAdapter() { - - } + protected SAMLMessageDecoder decoder; + protected String issuingEntityName; + protected SecurityPolicyResolver securityPolicyResolver; + + protected IssueInstantRule issueInstantRule; + protected MessageReplayRule messageReplayRule; + + protected KeyStoreLoader keyStoreLoader; + protected CredentialResolver credentialResolver; + + protected AppsSAML20Details saml20Detail; + + + public ExtractPostBindingAdapter() { + + } - public ExtractPostBindingAdapter(SAMLMessageDecoder decoder) { - super(); - this.decoder = decoder; - } - - public ExtractPostBindingAdapter(SAMLMessageDecoder decoder,String issuingEntityName) { - super(); - this.decoder = decoder; - this.issuingEntityName = issuingEntityName; - } - - public ExtractPostBindingAdapter(SAMLMessageDecoder decoder,String issuingEntityName, SecurityPolicyResolver securityPolicyResolver) { - super(); - this.decoder = decoder; - this.issuingEntityName = issuingEntityName; - - this.securityPolicyResolver = securityPolicyResolver; - } + public ExtractPostBindingAdapter(SAMLMessageDecoder decoder) { + super(); + this.decoder = decoder; + } + + public ExtractPostBindingAdapter(SAMLMessageDecoder decoder,String issuingEntityName) { + super(); + this.decoder = decoder; + this.issuingEntityName = issuingEntityName; + } + + public ExtractPostBindingAdapter(SAMLMessageDecoder decoder,String issuingEntityName, SecurityPolicyResolver securityPolicyResolver) { + super(); + this.decoder = decoder; + this.issuingEntityName = issuingEntityName; + + this.securityPolicyResolver = securityPolicyResolver; + } - + - - @Override - @SuppressWarnings("rawtypes") - public SAMLMessageContext extractSAMLMessageContext(HttpServletRequest request) throws MessageDecodingException, SecurityException { - - BasicSAMLMessageContext messageContext = new BasicSAMLMessageContext(); - - messageContext.setInboundMessageTransport(new HttpServletRequestAdapter(request)); - - messageContext.setSecurityPolicyResolver(securityPolicyResolver); + + @Override + @SuppressWarnings("rawtypes") + public SAMLMessageContext extractSAMLMessageContext(HttpServletRequest request) throws MessageDecodingException, SecurityException { + + BasicSAMLMessageContext messageContext = new BasicSAMLMessageContext(); + + messageContext.setInboundMessageTransport(new HttpServletRequestAdapter(request)); + + messageContext.setSecurityPolicyResolver(securityPolicyResolver); - decoder.decode(messageContext); - _logger.debug("decode successed "); - return messageContext; + decoder.decode(messageContext); + _logger.debug("decode successed "); + return messageContext; - } + } - @Override - public String extractSAMLMessage(HttpServletRequest request) { - - if(StringUtils.isNotBlank(request.getParameter(SAML_REQUEST_POST_PARAM_NAME))) { - return request.getParameter(SAML_REQUEST_POST_PARAM_NAME); - }else { - return request.getParameter(SAML_RESPONSE_POST_PARAM_NAME); - } - - } - - @Override - public void buildSecurityPolicyResolver(KeyStore trustKeyStore) { - _logger.debug("EntityName {}, KeystorePassword {}", - keyStoreLoader.getEntityName(),keyStoreLoader.getKeystorePassword()); - - TrustResolver trustResolver = new TrustResolver(trustKeyStore, - keyStoreLoader.getEntityName(), - keyStoreLoader.getKeystorePassword(), - issueInstantRule, - messageReplayRule,"POST"); - credentialResolver = (CredentialResolver)trustResolver.getKeyStoreCredentialResolver(); - this.securityPolicyResolver = trustResolver.getStaticSecurityPolicyResolver(); - } - - - /** - * @param securityPolicyResolver the securityPolicyResolver to set - */ - @Override - public void setSecurityPolicyResolver( - SecurityPolicyResolver securityPolicyResolver) { - this.securityPolicyResolver = securityPolicyResolver; - } + @Override + public String extractSAMLMessage(HttpServletRequest request) { + + if(StringUtils.isNotBlank(request.getParameter(SAML_REQUEST_POST_PARAM_NAME))) { + return request.getParameter(SAML_REQUEST_POST_PARAM_NAME); + }else { + return request.getParameter(SAML_RESPONSE_POST_PARAM_NAME); + } + + } + + @Override + public void buildSecurityPolicyResolver(KeyStore trustKeyStore) { + _logger.debug("EntityName {}, KeystorePassword {}", + keyStoreLoader.getEntityName(),keyStoreLoader.getKeystorePassword()); + + TrustResolver trustResolver = new TrustResolver(trustKeyStore, + keyStoreLoader.getEntityName(), + keyStoreLoader.getKeystorePassword(), + issueInstantRule, + messageReplayRule,"POST"); + credentialResolver = (CredentialResolver)trustResolver.getKeyStoreCredentialResolver(); + this.securityPolicyResolver = trustResolver.getStaticSecurityPolicyResolver(); + } + + + /** + * @param securityPolicyResolver the securityPolicyResolver to set + */ + @Override + public void setSecurityPolicyResolver( + SecurityPolicyResolver securityPolicyResolver) { + this.securityPolicyResolver = securityPolicyResolver; + } - @Override - public void afterPropertiesSet() throws Exception { - - } + @Override + public void afterPropertiesSet() throws Exception { + + } - @Override - public void setSaml20Detail(AppsSAML20Details saml20Detail) { - this.saml20Detail=saml20Detail; - } + @Override + public void setSaml20Detail(AppsSAML20Details saml20Detail) { + this.saml20Detail=saml20Detail; + } - @Override - public AppsSAML20Details getSaml20Detail() { - return saml20Detail; - } + @Override + public AppsSAML20Details getSaml20Detail() { + return saml20Detail; + } - @Override - public KeyStoreLoader getKeyStoreLoader() { - return keyStoreLoader; - } + @Override + public KeyStoreLoader getKeyStoreLoader() { + return keyStoreLoader; + } - public void setKeyStoreLoader(KeyStoreLoader keyStoreLoader) { - this.keyStoreLoader = keyStoreLoader; - } + public void setKeyStoreLoader(KeyStoreLoader keyStoreLoader) { + this.keyStoreLoader = keyStoreLoader; + } - @Override - public CredentialResolver getCredentialResolver() { - return this.credentialResolver; - } + @Override + public CredentialResolver getCredentialResolver() { + return this.credentialResolver; + } - public void setIssuingEntityName(String issuingEntityName) { - this.issuingEntityName = issuingEntityName; - } + public void setIssuingEntityName(String issuingEntityName) { + this.issuingEntityName = issuingEntityName; + } - public void setIssueInstantRule(IssueInstantRule issueInstantRule) { - this.issueInstantRule = issueInstantRule; - } + public void setIssueInstantRule(IssueInstantRule issueInstantRule) { + this.issueInstantRule = issueInstantRule; + } - public void setMessageReplayRule(MessageReplayRule messageReplayRule) { - this.messageReplayRule = messageReplayRule; - } - - + public void setMessageReplayRule(MessageReplayRule messageReplayRule) { + this.messageReplayRule = messageReplayRule; + } + + } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/impl/ExtractRedirectBindingAdapter.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/impl/ExtractRedirectBindingAdapter.java index 12cc3b6f5..4e2221ea6 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/impl/ExtractRedirectBindingAdapter.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/impl/ExtractRedirectBindingAdapter.java @@ -26,33 +26,33 @@ import org.opensaml.xml.security.credential.CredentialResolver; public class ExtractRedirectBindingAdapter extends ExtractPostBindingAdapter{ - public ExtractRedirectBindingAdapter(SAMLMessageDecoder decoder) { - this.decoder = decoder; - } - - public ExtractRedirectBindingAdapter(SAMLMessageDecoder decoder,String issuingEntityName) { - this.decoder = decoder; - this.issuingEntityName = issuingEntityName; - } - - public ExtractRedirectBindingAdapter(SAMLMessageDecoder decoder,String issuingEntityName, SecurityPolicyResolver securityPolicyResolver) { - this.decoder = decoder; - this.issuingEntityName = issuingEntityName; - - this.securityPolicyResolver = securityPolicyResolver; - } - - @Override - public void buildSecurityPolicyResolver(KeyStore trustKeyStore) { + public ExtractRedirectBindingAdapter(SAMLMessageDecoder decoder) { + this.decoder = decoder; + } + + public ExtractRedirectBindingAdapter(SAMLMessageDecoder decoder,String issuingEntityName) { + this.decoder = decoder; + this.issuingEntityName = issuingEntityName; + } + + public ExtractRedirectBindingAdapter(SAMLMessageDecoder decoder,String issuingEntityName, SecurityPolicyResolver securityPolicyResolver) { + this.decoder = decoder; + this.issuingEntityName = issuingEntityName; + + this.securityPolicyResolver = securityPolicyResolver; + } + + @Override + public void buildSecurityPolicyResolver(KeyStore trustKeyStore) { - TrustResolver trustResolver = new TrustResolver(trustKeyStore, - keyStoreLoader.getEntityName(), - keyStoreLoader.getKeystorePassword(), - issueInstantRule, - messageReplayRule, - "Redirect"); - credentialResolver = (CredentialResolver)trustResolver.getKeyStoreCredentialResolver(); - this.securityPolicyResolver = trustResolver.getStaticSecurityPolicyResolver(); - } + TrustResolver trustResolver = new TrustResolver(trustKeyStore, + keyStoreLoader.getEntityName(), + keyStoreLoader.getKeystorePassword(), + issueInstantRule, + messageReplayRule, + "Redirect"); + credentialResolver = (CredentialResolver)trustResolver.getKeyStoreCredentialResolver(); + this.securityPolicyResolver = trustResolver.getStaticSecurityPolicyResolver(); + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/impl/PostBindingAdapter.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/impl/PostBindingAdapter.java index 3483ce33f..ff584ccf0 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/impl/PostBindingAdapter.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/impl/PostBindingAdapter.java @@ -54,187 +54,187 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; public class PostBindingAdapter implements BindingAdapter, InitializingBean{ - private static final Logger logger = LoggerFactory.getLogger(PostBindingAdapter.class); + private static final Logger logger = LoggerFactory.getLogger(PostBindingAdapter.class); - static final String SAML_REQUEST_POST_PARAM_NAME = "SAMLRequest"; - static final String SAML_RESPONSE_POST_PARAM_NAME = "SAMLResponse"; + static final String SAML_REQUEST_POST_PARAM_NAME = "SAMLRequest"; + static final String SAML_RESPONSE_POST_PARAM_NAME = "SAMLResponse"; - protected VelocityEngine velocityEngine; + protected VelocityEngine velocityEngine; - protected SAMLMessageEncoder encoder; - protected String issuerEntityName; - - protected CredentialResolver credentialResolver; - protected Credential signingCredential; - protected Credential spSigningCredential; - protected SecurityPolicyResolver securityPolicyResolver; + protected SAMLMessageEncoder encoder; + protected String issuerEntityName; + + protected CredentialResolver credentialResolver; + protected Credential signingCredential; + protected Credential spSigningCredential; + protected SecurityPolicyResolver securityPolicyResolver; - protected ExtractBindingAdapter extractBindingAdapter; - - protected AuthnRequestInfo authnRequestInfo; - - protected String relayState; + protected ExtractBindingAdapter extractBindingAdapter; + + protected AuthnRequestInfo authnRequestInfo; + + protected String relayState; - public PostBindingAdapter() { - super(); - } - - public PostBindingAdapter(SAMLMessageDecoder decoder,String issuerEntityName) { - super(); - this.issuerEntityName = issuerEntityName; - } - - public PostBindingAdapter(String issuerEntityName, SecurityPolicyResolver securityPolicyResolver) { - super(); - this.issuerEntityName = issuerEntityName; - - this.securityPolicyResolver = securityPolicyResolver; - } + public PostBindingAdapter() { + super(); + } + + public PostBindingAdapter(SAMLMessageDecoder decoder,String issuerEntityName) { + super(); + this.issuerEntityName = issuerEntityName; + } + + public PostBindingAdapter(String issuerEntityName, SecurityPolicyResolver securityPolicyResolver) { + super(); + this.issuerEntityName = issuerEntityName; + + this.securityPolicyResolver = securityPolicyResolver; + } - public void setVelocityEngine(VelocityEngine velocityEngine) { - this.velocityEngine = velocityEngine; - } - - @Override - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void sendSAMLMessage(SignableSAMLObject samlMessage, - Endpoint endpoint, - HttpServletRequest request, - HttpServletResponse response) throws MessageEncodingException { - - HttpServletResponseAdapter outTransport = new HttpServletResponseAdapter(response, false); - - BasicSAMLMessageContext messageContext = new BasicSAMLMessageContext(); - - if (relayState!=null) { - messageContext.setRelayState(relayState); - } - - messageContext.setOutboundMessageTransport(outTransport); - messageContext.setPeerEntityEndpoint(endpoint); - messageContext.setOutboundSAMLMessage(samlMessage); - messageContext.setOutboundMessageIssuer(issuerEntityName); - messageContext.setOutboundSAMLMessageSigningCredential(signingCredential); - - encoder.encode(messageContext); - - } + public void setVelocityEngine(VelocityEngine velocityEngine) { + this.velocityEngine = velocityEngine; + } + + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void sendSAMLMessage(SignableSAMLObject samlMessage, + Endpoint endpoint, + HttpServletRequest request, + HttpServletResponse response) throws MessageEncodingException { + + HttpServletResponseAdapter outTransport = new HttpServletResponseAdapter(response, false); + + BasicSAMLMessageContext messageContext = new BasicSAMLMessageContext(); + + if (relayState!=null) { + messageContext.setRelayState(relayState); + } + + messageContext.setOutboundMessageTransport(outTransport); + messageContext.setPeerEntityEndpoint(endpoint); + messageContext.setOutboundSAMLMessage(samlMessage); + messageContext.setOutboundMessageIssuer(issuerEntityName); + messageContext.setOutboundSAMLMessageSigningCredential(signingCredential); + + encoder.encode(messageContext); + + } - public void buildCredentialResolver(CredentialResolver credentialResolver) throws Exception{ - this.credentialResolver=credentialResolver; - CriteriaSet criteriaSet = new CriteriaSet(); - criteriaSet.add(new EntityIDCriteria(getKeyStoreLoader().getEntityName())); - criteriaSet.add(new UsageCriteria(UsageType.SIGNING)); + public void buildCredentialResolver(CredentialResolver credentialResolver) throws Exception{ + this.credentialResolver=credentialResolver; + CriteriaSet criteriaSet = new CriteriaSet(); + criteriaSet.add(new EntityIDCriteria(getKeyStoreLoader().getEntityName())); + criteriaSet.add(new UsageCriteria(UsageType.SIGNING)); - try { - signingCredential = credentialResolver.resolveSingle(criteriaSet); - } catch (SecurityException e) { - logger.error("Credential Resolver error . ", e); - throw new Exception(e); - } - Validate.notNull(signingCredential); - } - - public Credential buildSPSigningCredential() throws Exception{ - KeyStore trustKeyStore = KeyStoreUtil.bytes2KeyStore(getSaml20Details().getKeyStore(), - getKeyStoreLoader().getKeyStore().getType(), - getKeyStoreLoader().getKeystorePassword()); - - TrustResolver trustResolver=new TrustResolver(); - KeyStoreCredentialResolver credentialResolver =trustResolver.buildKeyStoreCredentialResolver( - trustKeyStore, - getSaml20Details().getEntityId(), - getKeyStoreLoader().getKeystorePassword()); - - CriteriaSet criteriaSet = new CriteriaSet(); - criteriaSet.add(new EntityIDCriteria(getSaml20Details().getEntityId())); - criteriaSet.add(new UsageCriteria(UsageType.ENCRYPTION)); + try { + signingCredential = credentialResolver.resolveSingle(criteriaSet); + } catch (SecurityException e) { + logger.error("Credential Resolver error . ", e); + throw new Exception(e); + } + Validate.notNull(signingCredential); + } + + public Credential buildSPSigningCredential() throws Exception{ + KeyStore trustKeyStore = KeyStoreUtil.bytes2KeyStore(getSaml20Details().getKeyStore(), + getKeyStoreLoader().getKeyStore().getType(), + getKeyStoreLoader().getKeystorePassword()); + + TrustResolver trustResolver=new TrustResolver(); + KeyStoreCredentialResolver credentialResolver =trustResolver.buildKeyStoreCredentialResolver( + trustKeyStore, + getSaml20Details().getEntityId(), + getKeyStoreLoader().getKeystorePassword()); + + CriteriaSet criteriaSet = new CriteriaSet(); + criteriaSet.add(new EntityIDCriteria(getSaml20Details().getEntityId())); + criteriaSet.add(new UsageCriteria(UsageType.ENCRYPTION)); - try { - spSigningCredential = credentialResolver.resolveSingle(criteriaSet); - } catch (SecurityException e) { - logger.error("Credential Resolver error . ", e); - throw new Exception(e); - } - Validate.notNull(spSigningCredential); - - return spSigningCredential; - } - - @Override - public void afterPropertiesSet() throws Exception { - encoder = new HTTPPostEncoder(velocityEngine,"/templates/saml2-post-binding.vm"); - } + try { + spSigningCredential = credentialResolver.resolveSingle(criteriaSet); + } catch (SecurityException e) { + logger.error("Credential Resolver error . ", e); + throw new Exception(e); + } + Validate.notNull(spSigningCredential); + + return spSigningCredential; + } + + @Override + public void afterPropertiesSet() throws Exception { + encoder = new HTTPPostEncoder(velocityEngine,"/templates/saml2-post-binding.vm"); + } - /** - * @param securityPolicyResolver the securityPolicyResolver to set - */ - @Override - public void setSecurityPolicyResolver( - SecurityPolicyResolver securityPolicyResolver) { - this.securityPolicyResolver = securityPolicyResolver; - } + /** + * @param securityPolicyResolver the securityPolicyResolver to set + */ + @Override + public void setSecurityPolicyResolver( + SecurityPolicyResolver securityPolicyResolver) { + this.securityPolicyResolver = securityPolicyResolver; + } - public void setIssuerEntityName(String issuerEntityName) { - this.issuerEntityName = issuerEntityName; - } + public void setIssuerEntityName(String issuerEntityName) { + this.issuerEntityName = issuerEntityName; + } - public KeyStoreLoader getKeyStoreLoader() { - return extractBindingAdapter.getKeyStoreLoader(); - } + public KeyStoreLoader getKeyStoreLoader() { + return extractBindingAdapter.getKeyStoreLoader(); + } - @Override - public Credential getSigningCredential() { - return signingCredential; - } + @Override + public Credential getSigningCredential() { + return signingCredential; + } - public void setSigningCredential(Credential signingCredential) { - this.signingCredential = signingCredential; - } + public void setSigningCredential(Credential signingCredential) { + this.signingCredential = signingCredential; + } - @Override - public Credential getSpSigningCredential() { - return spSigningCredential; - } + @Override + public Credential getSpSigningCredential() { + return spSigningCredential; + } - public void setSpSigningCredential(Credential spSigningCredential) { - this.spSigningCredential = spSigningCredential; - } - - @Override - public AuthnRequestInfo getAuthnRequestInfo() { - return authnRequestInfo; - } + public void setSpSigningCredential(Credential spSigningCredential) { + this.spSigningCredential = spSigningCredential; + } + + @Override + public AuthnRequestInfo getAuthnRequestInfo() { + return authnRequestInfo; + } - @Override - public void setAuthnRequestInfo(AuthnRequestInfo authnRequestInfo) { - this.authnRequestInfo = authnRequestInfo; - } + @Override + public void setAuthnRequestInfo(AuthnRequestInfo authnRequestInfo) { + this.authnRequestInfo = authnRequestInfo; + } - @Override - public void setRelayState(String relayState) { - this.relayState = relayState; - } + @Override + public void setRelayState(String relayState) { + this.relayState = relayState; + } - @Override - public void setExtractBindingAdapter( - ExtractBindingAdapter extractBindingAdapter) { - this.extractBindingAdapter=extractBindingAdapter; - this.credentialResolver=extractBindingAdapter.getCredentialResolver(); - try { - buildCredentialResolver(extractBindingAdapter.getCredentialResolver()); - } catch (Exception e) { - e.printStackTrace(); - } - - } + @Override + public void setExtractBindingAdapter( + ExtractBindingAdapter extractBindingAdapter) { + this.extractBindingAdapter=extractBindingAdapter; + this.credentialResolver=extractBindingAdapter.getCredentialResolver(); + try { + buildCredentialResolver(extractBindingAdapter.getCredentialResolver()); + } catch (Exception e) { + e.printStackTrace(); + } + + } - @Override - public AppsSAML20Details getSaml20Details() { - return extractBindingAdapter.getSaml20Detail(); - } + @Override + public AppsSAML20Details getSaml20Details() { + return extractBindingAdapter.getSaml20Detail(); + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/impl/PostSimpleSignBindingAdapter.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/impl/PostSimpleSignBindingAdapter.java index 9ebb27143..53e9ca1ca 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/impl/PostSimpleSignBindingAdapter.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/binding/impl/PostSimpleSignBindingAdapter.java @@ -23,26 +23,26 @@ import org.opensaml.ws.security.SecurityPolicyResolver; public class PostSimpleSignBindingAdapter extends PostBindingAdapter{ - public PostSimpleSignBindingAdapter() { - super(); - } - - public PostSimpleSignBindingAdapter(String issuerEntityName) { - super(); - this.issuerEntityName = issuerEntityName; - } - - public PostSimpleSignBindingAdapter(String issuerEntityName, SecurityPolicyResolver securityPolicyResolver) { - super(); - this.issuerEntityName = issuerEntityName; - - this.securityPolicyResolver = securityPolicyResolver; - } + public PostSimpleSignBindingAdapter() { + super(); + } + + public PostSimpleSignBindingAdapter(String issuerEntityName) { + super(); + this.issuerEntityName = issuerEntityName; + } + + public PostSimpleSignBindingAdapter(String issuerEntityName, SecurityPolicyResolver securityPolicyResolver) { + super(); + this.issuerEntityName = issuerEntityName; + + this.securityPolicyResolver = securityPolicyResolver; + } - @Override - public void afterPropertiesSet() throws Exception { - encoder = new HTTPPostSimpleSignEncoder(velocityEngine,"/templates/saml2-post-simplesign-binding.vm", true); - } + @Override + public void afterPropertiesSet() throws Exception { + encoder = new HTTPPostSimpleSignEncoder(velocityEngine,"/templates/saml2-post-simplesign-binding.vm", true); + } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/AuthnRequestGenerator.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/AuthnRequestGenerator.java index 6faa2374a..b8eb33992 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/AuthnRequestGenerator.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/AuthnRequestGenerator.java @@ -27,35 +27,35 @@ import org.opensaml.saml2.core.impl.AuthnRequestBuilder; public class AuthnRequestGenerator { - - private final String issuingEntityName; - private final TimeService timeService; - private final IDService idService; - private IssuerGenerator issuerGenerator; - - public AuthnRequestGenerator(String issuingEntityName, TimeService timeService, IDService idService) { - super(); - this.issuingEntityName = issuingEntityName; - this.timeService = timeService; - this.idService = idService; - - issuerGenerator = new IssuerGenerator(this.issuingEntityName); - } + + private final String issuingEntityName; + private final TimeService timeService; + private final IDService idService; + private IssuerGenerator issuerGenerator; + + public AuthnRequestGenerator(String issuingEntityName, TimeService timeService, IDService idService) { + super(); + this.issuingEntityName = issuingEntityName; + this.timeService = timeService; + this.idService = idService; + + issuerGenerator = new IssuerGenerator(this.issuingEntityName); + } - public AuthnRequest generateAuthnRequest(String destination, String responseLocation) { - AuthnRequest authnRequest = new AuthnRequestBuilder().buildObject(); - - authnRequest.setAssertionConsumerServiceURL(responseLocation); - authnRequest.setID(idService.generateID()); - authnRequest.setIssueInstant(timeService.getCurrentDateTime()); - authnRequest.setDestination(destination); - - authnRequest.setIssuer(issuerGenerator.generateIssuer()); - - return authnRequest; - } + public AuthnRequest generateAuthnRequest(String destination, String responseLocation) { + AuthnRequest authnRequest = new AuthnRequestBuilder().buildObject(); + + authnRequest.setAssertionConsumerServiceURL(responseLocation); + authnRequest.setID(idService.generateID()); + authnRequest.setIssueInstant(timeService.getCurrentDateTime()); + authnRequest.setDestination(destination); + + authnRequest.setIssuer(issuerGenerator.generateIssuer()); + + return authnRequest; + } - - + + } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/endpoint/ConsumerEndpoint.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/endpoint/ConsumerEndpoint.java index f641da6b1..b02d6f644 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/endpoint/ConsumerEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/endpoint/ConsumerEndpoint.java @@ -80,275 +80,275 @@ import jakarta.servlet.http.HttpServletResponse; @Controller public class ConsumerEndpoint { - private static final Logger logger = LoggerFactory.getLogger(ConsumerEndpoint.class); + private static final Logger logger = LoggerFactory.getLogger(ConsumerEndpoint.class); - private BindingAdapter bindingAdapter; - - @Autowired - @Qualifier("serviceProviderKeyStoreLoader") - private KeyStoreLoader keyStoreLoader; + private BindingAdapter bindingAdapter; + + @Autowired + @Qualifier("serviceProviderKeyStoreLoader") + private KeyStoreLoader keyStoreLoader; - @Autowired - @Qualifier("timeService") - private TimeService timeService; + @Autowired + @Qualifier("timeService") + private TimeService timeService; - @Autowired - @Qualifier("idService") - private IDService idService; - - @Autowired + @Autowired + @Qualifier("idService") + private IDService idService; + + @Autowired @Qualifier("authenticationProvider") - AbstractAuthenticationProvider authenticationProvider ; + AbstractAuthenticationProvider authenticationProvider ; - private String singleSignOnServiceURL; - private String assertionConsumerServiceURL; - - @Autowired - @Qualifier("extractRedirectBindingAdapter") - private ExtractBindingAdapter extractBindingAdapter; + private String singleSignOnServiceURL; + private String assertionConsumerServiceURL; + + @Autowired + @Qualifier("extractRedirectBindingAdapter") + private ExtractBindingAdapter extractBindingAdapter; - @Autowired - private AppsSaml20DetailsService saml20DetailsService; + @Autowired + private AppsSaml20DetailsService saml20DetailsService; - @Autowired - @Qualifier("issueInstantRule") - private IssueInstantRule issueInstantRule; + @Autowired + @Qualifier("issueInstantRule") + private IssueInstantRule issueInstantRule; - @Autowired - @Qualifier("messageReplayRule") - private MessageReplayRule messageReplayRule; - - @Autowired - AuthTokenService authJwtService; + @Autowired + @Qualifier("messageReplayRule") + private MessageReplayRule messageReplayRule; + + @Autowired + AuthTokenService authJwtService; - EndpointGenerator endpointGenerator; - AuthnRequestGenerator authnRequestGenerator; - CredentialResolver credentialResolver; + EndpointGenerator endpointGenerator; + AuthnRequestGenerator authnRequestGenerator; + CredentialResolver credentialResolver; - Credential signingCredential; - - SAML2ValidatorSuite validatorSuite = new SAML2ValidatorSuite(); + Credential signingCredential; + + SAML2ValidatorSuite validatorSuite = new SAML2ValidatorSuite(); - @RequestMapping(value = "/authz/saml20/consumer/{id}") - public ModelAndView consumer(HttpServletRequest request, - HttpServletResponse response, @PathVariable("id") String appId) - throws Exception { + @RequestMapping(value = "/authz/saml20/consumer/{id}") + public ModelAndView consumer(HttpServletRequest request, + HttpServletResponse response, @PathVariable("id") String appId) + throws Exception { - logger.debug("Attempting authentication."); - // 初始化SP 证书 - initCredential(appId); + logger.debug("Attempting authentication."); + // 初始化SP 证书 + initCredential(appId); - SAMLMessageContext messageContext=null; - /* - try { - messageContext = bindingAdapter.extractSAMLMessageContext(request); - } catch (MessageDecodingException me) { - logger.error("Could not decode SAML Response", me); - throw new Exception(me); - } catch (SecurityException se) { - logger.error("Could not decode SAML Response", se); - throw new Exception(se); - }*/ + SAMLMessageContext messageContext=null; + /* + try { + messageContext = bindingAdapter.extractSAMLMessageContext(request); + } catch (MessageDecodingException me) { + logger.error("Could not decode SAML Response", me); + throw new Exception(me); + } catch (SecurityException se) { + logger.error("Could not decode SAML Response", se); + throw new Exception(se); + }*/ - logger.debug("Message received from issuer: " - + messageContext.getInboundMessageIssuer()); + logger.debug("Message received from issuer: " + + messageContext.getInboundMessageIssuer()); - if (!(messageContext.getInboundSAMLMessage() instanceof Response)) { - logger.error("SAML Message was not a Response"); - throw new Exception(); - } - List assertionList = ((Response) messageContext - .getInboundSAMLMessage()).getAssertions(); + if (!(messageContext.getInboundSAMLMessage() instanceof Response)) { + logger.error("SAML Message was not a Response"); + throw new Exception(); + } + List assertionList = ((Response) messageContext + .getInboundSAMLMessage()).getAssertions(); - String credentials = extractBindingAdapter.extractSAMLMessage(request); + String credentials = extractBindingAdapter.extractSAMLMessage(request); - // 未认证token - Response samlResponse=(Response) messageContext.getInboundSAMLMessage(); - - AuthenticationDetailsSource authenticationDetailsSource = new WebAuthenticationDetailsSource(); - + // 未认证token + Response samlResponse=(Response) messageContext.getInboundSAMLMessage(); + + AuthenticationDetailsSource authenticationDetailsSource = new WebAuthenticationDetailsSource(); + - try { - validatorSuite.validate(samlResponse); - } catch (ValidationException ve) { - logger.warn("Response Message failed Validation", ve); - throw new ServiceProviderAuthenticationException("Invalid SAML REsponse Message", ve); - } + try { + validatorSuite.validate(samlResponse); + } catch (ValidationException ve) { + logger.warn("Response Message failed Validation", ve); + throw new ServiceProviderAuthenticationException("Invalid SAML REsponse Message", ve); + } - - checkResponseStatus(samlResponse); + + checkResponseStatus(samlResponse); - Assertion assertion = samlResponse.getAssertions().get(0); - - logger.debug("authenticationResponseIssuingEntityName {}" ,samlResponse.getIssuer().getValue()); - - String username=assertion.getSubject().getNameID().getValue(); - - logger.debug("assertion.getID() " ,assertion.getID()); - logger.debug("assertion.getSubject().getNameID().getValue() ", username); - - - logger.debug("assertion.getID() ", assertion.getAuthnStatements()); - LoginCredential loginCredential =new LoginCredential( - username,"",ConstsLoginType.SAMLTRUST); - - Authentication authentication = authenticationProvider.authenticate(loginCredential,true); - if(authentication == null) { - String congress = authJwtService.createCongress(authentication); - } - ModelAndView mav = new ModelAndView(); - mav.addObject("username", username); - mav.setViewName("redirect:/appList"); - return mav; - } + Assertion assertion = samlResponse.getAssertions().get(0); + + logger.debug("authenticationResponseIssuingEntityName {}" ,samlResponse.getIssuer().getValue()); + + String username=assertion.getSubject().getNameID().getValue(); + + logger.debug("assertion.getID() " ,assertion.getID()); + logger.debug("assertion.getSubject().getNameID().getValue() ", username); + + + logger.debug("assertion.getID() ", assertion.getAuthnStatements()); + LoginCredential loginCredential =new LoginCredential( + username,"",ConstsLoginType.SAMLTRUST); + + Authentication authentication = authenticationProvider.authenticate(loginCredential,true); + if(authentication == null) { + String congress = authJwtService.createCongress(authentication); + } + ModelAndView mav = new ModelAndView(); + mav.addObject("username", username); + mav.setViewName("redirect:/appList"); + return mav; + } - public void afterPropertiesSet() throws Exception { + public void afterPropertiesSet() throws Exception { - authnRequestGenerator = new AuthnRequestGenerator(keyStoreLoader.getEntityName(), timeService, idService); - endpointGenerator = new EndpointGenerator(); + authnRequestGenerator = new AuthnRequestGenerator(keyStoreLoader.getEntityName(), timeService, idService); + endpointGenerator = new EndpointGenerator(); - CriteriaSet criteriaSet = new CriteriaSet(); - criteriaSet.add(new EntityIDCriteria(keyStoreLoader.getEntityName())); - criteriaSet.add(new UsageCriteria(UsageType.SIGNING)); + CriteriaSet criteriaSet = new CriteriaSet(); + criteriaSet.add(new EntityIDCriteria(keyStoreLoader.getEntityName())); + criteriaSet.add(new UsageCriteria(UsageType.SIGNING)); - try { - signingCredential = credentialResolver.resolveSingle(criteriaSet); - } catch (SecurityException e) { - logger.error("证书解析出错", e); - throw new Exception(e); - } - Validate.notNull(signingCredential); + try { + signingCredential = credentialResolver.resolveSingle(criteriaSet); + } catch (SecurityException e) { + logger.error("证书解析出错", e); + throw new Exception(e); + } + Validate.notNull(signingCredential); - } + } - /** - * 初始化sp证书 - * - * @throws Exception - */ - private void initCredential(String appId) throws Exception { - // 1. 获取 sp keyStore - AppsSAML20Details saml20Details = saml20DetailsService.get(appId); - if (saml20Details == null) { - logger.error("appId[" + appId + "] not exists"); - throw new Exception(); - } - byte[] keyStoreBytes = saml20Details.getKeyStore(); - InputStream keyStoreStream = new ByteArrayInputStream(keyStoreBytes); + /** + * 初始化sp证书 + * + * @throws Exception + */ + private void initCredential(String appId) throws Exception { + // 1. 获取 sp keyStore + AppsSAML20Details saml20Details = saml20DetailsService.get(appId); + if (saml20Details == null) { + logger.error("appId[" + appId + "] not exists"); + throw new Exception(); + } + byte[] keyStoreBytes = saml20Details.getKeyStore(); + InputStream keyStoreStream = new ByteArrayInputStream(keyStoreBytes); - try { - KeyStore keyStore = KeyStore.getInstance(keyStoreLoader.getKeystoreType()); - keyStore.load(keyStoreStream, keyStoreLoader.getKeystorePassword().toCharArray()); + try { + KeyStore keyStore = KeyStore.getInstance(keyStoreLoader.getKeystoreType()); + keyStore.load(keyStoreStream, keyStoreLoader.getKeystorePassword().toCharArray()); - Map passwords = new HashMap(); - for (Enumeration en = keyStore.aliases(); en.hasMoreElements();) { - String aliase = en.nextElement(); - if (aliase.equalsIgnoreCase(keyStoreLoader.getEntityName())) { - passwords.put(aliase, keyStoreLoader.getKeystorePassword()); - } - } - // TrustResolver trustResolver = new - // TrustResolver(keyStore,keyStoreLoader.getIdpIssuingEntityName(),keyStoreLoader.getKeystorePassword()); + Map passwords = new HashMap(); + for (Enumeration en = keyStore.aliases(); en.hasMoreElements();) { + String aliase = en.nextElement(); + if (aliase.equalsIgnoreCase(keyStoreLoader.getEntityName())) { + passwords.put(aliase, keyStoreLoader.getKeystorePassword()); + } + } + // TrustResolver trustResolver = new + // TrustResolver(keyStore,keyStoreLoader.getIdpIssuingEntityName(),keyStoreLoader.getKeystorePassword()); - AuthnResponseGenerator authnResponseGenerator = new AuthnResponseGenerator( - keyStoreLoader.getEntityName(), timeService, - idService); - // endpointGenerator = new EndpointGenerator(); + AuthnResponseGenerator authnResponseGenerator = new AuthnResponseGenerator( + keyStoreLoader.getEntityName(), timeService, + idService); + // endpointGenerator = new EndpointGenerator(); - CriteriaSet criteriaSet = new CriteriaSet(); - criteriaSet.add(new EntityIDCriteria(keyStoreLoader - .getEntityName())); - criteriaSet.add(new UsageCriteria(UsageType.SIGNING)); + CriteriaSet criteriaSet = new CriteriaSet(); + criteriaSet.add(new EntityIDCriteria(keyStoreLoader + .getEntityName())); + criteriaSet.add(new UsageCriteria(UsageType.SIGNING)); - KeyStoreCredentialResolver credentialResolver = new KeyStoreCredentialResolver( - keyStore, passwords); - signingCredential = credentialResolver.resolveSingle(criteriaSet); - Validate.notNull(signingCredential); + KeyStoreCredentialResolver credentialResolver = new KeyStoreCredentialResolver( + keyStore, passwords); + signingCredential = credentialResolver.resolveSingle(criteriaSet); + Validate.notNull(signingCredential); - // adapter set resolver - TrustResolver trustResolver = new TrustResolver(keyStore, - keyStoreLoader.getEntityName(), - keyStoreLoader.getKeystorePassword(), issueInstantRule, - messageReplayRule,"POST"); - extractBindingAdapter.setSecurityPolicyResolver(trustResolver - .getStaticSecurityPolicyResolver()); - } catch (Exception e) { - logger.error("初始化sp证书出错"); - throw new Exception(e); - } - } - - - private void checkResponseStatus(Response samlResponse) { + // adapter set resolver + TrustResolver trustResolver = new TrustResolver(keyStore, + keyStoreLoader.getEntityName(), + keyStoreLoader.getKeystorePassword(), issueInstantRule, + messageReplayRule,"POST"); + extractBindingAdapter.setSecurityPolicyResolver(trustResolver + .getStaticSecurityPolicyResolver()); + } catch (Exception e) { + logger.error("初始化sp证书出错"); + throw new Exception(e); + } + } + + + private void checkResponseStatus(Response samlResponse) { - - if(StatusCode.SUCCESS_URI.equals( StringUtils.trim(samlResponse.getStatus().getStatusCode().getValue()))) { - - additionalValidationChecksOnSuccessfulResponse(samlResponse); - - } - - - else { - - StringBuilder extraInformation = extractExtraInformation(samlResponse); - - if(extraInformation.length() > 0) { - logger.warn("Extra information extracted from authentication failure was {}", extraInformation.toString()); - - throw new IdentityProviderAuthenticationException("Identity Provider has failed the authentication.", extraInformation.toString()); - } - - else { - throw new IdentityProviderAuthenticationException("Identity Provider has failed the authentication."); - } - - } - } - - - private void additionalValidationChecksOnSuccessfulResponse( - Response samlResponse) { - //saml validator suite does not check for assertions on successful auths - if(samlResponse.getAssertions().isEmpty()){ - throw new ServiceProviderAuthenticationException("Successful Response did not contain any assertions"); - } - - //nor authnStatements - else if(samlResponse.getAssertions().get(0).getAuthnStatements().isEmpty()){ - throw new ServiceProviderAuthenticationException("Successful Response did not contain an assertions with an AuthnStatement"); - } + + if(StatusCode.SUCCESS_URI.equals( StringUtils.trim(samlResponse.getStatus().getStatusCode().getValue()))) { + + additionalValidationChecksOnSuccessfulResponse(samlResponse); + + } + + + else { + + StringBuilder extraInformation = extractExtraInformation(samlResponse); + + if(extraInformation.length() > 0) { + logger.warn("Extra information extracted from authentication failure was {}", extraInformation.toString()); + + throw new IdentityProviderAuthenticationException("Identity Provider has failed the authentication.", extraInformation.toString()); + } + + else { + throw new IdentityProviderAuthenticationException("Identity Provider has failed the authentication."); + } + + } + } + + + private void additionalValidationChecksOnSuccessfulResponse( + Response samlResponse) { + //saml validator suite does not check for assertions on successful auths + if(samlResponse.getAssertions().isEmpty()){ + throw new ServiceProviderAuthenticationException("Successful Response did not contain any assertions"); + } + + //nor authnStatements + else if(samlResponse.getAssertions().get(0).getAuthnStatements().isEmpty()){ + throw new ServiceProviderAuthenticationException("Successful Response did not contain an assertions with an AuthnStatement"); + } - //we require at attribute statements - else if(samlResponse.getAssertions().get(0).getAttributeStatements().isEmpty()){ - throw new ServiceProviderAuthenticationException("Successful Response did not contain an assertions with an AttributeStatements"); + //we require at attribute statements + else if(samlResponse.getAssertions().get(0).getAttributeStatements().isEmpty()){ + throw new ServiceProviderAuthenticationException("Successful Response did not contain an assertions with an AttributeStatements"); - } - //we will require an issuer - else if(samlResponse.getIssuer() == null) { - throw new ServiceProviderAuthenticationException("Successful Response did not contain any Issuer"); + } + //we will require an issuer + else if(samlResponse.getIssuer() == null) { + throw new ServiceProviderAuthenticationException("Successful Response did not contain any Issuer"); - } - } + } + } - private StringBuilder extractExtraInformation(Response samlResponse) { - StringBuilder extraInformation = new StringBuilder(); - - if( samlResponse.getStatus().getStatusCode().getStatusCode() !=null ) { - - extraInformation.append(samlResponse.getStatus().getStatusCode().getStatusCode().getValue()); - } - - if(samlResponse.getStatus().getStatusMessage() != null) { - if(extraInformation.length() > 0) { - extraInformation.append(" - "); - } - extraInformation.append(samlResponse.getStatus().getStatusMessage()); - } - return extraInformation; - } + private StringBuilder extractExtraInformation(Response samlResponse) { + StringBuilder extraInformation = new StringBuilder(); + + if( samlResponse.getStatus().getStatusCode().getStatusCode() !=null ) { + + extraInformation.append(samlResponse.getStatus().getStatusCode().getStatusCode().getValue()); + } + + if(samlResponse.getStatus().getStatusMessage() != null) { + if(extraInformation.length() > 0) { + extraInformation.append(" - "); + } + extraInformation.append(samlResponse.getStatus().getStatusMessage()); + } + return extraInformation; + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/spring/IdentityProviderAuthenticationException.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/spring/IdentityProviderAuthenticationException.java index a406b83db..850d0c452 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/spring/IdentityProviderAuthenticationException.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/spring/IdentityProviderAuthenticationException.java @@ -33,19 +33,19 @@ import org.springframework.security.core.AuthenticationException; */ public class IdentityProviderAuthenticationException extends AuthenticationException { - /** - * - */ - private static final long serialVersionUID = -1106622672393663684L; + /** + * + */ + private static final long serialVersionUID = -1106622672393663684L; - public IdentityProviderAuthenticationException(String msg, Object extraInformation) { - super(msg, (Throwable) extraInformation); - } + public IdentityProviderAuthenticationException(String msg, Object extraInformation) { + super(msg, (Throwable) extraInformation); + } - public IdentityProviderAuthenticationException(String msg) { - super(msg); - } + public IdentityProviderAuthenticationException(String msg) { + super(msg); + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/spring/RealAuthenticationFailureHandler.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/spring/RealAuthenticationFailureHandler.java index c6ec2fb5f..3f32c54b1 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/spring/RealAuthenticationFailureHandler.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/spring/RealAuthenticationFailureHandler.java @@ -48,38 +48,38 @@ import jakarta.servlet.http.HttpServletResponse; * */ public class RealAuthenticationFailureHandler implements - AuthenticationFailureHandler { + AuthenticationFailureHandler { - private static final Logger logger = LoggerFactory - .getLogger(RealAuthenticationFailureHandler.class); + private static final Logger logger = LoggerFactory + .getLogger(RealAuthenticationFailureHandler.class); - private final RequestCache requestCache; - - - public RealAuthenticationFailureHandler(RequestCache requestCache) { - super(); - this.requestCache = requestCache; - } + private final RequestCache requestCache; + + + public RealAuthenticationFailureHandler(RequestCache requestCache) { + super(); + this.requestCache = requestCache; + } - @Override - public void onAuthenticationFailure(HttpServletRequest request, - HttpServletResponse response, AuthenticationException authenticationException) - throws IOException, ServletException { - - SavedRequest savedRequest = requestCache.getRequest(request, response); - - logger.debug("saved Request: {}", savedRequest); - - if( authenticationException instanceof IdentityProviderAuthenticationException && savedRequest != null) { - - logger.warn("Authn Failure reported by the IDP.", authenticationException); - logger.debug("Retry original request of {}", savedRequest.getRedirectUrl()); - response.sendRedirect(savedRequest.getRedirectUrl()); - } + @Override + public void onAuthenticationFailure(HttpServletRequest request, + HttpServletResponse response, AuthenticationException authenticationException) + throws IOException, ServletException { + + SavedRequest savedRequest = requestCache.getRequest(request, response); + + logger.debug("saved Request: {}", savedRequest); + + if( authenticationException instanceof IdentityProviderAuthenticationException && savedRequest != null) { + + logger.warn("Authn Failure reported by the IDP.", authenticationException); + logger.debug("Retry original request of {}", savedRequest.getRedirectUrl()); + response.sendRedirect(savedRequest.getRedirectUrl()); + } - else { - logger.warn("Unrecoverable authn failure. Sending to Forbidden", authenticationException); - response.sendError(HttpServletResponse.SC_FORBIDDEN); - } - } + else { + logger.warn("Unrecoverable authn failure. Sending to Forbidden", authenticationException); + response.sendError(HttpServletResponse.SC_FORBIDDEN); + } + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/spring/ServiceProviderAuthenticationException.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/spring/ServiceProviderAuthenticationException.java index 490e4b8cd..db06feb12 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/spring/ServiceProviderAuthenticationException.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/consumer/spring/ServiceProviderAuthenticationException.java @@ -34,17 +34,17 @@ import org.springframework.security.core.AuthenticationException; */ public class ServiceProviderAuthenticationException extends AuthenticationException { - /** - * - */ - private static final long serialVersionUID = 8817095932085915398L; + /** + * + */ + private static final long serialVersionUID = 8817095932085915398L; - public ServiceProviderAuthenticationException(String msg, Throwable t) { - super(msg, t); - } + public ServiceProviderAuthenticationException(String msg, Throwable t) { + super(msg, t); + } - public ServiceProviderAuthenticationException(String msg) { - super(msg); - } + public ServiceProviderAuthenticationException(String msg) { + super(msg); + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/jit/ProvisioningAdapter.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/jit/ProvisioningAdapter.java index 0d0ae312f..0ea752bc3 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/jit/ProvisioningAdapter.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/jit/ProvisioningAdapter.java @@ -20,6 +20,6 @@ package org.dromara.maxkey.authz.saml20.jit; public interface ProvisioningAdapter { - //HashMap construct(UserInfo userInfo,Companys company,List listRoles) ; + //HashMap construct(UserInfo userInfo,Companys company,List listRoles) ; } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/metadata/MetadataDescriptorUtil.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/metadata/MetadataDescriptorUtil.java index 6636c0545..e176f9128 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/metadata/MetadataDescriptorUtil.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/metadata/MetadataDescriptorUtil.java @@ -56,159 +56,159 @@ import org.w3c.dom.Element; * */ public class MetadataDescriptorUtil { - private static final Logger logger = LoggerFactory.getLogger(MetadataDescriptorUtil.class); - - private static MetadataDescriptorUtil instance = null; - - /** - * - */ - public MetadataDescriptorUtil() { - try { - org.opensaml.DefaultBootstrap.bootstrap(); - } catch (ConfigurationException e) { - e.printStackTrace(); - } - } + private static final Logger logger = LoggerFactory.getLogger(MetadataDescriptorUtil.class); + + private static MetadataDescriptorUtil instance = null; + + /** + * + */ + public MetadataDescriptorUtil() { + try { + org.opensaml.DefaultBootstrap.bootstrap(); + } catch (ConfigurationException e) { + e.printStackTrace(); + } + } - public static synchronized MetadataDescriptorUtil getInstance() { - if (instance == null) { - instance = new MetadataDescriptorUtil(); - // instance.bootstrap(); - logger.debug("getInstance()" + " new ConfigFile instance"); - } - return instance; - } + public static synchronized MetadataDescriptorUtil getInstance() { + if (instance == null) { + instance = new MetadataDescriptorUtil(); + // instance.bootstrap(); + logger.debug("getInstance()" + " new ConfigFile instance"); + } + return instance; + } - // public void bootstrap() throws ConfigurationException { - // // DefaultBootstrap.bootstrap(); - // } + // public void bootstrap() throws ConfigurationException { + // // DefaultBootstrap.bootstrap(); + // } - public EntityDescriptor getEntityDescriptor(File file) - throws Exception { - try { - FilesystemMetadataProvider filesystemMetadataProvider = new FilesystemMetadataProvider( - file); - filesystemMetadataProvider.setRequireValidMetadata(true); // Enable - // validation - filesystemMetadataProvider.setParserPool(new BasicParserPool()); - filesystemMetadataProvider.initialize(); - EntityDescriptor entityDescriptor = (EntityDescriptorImpl) filesystemMetadataProvider.getMetadata(); - return entityDescriptor; - } catch (MetadataProviderException e) { - logger.error("元数据解析出错", e); - throw new Exception("元数据文件解析出错", e); - } + public EntityDescriptor getEntityDescriptor(File file) + throws Exception { + try { + FilesystemMetadataProvider filesystemMetadataProvider = new FilesystemMetadataProvider( + file); + filesystemMetadataProvider.setRequireValidMetadata(true); // Enable + // validation + filesystemMetadataProvider.setParserPool(new BasicParserPool()); + filesystemMetadataProvider.initialize(); + EntityDescriptor entityDescriptor = (EntityDescriptorImpl) filesystemMetadataProvider.getMetadata(); + return entityDescriptor; + } catch (MetadataProviderException e) { + logger.error("元数据解析出错", e); + throw new Exception("元数据文件解析出错", e); + } - } + } - public EntityDescriptor getEntityDescriptor(InputStream inputStream) - throws Exception { - BasicParserPool basicParserPool = new BasicParserPool(); - basicParserPool.setNamespaceAware(true); - try { - Document inMetadataDoc = basicParserPool.parse(inputStream); - Element metadataRoot = inMetadataDoc.getDocumentElement(); + public EntityDescriptor getEntityDescriptor(InputStream inputStream) + throws Exception { + BasicParserPool basicParserPool = new BasicParserPool(); + basicParserPool.setNamespaceAware(true); + try { + Document inMetadataDoc = basicParserPool.parse(inputStream); + Element metadataRoot = inMetadataDoc.getDocumentElement(); - UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory(); - Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(metadataRoot); + UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory(); + Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(metadataRoot); - // unmarshaller.unmarshall(arg0) - // Unmarshall using the document root element, an EntitiesDescriptor - // in this case - XMLObject xMLObject = unmarshaller.unmarshall(metadataRoot); + // unmarshaller.unmarshall(arg0) + // Unmarshall using the document root element, an EntitiesDescriptor + // in this case + XMLObject xMLObject = unmarshaller.unmarshall(metadataRoot); - EntityDescriptor entityDescriptor = (EntityDescriptorImpl) xMLObject; - return entityDescriptor; - } catch (XMLParserException e) { - logger.error("元数据解析出错", e); - throw new Exception("元数据文件解析出错", e); - } catch (UnmarshallingException e) { - logger.error("元数据解析出错", e); - throw new Exception("元数据文件解析出错", e); - } + EntityDescriptor entityDescriptor = (EntityDescriptorImpl) xMLObject; + return entityDescriptor; + } catch (XMLParserException e) { + logger.error("元数据解析出错", e); + throw new Exception("元数据文件解析出错", e); + } catch (UnmarshallingException e) { + logger.error("元数据解析出错", e); + throw new Exception("元数据文件解析出错", e); + } - } + } - public EntityDescriptor getEntityDescriptor(String strMetadata) - throws Exception { - InputStream inputStream = StringUtil.String2InputStream(strMetadata); - return getEntityDescriptor(inputStream); - } + public EntityDescriptor getEntityDescriptor(String strMetadata) + throws Exception { + InputStream inputStream = StringUtil.String2InputStream(strMetadata); + return getEntityDescriptor(inputStream); + } - // from dom - public EntityDescriptor getEntityDescriptor(Element elementMetadata) - throws Exception { - try { - DOMMetadataProvider dOMMetadataProvider = new DOMMetadataProvider(elementMetadata); - dOMMetadataProvider.setRequireValidMetadata(true); // Enable - // validation - dOMMetadataProvider.setParserPool(new BasicParserPool()); - dOMMetadataProvider.initialize(); - EntityDescriptor entityDescriptor = (EntityDescriptorImpl) dOMMetadataProvider.getMetadata(); - return entityDescriptor; - } catch (MetadataProviderException e) { - logger.error("元数据解析出错", e); - throw new Exception("元数据解析出错", e); - } + // from dom + public EntityDescriptor getEntityDescriptor(Element elementMetadata) + throws Exception { + try { + DOMMetadataProvider dOMMetadataProvider = new DOMMetadataProvider(elementMetadata); + dOMMetadataProvider.setRequireValidMetadata(true); // Enable + // validation + dOMMetadataProvider.setParserPool(new BasicParserPool()); + dOMMetadataProvider.initialize(); + EntityDescriptor entityDescriptor = (EntityDescriptorImpl) dOMMetadataProvider.getMetadata(); + return entityDescriptor; + } catch (MetadataProviderException e) { + logger.error("元数据解析出错", e); + throw new Exception("元数据解析出错", e); + } - } + } - /** - * - * @param args - * @throws Exception - * @throws ConfigurationException - * @throws FileNotFoundException - */ - public static void main(String[] args) throws Exception, - ConfigurationException, FileNotFoundException { - // - File file = new File("d:\\SAMLSP-00D90000000hf9n.xml"); - org.opensaml.DefaultBootstrap.bootstrap(); - - EntityDescriptor entityDescriptor = MetadataDescriptorUtil.getInstance().getEntityDescriptor(file); + /** + * + * @param args + * @throws Exception + * @throws ConfigurationException + * @throws FileNotFoundException + */ + public static void main(String[] args) throws Exception, + ConfigurationException, FileNotFoundException { + // + File file = new File("d:\\SAMLSP-00D90000000hf9n.xml"); + org.opensaml.DefaultBootstrap.bootstrap(); + + EntityDescriptor entityDescriptor = MetadataDescriptorUtil.getInstance().getEntityDescriptor(file); - // System.out.println("2 : "+entityDescriptor.getRoleDescriptors()); + // System.out.println("2 : "+entityDescriptor.getRoleDescriptors()); - // System.out.println("3 : "+idpEntityDescriptor.); - // System.out.println("+"+ entityDescriptor.getOrganization()); + // System.out.println("3 : "+idpEntityDescriptor.); + // System.out.println("+"+ entityDescriptor.getOrganization()); - List listRoleDescriptor = entityDescriptor.getRoleDescriptors(); - for (RoleDescriptor roleDescriptor : listRoleDescriptor) { + List listRoleDescriptor = entityDescriptor.getRoleDescriptors(); + for (RoleDescriptor roleDescriptor : listRoleDescriptor) { - // SPSSODescriptor - // sPSSODescriptor1=idpEntityDescriptor.getSPSSODescriptor(SAMLConstants.SAML20P_NS); - if (roleDescriptor instanceof IDPSSODescriptorImpl) { - IDPSSODescriptor iDPSSODescriptor = (IDPSSODescriptorImpl) roleDescriptor; - System.out.println("3 : "+iDPSSODescriptor.getSingleSignOnServices().get(0).getLocation()); - // System.out.println("- : "+iDPSSODescriptor.getNameIDFormats().get(0).getFormat()); + // SPSSODescriptor + // sPSSODescriptor1=idpEntityDescriptor.getSPSSODescriptor(SAMLConstants.SAML20P_NS); + if (roleDescriptor instanceof IDPSSODescriptorImpl) { + IDPSSODescriptor iDPSSODescriptor = (IDPSSODescriptorImpl) roleDescriptor; + System.out.println("3 : "+iDPSSODescriptor.getSingleSignOnServices().get(0).getLocation()); + // System.out.println("- : "+iDPSSODescriptor.getNameIDFormats().get(0).getFormat()); - // System.out.println("- : "+iDPSSODescriptor.getKeyDescriptors().get(0).getKeyInfo().getX509Datas().get(0)); - } else { - SPSSODescriptor sPSSODescriptor = (SPSSODescriptorImpl) roleDescriptor; + // System.out.println("- : "+iDPSSODescriptor.getKeyDescriptors().get(0).getKeyInfo().getX509Datas().get(0)); + } else { + SPSSODescriptor sPSSODescriptor = (SPSSODescriptorImpl) roleDescriptor; - System.out.println("- : "+sPSSODescriptor.getAssertionConsumerServices().get(0).getLocation()); + System.out.println("- : "+sPSSODescriptor.getAssertionConsumerServices().get(0).getLocation()); - // System.out.println("- : "+sPSSODescriptor.getAssertionConsumerServices().get(0).getBinding()); - } + // System.out.println("- : "+sPSSODescriptor.getAssertionConsumerServices().get(0).getBinding()); + } - // System.out.println("==============================================="); - } - // //two - InputStream in = new FileInputStream(file); + // System.out.println("==============================================="); + } + // //two + InputStream in = new FileInputStream(file); - EntityDescriptor entityDescriptor1 = MetadataDescriptorUtil.getInstance().getEntityDescriptor(in); + EntityDescriptor entityDescriptor1 = MetadataDescriptorUtil.getInstance().getEntityDescriptor(in); - SPSSODescriptor sPSSODescriptor = entityDescriptor1.getSPSSODescriptor(SAMLConstants.SAML20P_NS); + SPSSODescriptor sPSSODescriptor = entityDescriptor1.getSPSSODescriptor(SAMLConstants.SAML20P_NS); - System.out.println("ok :"+sPSSODescriptor.getAssertionConsumerServices().get(0).getLocation()); + System.out.println("ok :"+sPSSODescriptor.getAssertionConsumerServices().get(0).getLocation()); - // System.out.println("ok :"+sPSSODescriptor.getAssertionConsumerServices().get(0).getBinding()); + // System.out.println("ok :"+sPSSODescriptor.getAssertionConsumerServices().get(0).getBinding()); - // System.out.println("ok :"+sPSSODescriptor.getNameIDFormats().get(0).getFormat()); + // System.out.println("ok :"+sPSSODescriptor.getNameIDFormats().get(0).getFormat()); - // System.out.println("ok :"+sPSSODescriptor.getKeyDescriptors().get(0).getKeyInfo().getX509Datas().get(0)); - } + // System.out.println("ok :"+sPSSODescriptor.getKeyDescriptors().get(0).getKeyInfo().getX509Datas().get(0)); + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/metadata/MetadataGenerator.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/metadata/MetadataGenerator.java index 40402331a..4387e73c7 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/metadata/MetadataGenerator.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/metadata/MetadataGenerator.java @@ -95,95 +95,95 @@ import org.springframework.core.io.FileSystemResource; import java.security.KeyStore; public class MetadataGenerator { - private static final Logger logger = LoggerFactory.getLogger(MetadataGenerator.class); + private static final Logger logger = LoggerFactory.getLogger(MetadataGenerator.class); - /** Parser manager used to parse XML. */ - protected static BasicParserPool parser; + /** Parser manager used to parse XML. */ + protected static BasicParserPool parser; - /** XMLObject builder factory. */ - protected static XMLObjectBuilderFactory builderFactory; + /** XMLObject builder factory. */ + protected static XMLObjectBuilderFactory builderFactory; - /** XMLObject marshaller factory. */ - protected static MarshallerFactory marshallerFactory; + /** XMLObject marshaller factory. */ + protected static MarshallerFactory marshallerFactory; - /** XMLObject unmarshaller factory. */ - protected static UnmarshallerFactory unmarshallerFactory; + /** XMLObject unmarshaller factory. */ + protected static UnmarshallerFactory unmarshallerFactory; - /** Constructor. */ - public MetadataGenerator() { - try { - parser = new BasicParserPool(); - parser.setNamespaceAware(true); - DefaultBootstrap.bootstrap(); - builderFactory = org.opensaml.xml.Configuration.getBuilderFactory(); - marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory(); - unmarshallerFactory = org.opensaml.xml.Configuration.getUnmarshallerFactory(); - } catch (ConfigurationException e) { - e.printStackTrace(); - } + /** Constructor. */ + public MetadataGenerator() { + try { + parser = new BasicParserPool(); + parser.setNamespaceAware(true); + DefaultBootstrap.bootstrap(); + builderFactory = org.opensaml.xml.Configuration.getBuilderFactory(); + marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory(); + unmarshallerFactory = org.opensaml.xml.Configuration.getUnmarshallerFactory(); + } catch (ConfigurationException e) { + e.printStackTrace(); + } - } - + } + public static void main(String args[]) { - MetadataGenerator metadataGenerator=new MetadataGenerator(); - - metadataGenerator.samlmtest(); + MetadataGenerator metadataGenerator=new MetadataGenerator(); + + metadataGenerator.samlmtest(); } @SuppressWarnings({ "unchecked", "rawtypes" }) public void samlmtest(){ - try { - KeyStoreLoader keyStoreLoader=new KeyStoreLoader(); - keyStoreLoader.setKeystorePassword("secret"); - keyStoreLoader.setKeystoreFile(new FileSystemResource("D:/JavaIDE/cert/idp-keystore.jks")); - keyStoreLoader.afterPropertiesSet(); - KeyStore trustKeyStore =keyStoreLoader.getKeyStore(); - - IssueInstantRule issueInstantRule=new IssueInstantRule(90,300); - ReplayCache replayCache=new ReplayCache(new MapBasedStorageService(),14400000); - MessageReplayRule messageReplayRule=new MessageReplayRule(replayCache); - - TrustResolver trustResolver = new TrustResolver( - trustKeyStore, - "idp", - keyStoreLoader.getKeystorePassword(), issueInstantRule, - messageReplayRule, - "POST" - ); - CredentialResolver credentialResolver=(CredentialResolver)trustResolver.getKeyStoreCredentialResolver(); - - CriteriaSet criteriaSet = new CriteriaSet(); - - criteriaSet.add(new EntityIDCriteria("idp")); - - criteriaSet.add(new UsageCriteria(UsageType.SIGNING)); - Credential signingCredential=null; - - try { - signingCredential = credentialResolver.resolveSingle(criteriaSet); - } catch (SecurityException e) { - System.out.println("Credential resolve error : "+ e); - throw new Exception(e); - } - - IDPSSODescriptor descriptor = buildIDPSSODescriptor(); + try { + KeyStoreLoader keyStoreLoader=new KeyStoreLoader(); + keyStoreLoader.setKeystorePassword("secret"); + keyStoreLoader.setKeystoreFile(new FileSystemResource("D:/JavaIDE/cert/idp-keystore.jks")); + keyStoreLoader.afterPropertiesSet(); + KeyStore trustKeyStore =keyStoreLoader.getKeyStore(); + + IssueInstantRule issueInstantRule=new IssueInstantRule(90,300); + ReplayCache replayCache=new ReplayCache(new MapBasedStorageService(),14400000); + MessageReplayRule messageReplayRule=new MessageReplayRule(replayCache); + + TrustResolver trustResolver = new TrustResolver( + trustKeyStore, + "idp", + keyStoreLoader.getKeystorePassword(), issueInstantRule, + messageReplayRule, + "POST" + ); + CredentialResolver credentialResolver=(CredentialResolver)trustResolver.getKeyStoreCredentialResolver(); + + CriteriaSet criteriaSet = new CriteriaSet(); + + criteriaSet.add(new EntityIDCriteria("idp")); + + criteriaSet.add(new UsageCriteria(UsageType.SIGNING)); + Credential signingCredential=null; + + try { + signingCredential = credentialResolver.resolveSingle(criteriaSet); + } catch (SecurityException e) { + System.out.println("Credential resolve error : "+ e); + throw new Exception(e); + } + + IDPSSODescriptor descriptor = buildIDPSSODescriptor(); - descriptor.getSingleSignOnServices().add(getSingleSignOnService("http://sso.maxkey.org/sso",null)); - - descriptor.getSingleSignOnServices().add(getSingleSignOnService("http://sso.maxkey.org/sso",SAMLConstants.SAML2_POST_SIMPLE_SIGN_BINDING_URI)); - - descriptor.getSingleLogoutServices().add(getSingleLogoutService("http://sso.maxkey.org/slo",null)); - - descriptor.getKeyDescriptors().add(generateEncryptionKeyDescriptor(signingCredential)); - - descriptor.getKeyDescriptors().add(generateSignKeyDescriptor(signingCredential)); - - descriptor.getNameIDFormats().add(generateNameIDFormat(NameIDType.TRANSIENT)); - descriptor.getNameIDFormats().add(generateNameIDFormat(NameIDType.PERSISTENT)); - descriptor.getNameIDFormats().add(generateNameIDFormat(NameIDType.EMAIL)); - descriptor.getNameIDFormats().add(generateNameIDFormat(NameIDType.ENTITY)); - + descriptor.getSingleSignOnServices().add(getSingleSignOnService("http://sso.maxkey.org/sso",null)); + + descriptor.getSingleSignOnServices().add(getSingleSignOnService("http://sso.maxkey.org/sso",SAMLConstants.SAML2_POST_SIMPLE_SIGN_BINDING_URI)); + + descriptor.getSingleLogoutServices().add(getSingleLogoutService("http://sso.maxkey.org/slo",null)); + + descriptor.getKeyDescriptors().add(generateEncryptionKeyDescriptor(signingCredential)); + + descriptor.getKeyDescriptors().add(generateSignKeyDescriptor(signingCredential)); + + descriptor.getNameIDFormats().add(generateNameIDFormat(NameIDType.TRANSIENT)); + descriptor.getNameIDFormats().add(generateNameIDFormat(NameIDType.PERSISTENT)); + descriptor.getNameIDFormats().add(generateNameIDFormat(NameIDType.EMAIL)); + descriptor.getNameIDFormats().add(generateNameIDFormat(NameIDType.ENTITY)); + descriptor.getContactPersons().add(getContactPerson("maxkey","shi","ming","shimingxy@163.com","18724229876",null)); descriptor.setOrganization(getOrganization("maxkey","maxkey","http://sso.maxkey.org")); @@ -192,21 +192,21 @@ public void samlmtest(){ EntityDescriptor entityDescriptor=buildEntityDescriptor(entityId,descriptor); - String descriptorelementxml=XMLHelper.prettyPrintXML(marshallerMetadata(entityDescriptor)); - - System.out.println("descriptor elementxm:\\n"); - System.out.println(descriptorelementxml); - - logger.info(descriptorelementxml); - } - catch (Exception e) { - e.printStackTrace(); - } + String descriptorelementxml=XMLHelper.prettyPrintXML(marshallerMetadata(entityDescriptor)); + + System.out.println("descriptor elementxm:\\n"); + System.out.println(descriptorelementxml); + + logger.info(descriptorelementxml); + } + catch (Exception e) { + e.printStackTrace(); + } } public IDPSSODescriptor buildIDPSSODescriptor(){ - IDPSSODescriptor idpSSODescriptor = (IDPSSODescriptor) buildXMLObject(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); + IDPSSODescriptor idpSSODescriptor = (IDPSSODescriptor) buildXMLObject(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); idpSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); return idpSSODescriptor; } @@ -219,35 +219,35 @@ public void samlmtest(){ return entityDescriptor; } - public Document marshallerMetadata(EntityDescriptor entityDescriptor) { - Document document = null; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + public Document marshallerMetadata(EntityDescriptor entityDescriptor) { + Document document = null; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder documentBuilder = factory.newDocumentBuilder(); + DocumentBuilder documentBuilder = factory.newDocumentBuilder(); - document = documentBuilder.newDocument(); + document = documentBuilder.newDocument(); - Marshaller marshaller = marshallerFactory.getMarshaller(entityDescriptor); - marshaller.marshall(entityDescriptor, document); - } catch (Exception e) { - e.printStackTrace(); - } + Marshaller marshaller = marshallerFactory.getMarshaller(entityDescriptor); + marshaller.marshall(entityDescriptor, document); + } catch (Exception e) { + e.printStackTrace(); + } - return document; + return document; - } + } public ManageNameIDService getManageNameIDService(String url){ - ManageNameIDService manageNameIDService=new ManageNameIDServiceBuilder().buildObject(); - manageNameIDService.setLocation(url); - manageNameIDService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - return manageNameIDService; + ManageNameIDService manageNameIDService=new ManageNameIDServiceBuilder().buildObject(); + manageNameIDService.setLocation(url); + manageNameIDService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + return manageNameIDService; } public Organization getOrganization(String name,String displayName,String url){ - Organization organization=new OrganizationBuilder().buildObject(); - + Organization organization=new OrganizationBuilder().buildObject(); + OrganizationName organizationName=new OrganizationNameBuilder().buildObject(); LocalizedString orglocalizedString=new LocalizedString(); orglocalizedString.setLocalizedString(name); @@ -255,9 +255,9 @@ public void samlmtest(){ organization.getOrganizationNames().add(organizationName); OrganizationDisplayName organizationDisplayName=new OrganizationDisplayNameBuilder().buildObject(); - LocalizedString localizedString=new LocalizedString(); - localizedString.setLocalizedString(displayName); - organizationDisplayName.setName(localizedString); + LocalizedString localizedString=new LocalizedString(); + localizedString.setLocalizedString(displayName); + organizationDisplayName.setName(localizedString); organization.getDisplayNames().add(organizationDisplayName); OrganizationURL organizationURL=new OrganizationURLBuilder().buildObject(); @@ -270,69 +270,69 @@ public void samlmtest(){ } public ContactPerson getContactPerson(String companyName,String givenName,String surName,String emailAddress,String telephoneNumber,ContactPersonTypeEnumeration contactPersonType){ - ContactPerson contactPerson= (ContactPerson) buildXMLObject(ContactPerson.DEFAULT_ELEMENT_NAME); - - contactPerson.setType(contactPersonType); - - Company company =new CompanyBuilder ().buildObject(); - company.setName(companyName); - contactPerson.setCompany(company); - - GivenName contactPersonGivenName=(new GivenNameBuilder()).buildObject(); - contactPersonGivenName.setName(givenName); - contactPerson.setGivenName(contactPersonGivenName);//名 - - SurName contactPersonSurName =new SurNameBuilder().buildObject(); - contactPersonSurName.setName(surName); - contactPerson.setSurName(contactPersonSurName);//姓 + ContactPerson contactPerson= (ContactPerson) buildXMLObject(ContactPerson.DEFAULT_ELEMENT_NAME); + + contactPerson.setType(contactPersonType); + + Company company =new CompanyBuilder ().buildObject(); + company.setName(companyName); + contactPerson.setCompany(company); + + GivenName contactPersonGivenName=(new GivenNameBuilder()).buildObject(); + contactPersonGivenName.setName(givenName); + contactPerson.setGivenName(contactPersonGivenName);//名 + + SurName contactPersonSurName =new SurNameBuilder().buildObject(); + contactPersonSurName.setName(surName); + contactPerson.setSurName(contactPersonSurName);//姓 - EmailAddress contactPersonEmailAddress =(new EmailAddressBuilder()).buildObject(); - contactPersonEmailAddress.setAddress(emailAddress); - contactPerson.getEmailAddresses().add(contactPersonEmailAddress); - - TelephoneNumber contactPersonTelephoneNumber=(new TelephoneNumberBuilder()).buildObject(); - contactPersonTelephoneNumber.setNumber(telephoneNumber); - contactPerson.getTelephoneNumbers().add(contactPersonTelephoneNumber); - - return contactPerson; + EmailAddress contactPersonEmailAddress =(new EmailAddressBuilder()).buildObject(); + contactPersonEmailAddress.setAddress(emailAddress); + contactPerson.getEmailAddresses().add(contactPersonEmailAddress); + + TelephoneNumber contactPersonTelephoneNumber=(new TelephoneNumberBuilder()).buildObject(); + contactPersonTelephoneNumber.setNumber(telephoneNumber); + contactPerson.getTelephoneNumbers().add(contactPersonTelephoneNumber); + + return contactPerson; } public SingleSignOnService getSingleSignOnService(String location,String binding){ - SingleSignOnService singleSignOnService=(SingleSignOnService) buildXMLObject(SingleSignOnService.DEFAULT_ELEMENT_NAME); - if(binding==null){ - binding=SAMLConstants.SAML2_POST_BINDING_URI; - } - singleSignOnService.setBinding(binding); - singleSignOnService.setLocation(location); - - return singleSignOnService ; + SingleSignOnService singleSignOnService=(SingleSignOnService) buildXMLObject(SingleSignOnService.DEFAULT_ELEMENT_NAME); + if(binding==null){ + binding=SAMLConstants.SAML2_POST_BINDING_URI; + } + singleSignOnService.setBinding(binding); + singleSignOnService.setLocation(location); + + return singleSignOnService ; } public SingleLogoutService getSingleLogoutService(String location,String binding){ - SingleLogoutService singleLogoutService=(SingleLogoutService) buildXMLObject(SingleLogoutService.DEFAULT_ELEMENT_NAME); - if(binding==null){ - binding=SAMLConstants.SAML2_REDIRECT_BINDING_URI; - } - singleLogoutService.setBinding(binding); - singleLogoutService.setLocation(location); - return singleLogoutService; + SingleLogoutService singleLogoutService=(SingleLogoutService) buildXMLObject(SingleLogoutService.DEFAULT_ELEMENT_NAME); + if(binding==null){ + binding=SAMLConstants.SAML2_REDIRECT_BINDING_URI; + } + singleLogoutService.setBinding(binding); + singleLogoutService.setLocation(location); + return singleLogoutService; } public NameIDFormat generateNameIDFormat(String nameIDType){ - NameIDFormat nameIDFormat =new NameIDFormatBuilder().buildObject(); + NameIDFormat nameIDFormat =new NameIDFormatBuilder().buildObject(); nameIDFormat.setFormat(nameIDType); return nameIDFormat; } public KeyInfoGenerator getKeyInfoGenerator (){ - X509KeyInfoGeneratorFactory keyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory(); - keyInfoGeneratorFactory.setEmitEntityCertificate(true); - KeyInfoGenerator keyInfoGenerator = keyInfoGeneratorFactory.newInstance(); - return keyInfoGenerator; + X509KeyInfoGeneratorFactory keyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory(); + keyInfoGeneratorFactory.setEmitEntityCertificate(true); + KeyInfoGenerator keyInfoGenerator = keyInfoGeneratorFactory.newInstance(); + return keyInfoGenerator; } public KeyDescriptor generateSignKeyDescriptor(Credential signingCredential){ - KeyDescriptor signKeyDescriptor = new KeyDescriptorBuilder().buildObject(); + KeyDescriptor signKeyDescriptor = new KeyDescriptorBuilder().buildObject(); signKeyDescriptor.setUse(UsageType.SIGNING); //Set usage @@ -340,25 +340,25 @@ public void samlmtest(){ try { signKeyDescriptor.setKeyInfo(getKeyInfoGenerator().generate(signingCredential)); } catch (SecurityException e) { - logger.error(e.getMessage(), e); + logger.error(e.getMessage(), e); } return signKeyDescriptor; } public KeyDescriptor generateEncryptionKeyDescriptor(Credential signingCredential){ - KeyDescriptor encryptionKeyDescriptor = new KeyDescriptorBuilder().buildObject(); - - encryptionKeyDescriptor.setUse(UsageType.ENCRYPTION); - - // Generating key info. The element will contain the public key. The key is used to by the IDP to encrypt data - try { - encryptionKeyDescriptor.setKeyInfo(getKeyInfoGenerator().generate(signingCredential)); - } catch (SecurityException e) { - logger.error(e.getMessage(), e); - } - - return encryptionKeyDescriptor; + KeyDescriptor encryptionKeyDescriptor = new KeyDescriptorBuilder().buildObject(); + + encryptionKeyDescriptor.setUse(UsageType.ENCRYPTION); + + // Generating key info. The element will contain the public key. The key is used to by the IDP to encrypt data + try { + encryptionKeyDescriptor.setKeyInfo(getKeyInfoGenerator().generate(signingCredential)); + } catch (SecurityException e) { + logger.error(e.getMessage(), e); + } + + return encryptionKeyDescriptor; } @SuppressWarnings("rawtypes") @@ -377,12 +377,12 @@ public static XMLObject buildXMLObject(QName objectQName){ Unmarshaller unmarshaller = org.opensaml.xml.Configuration.getUnmarshallerFactory().getUnmarshaller(samlElement); if (unmarshaller == null) { - logger.error("Unable to retrieve unmarshaller by DOM Element"); + logger.error("Unable to retrieve unmarshaller by DOM Element"); } return unmarshaller.unmarshall(samlElement); }catch (UnmarshallingException e) { - logger.error("Unmarshalling failed when parsing doc : " , e); + logger.error("Unmarshalling failed when parsing doc : " , e); } return null; @@ -399,11 +399,11 @@ public static XMLObject buildXMLObject(QName objectQName){ try { generatedDOM = marshaller.marshall(xmlObject, parser.newDocument()); if(logger.isDebugEnabled()) { - logger.debug("Marshalled DOM was " + XMLHelper.nodeToString(generatedDOM)); + logger.debug("Marshalled DOM was " + XMLHelper.nodeToString(generatedDOM)); } // assertXMLEqual(failMessage, expectedDOM, generatedDOM.getOwnerDocument()); } catch (Exception e) { - logger.error("Marshalling failed with the following error:", e); + logger.error("Marshalling failed with the following error:", e); } return generatedDOM; } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/metadata/endpoint/SamlMetadataEndpoint.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/metadata/endpoint/SamlMetadataEndpoint.java index 7c4f28e6f..ed7e6c2fa 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/metadata/endpoint/SamlMetadataEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/metadata/endpoint/SamlMetadataEndpoint.java @@ -58,135 +58,135 @@ import jakarta.servlet.http.HttpServletResponse; @Controller @RequestMapping(value = { "/metadata/saml20/" }) public class SamlMetadataEndpoint { - private static final Logger logger = LoggerFactory - .getLogger(SamlMetadataEndpoint.class); + private static final Logger logger = LoggerFactory + .getLogger(SamlMetadataEndpoint.class); - @Autowired - @Qualifier("keyStoreLoader") - private KeyStoreLoader keyStoreLoader; - - @Autowired - @Qualifier("issuerEntityName") - private String issuerEntityName; - - @Autowired - @Qualifier("saml20Metadata") - private Saml20Metadata saml20Metadata; - - private Credential signingCredential; + @Autowired + @Qualifier("keyStoreLoader") + private KeyStoreLoader keyStoreLoader; + + @Autowired + @Qualifier("issuerEntityName") + private String issuerEntityName; + + @Autowired + @Qualifier("saml20Metadata") + private Saml20Metadata saml20Metadata; + + private Credential signingCredential; - @Operation(summary = "SAML 2.0 元数据接口", description = "参数mxk_metadata_APPID",method="GET") - @RequestMapping(value = "/" + WebConstants.MXK_METADATA_PREFIX + "{appid}.xml",produces = "application/xml", method={RequestMethod.POST, RequestMethod.GET}) - @ResponseBody - public String metadata(HttpServletRequest request, - HttpServletResponse response, @PathVariable("appid") String appId) { - response.setContentType(ContentType.APPLICATION_XML_UTF8); - if(signingCredential == null){ - TrustResolver trustResolver = new TrustResolver(); - CredentialResolver credentialResolver=(CredentialResolver)trustResolver.buildKeyStoreCredentialResolver( - keyStoreLoader.getKeyStore(), - keyStoreLoader.getEntityName(), - keyStoreLoader.getKeystorePassword()); - - CriteriaSet criteriaSet = new CriteriaSet(); - - criteriaSet.add(new EntityIDCriteria(keyStoreLoader.getEntityName())); - - criteriaSet.add(new UsageCriteria(UsageType.SIGNING)); - - try { - signingCredential = credentialResolver.resolveSingle(criteriaSet); - }catch (SecurityException e) { - logger.error("Credential Resolver error .", e); - - } - } - - Validate.notNull(signingCredential); - - try{ - - MetadataGenerator metadataGenerator =new MetadataGenerator(); - - IDPSSODescriptor descriptor = metadataGenerator.buildIDPSSODescriptor(); - - descriptor.getSingleSignOnServices().add( - metadataGenerator.getSingleSignOnService(WebContext.getContextPath(true) + "/authz/saml20/" + appId,null)); - - descriptor.getSingleSignOnServices().add( - metadataGenerator.getSingleSignOnService(WebContext.getContextPath(true) + "/authz/saml20/" + appId,SAMLConstants.SAML2_REDIRECT_BINDING_URI)); - - descriptor.getSingleSignOnServices().add( - metadataGenerator.getSingleSignOnService(WebContext.getContextPath(true) + "/authz/saml20/" + appId,SAMLConstants.SAML2_POST_SIMPLE_SIGN_BINDING_URI)); - - descriptor.getSingleLogoutServices().add( - metadataGenerator.getSingleLogoutService(WebContext.getContextPath(true) + "/force/logout" , null)); - - descriptor.getManageNameIDServices().add( - metadataGenerator.getManageNameIDService(WebContext.getContextPath(true) + "/metadata/saml20/" + WebConstants.MXK_METADATA_PREFIX + appId + ".xml")); - - descriptor.getKeyDescriptors().add(metadataGenerator.generateEncryptionKeyDescriptor(signingCredential)); - - descriptor.getKeyDescriptors().add(metadataGenerator.generateSignKeyDescriptor(signingCredential)); - - descriptor.getNameIDFormats().add(metadataGenerator.generateNameIDFormat(NameIDType.TRANSIENT)); - descriptor.getNameIDFormats().add(metadataGenerator.generateNameIDFormat(NameIDType.PERSISTENT)); - descriptor.getNameIDFormats().add(metadataGenerator.generateNameIDFormat(NameIDType.EMAIL)); - descriptor.getNameIDFormats().add(metadataGenerator.generateNameIDFormat(NameIDType.ENTITY)); - - ContactPersonTypeEnumeration contactPersonType=null; - if(saml20Metadata.getContactType().equalsIgnoreCase(Saml20Metadata.ContactPersonType.ADMINISTRATIVE)){ - contactPersonType=ContactPersonTypeEnumeration.ADMINISTRATIVE; - }else if(saml20Metadata.getContactType().equalsIgnoreCase(Saml20Metadata.ContactPersonType.TECHNICAL)){ - contactPersonType=ContactPersonTypeEnumeration.TECHNICAL; - }else if(saml20Metadata.getContactType().equalsIgnoreCase(Saml20Metadata.ContactPersonType.BILLING)){ - contactPersonType=ContactPersonTypeEnumeration.BILLING; - }else if(saml20Metadata.getContactType().equalsIgnoreCase(Saml20Metadata.ContactPersonType.SUPPORT)){ - contactPersonType=ContactPersonTypeEnumeration.SUPPORT; - }else if(saml20Metadata.getContactType().equalsIgnoreCase(Saml20Metadata.ContactPersonType.OTHER)){ - contactPersonType=ContactPersonTypeEnumeration.OTHER; - } - descriptor.getContactPersons().add(metadataGenerator.getContactPerson( - saml20Metadata.getCompany(), - saml20Metadata.getGivenName(), - saml20Metadata.getSurName(), - saml20Metadata.getEmailAddress(), - saml20Metadata.getTelephoneNumber(), - contactPersonType)); - - descriptor.setOrganization(metadataGenerator.getOrganization( - saml20Metadata.getOrgName(), - saml20Metadata.getOrgDisplayName(), - saml20Metadata.getOrgURL())); - - EntityDescriptor entityDescriptor=metadataGenerator.buildEntityDescriptor(issuerEntityName,descriptor); - - String entityDescriptorXml=XMLHelper.prettyPrintXML(metadataGenerator.marshallerMetadata(entityDescriptor)); - - logger.trace("EntityDescriptor element XML : \\n"); - logger.trace(entityDescriptorXml); - - return entityDescriptorXml; - }catch (Exception e) { - logger.error(e.getMessage(),e); + @Operation(summary = "SAML 2.0 元数据接口", description = "参数mxk_metadata_APPID",method="GET") + @RequestMapping(value = "/" + WebConstants.MXK_METADATA_PREFIX + "{appid}.xml",produces = "application/xml", method={RequestMethod.POST, RequestMethod.GET}) + @ResponseBody + public String metadata(HttpServletRequest request, + HttpServletResponse response, @PathVariable("appid") String appId) { + response.setContentType(ContentType.APPLICATION_XML_UTF8); + if(signingCredential == null){ + TrustResolver trustResolver = new TrustResolver(); + CredentialResolver credentialResolver=(CredentialResolver)trustResolver.buildKeyStoreCredentialResolver( + keyStoreLoader.getKeyStore(), + keyStoreLoader.getEntityName(), + keyStoreLoader.getKeystorePassword()); + + CriteriaSet criteriaSet = new CriteriaSet(); + + criteriaSet.add(new EntityIDCriteria(keyStoreLoader.getEntityName())); + + criteriaSet.add(new UsageCriteria(UsageType.SIGNING)); + + try { + signingCredential = credentialResolver.resolveSingle(criteriaSet); + }catch (SecurityException e) { + logger.error("Credential Resolver error .", e); + + } } - + + Validate.notNull(signingCredential); + + try{ + + MetadataGenerator metadataGenerator =new MetadataGenerator(); + + IDPSSODescriptor descriptor = metadataGenerator.buildIDPSSODescriptor(); + + descriptor.getSingleSignOnServices().add( + metadataGenerator.getSingleSignOnService(WebContext.getContextPath(true) + "/authz/saml20/" + appId,null)); + + descriptor.getSingleSignOnServices().add( + metadataGenerator.getSingleSignOnService(WebContext.getContextPath(true) + "/authz/saml20/" + appId,SAMLConstants.SAML2_REDIRECT_BINDING_URI)); + + descriptor.getSingleSignOnServices().add( + metadataGenerator.getSingleSignOnService(WebContext.getContextPath(true) + "/authz/saml20/" + appId,SAMLConstants.SAML2_POST_SIMPLE_SIGN_BINDING_URI)); + + descriptor.getSingleLogoutServices().add( + metadataGenerator.getSingleLogoutService(WebContext.getContextPath(true) + "/force/logout" , null)); + + descriptor.getManageNameIDServices().add( + metadataGenerator.getManageNameIDService(WebContext.getContextPath(true) + "/metadata/saml20/" + WebConstants.MXK_METADATA_PREFIX + appId + ".xml")); + + descriptor.getKeyDescriptors().add(metadataGenerator.generateEncryptionKeyDescriptor(signingCredential)); + + descriptor.getKeyDescriptors().add(metadataGenerator.generateSignKeyDescriptor(signingCredential)); + + descriptor.getNameIDFormats().add(metadataGenerator.generateNameIDFormat(NameIDType.TRANSIENT)); + descriptor.getNameIDFormats().add(metadataGenerator.generateNameIDFormat(NameIDType.PERSISTENT)); + descriptor.getNameIDFormats().add(metadataGenerator.generateNameIDFormat(NameIDType.EMAIL)); + descriptor.getNameIDFormats().add(metadataGenerator.generateNameIDFormat(NameIDType.ENTITY)); + + ContactPersonTypeEnumeration contactPersonType=null; + if(saml20Metadata.getContactType().equalsIgnoreCase(Saml20Metadata.ContactPersonType.ADMINISTRATIVE)){ + contactPersonType=ContactPersonTypeEnumeration.ADMINISTRATIVE; + }else if(saml20Metadata.getContactType().equalsIgnoreCase(Saml20Metadata.ContactPersonType.TECHNICAL)){ + contactPersonType=ContactPersonTypeEnumeration.TECHNICAL; + }else if(saml20Metadata.getContactType().equalsIgnoreCase(Saml20Metadata.ContactPersonType.BILLING)){ + contactPersonType=ContactPersonTypeEnumeration.BILLING; + }else if(saml20Metadata.getContactType().equalsIgnoreCase(Saml20Metadata.ContactPersonType.SUPPORT)){ + contactPersonType=ContactPersonTypeEnumeration.SUPPORT; + }else if(saml20Metadata.getContactType().equalsIgnoreCase(Saml20Metadata.ContactPersonType.OTHER)){ + contactPersonType=ContactPersonTypeEnumeration.OTHER; + } + descriptor.getContactPersons().add(metadataGenerator.getContactPerson( + saml20Metadata.getCompany(), + saml20Metadata.getGivenName(), + saml20Metadata.getSurName(), + saml20Metadata.getEmailAddress(), + saml20Metadata.getTelephoneNumber(), + contactPersonType)); + + descriptor.setOrganization(metadataGenerator.getOrganization( + saml20Metadata.getOrgName(), + saml20Metadata.getOrgDisplayName(), + saml20Metadata.getOrgURL())); + + EntityDescriptor entityDescriptor=metadataGenerator.buildEntityDescriptor(issuerEntityName,descriptor); + + String entityDescriptorXml=XMLHelper.prettyPrintXML(metadataGenerator.marshallerMetadata(entityDescriptor)); + + logger.trace("EntityDescriptor element XML : \\n"); + logger.trace(entityDescriptorXml); + + return entityDescriptorXml; + }catch (Exception e) { + logger.error(e.getMessage(),e); + } + - return "" - + "" + WebContext.version() + ""; - } + return "" + + "" + WebContext.version() + ""; + } - /** - * @param keyStoreLoader - * the keyStoreLoader to set - */ - public void setKeyStoreLoader(KeyStoreLoader keyStoreLoader) { - this.keyStoreLoader = keyStoreLoader; - } + /** + * @param keyStoreLoader + * the keyStoreLoader to set + */ + public void setKeyStoreLoader(KeyStoreLoader keyStoreLoader) { + this.keyStoreLoader = keyStoreLoader; + } - public void setIssuerEntityName(String issuerEntityName) { - this.issuerEntityName = issuerEntityName; - } + public void setIssuerEntityName(String issuerEntityName) { + this.issuerEntityName = issuerEntityName; + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/binding/encoding/WebServicePostEncoder.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/binding/encoding/WebServicePostEncoder.java index 030031307..efb171382 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/binding/encoding/WebServicePostEncoder.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/binding/encoding/WebServicePostEncoder.java @@ -46,262 +46,262 @@ import org.slf4j.LoggerFactory; public class WebServicePostEncoder extends HTTPPostEncoder { - /** Class logger. */ - private final Logger log = LoggerFactory.getLogger(WebServicePostEncoder.class); + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(WebServicePostEncoder.class); - public WebServicePostEncoder(VelocityEngine engine, String templateId) { - super(engine, templateId); - } + public WebServicePostEncoder(VelocityEngine engine, String templateId) { + super(engine, templateId); + } - @SuppressWarnings("rawtypes") - public VelocityContext encodeMsgContext(MessageContext messageContext) - throws MessageEncodingException { + @SuppressWarnings("rawtypes") + public VelocityContext encodeMsgContext(MessageContext messageContext) + throws MessageEncodingException { - SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; - SAMLObject outboundMessage = samlMsgCtx.getOutboundSAMLMessage(); - if (outboundMessage == null) { - throw new MessageEncodingException( - "No outbound SAML message contained in message context"); - } + SAMLObject outboundMessage = samlMsgCtx.getOutboundSAMLMessage(); + if (outboundMessage == null) { + throw new MessageEncodingException( + "No outbound SAML message contained in message context"); + } - signMessage(samlMsgCtx); - samlMsgCtx.setOutboundMessage(outboundMessage); + signMessage(samlMsgCtx); + samlMsgCtx.setOutboundMessage(outboundMessage); - return encodeMsgContext(samlMsgCtx); - } + return encodeMsgContext(samlMsgCtx); + } - /** - * Base64 and POST encodes the outbound message and writes it to the - * outbound transport. - * - * @param messageContext - * current message context - * @param endpointURL - * endpoint URL to encode message to - * - * @throws MessageEncodingException - * thrown if there is a problem encoding the message - */ - @SuppressWarnings("rawtypes") - protected VelocityContext encodeMsgContext(SAMLMessageContext messageContext) - throws MessageEncodingException { + /** + * Base64 and POST encodes the outbound message and writes it to the + * outbound transport. + * + * @param messageContext + * current message context + * @param endpointURL + * endpoint URL to encode message to + * + * @throws MessageEncodingException + * thrown if there is a problem encoding the message + */ + @SuppressWarnings("rawtypes") + protected VelocityContext encodeMsgContext(SAMLMessageContext messageContext) + throws MessageEncodingException { - try { - VelocityContext context = new VelocityContext(); + try { + VelocityContext context = new VelocityContext(); - populateVelocityContext(context, messageContext); + populateVelocityContext(context, messageContext); - return context; + return context; - } catch (Exception e) { - log.error("Error invoking velocity template", e); - throw new MessageEncodingException( - "Error creating output document", e); - } - } + } catch (Exception e) { + log.error("Error invoking velocity template", e); + throw new MessageEncodingException( + "Error creating output document", e); + } + } - @SuppressWarnings("rawtypes") - protected void populateVelocityContext(VelocityContext velocityContext, - SAMLMessageContext messageContext) throws MessageEncodingException { + @SuppressWarnings("rawtypes") + protected void populateVelocityContext(VelocityContext velocityContext, + SAMLMessageContext messageContext) throws MessageEncodingException { - log.debug("Marshalling and Base64 encoding SAML message"); - if (messageContext.getOutboundSAMLMessage().getDOM() == null) { - marshallMessage(messageContext.getOutboundSAMLMessage()); - } - try { - String messageXML = XMLHelper.nodeToString(messageContext.getOutboundSAMLMessage().getDOM()); - String encodedMessage = Base64.encodeBytes( - messageXML.getBytes("UTF-8"), Base64.DONT_BREAK_LINES); - if (messageContext.getOutboundSAMLMessage() instanceof RequestAbstractType) { - velocityContext.put("SAMLRequest", encodedMessage); - } else if (messageContext.getOutboundSAMLMessage() instanceof StatusResponseType) { - velocityContext.put("SAMLResponse", encodedMessage); - } else { - throw new MessageEncodingException( - "SAML message is neither a SAML RequestAbstractType or StatusResponseType"); - } - } catch (UnsupportedEncodingException e) { - log.error("UTF-8 encoding is not supported, this VM is not Java compliant."); - throw new MessageEncodingException( - "Unable to encode message, UTF-8 encoding is not supported"); - } + log.debug("Marshalling and Base64 encoding SAML message"); + if (messageContext.getOutboundSAMLMessage().getDOM() == null) { + marshallMessage(messageContext.getOutboundSAMLMessage()); + } + try { + String messageXML = XMLHelper.nodeToString(messageContext.getOutboundSAMLMessage().getDOM()); + String encodedMessage = Base64.encodeBytes( + messageXML.getBytes("UTF-8"), Base64.DONT_BREAK_LINES); + if (messageContext.getOutboundSAMLMessage() instanceof RequestAbstractType) { + velocityContext.put("SAMLRequest", encodedMessage); + } else if (messageContext.getOutboundSAMLMessage() instanceof StatusResponseType) { + velocityContext.put("SAMLResponse", encodedMessage); + } else { + throw new MessageEncodingException( + "SAML message is neither a SAML RequestAbstractType or StatusResponseType"); + } + } catch (UnsupportedEncodingException e) { + log.error("UTF-8 encoding is not supported, this VM is not Java compliant."); + throw new MessageEncodingException( + "Unable to encode message, UTF-8 encoding is not supported"); + } - Credential signingCredential = messageContext.getOuboundSAMLMessageSigningCredential(); - if (signingCredential == null) { - log.debug("No signing credential was supplied, skipping HTTP-Post simple signing"); - return; - } + Credential signingCredential = messageContext.getOuboundSAMLMessageSigningCredential(); + if (signingCredential == null) { + log.debug("No signing credential was supplied, skipping HTTP-Post simple signing"); + return; + } - String sigAlgURI = getSignatureAlgorithmURI(signingCredential, null); - velocityContext.put("SigAlg", sigAlgURI); + String sigAlgURI = getSignatureAlgorithmURI(signingCredential, null); + velocityContext.put("SigAlg", sigAlgURI); - String formControlData = buildFormDataToSign(velocityContext,messageContext, sigAlgURI); - velocityContext.put("Signature",generateSignature(signingCredential, sigAlgURI,formControlData)); + String formControlData = buildFormDataToSign(velocityContext,messageContext, sigAlgURI); + velocityContext.put("Signature",generateSignature(signingCredential, sigAlgURI,formControlData)); - KeyInfoGenerator kiGenerator = SecurityHelper.getKeyInfoGenerator(signingCredential, null, null); - - if (kiGenerator != null) { - String kiBase64 = buildKeyInfo(signingCredential, kiGenerator); - if (!DatatypeHelper.isEmpty(kiBase64)) { - velocityContext.put("KeyInfo", kiBase64); - } - } - } + KeyInfoGenerator kiGenerator = SecurityHelper.getKeyInfoGenerator(signingCredential, null, null); + + if (kiGenerator != null) { + String kiBase64 = buildKeyInfo(signingCredential, kiGenerator); + if (!DatatypeHelper.isEmpty(kiBase64)) { + velocityContext.put("KeyInfo", kiBase64); + } + } + } - /** - * Build the {@link KeyInfo} from the signing credential. - * - * @param signingCredential - * the credential used for signing - * @param kiGenerator - * the generator for the KeyInfo - * @throws MessageEncodingException - * thrown if there is an error generating or marshalling the - * KeyInfo - * @return the marshalled, serialized and base64-encoded KeyInfo, or null if - * none was generated - */ - protected String buildKeyInfo(Credential signingCredential, - KeyInfoGenerator kiGenerator) throws MessageEncodingException { + /** + * Build the {@link KeyInfo} from the signing credential. + * + * @param signingCredential + * the credential used for signing + * @param kiGenerator + * the generator for the KeyInfo + * @throws MessageEncodingException + * thrown if there is an error generating or marshalling the + * KeyInfo + * @return the marshalled, serialized and base64-encoded KeyInfo, or null if + * none was generated + */ + protected String buildKeyInfo(Credential signingCredential, + KeyInfoGenerator kiGenerator) throws MessageEncodingException { - try { - KeyInfo keyInfo = kiGenerator.generate(signingCredential); - if (keyInfo != null) { - Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(keyInfo); - if (marshaller == null) { - log.error("No KeyInfo marshaller available from configuration"); - throw new MessageEncodingException("No KeyInfo marshaller was configured"); - } - String kiXML = XMLHelper.nodeToString(marshaller.marshall(keyInfo)); - String kiBase64 = Base64.encodeBytes(kiXML.getBytes(),Base64.DONT_BREAK_LINES); - return kiBase64; - } else { - return null; - } - } catch (SecurityException e) { - log.error("Error generating KeyInfo from signing credential", e); - throw new MessageEncodingException( - "Error generating KeyInfo from signing credential", e); - } catch (MarshallingException e) { - log.error("Error marshalling KeyInfo based on signing credential", - e); - throw new MessageEncodingException( - "Error marshalling KeyInfo based on signing credential", e); - } - } + try { + KeyInfo keyInfo = kiGenerator.generate(signingCredential); + if (keyInfo != null) { + Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(keyInfo); + if (marshaller == null) { + log.error("No KeyInfo marshaller available from configuration"); + throw new MessageEncodingException("No KeyInfo marshaller was configured"); + } + String kiXML = XMLHelper.nodeToString(marshaller.marshall(keyInfo)); + String kiBase64 = Base64.encodeBytes(kiXML.getBytes(),Base64.DONT_BREAK_LINES); + return kiBase64; + } else { + return null; + } + } catch (SecurityException e) { + log.error("Error generating KeyInfo from signing credential", e); + throw new MessageEncodingException( + "Error generating KeyInfo from signing credential", e); + } catch (MarshallingException e) { + log.error("Error marshalling KeyInfo based on signing credential", + e); + throw new MessageEncodingException( + "Error marshalling KeyInfo based on signing credential", e); + } + } - /** - * Build the form control data string over which the signature is computed. - * - * @param velocityContext - * the Velocity context which is already populated with the - * values for SAML message and relay state - * @param messageContext - * the SAML message context being processed - * @param sigAlgURI - * the signature algorithm URI - * - * @return the form control data string for signature computation - */ - @SuppressWarnings("rawtypes") - protected String buildFormDataToSign(VelocityContext velocityContext, - SAMLMessageContext messageContext, String sigAlgURI) { - StringBuilder builder = new StringBuilder(); + /** + * Build the form control data string over which the signature is computed. + * + * @param velocityContext + * the Velocity context which is already populated with the + * values for SAML message and relay state + * @param messageContext + * the SAML message context being processed + * @param sigAlgURI + * the signature algorithm URI + * + * @return the form control data string for signature computation + */ + @SuppressWarnings("rawtypes") + protected String buildFormDataToSign(VelocityContext velocityContext, + SAMLMessageContext messageContext, String sigAlgURI) { + StringBuilder builder = new StringBuilder(); - boolean isRequest = false; - if (velocityContext.get("SAMLRequest") != null) { - isRequest = true; - } + boolean isRequest = false; + if (velocityContext.get("SAMLRequest") != null) { + isRequest = true; + } - String msgB64; - if (isRequest) { - msgB64 = (String) velocityContext.get("SAMLRequest"); - } else { - msgB64 = (String) velocityContext.get("SAMLResponse"); - } + String msgB64; + if (isRequest) { + msgB64 = (String) velocityContext.get("SAMLRequest"); + } else { + msgB64 = (String) velocityContext.get("SAMLResponse"); + } - String msg = null; - try { - msg = new String(Base64.decode(msgB64), "UTF-8"); - } catch (UnsupportedEncodingException e) { - // All JVM's required to support UTF-8 - } + String msg = null; + try { + msg = new String(Base64.decode(msgB64), "UTF-8"); + } catch (UnsupportedEncodingException e) { + // All JVM's required to support UTF-8 + } - if (isRequest) { - builder.append("SAMLRequest=" + msg); - } else { - builder.append("SAMLResponse=" + msg); - } + if (isRequest) { + builder.append("SAMLRequest=" + msg); + } else { + builder.append("SAMLResponse=" + msg); + } - if (messageContext.getRelayState() != null) { - builder.append("&RelayState=" + messageContext.getRelayState()); - } + if (messageContext.getRelayState() != null) { + builder.append("&RelayState=" + messageContext.getRelayState()); + } - builder.append("&SigAlg=" + sigAlgURI); + builder.append("&SigAlg=" + sigAlgURI); - return builder.toString(); - } + return builder.toString(); + } - protected String getSignatureAlgorithmURI(Credential credential, - SecurityConfiguration config) throws MessageEncodingException { + protected String getSignatureAlgorithmURI(Credential credential, + SecurityConfiguration config) throws MessageEncodingException { - SecurityConfiguration secConfig; - if (config != null) { - secConfig = config; - } else { - secConfig = Configuration.getGlobalSecurityConfiguration(); - } + SecurityConfiguration secConfig; + if (config != null) { + secConfig = config; + } else { + secConfig = Configuration.getGlobalSecurityConfiguration(); + } - String signAlgo = secConfig.getSignatureAlgorithmURI(credential); + String signAlgo = secConfig.getSignatureAlgorithmURI(credential); - if (signAlgo == null) { - throw new MessageEncodingException( - "The signing credential's algorithm URI could not be derived"); - } + if (signAlgo == null) { + throw new MessageEncodingException( + "The signing credential's algorithm URI could not be derived"); + } - return signAlgo; - } + return signAlgo; + } - /** - * Generates the signature over the string of concatenated form control data - * as indicated by the SimpleSign spec. - * - * @param signingCredential - * credential that will be used to sign - * @param algorithmURI - * algorithm URI of the signing credential - * @param formData - * form control data to be signed - * - * @return base64 encoded signature of form control data - * - * @throws MessageEncodingException - * there is an error computing the signature - */ - protected String generateSignature( - Credential signingCredential, - String algorithmURI, String formData) - throws MessageEncodingException { + /** + * Generates the signature over the string of concatenated form control data + * as indicated by the SimpleSign spec. + * + * @param signingCredential + * credential that will be used to sign + * @param algorithmURI + * algorithm URI of the signing credential + * @param formData + * form control data to be signed + * + * @return base64 encoded signature of form control data + * + * @throws MessageEncodingException + * there is an error computing the signature + */ + protected String generateSignature( + Credential signingCredential, + String algorithmURI, String formData) + throws MessageEncodingException { - log.debug(String - .format("Generating signature with key type '%s', algorithm URI '%s' over form control string '%s'", - SecurityHelper.extractSigningKey(signingCredential).getAlgorithm(), algorithmURI, formData)); + log.debug(String + .format("Generating signature with key type '%s', algorithm URI '%s' over form control string '%s'", + SecurityHelper.extractSigningKey(signingCredential).getAlgorithm(), algorithmURI, formData)); - String b64Signature = null; - try { - byte[] rawSignature = SigningUtil.signWithURI(signingCredential,algorithmURI, formData.getBytes("UTF-8")); - b64Signature = Base64.encodeBytes(rawSignature,Base64.DONT_BREAK_LINES); - log.debug("Generated digital signature value (base64-encoded) {}",b64Signature); - } catch (SecurityException e) { - log.error("Error during URL signing process", e); - throw new MessageEncodingException( - "Unable to sign form control string", e); - } catch (UnsupportedEncodingException e) { - // UTF-8 encoding is required to be supported by all JVMs - } + String b64Signature = null; + try { + byte[] rawSignature = SigningUtil.signWithURI(signingCredential,algorithmURI, formData.getBytes("UTF-8")); + b64Signature = Base64.encodeBytes(rawSignature,Base64.DONT_BREAK_LINES); + log.debug("Generated digital signature value (base64-encoded) {}",b64Signature); + } catch (SecurityException e) { + log.error("Error during URL signing process", e); + throw new MessageEncodingException( + "Unable to sign form control string", e); + } catch (UnsupportedEncodingException e) { + // UTF-8 encoding is required to be supported by all JVMs + } - return b64Signature; - } + return b64Signature; + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/endpoint/AssertionEndpoint.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/endpoint/AssertionEndpoint.java index 31a96aea6..0994becd3 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/endpoint/AssertionEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/endpoint/AssertionEndpoint.java @@ -46,63 +46,63 @@ import jakarta.servlet.http.HttpServletResponse; @Controller public class AssertionEndpoint { - private static final Logger logger = LoggerFactory.getLogger(AssertionEndpoint.class); - - private BindingAdapter bindingAdapter; + private static final Logger logger = LoggerFactory.getLogger(AssertionEndpoint.class); + + private BindingAdapter bindingAdapter; - @Autowired - @Qualifier("endpointGenerator") - EndpointGenerator endpointGenerator; - - @Autowired - @Qualifier("authnResponseGenerator") - AuthnResponseGenerator authnResponseGenerator; + @Autowired + @Qualifier("endpointGenerator") + EndpointGenerator endpointGenerator; + + @Autowired + @Qualifier("authnResponseGenerator") + AuthnResponseGenerator authnResponseGenerator; - @RequestMapping(value = "/authz/saml20/assertion") - 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); - logger.debug("saml20 assertion get session samlv20Adapter {}",bindingAdapter); - AppsSAML20Details saml20Details = bindingAdapter.getSaml20Details(); - logger.debug("saml20Details {}",saml20Details.getExtendAttr()); - AuthnRequestInfo authnRequestInfo = bindingAdapter.getAuthnRequestInfo(); - - if (authnRequestInfo == null) { - logger.warn("Could not find AuthnRequest on the request. Responding with SC_FORBIDDEN."); - throw new Exception(); - } + @RequestMapping(value = "/authz/saml20/assertion") + 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); + logger.debug("saml20 assertion get session samlv20Adapter {}",bindingAdapter); + AppsSAML20Details saml20Details = bindingAdapter.getSaml20Details(); + logger.debug("saml20Details {}",saml20Details.getExtendAttr()); + AuthnRequestInfo authnRequestInfo = bindingAdapter.getAuthnRequestInfo(); + + if (authnRequestInfo == null) { + logger.warn("Could not find AuthnRequest on the request. Responding with SC_FORBIDDEN."); + throw new Exception(); + } - logger.debug("AuthnRequestInfo: {}", authnRequestInfo); - HashMap attributeMap=new HashMap<>(); - attributeMap.put(WebConstants.ONLINE_TICKET_NAME, AuthorizationUtils.getPrincipal().getSessionId()); - - //saml20Details - Response authResponse = authnResponseGenerator.generateAuthnResponse( - saml20Details, - authnRequestInfo, - attributeMap, - bindingAdapter, - currentUser); - - Endpoint endpoint = endpointGenerator.generateEndpoint(saml20Details.getSpAcsUrl()); + logger.debug("AuthnRequestInfo: {}", authnRequestInfo); + HashMap attributeMap=new HashMap<>(); + attributeMap.put(WebConstants.ONLINE_TICKET_NAME, AuthorizationUtils.getPrincipal().getSessionId()); + + //saml20Details + Response authResponse = authnResponseGenerator.generateAuthnResponse( + saml20Details, + authnRequestInfo, + attributeMap, + bindingAdapter, + currentUser); + + Endpoint endpoint = endpointGenerator.generateEndpoint(saml20Details.getSpAcsUrl()); - request.getSession().removeAttribute(AuthnRequestInfo.class.getName()); + request.getSession().removeAttribute(AuthnRequestInfo.class.getName()); - // we could use a different adapter to send the response based on - // request issuer... - try { - bindingAdapter.sendSAMLMessage(authResponse, endpoint, request,response); - } catch (MessageEncodingException mee) { - logger.error("Exception encoding SAML message", mee); - throw new Exception(mee); - } - return null; - } - - + // we could use a different adapter to send the response based on + // request issuer... + try { + bindingAdapter.sendSAMLMessage(authResponse, endpoint, request,response); + } catch (MessageEncodingException mee) { + logger.error("Exception encoding SAML message", mee); + throw new Exception(mee); + } + return null; + } + + } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/endpoint/IdpInitEndpoint.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/endpoint/IdpInitEndpoint.java index d33c0d8c6..db7589d62 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/endpoint/IdpInitEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/endpoint/IdpInitEndpoint.java @@ -52,87 +52,87 @@ import jakarta.servlet.http.HttpServletResponse; @Tag(name = "2-2-SAML v2.0 API文档模块") @Controller public class IdpInitEndpoint { - private static final Logger logger = LoggerFactory.getLogger(IdpInitEndpoint.class); + private static final Logger logger = LoggerFactory.getLogger(IdpInitEndpoint.class); - private BindingAdapter bindingAdapter; - - @Autowired - @Qualifier("postSimpleSignBindingAdapter") - private BindingAdapter postSimpleSignBindingAdapter; - - @Autowired - @Qualifier("postBindingAdapter") - private BindingAdapter postBindingAdapter; - - @Autowired - @Qualifier("extractRedirectBindingAdapter") - private ExtractBindingAdapter extractRedirectBindingAdapter; + private BindingAdapter bindingAdapter; + + @Autowired + @Qualifier("postSimpleSignBindingAdapter") + private BindingAdapter postSimpleSignBindingAdapter; + + @Autowired + @Qualifier("postBindingAdapter") + private BindingAdapter postBindingAdapter; + + @Autowired + @Qualifier("extractRedirectBindingAdapter") + private ExtractBindingAdapter extractRedirectBindingAdapter; - @Autowired - @Qualifier("keyStoreLoader") - private KeyStoreLoader keyStoreLoader; + @Autowired + @Qualifier("keyStoreLoader") + private KeyStoreLoader keyStoreLoader; - @Autowired - private AppsSaml20DetailsService saml20DetailsService; - - /** - * - * @param request - * @param response - * @param appId - * @return - * @throws Exception - * - * - */ - @Operation(summary = "SAML 2.0 IDP Init接口", description = "传递参数应用ID",method="GET") - @RequestMapping(value = "/authz/saml20/idpinit/{appid}", method=RequestMethod.GET) - public ModelAndView authorizeIdpInit( - HttpServletRequest request, - HttpServletResponse response, - @PathVariable("appid") String appId)throws Exception { - logger.debug("SAML IDP init , app id is "+appId); - AppsSAML20Details saml20Details = saml20DetailsService.getAppDetails(appId , true); - WebContext.setAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP, saml20Details); - if (saml20Details == null) { - logger.error("samlId[" + appId + "] Error ."); - throw new Exception(); - } + @Autowired + private AppsSaml20DetailsService saml20DetailsService; + + /** + * + * @param request + * @param response + * @param appId + * @return + * @throws Exception + * + * + */ + @Operation(summary = "SAML 2.0 IDP Init接口", description = "传递参数应用ID",method="GET") + @RequestMapping(value = "/authz/saml20/idpinit/{appid}", method=RequestMethod.GET) + public ModelAndView authorizeIdpInit( + HttpServletRequest request, + HttpServletResponse response, + @PathVariable("appid") String appId)throws Exception { + logger.debug("SAML IDP init , app id is "+appId); + AppsSAML20Details saml20Details = saml20DetailsService.getAppDetails(appId , true); + WebContext.setAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP, saml20Details); + if (saml20Details == null) { + logger.error("samlId[" + appId + "] Error ."); + throw new Exception(); + } - KeyStore trustKeyStore = KeyStoreUtil.bytes2KeyStore(saml20Details.getKeyStore(), - keyStoreLoader.getKeyStore().getType(), - keyStoreLoader.getKeystorePassword()); + KeyStore trustKeyStore = KeyStoreUtil.bytes2KeyStore(saml20Details.getKeyStore(), + keyStoreLoader.getKeyStore().getType(), + keyStoreLoader.getKeystorePassword()); - extractRedirectBindingAdapter.setSaml20Detail(saml20Details); - extractRedirectBindingAdapter.buildSecurityPolicyResolver(trustKeyStore); - - String binding=saml20Details.getBinding(); - - if(binding.endsWith("PostSimpleSign")){ - bindingAdapter=postSimpleSignBindingAdapter; - }else{ - bindingAdapter=postBindingAdapter; - } - - //AuthnRequestInfo init authnRequestID to null - bindingAdapter.setAuthnRequestInfo(new AuthnRequestInfo()); + extractRedirectBindingAdapter.setSaml20Detail(saml20Details); + extractRedirectBindingAdapter.buildSecurityPolicyResolver(trustKeyStore); + + String binding=saml20Details.getBinding(); + + if(binding.endsWith("PostSimpleSign")){ + bindingAdapter=postSimpleSignBindingAdapter; + }else{ + bindingAdapter=postBindingAdapter; + } + + //AuthnRequestInfo init authnRequestID to null + bindingAdapter.setAuthnRequestInfo(new AuthnRequestInfo()); - bindingAdapter.setExtractBindingAdapter(extractRedirectBindingAdapter); - - request.getSession().setAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP_SAMLV20_ADAPTER, bindingAdapter); + bindingAdapter.setExtractBindingAdapter(extractRedirectBindingAdapter); + + request.getSession().setAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP_SAMLV20_ADAPTER, bindingAdapter); - logger.debug("idp init forwarding to assertion :","/authz/saml20/assertion"); + logger.debug("idp init forwarding to assertion :","/authz/saml20/assertion"); - return WebContext.forward("/authz/saml20/assertion"); - } + return WebContext.forward("/authz/saml20/assertion"); + } - /** - * @param keyStoreLoader - * the keyStoreLoader to set - */ - public void setKeyStoreLoader(KeyStoreLoader keyStoreLoader) { - this.keyStoreLoader = keyStoreLoader; - } + /** + * @param keyStoreLoader + * the keyStoreLoader to set + */ + public void setKeyStoreLoader(KeyStoreLoader keyStoreLoader) { + this.keyStoreLoader = keyStoreLoader; + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/endpoint/LogoutSamlEndpoint.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/endpoint/LogoutSamlEndpoint.java index d4bc3eaf9..d4663bc0b 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/endpoint/LogoutSamlEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/endpoint/LogoutSamlEndpoint.java @@ -74,7 +74,7 @@ public class LogoutSamlEndpoint { logger.debug("LogoutRequest NameID "+logoutRequest.getNameID().getValue()); //add Destination if(StringUtils.isNotBlank(logoutRequest.getDestination())) { - logoutUrl.append("?").append("redirect_uri=").append(logoutRequest.getDestination()); + logoutUrl.append("?").append("redirect_uri=").append(logoutRequest.getDestination()); } } catch (MessageDecodingException e1) { logger.error("Exception decoding SAML MessageDecodingException", e1); diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/endpoint/SingleSignOnEndpoint.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/endpoint/SingleSignOnEndpoint.java index b0c704a68..6b75006a9 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/endpoint/SingleSignOnEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/endpoint/SingleSignOnEndpoint.java @@ -51,156 +51,156 @@ import jakarta.servlet.http.HttpServletResponse; @Tag(name = "2-2-SAML v2.0 API文档模块") @Controller public class SingleSignOnEndpoint { - private static final Logger logger = LoggerFactory.getLogger(SingleSignOnEndpoint.class); + private static final Logger logger = LoggerFactory.getLogger(SingleSignOnEndpoint.class); - private BindingAdapter bindingAdapter; - - @Autowired - @Qualifier("postSimpleSignBindingAdapter") - private BindingAdapter postSimpleSignBindingAdapter; - - @Autowired - @Qualifier("postBindingAdapter") - private BindingAdapter postBindingAdapter; - - @Autowired - @Qualifier("extractPostBindingAdapter") - private ExtractBindingAdapter extractPostBindingAdapter; - - @Autowired - @Qualifier("extractRedirectBindingAdapter") - private ExtractBindingAdapter extractRedirectBindingAdapter; + private BindingAdapter bindingAdapter; + + @Autowired + @Qualifier("postSimpleSignBindingAdapter") + private BindingAdapter postSimpleSignBindingAdapter; + + @Autowired + @Qualifier("postBindingAdapter") + private BindingAdapter postBindingAdapter; + + @Autowired + @Qualifier("extractPostBindingAdapter") + private ExtractBindingAdapter extractPostBindingAdapter; + + @Autowired + @Qualifier("extractRedirectBindingAdapter") + private ExtractBindingAdapter extractRedirectBindingAdapter; - @Autowired - @Qualifier("samlValidaotrSuite") - private SAML2ValidatorSuite validatorSuite; + @Autowired + @Qualifier("samlValidaotrSuite") + private SAML2ValidatorSuite validatorSuite; - @Autowired - private AppsSaml20DetailsService saml20DetailsService; + @Autowired + private AppsSaml20DetailsService saml20DetailsService; - @Operation(summary = "SAML 2.0 SP Init接收接口", description = "传递参数应用ID",method="POST") - @RequestMapping(value = "/authz/saml20/{appid}", method=RequestMethod.POST) - public ModelAndView authorizePost( - HttpServletRequest request, - HttpServletResponse response, - @PathVariable("appid") String appId)throws Exception { - logger.debug("SAML Authorize Redirect do POST , app id is "+appId); - return extractSAMLRequest(extractPostBindingAdapter,appId,request); - } - - @Operation(summary = "SAML 2.0 SP Init接收接口", description = "传递参数应用ID",method="GET") - @RequestMapping(value = "/authz/saml20/{appid}", method=RequestMethod.GET) - public ModelAndView authorizeRedirect( - HttpServletRequest request, - HttpServletResponse response, - @PathVariable("appid") String appId)throws Exception { - logger.debug("SAML Authorize Redirect do GET , app id is "+appId); - return extractSAMLRequest(extractRedirectBindingAdapter,appId,request); - } - - public ModelAndView extractSAMLRequest(ExtractBindingAdapter extractBindingAdapter, - String appId, - HttpServletRequest request) throws Exception{ - logger.debug("SAML Redirect Binding , app id is "+appId); - - extractSaml20Detail(extractBindingAdapter,appId); + @Operation(summary = "SAML 2.0 SP Init接收接口", description = "传递参数应用ID",method="POST") + @RequestMapping(value = "/authz/saml20/{appid}", method=RequestMethod.POST) + public ModelAndView authorizePost( + HttpServletRequest request, + HttpServletResponse response, + @PathVariable("appid") String appId)throws Exception { + logger.debug("SAML Authorize Redirect do POST , app id is "+appId); + return extractSAMLRequest(extractPostBindingAdapter,appId,request); + } + + @Operation(summary = "SAML 2.0 SP Init接收接口", description = "传递参数应用ID",method="GET") + @RequestMapping(value = "/authz/saml20/{appid}", method=RequestMethod.GET) + public ModelAndView authorizeRedirect( + HttpServletRequest request, + HttpServletResponse response, + @PathVariable("appid") String appId)throws Exception { + logger.debug("SAML Authorize Redirect do GET , app id is "+appId); + return extractSAMLRequest(extractRedirectBindingAdapter,appId,request); + } + + public ModelAndView extractSAMLRequest(ExtractBindingAdapter extractBindingAdapter, + String appId, + HttpServletRequest request) throws Exception{ + logger.debug("SAML Redirect Binding , app id is "+appId); + + extractSaml20Detail(extractBindingAdapter,appId); - extractSAMLMessage(extractBindingAdapter,request); - - request.getSession().setAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP_SAMLV20_ADAPTER, bindingAdapter); - - return WebContext.forward("/authz/saml20/assertion"); - } + extractSAMLMessage(extractBindingAdapter,request); + + request.getSession().setAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP_SAMLV20_ADAPTER, bindingAdapter); + + return WebContext.forward("/authz/saml20/assertion"); + } - public void extractSaml20Detail(ExtractBindingAdapter extractBindingAdapter,String samlId) throws Exception{ - AppsSAML20Details saml20Details = saml20DetailsService.getAppDetails(samlId , true); - WebContext.setAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP, saml20Details); - if (saml20Details == null) { - logger.error("Request SAML APPID [" + samlId + "] is not exist ."); - throw new Exception(); - } + public void extractSaml20Detail(ExtractBindingAdapter extractBindingAdapter,String samlId) throws Exception{ + AppsSAML20Details saml20Details = saml20DetailsService.getAppDetails(samlId , true); + WebContext.setAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP, saml20Details); + if (saml20Details == null) { + logger.error("Request SAML APPID [" + samlId + "] is not exist ."); + throw new Exception(); + } - KeyStore trustKeyStore = KeyStoreUtil.bytes2KeyStore(saml20Details.getKeyStore(), - extractBindingAdapter.getKeyStoreLoader().getKeyStore().getType(), - extractBindingAdapter.getKeyStoreLoader().getKeystorePassword()); + KeyStore trustKeyStore = KeyStoreUtil.bytes2KeyStore(saml20Details.getKeyStore(), + extractBindingAdapter.getKeyStoreLoader().getKeyStore().getType(), + extractBindingAdapter.getKeyStoreLoader().getKeystorePassword()); - extractBindingAdapter.setSaml20Detail(saml20Details); - extractBindingAdapter.buildSecurityPolicyResolver(trustKeyStore); - } - + extractBindingAdapter.setSaml20Detail(saml20Details); + extractBindingAdapter.buildSecurityPolicyResolver(trustKeyStore); + } + - - @SuppressWarnings("rawtypes") - public void extractSAMLMessage(ExtractBindingAdapter extractBindingAdapter,HttpServletRequest request) throws Exception{ - - SAMLMessageContext messageContext; - logger.debug("extract SAML Message ."); - - try { - messageContext = extractBindingAdapter.extractSAMLMessageContext(request); - logger.debug("validate SAML AuthnRequest ."); - AuthnRequest authnRequest = (AuthnRequest) messageContext.getInboundSAMLMessage(); - logger.debug("AuthnRequest ProtocolBinding "+authnRequest.getProtocolBinding()); - logger.debug("InboundSAMLMessage Id "+messageContext.getInboundSAMLMessageId()); - logger.debug("AuthnRequest AssertionConsumerServiceURL "+authnRequest.getAssertionConsumerServiceURL()); - logger.debug("InboundMessage Issuer "+messageContext.getInboundMessageIssuer()); - logger.debug("InboundSAMLMessage IssueInstant "+messageContext.getInboundSAMLMessageIssueInstant()); - logger.debug("InboundSAMLMessage RelayState "+messageContext.getRelayState()); - logger.debug("AuthnRequest isPassive "+authnRequest.isPassive()); - logger.debug("AuthnRequest ForceAuthn "+authnRequest.isForceAuthn()); - - validatorSuite.validate(authnRequest); - + + @SuppressWarnings("rawtypes") + public void extractSAMLMessage(ExtractBindingAdapter extractBindingAdapter,HttpServletRequest request) throws Exception{ + + SAMLMessageContext messageContext; + logger.debug("extract SAML Message ."); + + try { + messageContext = extractBindingAdapter.extractSAMLMessageContext(request); + logger.debug("validate SAML AuthnRequest ."); + AuthnRequest authnRequest = (AuthnRequest) messageContext.getInboundSAMLMessage(); + logger.debug("AuthnRequest ProtocolBinding "+authnRequest.getProtocolBinding()); + logger.debug("InboundSAMLMessage Id "+messageContext.getInboundSAMLMessageId()); + logger.debug("AuthnRequest AssertionConsumerServiceURL "+authnRequest.getAssertionConsumerServiceURL()); + logger.debug("InboundMessage Issuer "+messageContext.getInboundMessageIssuer()); + logger.debug("InboundSAMLMessage IssueInstant "+messageContext.getInboundSAMLMessageIssueInstant()); + logger.debug("InboundSAMLMessage RelayState "+messageContext.getRelayState()); + logger.debug("AuthnRequest isPassive "+authnRequest.isPassive()); + logger.debug("AuthnRequest ForceAuthn "+authnRequest.isForceAuthn()); + + validatorSuite.validate(authnRequest); + - logger.debug("Select Authz Binding."); - String binding=extractBindingAdapter.getSaml20Detail().getBinding(); - - if(binding.endsWith("PostSimpleSign")){ - bindingAdapter=postSimpleSignBindingAdapter; - logger.debug("Authz POST Binding is use PostSimpleSign ."); - }else{ - bindingAdapter=postBindingAdapter; - logger.debug("Authz POST Binding is use Post ."); - } - - - AuthnRequestInfo authnRequestInfo = new AuthnRequestInfo( - authnRequest.getAssertionConsumerServiceURL(), - authnRequest.getID()); - - logger.debug("AuthnRequest vefified. Forwarding to AuthnResponder",authnRequestInfo); - - bindingAdapter.setAuthnRequestInfo(authnRequestInfo); - - bindingAdapter.setExtractBindingAdapter(extractBindingAdapter); - - String relayState=request.getParameter("RelayState"); - if (relayState != null) { - bindingAdapter.setRelayState(relayState); - logger.debug("RelayState : ",relayState); - } - - } catch (MessageDecodingException e1) { - logger.error("Exception decoding SAML MessageDecodingException", e1); - throw new Exception(e1); - } catch (SecurityException e1) { - logger.error("Exception decoding SAML SecurityException", e1); - throw new Exception(e1); - }catch (ValidationException ve) { + logger.debug("Select Authz Binding."); + String binding=extractBindingAdapter.getSaml20Detail().getBinding(); + + if(binding.endsWith("PostSimpleSign")){ + bindingAdapter=postSimpleSignBindingAdapter; + logger.debug("Authz POST Binding is use PostSimpleSign ."); + }else{ + bindingAdapter=postBindingAdapter; + logger.debug("Authz POST Binding is use Post ."); + } + + + AuthnRequestInfo authnRequestInfo = new AuthnRequestInfo( + authnRequest.getAssertionConsumerServiceURL(), + authnRequest.getID()); + + logger.debug("AuthnRequest vefified. Forwarding to AuthnResponder",authnRequestInfo); + + bindingAdapter.setAuthnRequestInfo(authnRequestInfo); + + bindingAdapter.setExtractBindingAdapter(extractBindingAdapter); + + String relayState=request.getParameter("RelayState"); + if (relayState != null) { + bindingAdapter.setRelayState(relayState); + logger.debug("RelayState : ",relayState); + } + + } catch (MessageDecodingException e1) { + logger.error("Exception decoding SAML MessageDecodingException", e1); + throw new Exception(e1); + } catch (SecurityException e1) { + logger.error("Exception decoding SAML SecurityException", e1); + throw new Exception(e1); + }catch (ValidationException ve) { logger.warn("AuthnRequest Message failed Validation", ve); throw new Exception(ve); } - - } + + } - /** - * @param validatorSuite - * the validatorSuite to set - */ - public void setValidatorSuite(SAML2ValidatorSuite validatorSuite) { - this.validatorSuite = validatorSuite; - } + /** + * @param validatorSuite + * the validatorSuite to set + */ + public void setValidatorSuite(SAML2ValidatorSuite validatorSuite) { + this.validatorSuite = validatorSuite; + } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/AssertionGenerator.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/AssertionGenerator.java index b73f37d72..e0b4c9c28 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/AssertionGenerator.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/AssertionGenerator.java @@ -51,102 +51,102 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; public class AssertionGenerator { - private static final Logger logger = LoggerFactory.getLogger(AssertionGenerator.class); + private static final Logger logger = LoggerFactory.getLogger(AssertionGenerator.class); - private final IssuerGenerator issuerGenerator; - private final SubjectGenerator subjectGenerator; - private final IDService idService; - private final TimeService timeService; - private final AuthnStatementGenerator authnStatementGenerator ; - private final AttributeStatementGenerator attributeStatementGenerator; - private final ConditionsGenerator conditionsGenerator; + private final IssuerGenerator issuerGenerator; + private final SubjectGenerator subjectGenerator; + private final IDService idService; + private final TimeService timeService; + private final AuthnStatementGenerator authnStatementGenerator ; + private final AttributeStatementGenerator attributeStatementGenerator; + private final ConditionsGenerator conditionsGenerator; - public AssertionGenerator( - String issuerName, - TimeService timeService, - IDService idService) { - this.timeService = timeService; - this.idService = idService; - issuerGenerator = new IssuerGenerator(issuerName); - subjectGenerator = new SubjectGenerator(timeService); - authnStatementGenerator = new AuthnStatementGenerator(); - attributeStatementGenerator = new AttributeStatementGenerator(); - conditionsGenerator = new ConditionsGenerator(); - } + public AssertionGenerator( + String issuerName, + TimeService timeService, + IDService idService) { + this.timeService = timeService; + this.idService = idService; + issuerGenerator = new IssuerGenerator(issuerName); + subjectGenerator = new SubjectGenerator(timeService); + authnStatementGenerator = new AuthnStatementGenerator(); + attributeStatementGenerator = new AttributeStatementGenerator(); + conditionsGenerator = new ConditionsGenerator(); + } - public Assertion generateAssertion( - AppsSAML20Details saml20Details, - BindingAdapter bindingAdapter, - String assertionConsumerURL, - String inResponseTo, - String audienceUrl, - int validInSeconds, - HashMapattributeMap, - UserInfo userInfo - ) { + public Assertion generateAssertion( + AppsSAML20Details saml20Details, + BindingAdapter bindingAdapter, + String assertionConsumerURL, + String inResponseTo, + String audienceUrl, + int validInSeconds, + HashMapattributeMap, + UserInfo userInfo + ) { - Assertion assertion = new AssertionBuilder().buildObject();; - //Subject - Subject subject = subjectGenerator.generateSubject( - saml20Details, - assertionConsumerURL, - inResponseTo, - validInSeconds, - userInfo); - assertion.setSubject(subject); - //issuer - Issuer issuer = issuerGenerator.generateIssuer(); - assertion.setIssuer(issuer); - //AuthnStatements - DateTime authnInstant = new DateTime(WebContext.getSession().getCreationTime()); - AuthnStatement authnStatement = authnStatementGenerator.generateAuthnStatement(authnInstant); - assertion.getAuthnStatements().add(authnStatement); - //AttributeStatements - ArrayList grantedAuthoritys = new ArrayList(); - grantedAuthoritys.add(new SimpleGrantedAuthority("ROLE_USER")); - for(GrantedAuthority anthGrantedAuthority: ((UsernamePasswordAuthenticationToken)AuthorizationUtils.getAuthentication()).getAuthorities()){ - grantedAuthoritys.add(anthGrantedAuthority); - } - AttributeStatement attributeStatement = - attributeStatementGenerator.generateAttributeStatement( - saml20Details, - grantedAuthoritys, - attributeMap, - userInfo); - assertion.getAttributeStatements().add(attributeStatement); - //ID - assertion.setID(idService.generateID()); - //IssueInstant - assertion.setIssueInstant(timeService.getCurrentDateTime()); - //Conditions - Conditions conditions = conditionsGenerator.generateConditions(audienceUrl,validInSeconds); - assertion.setConditions(conditions); - //sign Assertion - try{ - if(bindingAdapter.getSigningCredential() == null) { - throw new Exception("Signing Credential is null..." ); - } - logger.debug("EntityId " + bindingAdapter.getSigningCredential().getEntityId()); - BasicCredential basicCredential = new BasicCredential(); - basicCredential.setPrivateKey(bindingAdapter.getSigningCredential().getPrivateKey()); - - Signature signature = new SignatureBuilder().buildObject(); - signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); - - - signature.setSigningCredential(basicCredential); - KeyInfoGeneratorFactory keyInfoGeneratorFactory = Configuration - .getGlobalSecurityConfiguration() - .getKeyInfoGeneratorManager().getDefaultManager() - .getFactory(bindingAdapter.getSigningCredential()); - - signature.setKeyInfo(keyInfoGeneratorFactory.newInstance().generate(bindingAdapter.getSigningCredential())); - BasicSecurityConfiguration config = (BasicSecurityConfiguration) Configuration.getGlobalSecurityConfiguration(); - - if(saml20Details.getSignature().equalsIgnoreCase("RSAwithSHA1")) { - signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1); - config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1); - }else if(saml20Details.getSignature().equalsIgnoreCase("RSAwithSHA256")) { + Assertion assertion = new AssertionBuilder().buildObject();; + //Subject + Subject subject = subjectGenerator.generateSubject( + saml20Details, + assertionConsumerURL, + inResponseTo, + validInSeconds, + userInfo); + assertion.setSubject(subject); + //issuer + Issuer issuer = issuerGenerator.generateIssuer(); + assertion.setIssuer(issuer); + //AuthnStatements + DateTime authnInstant = new DateTime(WebContext.getSession().getCreationTime()); + AuthnStatement authnStatement = authnStatementGenerator.generateAuthnStatement(authnInstant); + assertion.getAuthnStatements().add(authnStatement); + //AttributeStatements + ArrayList grantedAuthoritys = new ArrayList(); + grantedAuthoritys.add(new SimpleGrantedAuthority("ROLE_USER")); + for(GrantedAuthority anthGrantedAuthority: ((UsernamePasswordAuthenticationToken)AuthorizationUtils.getAuthentication()).getAuthorities()){ + grantedAuthoritys.add(anthGrantedAuthority); + } + AttributeStatement attributeStatement = + attributeStatementGenerator.generateAttributeStatement( + saml20Details, + grantedAuthoritys, + attributeMap, + userInfo); + assertion.getAttributeStatements().add(attributeStatement); + //ID + assertion.setID(idService.generateID()); + //IssueInstant + assertion.setIssueInstant(timeService.getCurrentDateTime()); + //Conditions + Conditions conditions = conditionsGenerator.generateConditions(audienceUrl,validInSeconds); + assertion.setConditions(conditions); + //sign Assertion + try{ + if(bindingAdapter.getSigningCredential() == null) { + throw new Exception("Signing Credential is null..." ); + } + logger.debug("EntityId " + bindingAdapter.getSigningCredential().getEntityId()); + BasicCredential basicCredential = new BasicCredential(); + basicCredential.setPrivateKey(bindingAdapter.getSigningCredential().getPrivateKey()); + + Signature signature = new SignatureBuilder().buildObject(); + signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); + + + signature.setSigningCredential(basicCredential); + KeyInfoGeneratorFactory keyInfoGeneratorFactory = Configuration + .getGlobalSecurityConfiguration() + .getKeyInfoGeneratorManager().getDefaultManager() + .getFactory(bindingAdapter.getSigningCredential()); + + signature.setKeyInfo(keyInfoGeneratorFactory.newInstance().generate(bindingAdapter.getSigningCredential())); + BasicSecurityConfiguration config = (BasicSecurityConfiguration) Configuration.getGlobalSecurityConfiguration(); + + if(saml20Details.getSignature().equalsIgnoreCase("RSAwithSHA1")) { + signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1); + config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1); + }else if(saml20Details.getSignature().equalsIgnoreCase("RSAwithSHA256")) { signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); }else if(saml20Details.getSignature().equalsIgnoreCase("RSAwithSHA384")) { @@ -192,7 +192,7 @@ public class AssertionGenerator { signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_MAC_HMAC_RIPEMD160); config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_MAC_HMAC_RIPEMD160); } - + if(saml20Details.getDigestMethod().equalsIgnoreCase("MD5")) { config.setSignatureReferenceDigestMethod(SignatureConstants.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5); }else if(saml20Details.getDigestMethod().equalsIgnoreCase("SHA1")) { @@ -207,17 +207,17 @@ public class AssertionGenerator { config.setSignatureReferenceDigestMethod(SignatureConstants.ALGO_ID_DIGEST_RIPEMD160); } - assertion.setSignature(signature); + assertion.setSignature(signature); - Configuration.getMarshallerFactory().getMarshaller(assertion).marshall(assertion); + Configuration.getMarshallerFactory().getMarshaller(assertion).marshall(assertion); Signer.signObject(signature); - logger.debug("assertion.isSigned "+assertion.isSigned()); - }catch (Exception e) { - e.printStackTrace(); - logger.info("Unable to Signer assertion ",e); - } + logger.debug("assertion.isSigned "+assertion.isSigned()); + }catch (Exception e) { + e.printStackTrace(); + logger.info("Unable to Signer assertion ",e); + } - return assertion; - } + return assertion; + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/AttributeStatementGenerator.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/AttributeStatementGenerator.java index 018129014..fe772451b 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/AttributeStatementGenerator.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/AttributeStatementGenerator.java @@ -44,106 +44,106 @@ import org.slf4j.LoggerFactory; import org.springframework.security.core.GrantedAuthority; public class AttributeStatementGenerator { - private static final Logger logger = LoggerFactory.getLogger(AttributeStatementGenerator.class); - - private final XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory(); + private static final Logger logger = LoggerFactory.getLogger(AttributeStatementGenerator.class); + + private final XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory(); - public static String COMMA = ","; - public static String COMMA_ISO8859_1 = "#44;"; //#44; ->, - - public AttributeStatement generateAttributeStatement( - AppsSAML20Details saml20Details, - ArrayList grantedAuthoritys, - UserInfo userInfo) { - return generateAttributeStatement( - saml20Details, grantedAuthoritys,null,userInfo); + public static String COMMA = ","; + public static String COMMA_ISO8859_1 = "#44;"; //#44; ->, + + public AttributeStatement generateAttributeStatement( + AppsSAML20Details saml20Details, + ArrayList grantedAuthoritys, + UserInfo userInfo) { + return generateAttributeStatement( + saml20Details, grantedAuthoritys,null,userInfo); - } + } - public AttributeStatement generateAttributeStatement( - AppsSAML20Details saml20Details, - ArrayList grantedAuthoritys, - HashMapattributeMap, - UserInfo userInfo) { + public AttributeStatement generateAttributeStatement( + AppsSAML20Details saml20Details, + ArrayList grantedAuthoritys, + HashMapattributeMap, + UserInfo userInfo) { - AttributeStatementBuilder attributeStatementBuilder = (AttributeStatementBuilder) builderFactory.getBuilder(AttributeStatement.DEFAULT_ELEMENT_NAME); - AttributeStatement attributeStatement = attributeStatementBuilder.buildObject(); - - Attribute attributeGrantedAuthority=builderGrantedAuthority(grantedAuthoritys); - attributeStatement.getAttributes().add(attributeGrantedAuthority); - - putUserAttributes(attributeMap,userInfo); - - if(null!=attributeMap){ - Iterator> iterator = attributeMap.entrySet().iterator(); - while (iterator.hasNext()) { - Map.Entry entry = (Map.Entry) iterator.next(); - String key = entry.getKey(); - String value = entry.getValue(); - Attribute attribute=builderAttribute(key,value,Attribute.BASIC); - attributeStatement.getAttributes().add(attribute); - } - } - - logger.debug("ExtendAttr "+saml20Details.getExtendAttr()); - if(ConstsBoolean.isTrue(saml20Details.getIsExtendAttr()) && saml20Details.getExtendAttr() != null) { - ExtraAttrs extraAttrs=new ExtraAttrs(saml20Details.getExtendAttr()); - for(ExtraAttr extraAttr : extraAttrs.getExtraAttrs()) { - extraAttr.setValue(extraAttr.getValue().replaceAll(COMMA_ISO8859_1, COMMA)); - logger.debug("Attribute : {} , Vale : {} , Type : {}", - extraAttr.getAttr(),extraAttr.getValue(),extraAttr.getType()); - - attributeStatement.getAttributes().add(builderAttribute( - extraAttr.getAttr(), - extraAttr.getValue(), - extraAttr.getType() - ) - ); - } - } - - return attributeStatement; - } - - public Attribute builderAttribute(String attributeName,String value ,String nameFormat){ - AttributeBuilder attributeBuilder = (AttributeBuilder) builderFactory.getBuilder(Attribute.DEFAULT_ELEMENT_NAME); - Attribute attribute = attributeBuilder.buildObject(); - attribute.setName(attributeName); + AttributeStatementBuilder attributeStatementBuilder = (AttributeStatementBuilder) builderFactory.getBuilder(AttributeStatement.DEFAULT_ELEMENT_NAME); + AttributeStatement attributeStatement = attributeStatementBuilder.buildObject(); + + Attribute attributeGrantedAuthority=builderGrantedAuthority(grantedAuthoritys); + attributeStatement.getAttributes().add(attributeGrantedAuthority); + + putUserAttributes(attributeMap,userInfo); + + if(null!=attributeMap){ + Iterator> iterator = attributeMap.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry entry = (Map.Entry) iterator.next(); + String key = entry.getKey(); + String value = entry.getValue(); + Attribute attribute=builderAttribute(key,value,Attribute.BASIC); + attributeStatement.getAttributes().add(attribute); + } + } + + logger.debug("ExtendAttr "+saml20Details.getExtendAttr()); + if(ConstsBoolean.isTrue(saml20Details.getIsExtendAttr()) && saml20Details.getExtendAttr() != null) { + ExtraAttrs extraAttrs=new ExtraAttrs(saml20Details.getExtendAttr()); + for(ExtraAttr extraAttr : extraAttrs.getExtraAttrs()) { + extraAttr.setValue(extraAttr.getValue().replaceAll(COMMA_ISO8859_1, COMMA)); + logger.debug("Attribute : {} , Vale : {} , Type : {}", + extraAttr.getAttr(),extraAttr.getValue(),extraAttr.getType()); + + attributeStatement.getAttributes().add(builderAttribute( + extraAttr.getAttr(), + extraAttr.getValue(), + extraAttr.getType() + ) + ); + } + } + + return attributeStatement; + } + + public Attribute builderAttribute(String attributeName,String value ,String nameFormat){ + AttributeBuilder attributeBuilder = (AttributeBuilder) builderFactory.getBuilder(Attribute.DEFAULT_ELEMENT_NAME); + Attribute attribute = attributeBuilder.buildObject(); + attribute.setName(attributeName); - // urn:oasis:names:tc:SAML:2.0:attrname-format:basic - if(nameFormat==null || nameFormat.equals("")) { - nameFormat=Attribute.BASIC; - } - - attribute.setNameFormat(nameFormat); - if(value!=null) { - attribute.getAttributeValues().add(builderAttributeValue(value)); - } - - return attribute; - } - - public Attribute builderGrantedAuthority(Collection authorities){ - // Response/Assertion/AttributeStatement/Attribute - Attribute attribute = builderAttribute("GrantedAuthority",null,null); - for (GrantedAuthority grantedAuthority : authorities) { - // this was convoluted to figure out - // Response/Assertion/AttributeStatement/Attribute/AttributeValue - attribute.getAttributeValues().add(builderAttributeValue(grantedAuthority.getAuthority())); + // urn:oasis:names:tc:SAML:2.0:attrname-format:basic + if(nameFormat==null || nameFormat.equals("")) { + nameFormat=Attribute.BASIC; + } + + attribute.setNameFormat(nameFormat); + if(value!=null) { + attribute.getAttributeValues().add(builderAttributeValue(value)); + } + + return attribute; + } + + public Attribute builderGrantedAuthority(Collection authorities){ + // Response/Assertion/AttributeStatement/Attribute + Attribute attribute = builderAttribute("GrantedAuthority",null,null); + for (GrantedAuthority grantedAuthority : authorities) { + // this was convoluted to figure out + // Response/Assertion/AttributeStatement/Attribute/AttributeValue + attribute.getAttributeValues().add(builderAttributeValue(grantedAuthority.getAuthority())); - } - return attribute; - } - - public XSString builderAttributeValue(String value) { - XSString xsStringValue = new XSStringBuilder().buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME); - xsStringValue.setValue(value); - return xsStringValue; - } - - public HashMap putUserAttributes( - HashMap attributeMap, - UserInfo userInfo){ + } + return attribute; + } + + public XSString builderAttributeValue(String value) { + XSString xsStringValue = new XSStringBuilder().buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME); + xsStringValue.setValue(value); + return xsStringValue; + } + + public HashMap putUserAttributes( + HashMap attributeMap, + UserInfo userInfo){ attributeMap.put(ActiveDirectoryUser.USERNAME, userInfo.getUsername()); attributeMap.put(ActiveDirectoryUser.UID, userInfo.getUsername()); diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/AuthnResponseGenerator.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/AuthnResponseGenerator.java index 95ea9e580..a3a4c52a6 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/AuthnResponseGenerator.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/AuthnResponseGenerator.java @@ -44,80 +44,80 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AuthnResponseGenerator { - private static final Logger logger = LoggerFactory.getLogger(AuthnResponseGenerator.class); - private String issuerName; - private IDService idService; - private TimeService timeService; - private AssertionGenerator assertionGenerator; - private IssuerGenerator issuerGenerator; - private StatusGenerator statusGenerator; + private static final Logger logger = LoggerFactory.getLogger(AuthnResponseGenerator.class); + private String issuerName; + private IDService idService; + private TimeService timeService; + private AssertionGenerator assertionGenerator; + private IssuerGenerator issuerGenerator; + private StatusGenerator statusGenerator; - public AuthnResponseGenerator(String issuerName, TimeService timeService, IDService idService) { - this.issuerName = issuerName; - this.idService = idService; - this.timeService = timeService; - issuerGenerator = new IssuerGenerator(this.issuerName); - assertionGenerator = new AssertionGenerator(issuerName, timeService, idService); - statusGenerator = new StatusGenerator(); - } + public AuthnResponseGenerator(String issuerName, TimeService timeService, IDService idService) { + this.issuerName = issuerName; + this.idService = idService; + this.timeService = timeService; + issuerGenerator = new IssuerGenerator(this.issuerName); + assertionGenerator = new AssertionGenerator(issuerName, timeService, idService); + statusGenerator = new StatusGenerator(); + } - public Response generateAuthnResponse( AppsSAML20Details saml20Details, - AuthnRequestInfo authnRequestInfo, - HashMapattributeMap, - BindingAdapter bindingAdapter, - UserInfo currentUser){ - - Response authResponse = new ResponseBuilder().buildObject(); - //builder Assertion - Assertion assertion = assertionGenerator.generateAssertion( - saml20Details, - bindingAdapter, - saml20Details.getSpAcsUrl(), - authnRequestInfo.getAuthnRequestID(), - saml20Details.getAudience(), - Integer.parseInt(saml20Details.getValidityInterval()), - attributeMap, - currentUser); - - //Encrypt - if(ConstsBoolean.isYes(saml20Details.getEncrypted())) { - logger.info("begin to encrypt assertion"); - try { - // Assume this contains a recipient's RSA public - EncryptionParameters encryptionParameters = new EncryptionParameters(); - encryptionParameters.setAlgorithm(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128); - logger.info("encryption assertion Algorithm : "+EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128); - KeyEncryptionParameters keyEncryptionParameters = new KeyEncryptionParameters(); - keyEncryptionParameters.setEncryptionCredential(bindingAdapter.getSpSigningCredential()); - // kekParams.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP); - keyEncryptionParameters.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15); - logger.info("keyEncryption Algorithm : "+EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15); - KeyInfoGeneratorFactory keyInfoGeneratorFactory = Configuration - .getGlobalSecurityConfiguration() - .getKeyInfoGeneratorManager().getDefaultManager() - .getFactory(bindingAdapter.getSpSigningCredential()); - keyEncryptionParameters.setKeyInfoGenerator(keyInfoGeneratorFactory.newInstance()); - Encrypter encrypter = new Encrypter(encryptionParameters, keyEncryptionParameters); - encrypter.setKeyPlacement(KeyPlacement.PEER); - EncryptedAssertion encryptedAssertion = encrypter.encrypt(assertion); - authResponse.getEncryptedAssertions().add(encryptedAssertion); - }catch(Exception e) { - logger.info("Unable to encrypt assertion .",e); - } - }else { - authResponse.getAssertions().add(assertion); - } - - authResponse.setIssuer(issuerGenerator.generateIssuer()); - authResponse.setID(idService.generateID()); - authResponse.setIssueInstant(timeService.getCurrentDateTime()); - authResponse.setInResponseTo(authnRequestInfo.getAuthnRequestID()); - authResponse.setDestination(saml20Details.getSpAcsUrl()); - authResponse.setStatus(statusGenerator.generateStatus(StatusCode.SUCCESS_URI)); - logger.debug("authResponse.isSigned "+authResponse.isSigned()); - return authResponse; - } - - + public Response generateAuthnResponse( AppsSAML20Details saml20Details, + AuthnRequestInfo authnRequestInfo, + HashMapattributeMap, + BindingAdapter bindingAdapter, + UserInfo currentUser){ + + Response authResponse = new ResponseBuilder().buildObject(); + //builder Assertion + Assertion assertion = assertionGenerator.generateAssertion( + saml20Details, + bindingAdapter, + saml20Details.getSpAcsUrl(), + authnRequestInfo.getAuthnRequestID(), + saml20Details.getAudience(), + Integer.parseInt(saml20Details.getValidityInterval()), + attributeMap, + currentUser); + + //Encrypt + if(ConstsBoolean.isYes(saml20Details.getEncrypted())) { + logger.info("begin to encrypt assertion"); + try { + // Assume this contains a recipient's RSA public + EncryptionParameters encryptionParameters = new EncryptionParameters(); + encryptionParameters.setAlgorithm(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128); + logger.info("encryption assertion Algorithm : "+EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128); + KeyEncryptionParameters keyEncryptionParameters = new KeyEncryptionParameters(); + keyEncryptionParameters.setEncryptionCredential(bindingAdapter.getSpSigningCredential()); + // kekParams.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP); + keyEncryptionParameters.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15); + logger.info("keyEncryption Algorithm : "+EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15); + KeyInfoGeneratorFactory keyInfoGeneratorFactory = Configuration + .getGlobalSecurityConfiguration() + .getKeyInfoGeneratorManager().getDefaultManager() + .getFactory(bindingAdapter.getSpSigningCredential()); + keyEncryptionParameters.setKeyInfoGenerator(keyInfoGeneratorFactory.newInstance()); + Encrypter encrypter = new Encrypter(encryptionParameters, keyEncryptionParameters); + encrypter.setKeyPlacement(KeyPlacement.PEER); + EncryptedAssertion encryptedAssertion = encrypter.encrypt(assertion); + authResponse.getEncryptedAssertions().add(encryptedAssertion); + }catch(Exception e) { + logger.info("Unable to encrypt assertion .",e); + } + }else { + authResponse.getAssertions().add(assertion); + } + + authResponse.setIssuer(issuerGenerator.generateIssuer()); + authResponse.setID(idService.generateID()); + authResponse.setIssueInstant(timeService.getCurrentDateTime()); + authResponse.setInResponseTo(authnRequestInfo.getAuthnRequestID()); + authResponse.setDestination(saml20Details.getSpAcsUrl()); + authResponse.setStatus(statusGenerator.generateStatus(StatusCode.SUCCESS_URI)); + logger.debug("authResponse.isSigned "+authResponse.isSigned()); + return authResponse; + } + + } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/AuthnStatementGenerator.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/AuthnStatementGenerator.java index a6ece26ca..874019acd 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/AuthnStatementGenerator.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/AuthnStatementGenerator.java @@ -29,24 +29,24 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AuthnStatementGenerator { - private static final Logger logger = LoggerFactory.getLogger(AuthnStatementGenerator.class); - - public AuthnStatement generateAuthnStatement(DateTime authnInstant) { - //Response/Assertion/AuthnStatement/AuthContext/AuthContextClassRef - AuthnContextClassRef authnContextClassRef = new AuthnContextClassRefBuilder().buildObject(); - //urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport - authnContextClassRef.setAuthnContextClassRef(AuthnContext.PPT_AUTHN_CTX); + private static final Logger logger = LoggerFactory.getLogger(AuthnStatementGenerator.class); + + public AuthnStatement generateAuthnStatement(DateTime authnInstant) { + //Response/Assertion/AuthnStatement/AuthContext/AuthContextClassRef + AuthnContextClassRef authnContextClassRef = new AuthnContextClassRefBuilder().buildObject(); + //urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport + authnContextClassRef.setAuthnContextClassRef(AuthnContext.PPT_AUTHN_CTX); - //Response/Assertion/AuthnStatement/AuthContext - AuthnContext authnContext = new AuthnContextBuilder().buildObject(); - authnContext.setAuthnContextClassRef(authnContextClassRef); + //Response/Assertion/AuthnStatement/AuthContext + AuthnContext authnContext = new AuthnContextBuilder().buildObject(); + authnContext.setAuthnContextClassRef(authnContextClassRef); - //Response/Assertion/AuthnStatement - AuthnStatement authnStatement = new AuthnStatementBuilder().buildObject(); - authnStatement.setAuthnContext(authnContext); - authnStatement.setAuthnInstant(authnInstant); - logger.debug("generateAuthnStatement authnInstant "+authnInstant); - return authnStatement; + //Response/Assertion/AuthnStatement + AuthnStatement authnStatement = new AuthnStatementBuilder().buildObject(); + authnStatement.setAuthnContext(authnContext); + authnStatement.setAuthnInstant(authnInstant); + logger.debug("generateAuthnStatement authnInstant "+authnInstant); + return authnStatement; - } + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/ConditionsGenerator.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/ConditionsGenerator.java index b9f937f75..98e1bddf2 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/ConditionsGenerator.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/ConditionsGenerator.java @@ -29,28 +29,28 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ConditionsGenerator { - private static final Logger logger = LoggerFactory.getLogger(ConditionsGenerator.class); - - public Conditions generateConditions(String audienceUrl,int validInSeconds) { - Conditions conditions = new ConditionsBuilder().buildObject(); - conditions.setNotBefore(new DateTime()); - conditions.setNotOnOrAfter(new DateTime().plus(validInSeconds*1000)); - - AudienceRestriction audienceRestriction=builderAudienceRestriction(audienceUrl); - conditions.getAudienceRestrictions().add(audienceRestriction); - - return conditions; - } - - public AudienceRestriction builderAudienceRestriction(String audienceUrl){ - AudienceRestriction audienceRestriction = new AudienceRestrictionBuilder().buildObject(); - - Audience audience = new AudienceBuilder().buildObject(); - audience.setAudienceURI(audienceUrl); - - audienceRestriction.getAudiences().add(audience); - logger.debug("Audience URL "+audienceUrl); - return audienceRestriction; - - } + private static final Logger logger = LoggerFactory.getLogger(ConditionsGenerator.class); + + public Conditions generateConditions(String audienceUrl,int validInSeconds) { + Conditions conditions = new ConditionsBuilder().buildObject(); + conditions.setNotBefore(new DateTime()); + conditions.setNotOnOrAfter(new DateTime().plus(validInSeconds*1000)); + + AudienceRestriction audienceRestriction=builderAudienceRestriction(audienceUrl); + conditions.getAudienceRestrictions().add(audienceRestriction); + + return conditions; + } + + public AudienceRestriction builderAudienceRestriction(String audienceUrl){ + AudienceRestriction audienceRestriction = new AudienceRestrictionBuilder().buildObject(); + + Audience audience = new AudienceBuilder().buildObject(); + audience.setAudienceURI(audienceUrl); + + audienceRestriction.getAudiences().add(audience); + logger.debug("Audience URL "+audienceUrl); + return audienceRestriction; + + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/StatusGenerator.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/StatusGenerator.java index 2f8a4072d..046d9b235 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/StatusGenerator.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/StatusGenerator.java @@ -27,53 +27,53 @@ import org.opensaml.saml2.core.impl.StatusMessageBuilder; public class StatusGenerator { - - public Status generateStatus( String value ) { - Status status = builderStatus(); - - StatusCode statusCode = builderStatusCode(value); - - status.setStatusCode(statusCode); - - return status; - } - - public Status generateStatus( String value, String subStatus, String message ) { - Status status = builderStatus(); - - StatusCode statusCode = builderStatusCode(value); - - StatusCode subStatusCode =builderStatusCode(value); - - statusCode.setStatusCode(subStatusCode); - - status.setStatusCode(statusCode); - - StatusMessage statusMessage = builderStatusMessage(message); - - status.setStatusMessage(statusMessage); - - return status; - } - - public Status builderStatus(){ - Status status = (Status) new StatusBuilder().buildObject(); - return status; - } - - public StatusCode builderStatusCode(String value){ - StatusCode statusCode = (StatusCode) new StatusCodeBuilder().buildObject(); - statusCode.setValue(value); - - return statusCode; - } - - public StatusMessage builderStatusMessage(String message){ - StatusMessage statusMessage = new StatusMessageBuilder().buildObject(); - - statusMessage.setMessage(message); - - return statusMessage; - } - + + public Status generateStatus( String value ) { + Status status = builderStatus(); + + StatusCode statusCode = builderStatusCode(value); + + status.setStatusCode(statusCode); + + return status; + } + + public Status generateStatus( String value, String subStatus, String message ) { + Status status = builderStatus(); + + StatusCode statusCode = builderStatusCode(value); + + StatusCode subStatusCode =builderStatusCode(value); + + statusCode.setStatusCode(subStatusCode); + + status.setStatusCode(statusCode); + + StatusMessage statusMessage = builderStatusMessage(message); + + status.setStatusMessage(statusMessage); + + return status; + } + + public Status builderStatus(){ + Status status = (Status) new StatusBuilder().buildObject(); + return status; + } + + public StatusCode builderStatusCode(String value){ + StatusCode statusCode = (StatusCode) new StatusCodeBuilder().buildObject(); + statusCode.setValue(value); + + return statusCode; + } + + public StatusMessage builderStatusMessage(String message){ + StatusMessage statusMessage = new StatusMessageBuilder().buildObject(); + + statusMessage.setMessage(message); + + return statusMessage; + } + } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/SubjectGenerator.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/SubjectGenerator.java index bc3dce534..b63e570eb 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/SubjectGenerator.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/provider/xml/SubjectGenerator.java @@ -36,41 +36,41 @@ import org.opensaml.saml2.core.impl.SubjectConfirmationDataBuilder; public class SubjectGenerator { - //private final XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory(); - private final TimeService timeService; - - public SubjectGenerator(TimeService timeService) { - super(); - this.timeService = timeService; - } + //private final XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory(); + private final TimeService timeService; + + public SubjectGenerator(TimeService timeService) { + super(); + this.timeService = timeService; + } - public Subject generateSubject( AppsSAML20Details saml20Details, - String assertionConsumerURL, - String inResponseTo, - int validInSeconds, - UserInfo userInfo) { - String nameIdValue = userInfo.getUsername(); - String nameIDType = NameIDType.UNSPECIFIED; - if(saml20Details.getNameidFormat().equalsIgnoreCase("persistent")) { - nameIDType = NameIDType.PERSISTENT; - }else if(saml20Details.getNameidFormat().equalsIgnoreCase("transient")) { - nameIDType = NameIDType.TRANSIENT; + public Subject generateSubject( AppsSAML20Details saml20Details, + String assertionConsumerURL, + String inResponseTo, + int validInSeconds, + UserInfo userInfo) { + String nameIdValue = userInfo.getUsername(); + String nameIDType = NameIDType.UNSPECIFIED; + if(saml20Details.getNameidFormat().equalsIgnoreCase("persistent")) { + nameIDType = NameIDType.PERSISTENT; + }else if(saml20Details.getNameidFormat().equalsIgnoreCase("transient")) { + nameIDType = NameIDType.TRANSIENT; }else if(saml20Details.getNameidFormat().equalsIgnoreCase("unspecified")) { - nameIDType = NameIDType.UNSPECIFIED; + nameIDType = NameIDType.UNSPECIFIED; }else if(saml20Details.getNameidFormat().equalsIgnoreCase("emailAddress")) { if(userInfo.getEmail()!=null && !userInfo.getEmail().equals("")) { nameIdValue = userInfo.getEmail(); } nameIDType = NameIDType.EMAIL; }else if(saml20Details.getNameidFormat().equalsIgnoreCase("X509SubjectName")) { - nameIDType = NameIDType.X509_SUBJECT; + nameIDType = NameIDType.X509_SUBJECT; }else if(saml20Details.getNameidFormat().equalsIgnoreCase("WindowsDomainQualifiedName")) { if(userInfo.getWindowsAccount()!=null && !userInfo.getWindowsAccount().equals("")) { nameIdValue = userInfo.getWindowsAccount(); } nameIDType = NameIDType.WIN_DOMAIN_QUALIFIED; }else if(saml20Details.getNameidFormat().equalsIgnoreCase("entity")) { - nameIDType = NameIDType.ENTITY; + nameIDType = NameIDType.ENTITY; }else if(saml20Details.getNameidFormat().equalsIgnoreCase("custom")) { }else if(saml20Details.getNameidFormat().equalsIgnoreCase("Mobile")) { @@ -82,71 +82,71 @@ public class SubjectGenerator { nameIdValue = userInfo.getEmployeeNumber(); } } - - if(!StringUtils.isEmpty(saml20Details.getNameIdSuffix())) { - nameIdValue = nameIdValue + saml20Details.getNameIdSuffix(); - } - - if(saml20Details.getNameIdConvert().equalsIgnoreCase("uppercase")) { - nameIdValue = nameIdValue.toUpperCase(); + + if(!StringUtils.isEmpty(saml20Details.getNameIdSuffix())) { + nameIdValue = nameIdValue + saml20Details.getNameIdSuffix(); + } + + if(saml20Details.getNameIdConvert().equalsIgnoreCase("uppercase")) { + nameIdValue = nameIdValue.toUpperCase(); }else if(saml20Details.getNameIdConvert().equalsIgnoreCase("lowercase")) { nameIdValue = nameIdValue.toLowerCase(); }else { - //do nothing + //do nothing } - - NameID nameID = builderNameID(nameIdValue,assertionConsumerURL,nameIDType); - Subject subject =builderSubject(nameID); - - String clientAddress=WebContext.getRequestIpAddress(WebContext.getRequest()); - SubjectConfirmation subjectConfirmation =builderSubjectConfirmation( - assertionConsumerURL, - inResponseTo, - validInSeconds, - clientAddress); + + NameID nameID = builderNameID(nameIdValue,assertionConsumerURL,nameIDType); + Subject subject =builderSubject(nameID); + + String clientAddress=WebContext.getRequestIpAddress(WebContext.getRequest()); + SubjectConfirmation subjectConfirmation =builderSubjectConfirmation( + assertionConsumerURL, + inResponseTo, + validInSeconds, + clientAddress); - subject.getSubjectConfirmations().add(subjectConfirmation); - - return subject; - } - - public NameID builderNameID(String value,String strSPNameQualifier,String nameIDType){ - //Response/Assertion/Subject/NameID - NameID nameID = new NameIDBuilder().buildObject(); - nameID.setValue(value); - //nameID.setFormat(NameIDType.PERSISTENT); - nameID.setFormat(nameIDType); - //nameID.setSPNameQualifier(strSPNameQualifier); - - return nameID; - } - - public Subject builderSubject (NameID nameID){ - //Response/Assertion/Subject - Subject subject = new SubjectBuilder().buildObject(); - subject.setNameID(nameID); - return subject; - } - - public SubjectConfirmation builderSubjectConfirmation(String recipient,String inResponseTo,int validInSeconds,String clientAddress){ - //SubjectConfirmationBuilder subjectConfirmationBuilder = (SubjectConfirmationBuilder)builderFactory.getBuilder(SubjectConfirmation.DEFAULT_ELEMENT_NAME); - SubjectConfirmation subjectConfirmation = new SubjectConfirmationBuilder().buildObject(); - subjectConfirmation.setMethod(SubjectConfirmation.METHOD_BEARER); - - //SubjectConfirmationDataBuilder subjectConfirmationDataBuilder = (SubjectConfirmationDataBuilder)builderFactory.getBuilder(SubjectConfirmationData.DEFAULT_ELEMENT_NAME); - SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationDataBuilder().buildObject(); - - subjectConfirmationData.setRecipient(recipient); - //if idp-init not need inResponseTo - if(null!=inResponseTo){ - subjectConfirmationData.setInResponseTo(inResponseTo); - } - subjectConfirmationData.setNotOnOrAfter(timeService.getCurrentDateTime().plusSeconds(validInSeconds)); - subjectConfirmationData.setAddress(clientAddress); - - subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData); - - return subjectConfirmation; - } - + subject.getSubjectConfirmations().add(subjectConfirmation); + + return subject; + } + + public NameID builderNameID(String value,String strSPNameQualifier,String nameIDType){ + //Response/Assertion/Subject/NameID + NameID nameID = new NameIDBuilder().buildObject(); + nameID.setValue(value); + //nameID.setFormat(NameIDType.PERSISTENT); + nameID.setFormat(nameIDType); + //nameID.setSPNameQualifier(strSPNameQualifier); + + return nameID; + } + + public Subject builderSubject (NameID nameID){ + //Response/Assertion/Subject + Subject subject = new SubjectBuilder().buildObject(); + subject.setNameID(nameID); + return subject; + } + + public SubjectConfirmation builderSubjectConfirmation(String recipient,String inResponseTo,int validInSeconds,String clientAddress){ + //SubjectConfirmationBuilder subjectConfirmationBuilder = (SubjectConfirmationBuilder)builderFactory.getBuilder(SubjectConfirmation.DEFAULT_ELEMENT_NAME); + SubjectConfirmation subjectConfirmation = new SubjectConfirmationBuilder().buildObject(); + subjectConfirmation.setMethod(SubjectConfirmation.METHOD_BEARER); + + //SubjectConfirmationDataBuilder subjectConfirmationDataBuilder = (SubjectConfirmationDataBuilder)builderFactory.getBuilder(SubjectConfirmationData.DEFAULT_ELEMENT_NAME); + SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationDataBuilder().buildObject(); + + subjectConfirmationData.setRecipient(recipient); + //if idp-init not need inResponseTo + if(null!=inResponseTo){ + subjectConfirmationData.setInResponseTo(inResponseTo); + } + subjectConfirmationData.setNotOnOrAfter(timeService.getCurrentDateTime().plusSeconds(validInSeconds)); + subjectConfirmationData.setAddress(clientAddress); + + subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData); + + return subjectConfirmation; + } + } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/xml/IssuerGenerator.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/xml/IssuerGenerator.java index b537a8a38..8c78b618a 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/xml/IssuerGenerator.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/xml/IssuerGenerator.java @@ -23,21 +23,21 @@ import org.opensaml.saml2.core.NameIDType; import org.opensaml.saml2.core.impl.IssuerBuilder; public class IssuerGenerator { - - private final String issuerName; - - public IssuerGenerator(String issuerName) { - this.issuerName = issuerName; - } + + private final String issuerName; + + public IssuerGenerator(String issuerName) { + this.issuerName = issuerName; + } - public Issuer generateIssuer() { - ///Issuer - Issuer issuer = new IssuerBuilder().buildObject(); - - issuer.setValue(issuerName); - issuer.setFormat(NameIDType.ENTITY); - - return issuer; - } - + public Issuer generateIssuer() { + ///Issuer + Issuer issuer = new IssuerBuilder().buildObject(); + + issuer.setValue(issuerName); + issuer.setFormat(NameIDType.ENTITY); + + return issuer; + } + } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/xml/SAML2ValidatorSuite.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/xml/SAML2ValidatorSuite.java index 4a7f2eaba..73a8a4d31 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/xml/SAML2ValidatorSuite.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/dromara/maxkey/authz/saml20/xml/SAML2ValidatorSuite.java @@ -24,14 +24,14 @@ import org.opensaml.xml.validation.ValidatorSuite; public class SAML2ValidatorSuite { - public void validate(XMLObject xmlObject) throws ValidationException { - - ValidatorSuite schemaValidator = Configuration.getValidatorSuite("saml2-core-schema-validator"); - schemaValidator.validate(xmlObject); - ValidatorSuite specValidator = Configuration.getValidatorSuite("saml2-core-spec-validator"); - specValidator.validate(xmlObject); + public void validate(XMLObject xmlObject) throws ValidationException { + + ValidatorSuite schemaValidator = Configuration.getValidatorSuite("saml2-core-schema-validator"); + schemaValidator.validate(xmlObject); + ValidatorSuite specValidator = Configuration.getValidatorSuite("saml2-core-spec-validator"); + specValidator.validate(xmlObject); - } - - + } + + } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/springframework/ui/velocity/SpringResourceLoader.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/springframework/ui/velocity/SpringResourceLoader.java index 7001ef2f6..5f3608fc9 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/springframework/ui/velocity/SpringResourceLoader.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/springframework/ui/velocity/SpringResourceLoader.java @@ -67,79 +67,79 @@ import org.springframework.util.StringUtils; */ public class SpringResourceLoader extends ResourceLoader { - public static final String NAME = "spring"; + public static final String NAME = "spring"; - public static final String SPRING_RESOURCE_LOADER_CLASS = "spring.resource.loader.class"; + public static final String SPRING_RESOURCE_LOADER_CLASS = "spring.resource.loader.class"; - public static final String SPRING_RESOURCE_LOADER_CACHE = "spring.resource.loader.cache"; + public static final String SPRING_RESOURCE_LOADER_CACHE = "spring.resource.loader.cache"; - public static final String SPRING_RESOURCE_LOADER = "spring.resource.loader"; + public static final String SPRING_RESOURCE_LOADER = "spring.resource.loader"; - public static final String SPRING_RESOURCE_LOADER_PATH = "spring.resource.loader.path"; + public static final String SPRING_RESOURCE_LOADER_PATH = "spring.resource.loader.path"; - protected final Log logger = LogFactory.getLog(getClass()); + protected final Log logger = LogFactory.getLog(getClass()); - private org.springframework.core.io.ResourceLoader resourceLoader; + private org.springframework.core.io.ResourceLoader resourceLoader; - private String[] resourceLoaderPaths; + private String[] resourceLoaderPaths; - @Override - public void init(ExtendedProperties configuration) { - this.resourceLoader = (org.springframework.core.io.ResourceLoader) - this.rsvc.getApplicationAttribute(SPRING_RESOURCE_LOADER); - String resourceLoaderPath = (String) this.rsvc.getApplicationAttribute(SPRING_RESOURCE_LOADER_PATH); - if (this.resourceLoader == null) { - throw new IllegalArgumentException( - "'resourceLoader' application attribute must be present for SpringResourceLoader"); - } - if (resourceLoaderPath == null) { - throw new IllegalArgumentException( - "'resourceLoaderPath' application attribute must be present for SpringResourceLoader"); - } - this.resourceLoaderPaths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath); - for (int i = 0; i < this.resourceLoaderPaths.length; i++) { - String path = this.resourceLoaderPaths[i]; - if (!path.endsWith("/")) { - this.resourceLoaderPaths[i] = path + "/"; - } - } - if (logger.isInfoEnabled()) { - logger.info("SpringResourceLoader for Velocity: using resource loader [" + this.resourceLoader + - "] and resource loader paths " + Arrays.asList(this.resourceLoaderPaths)); - } - } + @Override + public void init(ExtendedProperties configuration) { + this.resourceLoader = (org.springframework.core.io.ResourceLoader) + this.rsvc.getApplicationAttribute(SPRING_RESOURCE_LOADER); + String resourceLoaderPath = (String) this.rsvc.getApplicationAttribute(SPRING_RESOURCE_LOADER_PATH); + if (this.resourceLoader == null) { + throw new IllegalArgumentException( + "'resourceLoader' application attribute must be present for SpringResourceLoader"); + } + if (resourceLoaderPath == null) { + throw new IllegalArgumentException( + "'resourceLoaderPath' application attribute must be present for SpringResourceLoader"); + } + this.resourceLoaderPaths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath); + for (int i = 0; i < this.resourceLoaderPaths.length; i++) { + String path = this.resourceLoaderPaths[i]; + if (!path.endsWith("/")) { + this.resourceLoaderPaths[i] = path + "/"; + } + } + if (logger.isInfoEnabled()) { + logger.info("SpringResourceLoader for Velocity: using resource loader [" + this.resourceLoader + + "] and resource loader paths " + Arrays.asList(this.resourceLoaderPaths)); + } + } - @Override - public InputStream getResourceStream(String source) throws ResourceNotFoundException { - if (logger.isDebugEnabled()) { - logger.debug("Looking for Velocity resource with name [" + source + "]"); - } - for (String resourceLoaderPath : this.resourceLoaderPaths) { - org.springframework.core.io.Resource resource = - this.resourceLoader.getResource(resourceLoaderPath + source); - try { - return resource.getInputStream(); - } - catch (IOException ex) { - if (logger.isDebugEnabled()) { - logger.debug("Could not find Velocity resource: " + resource); - } - } - } - throw new ResourceNotFoundException( - "Could not find resource [" + source + "] in Spring resource loader path"); - } + @Override + public InputStream getResourceStream(String source) throws ResourceNotFoundException { + if (logger.isDebugEnabled()) { + logger.debug("Looking for Velocity resource with name [" + source + "]"); + } + for (String resourceLoaderPath : this.resourceLoaderPaths) { + org.springframework.core.io.Resource resource = + this.resourceLoader.getResource(resourceLoaderPath + source); + try { + return resource.getInputStream(); + } + catch (IOException ex) { + if (logger.isDebugEnabled()) { + logger.debug("Could not find Velocity resource: " + resource); + } + } + } + throw new ResourceNotFoundException( + "Could not find resource [" + source + "] in Spring resource loader path"); + } - @Override - public boolean isSourceModified(Resource resource) { - return false; - } + @Override + public boolean isSourceModified(Resource resource) { + return false; + } - @Override - public long getLastModified(Resource resource) { - return 0; - } + @Override + public long getLastModified(Resource resource) { + return 0; + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/springframework/ui/velocity/VelocityEngineFactory.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/springframework/ui/velocity/VelocityEngineFactory.java index 9908e32aa..280b5e4a1 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/springframework/ui/velocity/VelocityEngineFactory.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/springframework/ui/velocity/VelocityEngineFactory.java @@ -90,284 +90,284 @@ import org.springframework.util.StringUtils; */ public class VelocityEngineFactory { - protected final Log logger = LogFactory.getLog(getClass()); + protected final Log logger = LogFactory.getLog(getClass()); - private Resource configLocation; + private Resource configLocation; - private final Map velocityProperties = new HashMap(); + private final Map velocityProperties = new HashMap(); - private String resourceLoaderPath; + private String resourceLoaderPath; - private ResourceLoader resourceLoader = new DefaultResourceLoader(); + private ResourceLoader resourceLoader = new DefaultResourceLoader(); - private boolean preferFileSystemAccess = true; + private boolean preferFileSystemAccess = true; - private boolean overrideLogging = true; + private boolean overrideLogging = true; - /** - * Set the location of the Velocity config file. - * Alternatively, you can specify all properties locally. - * @see #setVelocityProperties - * @see #setResourceLoaderPath - */ - public void setConfigLocation(Resource configLocation) { - this.configLocation = configLocation; - } + /** + * Set the location of the Velocity config file. + * Alternatively, you can specify all properties locally. + * @see #setVelocityProperties + * @see #setResourceLoaderPath + */ + public void setConfigLocation(Resource configLocation) { + this.configLocation = configLocation; + } - /** - * Set Velocity properties, like "file.resource.loader.path". - * Can be used to override values in a Velocity config file, - * or to specify all necessary properties locally. - *

Note that the Velocity resource loader path also be set to any - * Spring resource location via the "resourceLoaderPath" property. - * Setting it here is just necessary when using a non-file-based - * resource loader. - * @see #setVelocityPropertiesMap - * @see #setConfigLocation - * @see #setResourceLoaderPath - */ - public void setVelocityProperties(Properties velocityProperties) { - CollectionUtils.mergePropertiesIntoMap(velocityProperties, this.velocityProperties); - } + /** + * Set Velocity properties, like "file.resource.loader.path". + * Can be used to override values in a Velocity config file, + * or to specify all necessary properties locally. + *

Note that the Velocity resource loader path also be set to any + * Spring resource location via the "resourceLoaderPath" property. + * Setting it here is just necessary when using a non-file-based + * resource loader. + * @see #setVelocityPropertiesMap + * @see #setConfigLocation + * @see #setResourceLoaderPath + */ + public void setVelocityProperties(Properties velocityProperties) { + CollectionUtils.mergePropertiesIntoMap(velocityProperties, this.velocityProperties); + } - /** - * Set Velocity properties as Map, to allow for non-String values - * like "ds.resource.loader.instance". - * @see #setVelocityProperties - */ - public void setVelocityPropertiesMap(Map velocityPropertiesMap) { - if (velocityPropertiesMap != null) { - this.velocityProperties.putAll(velocityPropertiesMap); - } - } + /** + * Set Velocity properties as Map, to allow for non-String values + * like "ds.resource.loader.instance". + * @see #setVelocityProperties + */ + public void setVelocityPropertiesMap(Map velocityPropertiesMap) { + if (velocityPropertiesMap != null) { + this.velocityProperties.putAll(velocityPropertiesMap); + } + } - /** - * Set the Velocity resource loader path via a Spring resource location. - * Accepts multiple locations in Velocity's comma-separated path style. - *

When populated via a String, standard URLs like "file:" and "classpath:" - * pseudo URLs are supported, as understood by ResourceLoader. Allows for - * relative paths when running in an ApplicationContext. - *

Will define a path for the default Velocity resource loader with the name - * "file". If the specified resource cannot be resolved to a {@code java.io.File}, - * a generic SpringResourceLoader will be used under the name "spring", without - * modification detection. - *

Note that resource caching will be enabled in any case. With the file - * resource loader, the last-modified timestamp will be checked on access to - * detect changes. With SpringResourceLoader, the resource will be cached - * forever (for example for class path resources). - *

To specify a modification check interval for files, use Velocity's - * standard "file.resource.loader.modificationCheckInterval" property. By default, - * the file timestamp is checked on every access (which is surprisingly fast). - * Of course, this just applies when loading resources from the file system. - *

To enforce the use of SpringResourceLoader, i.e. to not resolve a path - * as file system resource in any case, turn off the "preferFileSystemAccess" - * flag. See the latter's javadoc for details. - * @see #setResourceLoader - * @see #setVelocityProperties - * @see #setPreferFileSystemAccess - * @see SpringResourceLoader - * @see org.apache.velocity.runtime.resource.loader.FileResourceLoader - */ - public void setResourceLoaderPath(String resourceLoaderPath) { - this.resourceLoaderPath = resourceLoaderPath; - } + /** + * Set the Velocity resource loader path via a Spring resource location. + * Accepts multiple locations in Velocity's comma-separated path style. + *

When populated via a String, standard URLs like "file:" and "classpath:" + * pseudo URLs are supported, as understood by ResourceLoader. Allows for + * relative paths when running in an ApplicationContext. + *

Will define a path for the default Velocity resource loader with the name + * "file". If the specified resource cannot be resolved to a {@code java.io.File}, + * a generic SpringResourceLoader will be used under the name "spring", without + * modification detection. + *

Note that resource caching will be enabled in any case. With the file + * resource loader, the last-modified timestamp will be checked on access to + * detect changes. With SpringResourceLoader, the resource will be cached + * forever (for example for class path resources). + *

To specify a modification check interval for files, use Velocity's + * standard "file.resource.loader.modificationCheckInterval" property. By default, + * the file timestamp is checked on every access (which is surprisingly fast). + * Of course, this just applies when loading resources from the file system. + *

To enforce the use of SpringResourceLoader, i.e. to not resolve a path + * as file system resource in any case, turn off the "preferFileSystemAccess" + * flag. See the latter's javadoc for details. + * @see #setResourceLoader + * @see #setVelocityProperties + * @see #setPreferFileSystemAccess + * @see SpringResourceLoader + * @see org.apache.velocity.runtime.resource.loader.FileResourceLoader + */ + public void setResourceLoaderPath(String resourceLoaderPath) { + this.resourceLoaderPath = resourceLoaderPath; + } - /** - * Set the Spring ResourceLoader to use for loading Velocity template files. - * The default is DefaultResourceLoader. Will get overridden by the - * ApplicationContext if running in a context. - * @see org.springframework.core.io.DefaultResourceLoader - * @see org.springframework.context.ApplicationContext - */ - public void setResourceLoader(ResourceLoader resourceLoader) { - this.resourceLoader = resourceLoader; - } + /** + * Set the Spring ResourceLoader to use for loading Velocity template files. + * The default is DefaultResourceLoader. Will get overridden by the + * ApplicationContext if running in a context. + * @see org.springframework.core.io.DefaultResourceLoader + * @see org.springframework.context.ApplicationContext + */ + public void setResourceLoader(ResourceLoader resourceLoader) { + this.resourceLoader = resourceLoader; + } - /** - * Return the Spring ResourceLoader to use for loading Velocity template files. - */ - protected ResourceLoader getResourceLoader() { - return this.resourceLoader; - } + /** + * Return the Spring ResourceLoader to use for loading Velocity template files. + */ + protected ResourceLoader getResourceLoader() { + return this.resourceLoader; + } - /** - * Set whether to prefer file system access for template loading. - * File system access enables hot detection of template changes. - *

If this is enabled, VelocityEngineFactory will try to resolve the - * specified "resourceLoaderPath" as file system resource (which will work - * for expanded class path resources and ServletContext resources too). - *

Default is "true". Turn this off to always load via SpringResourceLoader - * (i.e. as stream, without hot detection of template changes), which might - * be necessary if some of your templates reside in an expanded classes - * directory while others reside in jar files. - * @see #setResourceLoaderPath - */ - public void setPreferFileSystemAccess(boolean preferFileSystemAccess) { - this.preferFileSystemAccess = preferFileSystemAccess; - } + /** + * Set whether to prefer file system access for template loading. + * File system access enables hot detection of template changes. + *

If this is enabled, VelocityEngineFactory will try to resolve the + * specified "resourceLoaderPath" as file system resource (which will work + * for expanded class path resources and ServletContext resources too). + *

Default is "true". Turn this off to always load via SpringResourceLoader + * (i.e. as stream, without hot detection of template changes), which might + * be necessary if some of your templates reside in an expanded classes + * directory while others reside in jar files. + * @see #setResourceLoaderPath + */ + public void setPreferFileSystemAccess(boolean preferFileSystemAccess) { + this.preferFileSystemAccess = preferFileSystemAccess; + } - /** - * Return whether to prefer file system access for template loading. - */ - protected boolean isPreferFileSystemAccess() { - return this.preferFileSystemAccess; - } + /** + * Return whether to prefer file system access for template loading. + */ + protected boolean isPreferFileSystemAccess() { + return this.preferFileSystemAccess; + } - /** - * Set whether Velocity should log via Commons Logging, i.e. whether Velocity's - * log system should be set to {@link CommonsLogLogChute}. Default is "true". - */ - public void setOverrideLogging(boolean overrideLogging) { - this.overrideLogging = overrideLogging; - } + /** + * Set whether Velocity should log via Commons Logging, i.e. whether Velocity's + * log system should be set to {@link CommonsLogLogChute}. Default is "true". + */ + public void setOverrideLogging(boolean overrideLogging) { + this.overrideLogging = overrideLogging; + } - /** - * Prepare the VelocityEngine instance and return it. - * @return the VelocityEngine instance - * @throws IOException if the config file wasn't found - * @throws VelocityException on Velocity initialization failure - */ - public VelocityEngine createVelocityEngine() throws IOException, VelocityException { - VelocityEngine velocityEngine = newVelocityEngine(); - Map props = new HashMap(); + /** + * Prepare the VelocityEngine instance and return it. + * @return the VelocityEngine instance + * @throws IOException if the config file wasn't found + * @throws VelocityException on Velocity initialization failure + */ + public VelocityEngine createVelocityEngine() throws IOException, VelocityException { + VelocityEngine velocityEngine = newVelocityEngine(); + Map props = new HashMap(); - // Load config file if set. - if (this.configLocation != null) { - if (logger.isInfoEnabled()) { - logger.info("Loading Velocity config from [" + this.configLocation + "]"); - } - CollectionUtils.mergePropertiesIntoMap(PropertiesLoaderUtils.loadProperties(this.configLocation), props); - } + // Load config file if set. + if (this.configLocation != null) { + if (logger.isInfoEnabled()) { + logger.info("Loading Velocity config from [" + this.configLocation + "]"); + } + CollectionUtils.mergePropertiesIntoMap(PropertiesLoaderUtils.loadProperties(this.configLocation), props); + } - // Merge local properties if set. - if (!this.velocityProperties.isEmpty()) { - props.putAll(this.velocityProperties); - } + // Merge local properties if set. + if (!this.velocityProperties.isEmpty()) { + props.putAll(this.velocityProperties); + } - // Set a resource loader path, if required. - if (this.resourceLoaderPath != null) { - initVelocityResourceLoader(velocityEngine, this.resourceLoaderPath); - } + // Set a resource loader path, if required. + if (this.resourceLoaderPath != null) { + initVelocityResourceLoader(velocityEngine, this.resourceLoaderPath); + } - // Log via Commons Logging? - if (this.overrideLogging) { - velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new CommonsLogLogChute()); - } + // Log via Commons Logging? + if (this.overrideLogging) { + velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new CommonsLogLogChute()); + } - // Apply properties to VelocityEngine. - for (Map.Entry entry : props.entrySet()) { - velocityEngine.setProperty(entry.getKey(), entry.getValue()); - } + // Apply properties to VelocityEngine. + for (Map.Entry entry : props.entrySet()) { + velocityEngine.setProperty(entry.getKey(), entry.getValue()); + } - postProcessVelocityEngine(velocityEngine); + postProcessVelocityEngine(velocityEngine); - // Perform actual initialization. - velocityEngine.init(); + // Perform actual initialization. + velocityEngine.init(); - return velocityEngine; - } + return velocityEngine; + } - /** - * Return a new VelocityEngine. Subclasses can override this for - * custom initialization, or for using a mock object for testing. - *

Called by {@code createVelocityEngine()}. - * @return the VelocityEngine instance - * @throws IOException if a config file wasn't found - * @throws VelocityException on Velocity initialization failure - * @see #createVelocityEngine() - */ - protected VelocityEngine newVelocityEngine() throws IOException, VelocityException { - return new VelocityEngine(); - } + /** + * Return a new VelocityEngine. Subclasses can override this for + * custom initialization, or for using a mock object for testing. + *

Called by {@code createVelocityEngine()}. + * @return the VelocityEngine instance + * @throws IOException if a config file wasn't found + * @throws VelocityException on Velocity initialization failure + * @see #createVelocityEngine() + */ + protected VelocityEngine newVelocityEngine() throws IOException, VelocityException { + return new VelocityEngine(); + } - /** - * Initialize a Velocity resource loader for the given VelocityEngine: - * either a standard Velocity FileResourceLoader or a SpringResourceLoader. - *

Called by {@code createVelocityEngine()}. - * @param velocityEngine the VelocityEngine to configure - * @param resourceLoaderPath the path to load Velocity resources from - * @see org.apache.velocity.runtime.resource.loader.FileResourceLoader - * @see SpringResourceLoader - * @see #initSpringResourceLoader - * @see #createVelocityEngine() - */ - protected void initVelocityResourceLoader(VelocityEngine velocityEngine, String resourceLoaderPath) { - if (isPreferFileSystemAccess()) { - // Try to load via the file system, fall back to SpringResourceLoader - // (for hot detection of template changes, if possible). - try { - StringBuilder resolvedPath = new StringBuilder(); - String[] paths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath); - for (int i = 0; i < paths.length; i++) { - String path = paths[i]; - Resource resource = getResourceLoader().getResource(path); - File file = resource.getFile(); // will fail if not resolvable in the file system - if (logger.isDebugEnabled()) { - logger.debug("Resource loader path [" + path + "] resolved to file [" + file.getAbsolutePath() + "]"); - } - resolvedPath.append(file.getAbsolutePath()); - if (i < paths.length - 1) { - resolvedPath.append(','); - } - } - velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file"); - velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, "true"); - velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, resolvedPath.toString()); - } - catch (IOException ex) { - if (logger.isDebugEnabled()) { - logger.debug("Cannot resolve resource loader path [" + resourceLoaderPath + - "] to [java.io.File]: using SpringResourceLoader", ex); - } - initSpringResourceLoader(velocityEngine, resourceLoaderPath); - } - } - else { - // Always load via SpringResourceLoader - // (without hot detection of template changes). - if (logger.isDebugEnabled()) { - logger.debug("File system access not preferred: using SpringResourceLoader"); - } - initSpringResourceLoader(velocityEngine, resourceLoaderPath); - } - } + /** + * Initialize a Velocity resource loader for the given VelocityEngine: + * either a standard Velocity FileResourceLoader or a SpringResourceLoader. + *

Called by {@code createVelocityEngine()}. + * @param velocityEngine the VelocityEngine to configure + * @param resourceLoaderPath the path to load Velocity resources from + * @see org.apache.velocity.runtime.resource.loader.FileResourceLoader + * @see SpringResourceLoader + * @see #initSpringResourceLoader + * @see #createVelocityEngine() + */ + protected void initVelocityResourceLoader(VelocityEngine velocityEngine, String resourceLoaderPath) { + if (isPreferFileSystemAccess()) { + // Try to load via the file system, fall back to SpringResourceLoader + // (for hot detection of template changes, if possible). + try { + StringBuilder resolvedPath = new StringBuilder(); + String[] paths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath); + for (int i = 0; i < paths.length; i++) { + String path = paths[i]; + Resource resource = getResourceLoader().getResource(path); + File file = resource.getFile(); // will fail if not resolvable in the file system + if (logger.isDebugEnabled()) { + logger.debug("Resource loader path [" + path + "] resolved to file [" + file.getAbsolutePath() + "]"); + } + resolvedPath.append(file.getAbsolutePath()); + if (i < paths.length - 1) { + resolvedPath.append(','); + } + } + velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file"); + velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, "true"); + velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, resolvedPath.toString()); + } + catch (IOException ex) { + if (logger.isDebugEnabled()) { + logger.debug("Cannot resolve resource loader path [" + resourceLoaderPath + + "] to [java.io.File]: using SpringResourceLoader", ex); + } + initSpringResourceLoader(velocityEngine, resourceLoaderPath); + } + } + else { + // Always load via SpringResourceLoader + // (without hot detection of template changes). + if (logger.isDebugEnabled()) { + logger.debug("File system access not preferred: using SpringResourceLoader"); + } + initSpringResourceLoader(velocityEngine, resourceLoaderPath); + } + } - /** - * Initialize a SpringResourceLoader for the given VelocityEngine. - *

Called by {@code initVelocityResourceLoader}. - * @param velocityEngine the VelocityEngine to configure - * @param resourceLoaderPath the path to load Velocity resources from - * @see SpringResourceLoader - * @see #initVelocityResourceLoader - */ - protected void initSpringResourceLoader(VelocityEngine velocityEngine, String resourceLoaderPath) { - velocityEngine.setProperty( - RuntimeConstants.RESOURCE_LOADER, SpringResourceLoader.NAME); - velocityEngine.setProperty( - SpringResourceLoader.SPRING_RESOURCE_LOADER_CLASS, SpringResourceLoader.class.getName()); - velocityEngine.setProperty( - SpringResourceLoader.SPRING_RESOURCE_LOADER_CACHE, "true"); - velocityEngine.setApplicationAttribute( - SpringResourceLoader.SPRING_RESOURCE_LOADER, getResourceLoader()); - velocityEngine.setApplicationAttribute( - SpringResourceLoader.SPRING_RESOURCE_LOADER_PATH, resourceLoaderPath); - } + /** + * Initialize a SpringResourceLoader for the given VelocityEngine. + *

Called by {@code initVelocityResourceLoader}. + * @param velocityEngine the VelocityEngine to configure + * @param resourceLoaderPath the path to load Velocity resources from + * @see SpringResourceLoader + * @see #initVelocityResourceLoader + */ + protected void initSpringResourceLoader(VelocityEngine velocityEngine, String resourceLoaderPath) { + velocityEngine.setProperty( + RuntimeConstants.RESOURCE_LOADER, SpringResourceLoader.NAME); + velocityEngine.setProperty( + SpringResourceLoader.SPRING_RESOURCE_LOADER_CLASS, SpringResourceLoader.class.getName()); + velocityEngine.setProperty( + SpringResourceLoader.SPRING_RESOURCE_LOADER_CACHE, "true"); + velocityEngine.setApplicationAttribute( + SpringResourceLoader.SPRING_RESOURCE_LOADER, getResourceLoader()); + velocityEngine.setApplicationAttribute( + SpringResourceLoader.SPRING_RESOURCE_LOADER_PATH, resourceLoaderPath); + } - /** - * To be implemented by subclasses that want to perform custom - * post-processing of the VelocityEngine after this FactoryBean - * performed its default configuration (but before VelocityEngine.init). - *

Called by {@code createVelocityEngine()}. - * @param velocityEngine the current VelocityEngine - * @throws IOException if a config file wasn't found - * @throws VelocityException on Velocity initialization failure - * @see #createVelocityEngine() - * @see org.apache.velocity.app.VelocityEngine#init - */ - protected void postProcessVelocityEngine(VelocityEngine velocityEngine) - throws IOException, VelocityException { - } + /** + * To be implemented by subclasses that want to perform custom + * post-processing of the VelocityEngine after this FactoryBean + * performed its default configuration (but before VelocityEngine.init). + *

Called by {@code createVelocityEngine()}. + * @param velocityEngine the current VelocityEngine + * @throws IOException if a config file wasn't found + * @throws VelocityException on Velocity initialization failure + * @see #createVelocityEngine() + * @see org.apache.velocity.app.VelocityEngine#init + */ + protected void postProcessVelocityEngine(VelocityEngine velocityEngine) + throws IOException, VelocityException { + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/springframework/ui/velocity/VelocityEngineFactoryBean.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/springframework/ui/velocity/VelocityEngineFactoryBean.java index 33ead861c..9237ca87d 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/springframework/ui/velocity/VelocityEngineFactoryBean.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/springframework/ui/velocity/VelocityEngineFactoryBean.java @@ -66,30 +66,30 @@ import org.springframework.context.ResourceLoaderAware; * @deprecated as of Spring 4.3, in favor of FreeMarker */ public class VelocityEngineFactoryBean extends VelocityEngineFactory - implements FactoryBean, InitializingBean, ResourceLoaderAware { + implements FactoryBean, InitializingBean, ResourceLoaderAware { - private VelocityEngine velocityEngine; + private VelocityEngine velocityEngine; - @Override - public void afterPropertiesSet() throws IOException, VelocityException { - this.velocityEngine = createVelocityEngine(); - } + @Override + public void afterPropertiesSet() throws IOException, VelocityException { + this.velocityEngine = createVelocityEngine(); + } - @Override - public VelocityEngine getObject() { - return this.velocityEngine; - } + @Override + public VelocityEngine getObject() { + return this.velocityEngine; + } - @Override - public Class getObjectType() { - return VelocityEngine.class; - } + @Override + public Class getObjectType() { + return VelocityEngine.class; + } - @Override - public boolean isSingleton() { - return true; - } + @Override + public boolean isSingleton() { + return true; + } } diff --git a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/springframework/ui/velocity/VelocityEngineUtils.java b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/springframework/ui/velocity/VelocityEngineUtils.java index c48ab8494..ca0101f3e 100644 --- a/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/springframework/ui/velocity/VelocityEngineUtils.java +++ b/maxkey-protocols/maxkey-protocol-saml-2.0/src/main/java/org/springframework/ui/velocity/VelocityEngineUtils.java @@ -51,82 +51,82 @@ import org.apache.velocity.exception.VelocityException; */ public abstract class VelocityEngineUtils { - /** - * Merge the specified Velocity template with the given model and write - * the result to the given Writer. - * @param velocityEngine VelocityEngine to work with - * @param templateLocation the location of template, relative to Velocity's resource loader path - * @param model the Map that contains model names as keys and model objects as values - * @param writer the Writer to write the result to - * @throws VelocityException if the template wasn't found or rendering failed - * @deprecated Use {@link #mergeTemplate(VelocityEngine, String, String, Map, Writer)} - * instead, following Velocity 1.6's corresponding deprecation in its own API. - */ - public static void mergeTemplate( - VelocityEngine velocityEngine, String templateLocation, Map model, Writer writer) - throws VelocityException { + /** + * Merge the specified Velocity template with the given model and write + * the result to the given Writer. + * @param velocityEngine VelocityEngine to work with + * @param templateLocation the location of template, relative to Velocity's resource loader path + * @param model the Map that contains model names as keys and model objects as values + * @param writer the Writer to write the result to + * @throws VelocityException if the template wasn't found or rendering failed + * @deprecated Use {@link #mergeTemplate(VelocityEngine, String, String, Map, Writer)} + * instead, following Velocity 1.6's corresponding deprecation in its own API. + */ + public static void mergeTemplate( + VelocityEngine velocityEngine, String templateLocation, Map model, Writer writer) + throws VelocityException { - VelocityContext velocityContext = new VelocityContext(model); - velocityEngine.mergeTemplate(templateLocation, velocityContext, writer); - } + VelocityContext velocityContext = new VelocityContext(model); + velocityEngine.mergeTemplate(templateLocation, velocityContext, writer); + } - /** - * Merge the specified Velocity template with the given model and write the result - * to the given Writer. - * @param velocityEngine VelocityEngine to work with - * @param templateLocation the location of template, relative to Velocity's resource loader path - * @param encoding the encoding of the template file - * @param model the Map that contains model names as keys and model objects as values - * @param writer the Writer to write the result to - * @throws VelocityException if the template wasn't found or rendering failed - */ - public static void mergeTemplate( - VelocityEngine velocityEngine, String templateLocation, String encoding, - Map model, Writer writer) throws VelocityException { + /** + * Merge the specified Velocity template with the given model and write the result + * to the given Writer. + * @param velocityEngine VelocityEngine to work with + * @param templateLocation the location of template, relative to Velocity's resource loader path + * @param encoding the encoding of the template file + * @param model the Map that contains model names as keys and model objects as values + * @param writer the Writer to write the result to + * @throws VelocityException if the template wasn't found or rendering failed + */ + public static void mergeTemplate( + VelocityEngine velocityEngine, String templateLocation, String encoding, + Map model, Writer writer) throws VelocityException { - VelocityContext velocityContext = new VelocityContext(model); - velocityEngine.mergeTemplate(templateLocation, encoding, velocityContext, writer); - } + VelocityContext velocityContext = new VelocityContext(model); + velocityEngine.mergeTemplate(templateLocation, encoding, velocityContext, writer); + } - /** - * Merge the specified Velocity template with the given model into a String. - *

When using this method to prepare a text for a mail to be sent with Spring's - * mail support, consider wrapping VelocityException in MailPreparationException. - * @param velocityEngine VelocityEngine to work with - * @param templateLocation the location of template, relative to Velocity's resource loader path - * @param model the Map that contains model names as keys and model objects as values - * @return the result as String - * @throws VelocityException if the template wasn't found or rendering failed - * @see org.springframework.mail.MailPreparationException - * @deprecated Use {@link #mergeTemplateIntoString(VelocityEngine, String, String, Map)} - * instead, following Velocity 1.6's corresponding deprecation in its own API. - */ - public static String mergeTemplateIntoString(VelocityEngine velocityEngine, String templateLocation, - Map model) throws VelocityException { + /** + * Merge the specified Velocity template with the given model into a String. + *

When using this method to prepare a text for a mail to be sent with Spring's + * mail support, consider wrapping VelocityException in MailPreparationException. + * @param velocityEngine VelocityEngine to work with + * @param templateLocation the location of template, relative to Velocity's resource loader path + * @param model the Map that contains model names as keys and model objects as values + * @return the result as String + * @throws VelocityException if the template wasn't found or rendering failed + * @see org.springframework.mail.MailPreparationException + * @deprecated Use {@link #mergeTemplateIntoString(VelocityEngine, String, String, Map)} + * instead, following Velocity 1.6's corresponding deprecation in its own API. + */ + public static String mergeTemplateIntoString(VelocityEngine velocityEngine, String templateLocation, + Map model) throws VelocityException { - StringWriter result = new StringWriter(); - mergeTemplate(velocityEngine, templateLocation, model, result); - return result.toString(); - } + StringWriter result = new StringWriter(); + mergeTemplate(velocityEngine, templateLocation, model, result); + return result.toString(); + } - /** - * Merge the specified Velocity template with the given model into a String. - *

When using this method to prepare a text for a mail to be sent with Spring's - * mail support, consider wrapping VelocityException in MailPreparationException. - * @param velocityEngine VelocityEngine to work with - * @param templateLocation the location of template, relative to Velocity's resource loader path - * @param encoding the encoding of the template file - * @param model the Map that contains model names as keys and model objects as values - * @return the result as String - * @throws VelocityException if the template wasn't found or rendering failed - * @see org.springframework.mail.MailPreparationException - */ - public static String mergeTemplateIntoString(VelocityEngine velocityEngine, String templateLocation, - String encoding, Map model) throws VelocityException { + /** + * Merge the specified Velocity template with the given model into a String. + *

When using this method to prepare a text for a mail to be sent with Spring's + * mail support, consider wrapping VelocityException in MailPreparationException. + * @param velocityEngine VelocityEngine to work with + * @param templateLocation the location of template, relative to Velocity's resource loader path + * @param encoding the encoding of the template file + * @param model the Map that contains model names as keys and model objects as values + * @return the result as String + * @throws VelocityException if the template wasn't found or rendering failed + * @see org.springframework.mail.MailPreparationException + */ + public static String mergeTemplateIntoString(VelocityEngine velocityEngine, String templateLocation, + String encoding, Map model) throws VelocityException { - StringWriter result = new StringWriter(); - mergeTemplate(velocityEngine, templateLocation, encoding, model, result); - return result.toString(); - } + StringWriter result = new StringWriter(); + mergeTemplate(velocityEngine, templateLocation, encoding, model, result); + return result.toString(); + } } diff --git a/maxkey-protocols/maxkey-protocol-tokenbased/src/main/java/org/dromara/maxkey/authz/token/endpoint/TokenBasedAuthorizeEndpoint.java b/maxkey-protocols/maxkey-protocol-tokenbased/src/main/java/org/dromara/maxkey/authz/token/endpoint/TokenBasedAuthorizeEndpoint.java index 415659a2f..737ba953e 100644 --- a/maxkey-protocols/maxkey-protocol-tokenbased/src/main/java/org/dromara/maxkey/authz/token/endpoint/TokenBasedAuthorizeEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-tokenbased/src/main/java/org/dromara/maxkey/authz/token/endpoint/TokenBasedAuthorizeEndpoint.java @@ -55,75 +55,75 @@ import jakarta.servlet.http.HttpServletResponse; @Controller public class TokenBasedAuthorizeEndpoint extends AuthorizeBaseEndpoint{ - static final Logger _logger = LoggerFactory.getLogger(TokenBasedAuthorizeEndpoint.class); - @Autowired - AppsTokenBasedDetailsService tokenBasedDetailsService; + static final Logger _logger = LoggerFactory.getLogger(TokenBasedAuthorizeEndpoint.class); + @Autowired + AppsTokenBasedDetailsService tokenBasedDetailsService; - @Autowired - ApplicationConfig applicationConfig; - - @Operation(summary = "TokenBased认证接口", description = "传递参数应用ID",method="GET") - @RequestMapping("/authz/tokenbased/{id}") - public ModelAndView authorize( - HttpServletRequest request, - HttpServletResponse response, - @PathVariable("id") String id, - @CurrentUser UserInfo currentUser){ - ModelAndView modelAndView=new ModelAndView(); - - - AppsTokenBasedDetails tokenBasedDetails=null; - tokenBasedDetails=tokenBasedDetailsService.getAppDetails(id , true); - _logger.debug(""+tokenBasedDetails); - - Apps application= getApp(id); - tokenBasedDetails.setAdapter(application.getAdapter()); - tokenBasedDetails.setIsAdapter(application.getIsAdapter()); - - AbstractAuthorizeAdapter adapter; - if(ConstsBoolean.isTrue(tokenBasedDetails.getIsAdapter())){ - adapter =(AbstractAuthorizeAdapter)Instance.newInstance(tokenBasedDetails.getAdapter()); - }else{ - adapter =(AbstractAuthorizeAdapter)new TokenBasedDefaultAdapter(); - } - adapter.setPrincipal(AuthorizationUtils.getPrincipal()); - adapter.setApp(tokenBasedDetails); - - adapter.generateInfo(); - - adapter.encrypt( - null, - tokenBasedDetails.getAlgorithmKey(), - tokenBasedDetails.getAlgorithm()); - - if(tokenBasedDetails.getTokenType().equalsIgnoreCase("POST")) { - return adapter.authorize(modelAndView); - }else { - _logger.debug("Cookie Name : {}" ,tokenBasedDetails.getCookieName()); - - Cookie cookie= new Cookie(tokenBasedDetails.getCookieName(),adapter.serialize()); - - Integer maxAge = tokenBasedDetails.getExpires(); - _logger.debug("Cookie Max Age : {} seconds.",maxAge); - cookie.setMaxAge(maxAge); - - cookie.setPath("/"); - // - //cookie.setDomain("."+applicationConfig.getBaseDomainName()); - //tomcat 8.5 - cookie.setDomain(applicationConfig.getBaseDomainName()); - - _logger.debug("Sub Domain Name : .{}",applicationConfig.getBaseDomainName()); - response.addCookie(cookie); - - if(tokenBasedDetails.getRedirectUri().indexOf(applicationConfig.getBaseDomainName())>-1){ - return WebContext.redirect(tokenBasedDetails.getRedirectUri()); - }else{ - _logger.error(tokenBasedDetails.getRedirectUri()+" not in domain "+applicationConfig.getBaseDomainName()); - return null; - } - } - - } + @Autowired + ApplicationConfig applicationConfig; + + @Operation(summary = "TokenBased认证接口", description = "传递参数应用ID",method="GET") + @RequestMapping("/authz/tokenbased/{id}") + public ModelAndView authorize( + HttpServletRequest request, + HttpServletResponse response, + @PathVariable("id") String id, + @CurrentUser UserInfo currentUser){ + ModelAndView modelAndView=new ModelAndView(); + + + AppsTokenBasedDetails tokenBasedDetails=null; + tokenBasedDetails=tokenBasedDetailsService.getAppDetails(id , true); + _logger.debug(""+tokenBasedDetails); + + Apps application= getApp(id); + tokenBasedDetails.setAdapter(application.getAdapter()); + tokenBasedDetails.setIsAdapter(application.getIsAdapter()); + + AbstractAuthorizeAdapter adapter; + if(ConstsBoolean.isTrue(tokenBasedDetails.getIsAdapter())){ + adapter =(AbstractAuthorizeAdapter)Instance.newInstance(tokenBasedDetails.getAdapter()); + }else{ + adapter =(AbstractAuthorizeAdapter)new TokenBasedDefaultAdapter(); + } + adapter.setPrincipal(AuthorizationUtils.getPrincipal()); + adapter.setApp(tokenBasedDetails); + + adapter.generateInfo(); + + adapter.encrypt( + null, + tokenBasedDetails.getAlgorithmKey(), + tokenBasedDetails.getAlgorithm()); + + if(tokenBasedDetails.getTokenType().equalsIgnoreCase("POST")) { + return adapter.authorize(modelAndView); + }else { + _logger.debug("Cookie Name : {}" ,tokenBasedDetails.getCookieName()); + + Cookie cookie= new Cookie(tokenBasedDetails.getCookieName(),adapter.serialize()); + + Integer maxAge = tokenBasedDetails.getExpires(); + _logger.debug("Cookie Max Age : {} seconds.",maxAge); + cookie.setMaxAge(maxAge); + + cookie.setPath("/"); + // + //cookie.setDomain("."+applicationConfig.getBaseDomainName()); + //tomcat 8.5 + cookie.setDomain(applicationConfig.getBaseDomainName()); + + _logger.debug("Sub Domain Name : .{}",applicationConfig.getBaseDomainName()); + response.addCookie(cookie); + + if(tokenBasedDetails.getRedirectUri().indexOf(applicationConfig.getBaseDomainName())>-1){ + return WebContext.redirect(tokenBasedDetails.getRedirectUri()); + }else{ + _logger.error(tokenBasedDetails.getRedirectUri()+" not in domain "+applicationConfig.getBaseDomainName()); + return null; + } + } + + } } diff --git a/maxkey-protocols/maxkey-protocol-tokenbased/src/main/java/org/dromara/maxkey/authz/token/endpoint/adapter/TokenBasedDefaultAdapter.java b/maxkey-protocols/maxkey-protocol-tokenbased/src/main/java/org/dromara/maxkey/authz/token/endpoint/adapter/TokenBasedDefaultAdapter.java index f51ef8eba..785c70eb0 100644 --- a/maxkey-protocols/maxkey-protocol-tokenbased/src/main/java/org/dromara/maxkey/authz/token/endpoint/adapter/TokenBasedDefaultAdapter.java +++ b/maxkey-protocols/maxkey-protocol-tokenbased/src/main/java/org/dromara/maxkey/authz/token/endpoint/adapter/TokenBasedDefaultAdapter.java @@ -32,89 +32,89 @@ import org.slf4j.LoggerFactory; import org.springframework.web.servlet.ModelAndView; public class TokenBasedDefaultAdapter extends AbstractAuthorizeAdapter { - static final Logger _logger = LoggerFactory.getLogger(TokenBasedDefaultAdapter.class); - String token = ""; - - @Override - public Object generateInfo() { - AppsTokenBasedDetails details=(AppsTokenBasedDetails)app; - HashMap beanMap=new HashMap(); - - beanMap.put("randomId",(new StringGenerator()).uuidGenerate()); - if(details.getUserPropertys()!=null && !details.getUserPropertys().equals("")) { - - if(details.getUserPropertys().indexOf("userId")>-1){ + static final Logger _logger = LoggerFactory.getLogger(TokenBasedDefaultAdapter.class); + String token = ""; + + @Override + public Object generateInfo() { + AppsTokenBasedDetails details=(AppsTokenBasedDetails)app; + HashMap beanMap=new HashMap(); + + beanMap.put("randomId",(new StringGenerator()).uuidGenerate()); + if(details.getUserPropertys()!=null && !details.getUserPropertys().equals("")) { + + if(details.getUserPropertys().indexOf("userId")>-1){ beanMap.put("userId",userInfo.getId()); } - - if(details.getUserPropertys().indexOf("username")>-1){ + + if(details.getUserPropertys().indexOf("username")>-1){ beanMap.put("username",userInfo.getUsername()); } - - if(details.getUserPropertys().indexOf("email")>-1){ + + if(details.getUserPropertys().indexOf("email")>-1){ beanMap.put("email",userInfo.getEmail()); } - - if(details.getUserPropertys().indexOf("windowsAccount")>-1){ + + if(details.getUserPropertys().indexOf("windowsAccount")>-1){ beanMap.put("windowsAccount",userInfo.getWindowsAccount()); } - - if(details.getUserPropertys().indexOf("employeeNumber")>-1){ + + if(details.getUserPropertys().indexOf("employeeNumber")>-1){ beanMap.put("employeeNumber",userInfo.getEmployeeNumber()); } - - if(details.getUserPropertys().indexOf("department")>-1){ + + if(details.getUserPropertys().indexOf("department")>-1){ beanMap.put("department",userInfo.getDepartment()); } - - if(details.getUserPropertys().indexOf("departmentId")>-1){ + + if(details.getUserPropertys().indexOf("departmentId")>-1){ beanMap.put("departmentId",userInfo.getDepartmentId()); } - } - - beanMap.put("displayName", userInfo.getDisplayName()); - beanMap.put(WebConstants.ONLINE_TICKET_NAME, principal.getSessionId()); - - /* - * use UTC date time format - * current date plus expires minute - */ - DateTime currentDateTime = DateTime.now(); - Date expirationTime = currentDateTime.plusSeconds(details.getExpires()).toDate(); - String expiresString = DateUtils.toUtc(expirationTime); - _logger.debug("UTC Local current date : "+DateUtils.toUtcLocal(currentDateTime.toDate())); - _logger.debug("UTC current Date : "+DateUtils.toUtc(currentDateTime)); - _logger.debug("UTC expires Date : "+DateUtils.toUtc(currentDateTime)); - - beanMap.put("at", DateUtils.toUtc(currentDateTime)); - - beanMap.put("expires", expiresString); - - token = JsonUtils.toString(beanMap); - _logger.debug("Token : {}",token); - - return token; - } + } + + beanMap.put("displayName", userInfo.getDisplayName()); + beanMap.put(WebConstants.ONLINE_TICKET_NAME, principal.getSessionId()); + + /* + * use UTC date time format + * current date plus expires minute + */ + DateTime currentDateTime = DateTime.now(); + Date expirationTime = currentDateTime.plusSeconds(details.getExpires()).toDate(); + String expiresString = DateUtils.toUtc(expirationTime); + _logger.debug("UTC Local current date : "+DateUtils.toUtcLocal(currentDateTime.toDate())); + _logger.debug("UTC current Date : "+DateUtils.toUtc(currentDateTime)); + _logger.debug("UTC expires Date : "+DateUtils.toUtc(currentDateTime)); + + beanMap.put("at", DateUtils.toUtc(currentDateTime)); + + beanMap.put("expires", expiresString); + + token = JsonUtils.toString(beanMap); + _logger.debug("Token : {}",token); + + return token; + } - @Override - public Object encrypt(Object data, String algorithmKey, String algorithm) { - token = super.encrypt(token, algorithmKey, algorithm).toString(); - return token; - } + @Override + public Object encrypt(Object data, String algorithmKey, String algorithm) { + token = super.encrypt(token, algorithmKey, algorithm).toString(); + return token; + } - @Override - public ModelAndView authorize(ModelAndView modelAndView) { - modelAndView.setViewName("authorize/tokenbased_sso_submint"); - AppsTokenBasedDetails details=(AppsTokenBasedDetails)app; - modelAndView.addObject("action", details.getRedirectUri()); - - modelAndView.addObject("token",token ); - return modelAndView; - } + @Override + public ModelAndView authorize(ModelAndView modelAndView) { + modelAndView.setViewName("authorize/tokenbased_sso_submint"); + AppsTokenBasedDetails details=(AppsTokenBasedDetails)app; + modelAndView.addObject("action", details.getRedirectUri()); + + modelAndView.addObject("token",token ); + return modelAndView; + } - @Override - public String serialize() { - return token; - } - + @Override + public String serialize() { + return token; + } + } diff --git a/maxkey-protocols/maxkey-protocol-tokenbased/src/main/java/org/dromara/maxkey/authz/token/endpoint/adapter/TokenBasedSimpleAdapter.java b/maxkey-protocols/maxkey-protocol-tokenbased/src/main/java/org/dromara/maxkey/authz/token/endpoint/adapter/TokenBasedSimpleAdapter.java index 75ad266ca..521424812 100644 --- a/maxkey-protocols/maxkey-protocol-tokenbased/src/main/java/org/dromara/maxkey/authz/token/endpoint/adapter/TokenBasedSimpleAdapter.java +++ b/maxkey-protocols/maxkey-protocol-tokenbased/src/main/java/org/dromara/maxkey/authz/token/endpoint/adapter/TokenBasedSimpleAdapter.java @@ -27,66 +27,66 @@ import org.slf4j.LoggerFactory; import org.springframework.web.servlet.ModelAndView; public class TokenBasedSimpleAdapter extends AbstractAuthorizeAdapter { - static final Logger _logger = LoggerFactory.getLogger(TokenBasedSimpleAdapter.class); - String token = ""; - - @Override - public Object generateInfo() { - AppsTokenBasedDetails details=(AppsTokenBasedDetails)app; - - String tokenUsername = userInfo.getUsername(); - - if(details.getUserPropertys()!=null && !details.getUserPropertys().equals("")) { - if(details.getUserPropertys().indexOf("userId")>-1){ - tokenUsername=userInfo.getId(); - }else if(details.getUserPropertys().indexOf("username")>-1){ - tokenUsername= userInfo.getUsername(); - }else if(details.getUserPropertys().indexOf("email")>-1){ - tokenUsername=userInfo.getEmail(); - }else if(details.getUserPropertys().indexOf("windowsAccount")>-1){ - tokenUsername= userInfo.getWindowsAccount(); - }else if(details.getUserPropertys().indexOf("employeeNumber")>-1){ - tokenUsername=userInfo.getEmployeeNumber(); - }else if(details.getUserPropertys().indexOf("department")>-1){ - tokenUsername= userInfo.getDepartmentId(); - }else if(details.getUserPropertys().indexOf("departmentId")>-1){ + static final Logger _logger = LoggerFactory.getLogger(TokenBasedSimpleAdapter.class); + String token = ""; + + @Override + public Object generateInfo() { + AppsTokenBasedDetails details=(AppsTokenBasedDetails)app; + + String tokenUsername = userInfo.getUsername(); + + if(details.getUserPropertys()!=null && !details.getUserPropertys().equals("")) { + if(details.getUserPropertys().indexOf("userId")>-1){ + tokenUsername=userInfo.getId(); + }else if(details.getUserPropertys().indexOf("username")>-1){ + tokenUsername= userInfo.getUsername(); + }else if(details.getUserPropertys().indexOf("email")>-1){ + tokenUsername=userInfo.getEmail(); + }else if(details.getUserPropertys().indexOf("windowsAccount")>-1){ + tokenUsername= userInfo.getWindowsAccount(); + }else if(details.getUserPropertys().indexOf("employeeNumber")>-1){ + tokenUsername=userInfo.getEmployeeNumber(); + }else if(details.getUserPropertys().indexOf("department")>-1){ + tokenUsername= userInfo.getDepartmentId(); + }else if(details.getUserPropertys().indexOf("departmentId")>-1){ tokenUsername= userInfo.getDepartment(); } - } + } - /* - * use UTC date time format - */ - Date currentDate=new Date(); - _logger.debug("UTC Local current date : "+DateUtils.toUtcLocal(currentDate)); - _logger.debug("UTC current Date : "+DateUtils.toUtc(currentDate)); - - - token = tokenUsername+"@@"+DateUtils.toUtc(currentDate); - _logger.debug("Token : {}",token); - - return token; - } + /* + * use UTC date time format + */ + Date currentDate=new Date(); + _logger.debug("UTC Local current date : "+DateUtils.toUtcLocal(currentDate)); + _logger.debug("UTC current Date : "+DateUtils.toUtc(currentDate)); + + + token = tokenUsername+"@@"+DateUtils.toUtc(currentDate); + _logger.debug("Token : {}",token); + + return token; + } - @Override - public Object encrypt(Object data, String algorithmKey, String algorithm) { - token = super.encrypt(token, algorithmKey, algorithm).toString(); - return token; - } + @Override + public Object encrypt(Object data, String algorithmKey, String algorithm) { + token = super.encrypt(token, algorithmKey, algorithm).toString(); + return token; + } - @Override - public ModelAndView authorize(ModelAndView modelAndView) { - modelAndView.setViewName("authorize/tokenbased_sso_submint"); - AppsTokenBasedDetails details=(AppsTokenBasedDetails)app; - modelAndView.addObject("action", details.getRedirectUri()); - - modelAndView.addObject("token",token); - - return modelAndView; - } + @Override + public ModelAndView authorize(ModelAndView modelAndView) { + modelAndView.setViewName("authorize/tokenbased_sso_submint"); + AppsTokenBasedDetails details=(AppsTokenBasedDetails)app; + modelAndView.addObject("action", details.getRedirectUri()); + + modelAndView.addObject("token",token); + + return modelAndView; + } - @Override - public String serialize() { - return token; - } + @Override + public String serialize() { + return token; + } } diff --git a/maxkey-starter/maxkey-starter-captcha/src/main/java/com/google/code/kaptcha/impl/LightNoise.java b/maxkey-starter/maxkey-starter-captcha/src/main/java/com/google/code/kaptcha/impl/LightNoise.java index e4b32f22f..5ca29cbc3 100644 --- a/maxkey-starter/maxkey-starter-captcha/src/main/java/com/google/code/kaptcha/impl/LightNoise.java +++ b/maxkey-starter/maxkey-starter-captcha/src/main/java/com/google/code/kaptcha/impl/LightNoise.java @@ -37,76 +37,76 @@ import com.google.code.kaptcha.util.Configurable; */ public class LightNoise extends Configurable implements NoiseProducer { - /** - * Draws a noise on the image. The noise curve depends on the factor values. - * Noise won't be visible if all factors have the value > 1.0f - * - * @param image - * the image to add the noise to - * @param factorOne - * @param factorTwo - * @param factorThree - * @param factorFour - */ - @Override - public void makeNoise(BufferedImage image, float factorOne, - float factorTwo, float factorThree, float factorFour) - { - Color color = getConfig().getNoiseColor(); + /** + * Draws a noise on the image. The noise curve depends on the factor values. + * Noise won't be visible if all factors have the value > 1.0f + * + * @param image + * the image to add the noise to + * @param factorOne + * @param factorTwo + * @param factorThree + * @param factorFour + */ + @Override + public void makeNoise(BufferedImage image, float factorOne, + float factorTwo, float factorThree, float factorFour) + { + Color color = getConfig().getNoiseColor(); - // image size - int width = image.getWidth(); - int height = image.getHeight(); + // image size + int width = image.getWidth(); + int height = image.getHeight(); - // the points where the line changes the stroke and direction - Point2D[] pts = null; - Random rand = new SecureRandom(); + // the points where the line changes the stroke and direction + Point2D[] pts = null; + Random rand = new SecureRandom(); - // the curve from where the points are taken - CubicCurve2D cc = new CubicCurve2D.Float(width * factorOne, height - * rand.nextFloat(), width * factorTwo, height - * rand.nextFloat(), width * factorThree, height - * rand.nextFloat(), width * factorFour, height - * rand.nextFloat()); + // the curve from where the points are taken + CubicCurve2D cc = new CubicCurve2D.Float(width * factorOne, height + * rand.nextFloat(), width * factorTwo, height + * rand.nextFloat(), width * factorThree, height + * rand.nextFloat(), width * factorFour, height + * rand.nextFloat()); - // creates an iterator to define the boundary of the flattened curve - PathIterator pi = cc.getPathIterator(null, 2); - Point2D tmp[] = new Point2D[200]; - int i = 0; + // creates an iterator to define the boundary of the flattened curve + PathIterator pi = cc.getPathIterator(null, 2); + Point2D tmp[] = new Point2D[200]; + int i = 0; - // while pi is iterating the curve, adds points to tmp array - while (!pi.isDone()) - { - float[] coords = new float[6]; - switch (pi.currentSegment(coords)){ - case PathIterator.SEG_MOVETO,PathIterator.SEG_LINETO:{ - tmp[i] = new Point2D.Float(coords[0], coords[1]); - } - } - i++; - pi.next(); - } + // while pi is iterating the curve, adds points to tmp array + while (!pi.isDone()) + { + float[] coords = new float[6]; + switch (pi.currentSegment(coords)){ + case PathIterator.SEG_MOVETO,PathIterator.SEG_LINETO:{ + tmp[i] = new Point2D.Float(coords[0], coords[1]); + } + } + i++; + pi.next(); + } - pts = new Point2D[i]; - System.arraycopy(tmp, 0, pts, 0, i); + pts = new Point2D[i]; + System.arraycopy(tmp, 0, pts, 0, i); - Graphics2D graph = (Graphics2D) image.getGraphics(); - graph.setRenderingHints(new RenderingHints( - RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON)); + Graphics2D graph = (Graphics2D) image.getGraphics(); + graph.setRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); - graph.setColor(color); + graph.setColor(color); - // for the maximum 3 point change the stroke and direction - for (i = 0; i < pts.length - 1; i++) - { - if (i < 3) { - graph.setStroke(new BasicStroke(0.7f * (2 - i))); - } - graph.drawLine((int) pts[i].getX(), (int) pts[i].getY(), - (int) pts[i + 1].getX(), (int) pts[i + 1].getY()); - } + // for the maximum 3 point change the stroke and direction + for (i = 0; i < pts.length - 1; i++) + { + if (i < 3) { + graph.setStroke(new BasicStroke(0.7f * (2 - i))); + } + graph.drawLine((int) pts[i].getX(), (int) pts[i].getY(), + (int) pts[i + 1].getX(), (int) pts[i + 1].getY()); + } - graph.dispose(); - } + graph.dispose(); + } } diff --git a/maxkey-starter/maxkey-starter-captcha/src/main/java/com/google/code/kaptcha/impl/Ripple.java b/maxkey-starter/maxkey-starter-captcha/src/main/java/com/google/code/kaptcha/impl/Ripple.java index cbc503691..0da5e8b61 100644 --- a/maxkey-starter/maxkey-starter-captcha/src/main/java/com/google/code/kaptcha/impl/Ripple.java +++ b/maxkey-starter/maxkey-starter-captcha/src/main/java/com/google/code/kaptcha/impl/Ripple.java @@ -31,37 +31,37 @@ import com.jhlabs.image.TransformFilter; */ public class Ripple extends Configurable implements GimpyEngine { - /** - * Applies distortion by adding water ripple effect. - * - * @param baseImage the base image - * @return the distorted image - */ - @Override - public BufferedImage getDistortedImage(BufferedImage baseImage) - { - NoiseProducer noiseProducer = getConfig().getNoiseImpl(); - BufferedImage distortedImage = new BufferedImage(baseImage.getWidth(), - baseImage.getHeight(), BufferedImage.TYPE_INT_ARGB); + /** + * Applies distortion by adding water ripple effect. + * + * @param baseImage the base image + * @return the distorted image + */ + @Override + public BufferedImage getDistortedImage(BufferedImage baseImage) + { + NoiseProducer noiseProducer = getConfig().getNoiseImpl(); + BufferedImage distortedImage = new BufferedImage(baseImage.getWidth(), + baseImage.getHeight(), BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = (Graphics2D) distortedImage.getGraphics(); + Graphics2D graphics = (Graphics2D) distortedImage.getGraphics(); - RippleFilter rippleFilter = new RippleFilter(); - rippleFilter.setWaveType(RippleFilter.SINE); - rippleFilter.setXAmplitude(2.6f); - rippleFilter.setYAmplitude(1.7f); - rippleFilter.setXWavelength(15); - rippleFilter.setYWavelength(5); - rippleFilter.setEdgeAction(TransformFilter.NEAREST_NEIGHBOUR); + RippleFilter rippleFilter = new RippleFilter(); + rippleFilter.setWaveType(RippleFilter.SINE); + rippleFilter.setXAmplitude(2.6f); + rippleFilter.setYAmplitude(1.7f); + rippleFilter.setXWavelength(15); + rippleFilter.setYWavelength(5); + rippleFilter.setEdgeAction(TransformFilter.NEAREST_NEIGHBOUR); - BufferedImage effectImage = rippleFilter.filter(baseImage, null); - - graphics.drawImage(effectImage, 0, 0, null, null); + BufferedImage effectImage = rippleFilter.filter(baseImage, null); + + graphics.drawImage(effectImage, 0, 0, null, null); - graphics.dispose(); + graphics.dispose(); - noiseProducer.makeNoise(distortedImage, .1f, .1f, .25f, .25f); - noiseProducer.makeNoise(distortedImage, .1f, .25f, .5f, .9f); - return distortedImage; - } + noiseProducer.makeNoise(distortedImage, .1f, .1f, .25f, .25f); + noiseProducer.makeNoise(distortedImage, .1f, .25f, .5f, .9f); + return distortedImage; + } } diff --git a/maxkey-starter/maxkey-starter-captcha/src/main/java/com/google/code/kaptcha/impl/UniqueTextCreator.java b/maxkey-starter/maxkey-starter-captcha/src/main/java/com/google/code/kaptcha/impl/UniqueTextCreator.java index 4bbf6007e..e48fc4e70 100644 --- a/maxkey-starter/maxkey-starter-captcha/src/main/java/com/google/code/kaptcha/impl/UniqueTextCreator.java +++ b/maxkey-starter/maxkey-starter-captcha/src/main/java/com/google/code/kaptcha/impl/UniqueTextCreator.java @@ -23,22 +23,22 @@ import com.google.code.kaptcha.text.TextProducer; import com.google.code.kaptcha.util.Configurable; public class UniqueTextCreator extends Configurable implements TextProducer{ - Random rand = new Random(); - - @Override - public String getText() { - int length = getConfig().getTextProducerCharLength(); - char[] chars = getConfig().getTextProducerCharString(); - StringBuffer text = new StringBuffer(); - int i = 0; - while ( i < length){ - char word= chars[rand.nextInt(chars.length)]; - if(text.indexOf(word + "") <= -1 ) { - text.append(word); - i++; - } - } - return text.toString(); - } + Random rand = new Random(); + + @Override + public String getText() { + int length = getConfig().getTextProducerCharLength(); + char[] chars = getConfig().getTextProducerCharString(); + StringBuffer text = new StringBuffer(); + int i = 0; + while ( i < length){ + char word= chars[rand.nextInt(chars.length)]; + if(text.indexOf(word + "") <= -1 ) { + text.append(word); + i++; + } + } + return text.toString(); + } } diff --git a/maxkey-starter/maxkey-starter-captcha/src/main/java/com/google/code/kaptcha/text/impl/RandomColorWordRenderer.java b/maxkey-starter/maxkey-starter-captcha/src/main/java/com/google/code/kaptcha/text/impl/RandomColorWordRenderer.java index 705f7714f..848d73b5b 100644 --- a/maxkey-starter/maxkey-starter-captcha/src/main/java/com/google/code/kaptcha/text/impl/RandomColorWordRenderer.java +++ b/maxkey-starter/maxkey-starter-captcha/src/main/java/com/google/code/kaptcha/text/impl/RandomColorWordRenderer.java @@ -37,117 +37,117 @@ import com.google.code.kaptcha.util.Configurable; */ public class RandomColorWordRenderer extends Configurable implements WordRenderer { - ConfigHelper configHelper = new ConfigHelper(); - - Random random = new SecureRandom(); - - /** - * Renders a word to an image. - * - * @param word - * The word to be rendered. - * @param width - * The width of the image to be created. - * @param height - * The height of the image to be created. - * @return The BufferedImage created from the word. - */ - @Override - public BufferedImage renderWord(String word, int width, int height) - { - int fontSize = getConfig().getTextProducerFontSize(); - Font[] fonts = getConfig().getTextProducerFonts(fontSize); - Color color = getConfig().getTextProducerFontColor(); - int charSpace = getConfig().getTextProducerCharSpace(); - BufferedImage image = new BufferedImage(width, height, - BufferedImage.TYPE_INT_ARGB); - Graphics2D g2D = image.createGraphics(); - g2D.setColor(color); + ConfigHelper configHelper = new ConfigHelper(); + + Random random = new SecureRandom(); + + /** + * Renders a word to an image. + * + * @param word + * The word to be rendered. + * @param width + * The width of the image to be created. + * @param height + * The height of the image to be created. + * @return The BufferedImage created from the word. + */ + @Override + public BufferedImage renderWord(String word, int width, int height) + { + int fontSize = getConfig().getTextProducerFontSize(); + Font[] fonts = getConfig().getTextProducerFonts(fontSize); + Color color = getConfig().getTextProducerFontColor(); + int charSpace = getConfig().getTextProducerCharSpace(); + BufferedImage image = new BufferedImage(width, height, + BufferedImage.TYPE_INT_ARGB); + Graphics2D g2D = image.createGraphics(); + g2D.setColor(color); - RenderingHints hints = new RenderingHints( - RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, - RenderingHints.VALUE_RENDER_QUALITY)); - g2D.setRenderingHints(hints); + RenderingHints hints = new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, + RenderingHints.VALUE_RENDER_QUALITY)); + g2D.setRenderingHints(hints); - FontRenderContext frc = g2D.getFontRenderContext(); - - int startPosY = (height - fontSize) / 5 + fontSize; + FontRenderContext frc = g2D.getFontRenderContext(); + + int startPosY = (height - fontSize) / 5 + fontSize; - char[] wordChars = word.toCharArray(); - Font[] chosenFonts = new Font[wordChars.length]; - int [] charWidths = new int[wordChars.length]; - int widthNeeded = 0; - for (int i = 0; i < wordChars.length; i++){ - //random - chosenFonts[i] = fonts[random.nextInt(fonts.length)]; + char[] wordChars = word.toCharArray(); + Font[] chosenFonts = new Font[wordChars.length]; + int [] charWidths = new int[wordChars.length]; + int widthNeeded = 0; + for (int i = 0; i < wordChars.length; i++){ + //random + chosenFonts[i] = fonts[random.nextInt(fonts.length)]; - char[] charToDraw = new char[]{ - wordChars[i] - }; - GlyphVector gv = chosenFonts[i].createGlyphVector(frc, charToDraw); - charWidths[i] = (int)gv.getVisualBounds().getWidth(); - if (i > 0) - { - widthNeeded = widthNeeded + 2; - } - widthNeeded = widthNeeded + charWidths[i]; - } - - HashMap selectedColor =new HashMap<>(); - int startPosX = (width - widthNeeded) / 2; - - for (int i = 0; i < wordChars.length; i++) - { - String randomcolor=""; - do { - randomcolor=COLOR_LIST[random.nextInt(COLOR_LIST.length)].replace(" ", ""); - }while(selectedColor.containsKey(randomcolor)); - - selectedColor.put(randomcolor, randomcolor); - - color = configHelper.getColor(randomcolor, randomcolor, Color.LIGHT_GRAY); - g2D.setColor(color); - - g2D.setFont(chosenFonts[i]); - - char[] charToDraw = new char[] { - wordChars[i] - }; - - g2D.drawChars(charToDraw, 0, charToDraw.length, startPosX, startPosY); - startPosX = startPosX + (int) charWidths[i] + charSpace; - } - - return image; - } - - static final String [] COLOR_LIST = { - //"255, 255, 255", //white - //"192, 192, 192", //silver - //"128, 128, 128", //gray - "0, 0, 0", //black - "0, 0, 128", //navy - "0, 0, 255", //blue - "0, 128, 0", //green - "0, 128, 128", //teal - "0, 255, 0", //lime - "0, 255, 255", //aqua - "75, 0, 130", //Indigo - "128, 0, 0", //maroon - "128, 0, 128", //purple - "128, 128, 0", //olive - "135, 206, 235", //SkyBlue````` - "165, 42, 42", //Brown - "210, 105, 30", //Chocolate - "255, 0, 0", //red - "255, 0, 255", //fuchsia - "255, 69, 0", //OrangeRed - "255, 127, 80", //Coral - "255, 165, 0", //Orange - "255, 192, 203", //Pink - "255, 215, 0", //Gold - "255, 255, 0", //yellow - }; + char[] charToDraw = new char[]{ + wordChars[i] + }; + GlyphVector gv = chosenFonts[i].createGlyphVector(frc, charToDraw); + charWidths[i] = (int)gv.getVisualBounds().getWidth(); + if (i > 0) + { + widthNeeded = widthNeeded + 2; + } + widthNeeded = widthNeeded + charWidths[i]; + } + + HashMap selectedColor =new HashMap<>(); + int startPosX = (width - widthNeeded) / 2; + + for (int i = 0; i < wordChars.length; i++) + { + String randomcolor=""; + do { + randomcolor=COLOR_LIST[random.nextInt(COLOR_LIST.length)].replace(" ", ""); + }while(selectedColor.containsKey(randomcolor)); + + selectedColor.put(randomcolor, randomcolor); + + color = configHelper.getColor(randomcolor, randomcolor, Color.LIGHT_GRAY); + g2D.setColor(color); + + g2D.setFont(chosenFonts[i]); + + char[] charToDraw = new char[] { + wordChars[i] + }; + + g2D.drawChars(charToDraw, 0, charToDraw.length, startPosX, startPosY); + startPosX = startPosX + (int) charWidths[i] + charSpace; + } + + return image; + } + + static final String [] COLOR_LIST = { + //"255, 255, 255", //white + //"192, 192, 192", //silver + //"128, 128, 128", //gray + "0, 0, 0", //black + "0, 0, 128", //navy + "0, 0, 255", //blue + "0, 128, 0", //green + "0, 128, 128", //teal + "0, 255, 0", //lime + "0, 255, 255", //aqua + "75, 0, 130", //Indigo + "128, 0, 0", //maroon + "128, 0, 128", //purple + "128, 128, 0", //olive + "135, 206, 235", //SkyBlue````` + "165, 42, 42", //Brown + "210, 105, 30", //Chocolate + "255, 0, 0", //red + "255, 0, 255", //fuchsia + "255, 69, 0", //OrangeRed + "255, 127, 80", //Coral + "255, 165, 0", //Orange + "255, 192, 203", //Pink + "255, 215, 0", //Gold + "255, 255, 0", //yellow + }; } diff --git a/maxkey-starter/maxkey-starter-captcha/src/main/java/org/dromara/maxkey/web/contorller/ImageCaptcha.java b/maxkey-starter/maxkey-starter-captcha/src/main/java/org/dromara/maxkey/web/contorller/ImageCaptcha.java index 539a6acc6..5a1e85f21 100644 --- a/maxkey-starter/maxkey-starter-captcha/src/main/java/org/dromara/maxkey/web/contorller/ImageCaptcha.java +++ b/maxkey-starter/maxkey-starter-captcha/src/main/java/org/dromara/maxkey/web/contorller/ImageCaptcha.java @@ -17,35 +17,35 @@ package org.dromara.maxkey.web.contorller; public class ImageCaptcha { - - String state; - - String image; - - public ImageCaptcha(String state, String image) { - super(); - this.state = state; - this.image = image; - } - + + String state; + + String image; + + public ImageCaptcha(String state, String image) { + super(); + this.state = state; + this.image = image; + } + - public String getState() { - return state; - } + public String getState() { + return state; + } - public void setState(String state) { - this.state = state; - } + public void setState(String state) { + this.state = state; + } - public String getImage() { - return image; - } - public void setImage(String image) { - this.image = image; - } - - - + public String getImage() { + return image; + } + public void setImage(String image) { + this.image = image; + } + + + } diff --git a/maxkey-starter/maxkey-starter-captcha/src/main/java/org/dromara/maxkey/web/contorller/ImageCaptchaEndpoint.java b/maxkey-starter/maxkey-starter-captcha/src/main/java/org/dromara/maxkey/web/contorller/ImageCaptchaEndpoint.java index e9629e596..dea382f5d 100644 --- a/maxkey-starter/maxkey-starter-captcha/src/main/java/org/dromara/maxkey/web/contorller/ImageCaptchaEndpoint.java +++ b/maxkey-starter/maxkey-starter-captcha/src/main/java/org/dromara/maxkey/web/contorller/ImageCaptchaEndpoint.java @@ -46,10 +46,10 @@ public class ImageCaptchaEndpoint { Producer captchaProducer; @Autowired - MomentaryService momentaryService; + MomentaryService momentaryService; @Autowired - AuthTokenService authTokenService; + AuthTokenService authTokenService; /** * captcha image Producer. @@ -59,32 +59,32 @@ public class ImageCaptchaEndpoint { */ @GetMapping(value={"/captcha"}, produces = {MediaType.APPLICATION_JSON_VALUE}) public Message captchaHandleRequest( - @RequestParam(value="captcha",required=false,defaultValue="text") String captchaType, - @RequestParam(value="state",required=false,defaultValue="state") String state) { + @RequestParam(value="captcha",required=false,defaultValue="text") String captchaType, + @RequestParam(value="state",required=false,defaultValue="state") String state) { try { String kaptchaText = captchaProducer.createText(); String kaptchaValue = kaptchaText; if (captchaType.equalsIgnoreCase("Arithmetic")) { - //去除0,增加计算复杂度 - kaptchaText = kaptchaText.replace("0", ""); + //去除0,增加计算复杂度 + kaptchaText = kaptchaText.replace("0", ""); Integer minuend = Integer.valueOf(kaptchaText.substring(0, 1)); Integer subtrahend = Integer.valueOf(kaptchaText.substring(1, 2)); if (minuend - subtrahend > 0) { - kaptchaValue = (minuend - subtrahend ) + ""; + kaptchaValue = (minuend - subtrahend ) + ""; kaptchaText = minuend + "-" + subtrahend + "=?"; } else { - kaptchaValue = (minuend + subtrahend) + ""; + kaptchaValue = (minuend + subtrahend) + ""; kaptchaText = minuend + "+" + subtrahend + "=?"; } } String kaptchaKey = ""; if(StringUtils.isNotBlank(state) && !state.equalsIgnoreCase("state")) { - //just validate state Token - if(!authTokenService.validateJwtToken(state)) { - return new Message<>(Message.FAIL,"JwtToken is not Validate "); - } + //just validate state Token + if(!authTokenService.validateJwtToken(state)) { + return new Message<>(Message.FAIL,"JwtToken is not Validate "); + } }else { - state = authTokenService.genRandomJwt(); + state = authTokenService.genRandomJwt(); } kaptchaKey = authTokenService.resolveJWTID(state); _logger.trace("kaptchaKey {} , Captcha Text is {}" ,kaptchaKey, kaptchaValue); @@ -92,7 +92,7 @@ public class ImageCaptchaEndpoint { momentaryService.put("", kaptchaKey, kaptchaValue); // create the image with the text BufferedImage bufferedImage = captchaProducer.createImage(kaptchaText); - String b64Image = Base64Utils.encodeImage(bufferedImage); + String b64Image = Base64Utils.encodeImage(bufferedImage); _logger.trace("b64Image {}" , b64Image); @@ -103,7 +103,7 @@ public class ImageCaptchaEndpoint { return new Message<>(Message.FAIL); } - public void setCaptchaProducer(Producer captchaProducer) { + public void setCaptchaProducer(Producer captchaProducer) { this.captchaProducer = captchaProducer; } diff --git a/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/autoconfigure/IpLocationAutoConfiguration.java b/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/autoconfigure/IpLocationAutoConfiguration.java index ff84dc9e5..71a0b968f 100644 --- a/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/autoconfigure/IpLocationAutoConfiguration.java +++ b/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/autoconfigure/IpLocationAutoConfiguration.java @@ -40,80 +40,80 @@ import com.maxmind.geoip2.DatabaseReader; @AutoConfiguration public class IpLocationAutoConfiguration { - static final Logger _logger = LoggerFactory.getLogger(IpLocationAutoConfiguration.class); - - /** - * 加载Ip2Region离线库数据 version 2.7.0 - * @return Ip2regionV2 - * @throws Exception - */ - public Ip2regionV2 ip2regionV2() throws Exception { - _logger.debug("IpRegion OffLine init..."); - ClassPathResource resource = new ClassPathResource("/ip2region/ip2region.xdb"); + static final Logger _logger = LoggerFactory.getLogger(IpLocationAutoConfiguration.class); + + /** + * 加载Ip2Region离线库数据 version 2.7.0 + * @return Ip2regionV2 + * @throws Exception + */ + public Ip2regionV2 ip2regionV2() throws Exception { + _logger.debug("IpRegion OffLine init..."); + ClassPathResource resource = new ClassPathResource("/ip2region/ip2region.xdb"); byte[] dbBinStr = StreamUtils.copyToByteArray(resource.getInputStream()); _logger.debug("ip2region length {}",dbBinStr.length); Searcher searcher = Searcher.newWithBuffer(dbBinStr); return new Ip2regionV2(searcher); - } - - - /** - * 加载GeoIP2离线库数据 version 4.0.1 - * @return GeoIp2V4 - * @throws Exception - */ - public GeoIP2V4 geoIP2() throws Exception { - _logger.debug("GeoIP2 OffLine init..."); - ClassPathResource resource = new ClassPathResource("/geoip2/GeoLite2-City.mmdb"); - DatabaseReader databaseReader = new DatabaseReader.Builder(resource.getInputStream()).build(); + } + + + /** + * 加载GeoIP2离线库数据 version 4.0.1 + * @return GeoIp2V4 + * @throws Exception + */ + public GeoIP2V4 geoIP2() throws Exception { + _logger.debug("GeoIP2 OffLine init..."); + ClassPathResource resource = new ClassPathResource("/geoip2/GeoLite2-City.mmdb"); + DatabaseReader databaseReader = new DatabaseReader.Builder(resource.getInputStream()).build(); return new GeoIP2V4(databaseReader); - } - - /** - * builder offline provider IpLocation - * @param offlineProvider - * @return IpLocation - */ - public IpLocation builderOfflineProvider(String offlineProvider) { - IpLocation ipLocationOffLine = null; - try { - if(offlineProvider.equalsIgnoreCase("none")) { - //do nothing - _logger.debug("IpLocation offline Provider none"); - }else if(offlineProvider.equalsIgnoreCase("Ip2Region")){ - ipLocationOffLine = ip2regionV2(); - _logger.debug("IpLocation offline Provider Ip2Region"); - }else if(offlineProvider.equalsIgnoreCase("GeoIp2")){ - ipLocationOffLine = geoIP2(); - _logger.debug("IpLocation offline Provider GeoIp2"); - } - }catch(Exception e) { - _logger.error("builder Offline IpLocation error", e); - } - return ipLocationOffLine; - } - + } + + /** + * builder offline provider IpLocation + * @param offlineProvider + * @return IpLocation + */ + public IpLocation builderOfflineProvider(String offlineProvider) { + IpLocation ipLocationOffLine = null; + try { + if(offlineProvider.equalsIgnoreCase("none")) { + //do nothing + _logger.debug("IpLocation offline Provider none"); + }else if(offlineProvider.equalsIgnoreCase("Ip2Region")){ + ipLocationOffLine = ip2regionV2(); + _logger.debug("IpLocation offline Provider Ip2Region"); + }else if(offlineProvider.equalsIgnoreCase("GeoIp2")){ + ipLocationOffLine = geoIP2(); + _logger.debug("IpLocation offline Provider GeoIp2"); + } + }catch(Exception e) { + _logger.error("builder Offline IpLocation error", e); + } + return ipLocationOffLine; + } + - - /** - * IP转换区域地址解析 - * @param isIplocation 是否转换 - * @param onlineProvider 在线转换实现提供商none/Ip138 - * @param offlineProvider 离线转换实现提供商none/Ip2Region/GeoIp2 - * @return IpLocationParser - * @throws Exception - */ - @Bean - IpLocationParser ipLocationParser( - @Value("${maxkey.login.iplocation:true}") boolean isIplocation, - @Value("${maxkey.login.iplocation.online.provider:none}") String onlineProvider, - @Value("${maxkey.login.iplocation.offline.provider:Ip2Region}") String offlineProvider) throws Exception { + + /** + * IP转换区域地址解析 + * @param isIplocation 是否转换 + * @param onlineProvider 在线转换实现提供商none/Ip138 + * @param offlineProvider 离线转换实现提供商none/Ip2Region/GeoIp2 + * @return IpLocationParser + * @throws Exception + */ + @Bean + IpLocationParser ipLocationParser( + @Value("${maxkey.login.iplocation:true}") boolean isIplocation, + @Value("${maxkey.login.iplocation.online.provider:none}") String onlineProvider, + @Value("${maxkey.login.iplocation.offline.provider:Ip2Region}") String offlineProvider) throws Exception { return new IpLocationParser( - isIplocation, - null, - builderOfflineProvider(offlineProvider) - ); - } - + isIplocation, + null, + builderOfflineProvider(offlineProvider) + ); + } + } diff --git a/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/AbstractIpLocation.java b/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/AbstractIpLocation.java index 894430de6..eb7995dcb 100644 --- a/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/AbstractIpLocation.java +++ b/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/AbstractIpLocation.java @@ -25,28 +25,28 @@ package org.dromara.maxkey.ip2location; */ public abstract class AbstractIpLocation implements IpLocation{ - int failCount = 0; - - @Override - public int getFailCount() { - return failCount; - }; - - @Override - public int plusFailCount() { - return failCount++; - }; - - @Override - public String getLocation(String region) { - if(region.endsWith("电信") || region.endsWith("移动") || region.endsWith("联通")) { - region.substring(0, region.length() - 2).trim(); - } - - if(region.indexOf(" ") > 0) { - return region.split(" ")[0]; - } - - return region; - } + int failCount = 0; + + @Override + public int getFailCount() { + return failCount; + }; + + @Override + public int plusFailCount() { + return failCount++; + }; + + @Override + public String getLocation(String region) { + if(region.endsWith("电信") || region.endsWith("移动") || region.endsWith("联通")) { + region.substring(0, region.length() - 2).trim(); + } + + if(region.indexOf(" ") > 0) { + return region.split(" ")[0]; + } + + return region; + } } diff --git a/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/IpLocation.java b/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/IpLocation.java index 808ab816b..0156f61ff 100644 --- a/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/IpLocation.java +++ b/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/IpLocation.java @@ -24,16 +24,16 @@ package org.dromara.maxkey.ip2location; * */ public interface IpLocation { - public static final String USERAGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36"; - - public static final int TIMEOUT = 5000; - - public Region region(String ipAddress); - - public String getLocation(String region); - - public int getFailCount(); - - public int plusFailCount() ; - + public static final String USERAGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36"; + + public static final int TIMEOUT = 5000; + + public Region region(String ipAddress); + + public String getLocation(String region); + + public int getFailCount(); + + public int plusFailCount() ; + } diff --git a/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/IpLocationLocal.java b/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/IpLocationLocal.java index fca29a401..37aaba151 100644 --- a/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/IpLocationLocal.java +++ b/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/IpLocationLocal.java @@ -24,12 +24,12 @@ package org.dromara.maxkey.ip2location; * */ public class IpLocationLocal extends AbstractIpLocation implements IpLocation{ - - @Override - public Region region(String ipAddress) { - if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) { - return new Region("local"); - } - return null; - } + + @Override + public Region region(String ipAddress) { + if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) { + return new Region("local"); + } + return null; + } } diff --git a/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/IpLocationParser.java b/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/IpLocationParser.java index 4a07fc165..aa6882f68 100644 --- a/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/IpLocationParser.java +++ b/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/IpLocationParser.java @@ -27,47 +27,47 @@ package org.dromara.maxkey.ip2location; */ public class IpLocationParser extends AbstractIpLocation implements IpLocation{ - IpLocation ipRegionLocal = new IpLocationLocal(); - - IpLocation ipLocationOnLine; - - IpLocation ipLocationOffLine; - - boolean isIpLocation; + IpLocation ipRegionLocal = new IpLocationLocal(); + + IpLocation ipLocationOnLine; + + IpLocation ipLocationOffLine; + + boolean isIpLocation; - - public IpLocationParser() { - } + + public IpLocationParser() { + } - public IpLocationParser(boolean isIpLocation,IpLocation ipLocationOnLine, IpLocation ipLocationOffLine) { - super(); - this.ipLocationOnLine = ipLocationOnLine; - this.ipLocationOffLine = ipLocationOffLine; - this.isIpLocation = isIpLocation; - } + public IpLocationParser(boolean isIpLocation,IpLocation ipLocationOnLine, IpLocation ipLocationOffLine) { + super(); + this.ipLocationOnLine = ipLocationOnLine; + this.ipLocationOffLine = ipLocationOffLine; + this.isIpLocation = isIpLocation; + } - /** - * ip转换区域地址 - */ - @Override - public Region region(String ipAddress) { - Region region = null; - if( isIpLocation ){//true 需要转换,否则跳过 - //本地转换 - region = ipRegionLocal.region(ipAddress); - //在线转换 - if(ipLocationOnLine != null && region == null) { - region = ipLocationOnLine.region(ipAddress); - } - //离线转换 - if(ipLocationOffLine != null && region == null) { - region = ipLocationOffLine.region(ipAddress); - } - } - //不转换或者未找到返回unknown - return region == null ? new Region("unknown") : region; - } + /** + * ip转换区域地址 + */ + @Override + public Region region(String ipAddress) { + Region region = null; + if( isIpLocation ){//true 需要转换,否则跳过 + //本地转换 + region = ipRegionLocal.region(ipAddress); + //在线转换 + if(ipLocationOnLine != null && region == null) { + region = ipLocationOnLine.region(ipAddress); + } + //离线转换 + if(ipLocationOffLine != null && region == null) { + region = ipLocationOffLine.region(ipAddress); + } + } + //不转换或者未找到返回unknown + return region == null ? new Region("unknown") : region; + } - + } diff --git a/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/Region.java b/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/Region.java index 3dc9d37dd..8bda3228a 100644 --- a/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/Region.java +++ b/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/Region.java @@ -24,88 +24,88 @@ package org.dromara.maxkey.ip2location; * */ public class Region { - - /** - * 国家 - */ - String country; - - /** - * 省/州 - */ - String province; - - /** - * 城市 - */ - String city; - - /** - * 区域位置 - */ - String addr; + + /** + * 国家 + */ + String country; + + /** + * 省/州 + */ + String province; + + /** + * 城市 + */ + String city; + + /** + * 区域位置 + */ + String addr; - public Region() { + public Region() { - } - - public Region(String addr) { - this.addr = addr; - } + } + + public Region(String addr) { + this.addr = addr; + } - public Region(String country, String province, String city, String addr) { - super(); - this.country = country; - this.province = province; - this.city = city; - this.addr = addr; - } + public Region(String country, String province, String city, String addr) { + super(); + this.country = country; + this.province = province; + this.city = city; + this.addr = addr; + } - public String getCountry() { - return country; - } + public String getCountry() { + return country; + } - public void setCountry(String country) { - this.country = country; - } + public void setCountry(String country) { + this.country = country; + } - public String getProvince() { - return province; - } + public String getProvince() { + return province; + } - public void setProvince(String province) { - this.province = province; - } + public void setProvince(String province) { + this.province = province; + } - public String getCity() { - return city; - } + public String getCity() { + return city; + } - public void setCity(String city) { - this.city = city; - } + public void setCity(String city) { + this.city = city; + } - public String getAddr() { - return addr; - } + public String getAddr() { + return addr; + } - public void setAddr(String addr) { - this.addr = addr; - } + public void setAddr(String addr) { + this.addr = addr; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Region [country="); - builder.append(country); - builder.append(", province="); - builder.append(province); - builder.append(", city="); - builder.append(city); - builder.append(", addr="); - builder.append(addr); - builder.append("]"); - return builder.toString(); - } - + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Region [country="); + builder.append(country); + builder.append(", province="); + builder.append(province); + builder.append(", city="); + builder.append(city); + builder.append(", addr="); + builder.append(addr); + builder.append("]"); + return builder.toString(); + } + } diff --git a/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/offline/GeoIP2V4.java b/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/offline/GeoIP2V4.java index 3f3726db5..9b6bb0f2b 100644 --- a/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/offline/GeoIP2V4.java +++ b/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/offline/GeoIP2V4.java @@ -27,19 +27,19 @@ import com.maxmind.geoip2.exception.GeoIp2Exception; import com.maxmind.geoip2.model.CityResponse; public class GeoIP2V4 extends AbstractIpLocation implements IpLocation{ - - DatabaseReader databaseReader; - - public GeoIP2V4(DatabaseReader databaseReader) { - this.databaseReader = databaseReader; - } + + DatabaseReader databaseReader; + + public GeoIP2V4(DatabaseReader databaseReader) { + this.databaseReader = databaseReader; + } - @Override - public Region region(String ipAddress) { + @Override + public Region region(String ipAddress) { try { - //解析IP地址 - InetAddress inetAddress = InetAddress.getByName(ipAddress); - // 获取查询结果 + //解析IP地址 + InetAddress inetAddress = InetAddress.getByName(ipAddress); + // 获取查询结果 CityResponse response = databaseReader.city(inetAddress); // 获取国家信息 String country = response.getCountry().getNames().get("zh-CN"); @@ -48,10 +48,10 @@ public class GeoIP2V4 extends AbstractIpLocation implements IpLocation{ // 获取城市 String city = response.getCity().getNames().get("zh-CN"); return new Region(country , state , city , country +" " + state + " " + city); - } catch (IOException | GeoIp2Exception e) { - e.printStackTrace(); - } - return null; - } + } catch (IOException | GeoIp2Exception e) { + e.printStackTrace(); + } + return null; + } } diff --git a/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/offline/Ip2regionV2.java b/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/offline/Ip2regionV2.java index 004e86542..97744a752 100644 --- a/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/offline/Ip2regionV2.java +++ b/maxkey-starter/maxkey-starter-ip2location/src/main/java/org/dromara/maxkey/ip2location/offline/Ip2regionV2.java @@ -36,26 +36,26 @@ import org.lionsoul.ip2region.xdb.Searcher; * */ public class Ip2regionV2 extends AbstractIpLocation implements IpLocation{ - - Searcher searcher;; - - public Ip2regionV2(Searcher searcher) { - this.searcher = searcher; - } + + Searcher searcher;; + + public Ip2regionV2(Searcher searcher) { + this.searcher = searcher; + } - @Override - public Region region(String ipAddress) { - try { - String regionAddr = searcher.search(ipAddress); - if(regionAddr.indexOf("内网IP")>-1) { - return new Region("内网IP"); - } - String[] regionAddrs =regionAddr.split("\\|"); - return new Region(regionAddrs[0],regionAddrs[2],regionAddrs[3],regionAddrs[0]+regionAddrs[2]+regionAddrs[3]); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - + @Override + public Region region(String ipAddress) { + try { + String regionAddr = searcher.search(ipAddress); + if(regionAddr.indexOf("内网IP")>-1) { + return new Region("内网IP"); + } + String[] regionAddrs =regionAddr.split("\\|"); + return new Region(regionAddrs[0],regionAddrs[2],regionAddrs[3],regionAddrs[0]+regionAddrs[2]+regionAddrs[3]); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + } diff --git a/maxkey-starter/maxkey-starter-ip2location/src/test/java/org/dromara/maxkey/ip2location/Geoip2Test.java b/maxkey-starter/maxkey-starter-ip2location/src/test/java/org/dromara/maxkey/ip2location/Geoip2Test.java index 67a5cb6c5..8327a4b3e 100644 --- a/maxkey-starter/maxkey-starter-ip2location/src/test/java/org/dromara/maxkey/ip2location/Geoip2Test.java +++ b/maxkey-starter/maxkey-starter-ip2location/src/test/java/org/dromara/maxkey/ip2location/Geoip2Test.java @@ -26,11 +26,11 @@ import com.maxmind.geoip2.model.CityResponse; public class Geoip2Test { - public static void main(String[] args) throws IOException { - // TODO Auto-generated method stub - ClassPathResource resource = new ClassPathResource("/geoip2/GeoLite2-City.mmdb"); - String ip = "117.155.70.59"; - + public static void main(String[] args) throws IOException { + // TODO Auto-generated method stub + ClassPathResource resource = new ClassPathResource("/geoip2/GeoLite2-City.mmdb"); + String ip = "117.155.70.59"; + if (!resource.getFile().exists()) { System.out.println("Error: Invalid GeoLite2-City.mmdb file, filePath:" + resource.getFile().getPath()); @@ -49,18 +49,18 @@ public class Geoip2Test { String state = response.getMostSpecificSubdivision().getNames().get("zh-CN"); //查询不到时保持与ip2region方式的返回结果一致 if (state == null){ - state = "0"; + state = "0"; } // 获取城市 String city = response.getCity().getNames().get("zh-CN"); if (city == null){ - city = "0"; + city = "0"; } String[] resu = {state,city}; System.out.println(" " +country+" " +state +" " +city); } catch (IOException | GeoIp2Exception e) { e.printStackTrace(); } - } + } } diff --git a/maxkey-starter/maxkey-starter-ip2location/src/test/java/org/dromara/maxkey/ip2location/Ip2RegionV2Test.java b/maxkey-starter/maxkey-starter-ip2location/src/test/java/org/dromara/maxkey/ip2location/Ip2RegionV2Test.java index b6a14c321..02b04cc56 100644 --- a/maxkey-starter/maxkey-starter-ip2location/src/test/java/org/dromara/maxkey/ip2location/Ip2RegionV2Test.java +++ b/maxkey-starter/maxkey-starter-ip2location/src/test/java/org/dromara/maxkey/ip2location/Ip2RegionV2Test.java @@ -24,10 +24,10 @@ import org.springframework.util.StreamUtils; public class Ip2RegionV2Test { - public static void main(String[] args) throws Exception { - // TODO Auto-generated method stub - String ip ="101.227.131.220"; - ClassPathResource resource = new ClassPathResource("/ip2region/ip2region.xdb"); + public static void main(String[] args) throws Exception { + // TODO Auto-generated method stub + String ip ="101.227.131.220"; + ClassPathResource resource = new ClassPathResource("/ip2region/ip2region.xdb"); byte[] dbBinStr = StreamUtils.copyToByteArray(resource.getInputStream()); System.out.println(dbBinStr.length); //_logger.debug("ip2region length {}",dbBinStr.length); @@ -36,5 +36,5 @@ public class Ip2RegionV2Test { String region = ipRegionV2OffLine.region(ip).toString(); System.out.println(region); - } + } } diff --git a/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/autoconfigure/OneTimePasswordAutoConfiguration.java b/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/autoconfigure/OneTimePasswordAutoConfiguration.java index 48e2cbe60..d6a3978be 100644 --- a/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/autoconfigure/OneTimePasswordAutoConfiguration.java +++ b/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/autoconfigure/OneTimePasswordAutoConfiguration.java @@ -41,7 +41,7 @@ public class OneTimePasswordAutoConfiguration { CnfEmailSendersService emailSendersService, RedisConnectionFactory redisConnFactory) { MailOtpAuthnService otpAuthnService = - new MailOtpAuthnService(emailSendersService); + new MailOtpAuthnService(emailSendersService); if (persistence == ConstsPersistence.REDIS) { RedisOtpTokenStore redisOptTokenStore = new RedisOtpTokenStore(redisConnFactory); @@ -49,7 +49,7 @@ public class OneTimePasswordAutoConfiguration { } _logger.debug("MailOtpAuthnService {} inited." , - persistence == ConstsPersistence.REDIS ? "Redis" : "InMemory"); + persistence == ConstsPersistence.REDIS ? "Redis" : "InMemory"); return otpAuthnService; } diff --git a/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/MailOtpAuthnService.java b/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/MailOtpAuthnService.java index cf6a2caf9..bd07ff74b 100644 --- a/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/MailOtpAuthnService.java +++ b/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/MailOtpAuthnService.java @@ -43,43 +43,43 @@ public class MailOtpAuthnService { RedisOtpTokenStore redisOptTokenStore; public MailOtpAuthnService(CnfEmailSendersService emailSendersService) { - this.emailSendersService = emailSendersService; - } + this.emailSendersService = emailSendersService; + } - public MailOtpAuthnService(RedisOtpTokenStore redisOptTokenStore) { - this.redisOptTokenStore = redisOptTokenStore; - } + public MailOtpAuthnService(RedisOtpTokenStore redisOptTokenStore) { + this.redisOptTokenStore = redisOptTokenStore; + } - public AbstractOtpAuthn getMailOtpAuthn(String instId) { - AbstractOtpAuthn otpAuthn = otpAuthnStore.getIfPresent(instId); - if(otpAuthn == null) { - CnfEmailSenders emailSender = - emailSendersService.findOne("where instid = ? ", new Object[]{instId}, new int[]{Types.VARCHAR}); - - String credentials = PasswordReciprocal.getInstance().decoder(emailSender.getCredentials()); - EmailConfig emailConfig = - new EmailConfig( - emailSender.getAccount(), - credentials, - emailSender.getSmtpHost(), - emailSender.getPort(), - ConstsBoolean.isTrue(emailSender.getSslSwitch()), - emailSender.getSender()); - MailOtpAuthn mailOtpAuthn = new MailOtpAuthn(emailConfig); - mailOtpAuthn.setInterval(60 * 5);//5 minute - if(redisOptTokenStore != null) { - mailOtpAuthn.setOptTokenStore(redisOptTokenStore); - } - otpAuthn = mailOtpAuthn; - } - otpAuthnStore.put(instId, otpAuthn); - return otpAuthn; - } + public AbstractOtpAuthn getMailOtpAuthn(String instId) { + AbstractOtpAuthn otpAuthn = otpAuthnStore.getIfPresent(instId); + if(otpAuthn == null) { + CnfEmailSenders emailSender = + emailSendersService.findOne("where instid = ? ", new Object[]{instId}, new int[]{Types.VARCHAR}); + + String credentials = PasswordReciprocal.getInstance().decoder(emailSender.getCredentials()); + EmailConfig emailConfig = + new EmailConfig( + emailSender.getAccount(), + credentials, + emailSender.getSmtpHost(), + emailSender.getPort(), + ConstsBoolean.isTrue(emailSender.getSslSwitch()), + emailSender.getSender()); + MailOtpAuthn mailOtpAuthn = new MailOtpAuthn(emailConfig); + mailOtpAuthn.setInterval(60 * 5);//5 minute + if(redisOptTokenStore != null) { + mailOtpAuthn.setOptTokenStore(redisOptTokenStore); + } + otpAuthn = mailOtpAuthn; + } + otpAuthnStore.put(instId, otpAuthn); + return otpAuthn; + } - public void setRedisOptTokenStore(RedisOtpTokenStore redisOptTokenStore) { - this.redisOptTokenStore = redisOptTokenStore; - } - - + public void setRedisOptTokenStore(RedisOtpTokenStore redisOptTokenStore) { + this.redisOptTokenStore = redisOptTokenStore; + } + + } diff --git a/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/CapOtpAuthn.java b/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/CapOtpAuthn.java index acb1459de..0a08aa967 100644 --- a/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/CapOtpAuthn.java +++ b/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/CapOtpAuthn.java @@ -48,10 +48,10 @@ public class CapOtpAuthn extends AbstractOtpAuthn { return false; } - @Override - public boolean validate(String sharedSecret, String token) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean validate(String sharedSecret, String token) { + // TODO Auto-generated method stub + return false; + } } diff --git a/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/CounterBasedOtpAuthn.java b/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/CounterBasedOtpAuthn.java index 8b82bc73f..8f7f203ea 100644 --- a/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/CounterBasedOtpAuthn.java +++ b/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/CounterBasedOtpAuthn.java @@ -72,10 +72,10 @@ public class CounterBasedOtpAuthn extends AbstractOtpAuthn { return false; } - @Override - public boolean validate(String sharedSecret, String token) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean validate(String sharedSecret, String token) { + // TODO Auto-generated method stub + return false; + } } diff --git a/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/HotpOtpAuthn.java b/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/HotpOtpAuthn.java index f9c56699f..d72b49a14 100644 --- a/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/HotpOtpAuthn.java +++ b/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/HotpOtpAuthn.java @@ -95,10 +95,10 @@ public class HotpOtpAuthn extends AbstractOtpAuthn { this.truncation = truncation; } - @Override - public boolean validate(String sharedSecret, String token) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean validate(String sharedSecret, String token) { + // TODO Auto-generated method stub + return false; + } } diff --git a/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/MailOtpAuthn.java b/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/MailOtpAuthn.java index c3f827a0d..d1bd067bf 100644 --- a/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/MailOtpAuthn.java +++ b/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/MailOtpAuthn.java @@ -42,20 +42,20 @@ public class MailOtpAuthn extends AbstractOtpAuthn { } public MailOtpAuthn(EmailConfig emailConfig) { - otpType = OtpTypes.EMAIL; - this.emailConfig = emailConfig; - } + otpType = OtpTypes.EMAIL; + this.emailConfig = emailConfig; + } - public MailOtpAuthn(EmailConfig emailConfig, String subject, String messageTemplate) { - otpType = OtpTypes.EMAIL; - this.emailConfig = emailConfig; - this.subject = subject; - this.messageTemplate = messageTemplate; - } + public MailOtpAuthn(EmailConfig emailConfig, String subject, String messageTemplate) { + otpType = OtpTypes.EMAIL; + this.emailConfig = emailConfig; + this.subject = subject; + this.messageTemplate = messageTemplate; + } - @Override + @Override public boolean produce(UserInfo userInfo) { try { String token = this.genToken(userInfo); @@ -78,7 +78,7 @@ public class MailOtpAuthn extends AbstractOtpAuthn { mailMessage.setTo(userInfo.getEmail()); mailMessage.setSubject(subject); mailMessage.setText( - MessageFormat.format( + MessageFormat.format( messageTemplate,userInfo.getUsername(),token,(interval / 60))); javaMailSender.send(mailMessage); @@ -124,11 +124,11 @@ public class MailOtpAuthn extends AbstractOtpAuthn { this.messageTemplate = messageTemplate; } - @Override - public boolean validate(String sharedSecret, String token) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean validate(String sharedSecret, String token) { + // TODO Auto-generated method stub + return false; + } } diff --git a/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/MobileOtpAuthn.java b/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/MobileOtpAuthn.java index 5070c1fd9..0d4a11ed1 100644 --- a/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/MobileOtpAuthn.java +++ b/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/MobileOtpAuthn.java @@ -38,10 +38,10 @@ public class MobileOtpAuthn extends AbstractOtpAuthn { return false; } - @Override - public boolean validate(String sharedSecret, String token) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean validate(String sharedSecret, String token) { + // TODO Auto-generated method stub + return false; + } } diff --git a/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/RsaOtpAuthn.java b/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/RsaOtpAuthn.java index 78b896f48..6fe0ddd44 100644 --- a/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/RsaOtpAuthn.java +++ b/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/RsaOtpAuthn.java @@ -48,10 +48,10 @@ public class RsaOtpAuthn extends AbstractOtpAuthn { return false; } - @Override - public boolean validate(String sharedSecret, String token) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean validate(String sharedSecret, String token) { + // TODO Auto-generated method stub + return false; + } } diff --git a/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/TimeBasedOtpAuthn.java b/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/TimeBasedOtpAuthn.java index 84242ba7a..1b685283f 100644 --- a/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/TimeBasedOtpAuthn.java +++ b/maxkey-starter/maxkey-starter-otp/src/main/java/org/dromara/maxkey/password/onetimepwd/impl/TimeBasedOtpAuthn.java @@ -54,9 +54,9 @@ public class TimeBasedOtpAuthn extends AbstractOtpAuthn { return validate(userInfo.getSharedSecret() , token); } - @Override - public boolean validate(String secret, String token) { - _logger.debug("utcTime : {}" , dateFormat.format(new Date())); + @Override + public boolean validate(String secret, String token) { + _logger.debug("utcTime : {}" , dateFormat.format(new Date())); long currentTimeSeconds = System.currentTimeMillis() / 1000; String sharedSecret = PasswordReciprocal.getInstance().decoder(secret); byte[] byteSharedSecret = Base32Utils.decode(sharedSecret); @@ -84,6 +84,6 @@ public class TimeBasedOtpAuthn extends AbstractOtpAuthn { return true; } return false; - } + } } diff --git a/maxkey-starter/maxkey-starter-otp/src/test/java/org/maxkey/otp/algorithm/HmacOTPTest.java b/maxkey-starter/maxkey-starter-otp/src/test/java/org/maxkey/otp/algorithm/HmacOTPTest.java index cea4a95d3..9dd7bdc4d 100644 --- a/maxkey-starter/maxkey-starter-otp/src/test/java/org/maxkey/otp/algorithm/HmacOTPTest.java +++ b/maxkey-starter/maxkey-starter-otp/src/test/java/org/maxkey/otp/algorithm/HmacOTPTest.java @@ -29,17 +29,17 @@ import org.dromara.maxkey.password.onetimepwd.algorithm.HmacOTP; public class HmacOTPTest { public static void main(String[] args) { - - byte[]byteseed= Base32Utils.decode("DCGAGPE2BCDBD6D3FG4NX2QGACVIHXP4"); - + + byte[]byteseed= Base32Utils.decode("DCGAGPE2BCDBD6D3FG4NX2QGACVIHXP4"); + System.out.println(HmacOTP.gen(Base32Utils.decode("DCGAGPE2BCDBD6D3FG4NX2QGACVIHXP4"),3,6)); try { - System.out.println(HOTP.generateOTP(byteseed, 3, 6, false, -1)); - } catch (InvalidKeyException e) { - e.printStackTrace(); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } + System.out.println(HOTP.generateOTP(byteseed, 3, 6, false, -1)); + } catch (InvalidKeyException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } } } diff --git a/maxkey-starter/maxkey-starter-otp/src/test/java/org/maxkey/otp/algorithm/KeyUriFormatTest.java b/maxkey-starter/maxkey-starter-otp/src/test/java/org/maxkey/otp/algorithm/KeyUriFormatTest.java index 88bb09bba..ad72513c6 100644 --- a/maxkey-starter/maxkey-starter-otp/src/test/java/org/maxkey/otp/algorithm/KeyUriFormatTest.java +++ b/maxkey-starter/maxkey-starter-otp/src/test/java/org/maxkey/otp/algorithm/KeyUriFormatTest.java @@ -27,12 +27,12 @@ import com.google.zxing.MultiFormatWriter; import com.google.zxing.common.BitMatrix; public class KeyUriFormatTest { - public static void main(String[] args) { + public static void main(String[] args) { try { - OtpKeyUriFormat kuf=new OtpKeyUriFormat(OtpKeyUriFormat.Types.TOTP, - "GIWVWOL7EI5WLVZPDMROEPSTFBEVO77Q", - "connsec.com"); - kuf.setPeriod(60); + OtpKeyUriFormat kuf=new OtpKeyUriFormat(OtpKeyUriFormat.Types.TOTP, + "GIWVWOL7EI5WLVZPDMROEPSTFBEVO77Q", + "connsec.com"); + kuf.setPeriod(60); String path = "D:\\totp.png"; BitMatrix byteMatrix; byteMatrix = new MultiFormatWriter().encode(new String(kuf.format("shiming").getBytes("GBK"),"iso-8859-1"), diff --git a/maxkey-starter/maxkey-starter-otp/src/test/java/org/maxkey/otp/algorithm/TimeBasedOTPTest.java b/maxkey-starter/maxkey-starter-otp/src/test/java/org/maxkey/otp/algorithm/TimeBasedOTPTest.java index e584abecd..404933f6d 100644 --- a/maxkey-starter/maxkey-starter-otp/src/test/java/org/maxkey/otp/algorithm/TimeBasedOTPTest.java +++ b/maxkey-starter/maxkey-starter-otp/src/test/java/org/maxkey/otp/algorithm/TimeBasedOTPTest.java @@ -35,11 +35,11 @@ import org.dromara.maxkey.password.onetimepwd.algorithm.TimeBasedOTP; public class TimeBasedOTPTest { public static void main(String[] args) { - - //byte[]byteseed=OPTSecret.generate(); - - - byte[]byteseed= Base32Utils.decode("DCGAGPE2BCDBD6D3FG4NX2QGACVIHXP4");//HexUtils.hex2Bytes( "a1270caecf007f2303cc9db12597a9694ff541aa"); + + //byte[]byteseed=OPTSecret.generate(); + + + byte[]byteseed= Base32Utils.decode("DCGAGPE2BCDBD6D3FG4NX2QGACVIHXP4");//HexUtils.hex2Bytes( "a1270caecf007f2303cc9db12597a9694ff541aa"); String seed=Base32Utils.encode(byteseed); System.out.println(seed); String hexString=Hex.encodeHexString(byteseed); @@ -53,10 +53,10 @@ public class TimeBasedOTPTest { String utcTime = df.format(new Date()); Date curr=null; try { - curr=df.parse(utcTime); - } catch (ParseException e) { - e.printStackTrace(); - } + curr=df.parse(utcTime); + } catch (ParseException e) { + e.printStackTrace(); + } long currentTimeSeconds = curr.getTime() / 1000; currentTimeSeconds =System.currentTimeMillis() / 1000; int INTERVAL = 30; @@ -64,12 +64,12 @@ public class TimeBasedOTPTest { System.out.println(utcTime); //google time based - System.out.println(TimeBasedOTP.genOTP(hexString,Long.toHexString(currentTimeSeconds/INTERVAL).toUpperCase()+"","6")); - //google counter based - System.out.println(TimeBasedOTP.genOTP(hexString,3+"","6")); - + System.out.println(TimeBasedOTP.genOTP(hexString,Long.toHexString(currentTimeSeconds/INTERVAL).toUpperCase()+"","6")); + //google counter based + System.out.println(TimeBasedOTP.genOTP(hexString,3+"","6")); + } - + } diff --git a/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/autoconfigure/SmsAutoConfiguration.java b/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/autoconfigure/SmsAutoConfiguration.java index 6cd85b19e..460560e1b 100644 --- a/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/autoconfigure/SmsAutoConfiguration.java +++ b/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/autoconfigure/SmsAutoConfiguration.java @@ -41,8 +41,8 @@ public class SmsAutoConfiguration { CnfSmsProviderService smsProviderService, CnfEmailSendersService emailSendersService, RedisConnectionFactory redisConnFactory) { - SmsOtpAuthnService smsOtpAuthnService = - new SmsOtpAuthnService(smsProviderService,emailSendersService); + SmsOtpAuthnService smsOtpAuthnService = + new SmsOtpAuthnService(smsProviderService,emailSendersService); if (persistence == ConstsPersistence.REDIS) { RedisOtpTokenStore redisOptTokenStore = new RedisOtpTokenStore(redisConnFactory); diff --git a/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/SmsOtpAuthn.java b/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/SmsOtpAuthn.java index 7e8789a23..7322495d1 100644 --- a/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/SmsOtpAuthn.java +++ b/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/SmsOtpAuthn.java @@ -45,10 +45,10 @@ public class SmsOtpAuthn extends AbstractOtpAuthn { } public void setProperties(StandardEnvironment properties) { - this.properties = properties; - } + this.properties = properties; + } - protected void loadProperties() throws IOException { + protected void loadProperties() throws IOException { } @@ -56,10 +56,10 @@ public class SmsOtpAuthn extends AbstractOtpAuthn { } - @Override - public boolean validate(String sharedSecret, String token) { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean validate(String sharedSecret, String token) { + // TODO Auto-generated method stub + return false; + } } diff --git a/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/SmsOtpAuthnService.java b/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/SmsOtpAuthnService.java index dec31ae6f..8b271150a 100644 --- a/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/SmsOtpAuthnService.java +++ b/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/SmsOtpAuthnService.java @@ -39,8 +39,8 @@ import com.github.benmanes.caffeine.cache.Caffeine; public class SmsOtpAuthnService { - static final Cache smsAuthnStore = - Caffeine.newBuilder().expireAfterWrite(60, TimeUnit.MINUTES).build(); + static final Cache smsAuthnStore = + Caffeine.newBuilder().expireAfterWrite(60, TimeUnit.MINUTES).build(); CnfSmsProviderService smsProviderService; @@ -49,67 +49,67 @@ public class SmsOtpAuthnService { RedisOtpTokenStore redisOptTokenStore; public SmsOtpAuthnService(CnfSmsProviderService smsProviderService, CnfEmailSendersService emailSendersService) { - this.smsProviderService = smsProviderService; - this.emailSendersService = emailSendersService; - } - - public SmsOtpAuthnService(CnfSmsProviderService smsProviderService,CnfEmailSendersService emailSendersService,RedisOtpTokenStore redisOptTokenStore) { - this.smsProviderService = smsProviderService; - this.emailSendersService = emailSendersService; - this.redisOptTokenStore = redisOptTokenStore; - } - - public AbstractOtpAuthn getByInstId(String instId) { - AbstractOtpAuthn smsOtpAuthn = smsAuthnStore.getIfPresent(instId); - if(smsOtpAuthn == null) { - LambdaQuery lambdaQuery = new LambdaQuery(); - lambdaQuery.eq(CnfSmsProvider::getInstId, instId); - CnfSmsProvider smsProvider = smsProviderService.get(lambdaQuery); - if(smsProvider != null ) { - if(smsProvider.getProvider().equalsIgnoreCase("aliyun")) { - smsOtpAuthn = new SmsOtpAuthnAliyun( - smsProvider.getAppKey(), - PasswordReciprocal.getInstance().decoder(smsProvider.getAppSecret()), - smsProvider.getTemplateId(), - smsProvider.getSignName()); - }else if(smsProvider.getProvider().equalsIgnoreCase("tencentcloud")) { - smsOtpAuthn = new SmsOtpAuthnTencentCloud( - smsProvider.getAppKey(), - PasswordReciprocal.getInstance().decoder(smsProvider.getAppSecret()), - smsProvider.getSmsSdkAppId(), - smsProvider.getTemplateId(), smsProvider.getSignName()); - }else if(smsProvider.getProvider().equalsIgnoreCase("neteasesms")) { - smsOtpAuthn = new SmsOtpAuthnYunxin( - smsProvider.getAppKey(), - PasswordReciprocal.getInstance().decoder(smsProvider.getAppSecret()), - smsProvider.getTemplateId()); - }else if(smsProvider.getProvider().equalsIgnoreCase("email")) { - LambdaQuery emailSenderslambdaQuery = new LambdaQuery(); - emailSenderslambdaQuery.eq(CnfEmailSenders::getInstId, instId); - CnfEmailSenders emailSender = emailSendersService.get(emailSenderslambdaQuery); - String credentials = PasswordReciprocal.getInstance().decoder(emailSender.getCredentials()); - EmailConfig emailConfig = new EmailConfig( - emailSender.getAccount(), - credentials, - emailSender.getSmtpHost(), - emailSender.getPort(), - ConstsBoolean.isTrue(emailSender.getSslSwitch()), - emailSender.getSender()); - smsOtpAuthn = new MailOtpAuthn(emailConfig); - } - - if(redisOptTokenStore != null) { - smsOtpAuthn.setOptTokenStore(redisOptTokenStore); - } - smsAuthnStore.put(instId, smsOtpAuthn); - } - } - return smsOtpAuthn; + this.smsProviderService = smsProviderService; + this.emailSendersService = emailSendersService; } - public void setRedisOptTokenStore(RedisOtpTokenStore redisOptTokenStore) { - this.redisOptTokenStore = redisOptTokenStore; - } - - + public SmsOtpAuthnService(CnfSmsProviderService smsProviderService,CnfEmailSendersService emailSendersService,RedisOtpTokenStore redisOptTokenStore) { + this.smsProviderService = smsProviderService; + this.emailSendersService = emailSendersService; + this.redisOptTokenStore = redisOptTokenStore; + } + + public AbstractOtpAuthn getByInstId(String instId) { + AbstractOtpAuthn smsOtpAuthn = smsAuthnStore.getIfPresent(instId); + if(smsOtpAuthn == null) { + LambdaQuery lambdaQuery = new LambdaQuery(); + lambdaQuery.eq(CnfSmsProvider::getInstId, instId); + CnfSmsProvider smsProvider = smsProviderService.get(lambdaQuery); + if(smsProvider != null ) { + if(smsProvider.getProvider().equalsIgnoreCase("aliyun")) { + smsOtpAuthn = new SmsOtpAuthnAliyun( + smsProvider.getAppKey(), + PasswordReciprocal.getInstance().decoder(smsProvider.getAppSecret()), + smsProvider.getTemplateId(), + smsProvider.getSignName()); + }else if(smsProvider.getProvider().equalsIgnoreCase("tencentcloud")) { + smsOtpAuthn = new SmsOtpAuthnTencentCloud( + smsProvider.getAppKey(), + PasswordReciprocal.getInstance().decoder(smsProvider.getAppSecret()), + smsProvider.getSmsSdkAppId(), + smsProvider.getTemplateId(), smsProvider.getSignName()); + }else if(smsProvider.getProvider().equalsIgnoreCase("neteasesms")) { + smsOtpAuthn = new SmsOtpAuthnYunxin( + smsProvider.getAppKey(), + PasswordReciprocal.getInstance().decoder(smsProvider.getAppSecret()), + smsProvider.getTemplateId()); + }else if(smsProvider.getProvider().equalsIgnoreCase("email")) { + LambdaQuery emailSenderslambdaQuery = new LambdaQuery(); + emailSenderslambdaQuery.eq(CnfEmailSenders::getInstId, instId); + CnfEmailSenders emailSender = emailSendersService.get(emailSenderslambdaQuery); + String credentials = PasswordReciprocal.getInstance().decoder(emailSender.getCredentials()); + EmailConfig emailConfig = new EmailConfig( + emailSender.getAccount(), + credentials, + emailSender.getSmtpHost(), + emailSender.getPort(), + ConstsBoolean.isTrue(emailSender.getSslSwitch()), + emailSender.getSender()); + smsOtpAuthn = new MailOtpAuthn(emailConfig); + } + + if(redisOptTokenStore != null) { + smsOtpAuthn.setOptTokenStore(redisOptTokenStore); + } + smsAuthnStore.put(instId, smsOtpAuthn); + } + } + return smsOtpAuthn; + } + + public void setRedisOptTokenStore(RedisOtpTokenStore redisOptTokenStore) { + this.redisOptTokenStore = redisOptTokenStore; + } + + } diff --git a/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/impl/SmsOtpAuthnAliyun.java b/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/impl/SmsOtpAuthnAliyun.java index 53982fc24..d809535ef 100644 --- a/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/impl/SmsOtpAuthnAliyun.java +++ b/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/impl/SmsOtpAuthnAliyun.java @@ -42,12 +42,12 @@ public class SmsOtpAuthnAliyun extends SmsOtpAuthn { } public SmsOtpAuthnAliyun(String accessKeyId, String accessSecret, String templateCode, String signName) { - otpType = OtpTypes.SMS; - this.accessKeyId = accessKeyId; - this.accessSecret = accessSecret; - this.templateCode = templateCode; - this.signName = signName; - } + otpType = OtpTypes.SMS; + this.accessKeyId = accessKeyId; + this.accessSecret = accessSecret; + this.templateCode = templateCode; + this.signName = signName; + } //请替换你在管理后台应用下申请的accessKeyId private String accessKeyId = "94395d754eb55693043f5d6a2b772ef3"; @@ -60,7 +60,7 @@ public class SmsOtpAuthnAliyun extends SmsOtpAuthn { - @Override + @Override public boolean produce(UserInfo userInfo) { // 手机号 String mobile = userInfo.getMobile(); diff --git a/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/impl/SmsOtpAuthnTencentCloud.java b/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/impl/SmsOtpAuthnTencentCloud.java index 03b6bbcea..76b60c10d 100644 --- a/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/impl/SmsOtpAuthnTencentCloud.java +++ b/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/impl/SmsOtpAuthnTencentCloud.java @@ -54,16 +54,16 @@ public class SmsOtpAuthnTencentCloud extends SmsOtpAuthn { } public SmsOtpAuthnTencentCloud(String secretId, String secretKey, String smsSdkAppid, String templateId, - String sign) { - otpType = OtpTypes.SMS; - this.secretId = secretId; - this.secretKey = secretKey; - this.smsSdkAppid = smsSdkAppid; - this.templateId = templateId; - this.sign = sign; - } + String sign) { + otpType = OtpTypes.SMS; + this.secretId = secretId; + this.secretKey = secretKey; + this.smsSdkAppid = smsSdkAppid; + this.templateId = templateId; + this.sign = sign; + } - @Override + @Override public boolean produce(UserInfo userInfo) { // 手机号 String mobile = userInfo.getMobile(); diff --git a/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/impl/SmsOtpAuthnYunxin.java b/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/impl/SmsOtpAuthnYunxin.java index 5d48bef53..ecb7af925 100644 --- a/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/impl/SmsOtpAuthnYunxin.java +++ b/maxkey-starter/maxkey-starter-sms/src/main/java/org/dromara/maxkey/password/sms/impl/SmsOtpAuthnYunxin.java @@ -49,13 +49,13 @@ public class SmsOtpAuthnYunxin extends SmsOtpAuthn { } public SmsOtpAuthnYunxin(String appKey, String appSecret, String templateId) { - otpType = OtpTypes.SMS; - this.appKey = appKey; - this.appSecret = appSecret; - this.templateId = templateId; - } + otpType = OtpTypes.SMS; + this.appKey = appKey; + this.appSecret = appSecret; + this.templateId = templateId; + } - //发送验证码的请求路径URL + //发送验证码的请求路径URL private static final String SERVER_URL = "https://api.netease.im/sms/sendcode.action"; //网易云信分配的账号,请替换你在管理后台应用下申请的Appkey diff --git a/maxkey-starter/maxkey-starter-social/src/main/java/me/zhyd/oauth/config/AuthMxkDefaultSource.java b/maxkey-starter/maxkey-starter-social/src/main/java/me/zhyd/oauth/config/AuthMxkDefaultSource.java index 4f171bb94..942569640 100644 --- a/maxkey-starter/maxkey-starter-social/src/main/java/me/zhyd/oauth/config/AuthMxkDefaultSource.java +++ b/maxkey-starter/maxkey-starter-social/src/main/java/me/zhyd/oauth/config/AuthMxkDefaultSource.java @@ -21,31 +21,31 @@ import me.zhyd.oauth.request.AuthDefaultRequest; import me.zhyd.oauth.request.AuthFeishu2Request; public enum AuthMxkDefaultSource implements AuthSource { - FEISHU2 { - @Override - public String authorize() { - return "https://passport.feishu.cn/suite/passport/oauth/authorize"; - } + FEISHU2 { + @Override + public String authorize() { + return "https://passport.feishu.cn/suite/passport/oauth/authorize"; + } - @Override - public String accessToken() { - return "https://passport.feishu.cn/suite/passport/oauth/token"; - } + @Override + public String accessToken() { + return "https://passport.feishu.cn/suite/passport/oauth/token"; + } - @Override - public String userInfo() { - return "https://passport.feishu.cn/suite/passport/oauth/userinfo"; - } + @Override + public String userInfo() { + return "https://passport.feishu.cn/suite/passport/oauth/userinfo"; + } - @Override - public String refresh() { - return "https://passport.feishu.cn/suite/passport/oauth/token"; - } + @Override + public String refresh() { + return "https://passport.feishu.cn/suite/passport/oauth/token"; + } - @Override - public Class getTargetClass() { - return AuthFeishu2Request.class; - } - } + @Override + public Class getTargetClass() { + return AuthFeishu2Request.class; + } + } } diff --git a/maxkey-starter/maxkey-starter-social/src/main/java/me/zhyd/oauth/request/MaxkeyAuthDefaultSource.java b/maxkey-starter/maxkey-starter-social/src/main/java/me/zhyd/oauth/request/MaxkeyAuthDefaultSource.java index d0bb19ce0..a1668a22c 100644 --- a/maxkey-starter/maxkey-starter-social/src/main/java/me/zhyd/oauth/request/MaxkeyAuthDefaultSource.java +++ b/maxkey-starter/maxkey-starter-social/src/main/java/me/zhyd/oauth/request/MaxkeyAuthDefaultSource.java @@ -22,30 +22,30 @@ import me.zhyd.oauth.config.AuthSource; public enum MaxkeyAuthDefaultSource implements AuthSource{ - MAXKEY { - @Override - public String authorize() { - return "https://login.welink.huaweicloud.com/connect/oauth2/sns_authorize"; - } + MAXKEY { + @Override + public String authorize() { + return "https://login.welink.huaweicloud.com/connect/oauth2/sns_authorize"; + } - @Override - public String accessToken() { - return "https://open.welink.huaweicloud.com/api/auth/v2/tickets"; - } + @Override + public String accessToken() { + return "https://open.welink.huaweicloud.com/api/auth/v2/tickets"; + } - @Override - public String userInfo() { - return "https://open.welink.huaweicloud.com/api/contact/v1/users"; - } + @Override + public String userInfo() { + return "https://open.welink.huaweicloud.com/api/contact/v1/users"; + } - @Override - public String refresh() { - return ""; - } + @Override + public String refresh() { + return ""; + } - @Override - public Class getTargetClass() { - return AuthHuaweiWeLinkRequest.class; - } - } + @Override + public Class getTargetClass() { + return AuthHuaweiWeLinkRequest.class; + } + } } diff --git a/maxkey-starter/maxkey-starter-social/src/main/java/me/zhyd/oauth/request/WeLinkAuthDefaultSource.java b/maxkey-starter/maxkey-starter-social/src/main/java/me/zhyd/oauth/request/WeLinkAuthDefaultSource.java index 5e3f7c705..f91571218 100644 --- a/maxkey-starter/maxkey-starter-social/src/main/java/me/zhyd/oauth/request/WeLinkAuthDefaultSource.java +++ b/maxkey-starter/maxkey-starter-social/src/main/java/me/zhyd/oauth/request/WeLinkAuthDefaultSource.java @@ -21,30 +21,30 @@ import me.zhyd.oauth.config.AuthSource; public enum WeLinkAuthDefaultSource implements AuthSource{ - HUAWEI_WELINK { - @Override - public String authorize() { - return "https://login.welink.huaweicloud.com/connect/oauth2/sns_authorize"; - } + HUAWEI_WELINK { + @Override + public String authorize() { + return "https://login.welink.huaweicloud.com/connect/oauth2/sns_authorize"; + } - @Override - public String accessToken() { - return "https://open.welink.huaweicloud.com/api/auth/v2/tickets"; - } + @Override + public String accessToken() { + return "https://open.welink.huaweicloud.com/api/auth/v2/tickets"; + } - @Override - public String userInfo() { - return "https://open.welink.huaweicloud.com/api/contact/v1/users"; - } + @Override + public String userInfo() { + return "https://open.welink.huaweicloud.com/api/contact/v1/users"; + } - @Override - public String refresh() { - return ""; - } + @Override + public String refresh() { + return ""; + } - @Override - public Class getTargetClass() { - return AuthHuaweiWeLinkRequest.class; - } - } + @Override + public Class getTargetClass() { + return AuthHuaweiWeLinkRequest.class; + } + } } diff --git a/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/AbstractSocialSignOnEndpoint.java b/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/AbstractSocialSignOnEndpoint.java index 3578cb1ee..aaca2f9ae 100644 --- a/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/AbstractSocialSignOnEndpoint.java +++ b/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/AbstractSocialSignOnEndpoint.java @@ -42,46 +42,46 @@ import me.zhyd.oauth.request.AuthRequest; * */ public class AbstractSocialSignOnEndpoint { - static final Logger _logger = LoggerFactory.getLogger(AbstractSocialSignOnEndpoint.class); - - protected AuthRequest authRequest; - - protected String accountJsonString; - - @Autowired - protected SocialSignOnProviderService socialSignOnProviderService; - - @Autowired - protected SocialsAssociateService socialsAssociateService; - - @Autowired + static final Logger _logger = LoggerFactory.getLogger(AbstractSocialSignOnEndpoint.class); + + protected AuthRequest authRequest; + + protected String accountJsonString; + + @Autowired + protected SocialSignOnProviderService socialSignOnProviderService; + + @Autowired + protected SocialsAssociateService socialsAssociateService; + + @Autowired @Qualifier("authenticationProvider") - AbstractAuthenticationProvider authenticationProvider ; - - @Autowired - AuthTokenService authTokenService; - - @Autowired - ApplicationConfig applicationConfig; - - protected AuthRequest buildAuthRequest(String instId,String provider,String baseUrl){ - try { - SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(instId,provider); - _logger.debug("socialSignOn Provider : "+socialSignOnProvider); - - if(socialSignOnProvider != null){ - authRequest = socialSignOnProviderService.getAuthRequest(instId,provider,baseUrl); - return authRequest; - } - }catch(Exception e) { - _logger.debug("buildAuthRequest Exception ",e); - } - return null; - } - - protected SocialsAssociate authCallback(String instId,String provider,String baseUrl) throws Exception { - SocialsAssociate socialsAssociate = null; - AuthCallback authCallback=new AuthCallback(); + AbstractAuthenticationProvider authenticationProvider ; + + @Autowired + AuthTokenService authTokenService; + + @Autowired + ApplicationConfig applicationConfig; + + protected AuthRequest buildAuthRequest(String instId,String provider,String baseUrl){ + try { + SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(instId,provider); + _logger.debug("socialSignOn Provider : "+socialSignOnProvider); + + if(socialSignOnProvider != null){ + authRequest = socialSignOnProviderService.getAuthRequest(instId,provider,baseUrl); + return authRequest; + } + }catch(Exception e) { + _logger.debug("buildAuthRequest Exception ",e); + } + return null; + } + + protected SocialsAssociate authCallback(String instId,String provider,String baseUrl) throws Exception { + SocialsAssociate socialsAssociate = null; + AuthCallback authCallback=new AuthCallback(); authCallback.setCode(WebContext.getRequest().getParameter("code")); authCallback.setAuth_code(WebContext.getRequest().getParameter("auth_code")); authCallback.setOauth_token(WebContext.getRequest().getParameter("oauthToken")); @@ -96,25 +96,25 @@ public class AbstractSocialSignOnEndpoint { authCallback.getOauth_verifier(), authCallback.getState()); - if(authRequest == null) {//if authRequest is null renew one - authRequest=socialSignOnProviderService.getAuthRequest(instId,provider,baseUrl); - _logger.debug("session authRequest is null , renew one"); - } - - //State time out, re set - if(authCallback.getState() != null) { + if(authRequest == null) {//if authRequest is null renew one + authRequest=socialSignOnProviderService.getAuthRequest(instId,provider,baseUrl); + _logger.debug("session authRequest is null , renew one"); + } + + //State time out, re set + if(authCallback.getState() != null) { authRequest.authorize(WebContext.getRequest().getSession().getId()); } - - AuthResponse authResponse=authRequest.login(authCallback); - _logger.debug("Response : {}" , authResponse.getData()); - String socialUserId = socialSignOnProviderService.getAccountId(provider, authResponse); - socialsAssociate =new SocialsAssociate(); - socialsAssociate.setProvider(provider); - socialsAssociate.setSocialUserId(socialUserId); - socialsAssociate.setInstId(instId); - - return socialsAssociate; - } - + + AuthResponse authResponse=authRequest.login(authCallback); + _logger.debug("Response : {}" , authResponse.getData()); + String socialUserId = socialSignOnProviderService.getAccountId(provider, authResponse); + socialsAssociate =new SocialsAssociate(); + socialsAssociate.setProvider(provider); + socialsAssociate.setSocialUserId(socialUserId); + socialsAssociate.setInstId(instId); + + return socialsAssociate; + } + } diff --git a/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/SocialSignOnEndpoint.java b/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/SocialSignOnEndpoint.java index 0753bf56e..1e6d71614 100644 --- a/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/SocialSignOnEndpoint.java +++ b/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/SocialSignOnEndpoint.java @@ -49,212 +49,212 @@ import java.util.Map; @RestController @RequestMapping(value = "/logon/oauth20") public class SocialSignOnEndpoint extends AbstractSocialSignOnEndpoint{ - static final Logger _logger = LoggerFactory.getLogger(SocialSignOnEndpoint.class); + static final Logger _logger = LoggerFactory.getLogger(SocialSignOnEndpoint.class); - @GetMapping("/authorize/{provider}") - public Message authorize( HttpServletRequest request,@PathVariable("provider") String provider) { - _logger.trace("SocialSignOn provider : {}" , provider); - String instId = WebContext.getInst().getId(); - String originURL =WebContext.getContextPath(request,false); - String authorizationUrl = - buildAuthRequest( - instId, - provider, - originURL + applicationConfig.getFrontendUri() - ).authorize(authTokenService.genRandomJwt()); + @GetMapping("/authorize/{provider}") + public Message authorize( HttpServletRequest request,@PathVariable("provider") String provider) { + _logger.trace("SocialSignOn provider : {}" , provider); + String instId = WebContext.getInst().getId(); + String originURL =WebContext.getContextPath(request,false); + String authorizationUrl = + buildAuthRequest( + instId, + provider, + originURL + applicationConfig.getFrontendUri() + ).authorize(authTokenService.genRandomJwt()); - _logger.trace("authorize SocialSignOn : {}" , authorizationUrl); - return new Message(authorizationUrl); - } + _logger.trace("authorize SocialSignOn : {}" , authorizationUrl); + return new Message(authorizationUrl); + } - @GetMapping("/scanqrcode/{provider}") - public Message scanQRCode(HttpServletRequest request,@PathVariable("provider") String provider) { - String instId = WebContext.getInst().getId(); - String originURL =WebContext.getContextPath(request,false); - AuthRequest authRequest = - buildAuthRequest( - instId, - provider, - originURL + applicationConfig.getFrontendUri()); - SocialsProvider scanQrProvider = null; - if(authRequest != null ) { - String state = UUID.generate().toString(); - //String state = authTokenService.genRandomJwt(); - authRequest.authorize(state); - - SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(instId,provider); - scanQrProvider = new SocialsProvider(socialSignOnProvider); - scanQrProvider.setState(state); - scanQrProvider.setRedirectUri( - socialSignOnProviderService.getRedirectUri( - originURL + applicationConfig.getFrontendUri(), provider)); - //缓存state票据在缓存或者是redis中五分钟过期 - if (provider.equalsIgnoreCase(AuthMaxkeyRequest.KEY)) { - socialSignOnProviderService.setToken(state); - } - }else { - _logger.error("build authRequest fail ."); - } - - return new Message<>(scanQrProvider); - } + @GetMapping("/scanqrcode/{provider}") + public Message scanQRCode(HttpServletRequest request,@PathVariable("provider") String provider) { + String instId = WebContext.getInst().getId(); + String originURL =WebContext.getContextPath(request,false); + AuthRequest authRequest = + buildAuthRequest( + instId, + provider, + originURL + applicationConfig.getFrontendUri()); + SocialsProvider scanQrProvider = null; + if(authRequest != null ) { + String state = UUID.generate().toString(); + //String state = authTokenService.genRandomJwt(); + authRequest.authorize(state); + + SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(instId,provider); + scanQrProvider = new SocialsProvider(socialSignOnProvider); + scanQrProvider.setState(state); + scanQrProvider.setRedirectUri( + socialSignOnProviderService.getRedirectUri( + originURL + applicationConfig.getFrontendUri(), provider)); + //缓存state票据在缓存或者是redis中五分钟过期 + if (provider.equalsIgnoreCase(AuthMaxkeyRequest.KEY)) { + socialSignOnProviderService.setToken(state); + } + }else { + _logger.error("build authRequest fail ."); + } + + return new Message<>(scanQrProvider); + } - @GetMapping("/bind/{provider}") - public Message bind(@PathVariable("provider") String provider, - @CurrentUser UserInfo userInfo, - HttpServletRequest request) { - //auth call back may exception - try { - String originURL = WebContext.getContextPath(request,false); - SocialsAssociate socialsAssociate = - this.authCallback(userInfo.getInstId(),provider,originURL + applicationConfig.getFrontendUri()); - socialsAssociate.setSocialUserInfo(accountJsonString); - socialsAssociate.setUserId(userInfo.getId()); - socialsAssociate.setUsername(userInfo.getUsername()); - socialsAssociate.setInstId(userInfo.getInstId()); - _logger.debug("Social Bind : {}",socialsAssociate); - this.socialsAssociateService.delete(socialsAssociate); - this.socialsAssociateService.insert(socialsAssociate); - return new Message<>(); - }catch(Exception e) { - _logger.error("callback Exception ",e); - } - return new Message<>(Message.ERROR); - } + @GetMapping("/bind/{provider}") + public Message bind(@PathVariable("provider") String provider, + @CurrentUser UserInfo userInfo, + HttpServletRequest request) { + //auth call back may exception + try { + String originURL = WebContext.getContextPath(request,false); + SocialsAssociate socialsAssociate = + this.authCallback(userInfo.getInstId(),provider,originURL + applicationConfig.getFrontendUri()); + socialsAssociate.setSocialUserInfo(accountJsonString); + socialsAssociate.setUserId(userInfo.getId()); + socialsAssociate.setUsername(userInfo.getUsername()); + socialsAssociate.setInstId(userInfo.getInstId()); + _logger.debug("Social Bind : {}",socialsAssociate); + this.socialsAssociateService.delete(socialsAssociate); + this.socialsAssociateService.insert(socialsAssociate); + return new Message<>(); + }catch(Exception e) { + _logger.error("callback Exception ",e); + } + return new Message<>(Message.ERROR); + } - @GetMapping("/callback/{provider}") - public Message callback(@PathVariable("provider") String provider,HttpServletRequest request) { - //auth call back may exception - try { - String originURL =WebContext.getContextPath(request,false); - String instId = WebContext.getInst().getId(); - SocialsAssociate socialsAssociate = - this.authCallback(instId,provider,originURL + applicationConfig.getFrontendUri()); + @GetMapping("/callback/{provider}") + public Message callback(@PathVariable("provider") String provider,HttpServletRequest request) { + //auth call back may exception + try { + String originURL =WebContext.getContextPath(request,false); + String instId = WebContext.getInst().getId(); + SocialsAssociate socialsAssociate = + this.authCallback(instId,provider,originURL + applicationConfig.getFrontendUri()); - SocialsAssociate socialssssociate1 = this.socialsAssociateService.get(socialsAssociate); - - _logger.debug("Loaded SocialSignOn Socials Associate : {}",socialssssociate1); - - if (null == socialssssociate1) { - //如果存在第三方ID并且在数据库无法找到映射关系,则进行绑定逻辑 - if (StringUtils.isNotEmpty(socialsAssociate.getSocialUserId())) { - //返回message为第三方用户标识 - return new Message<>(Message.PROMPT,socialsAssociate.getSocialUserId()); - } - } + SocialsAssociate socialssssociate1 = this.socialsAssociateService.get(socialsAssociate); + + _logger.debug("Loaded SocialSignOn Socials Associate : {}",socialssssociate1); + + if (null == socialssssociate1) { + //如果存在第三方ID并且在数据库无法找到映射关系,则进行绑定逻辑 + if (StringUtils.isNotEmpty(socialsAssociate.getSocialUserId())) { + //返回message为第三方用户标识 + return new Message<>(Message.PROMPT,socialsAssociate.getSocialUserId()); + } + } - socialsAssociate = socialssssociate1; - if(socialsAssociate != null) { - _logger.debug("Social Sign On from {} mapping to user {}", - socialsAssociate.getProvider(),socialsAssociate.getUsername()); - LoginCredential loginCredential =new LoginCredential( - socialsAssociate.getUsername(),"",ConstsLoginType.SOCIALSIGNON); - SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(instId,provider); - loginCredential.setProvider(socialSignOnProvider.getProviderName()); - - Authentication authentication = authenticationProvider.authenticate(loginCredential,true); - socialsAssociate.setSocialUserInfo(accountJsonString); - - this.socialsAssociateService.update(socialsAssociate); - return new Message<>(authTokenService.genAuthJwt(authentication)); - }else { - - } - }catch(Exception e) { - _logger.error("callback Exception ",e); - - } - return new Message<>(Message.ERROR); - } + socialsAssociate = socialssssociate1; + if(socialsAssociate != null) { + _logger.debug("Social Sign On from {} mapping to user {}", + socialsAssociate.getProvider(),socialsAssociate.getUsername()); + LoginCredential loginCredential =new LoginCredential( + socialsAssociate.getUsername(),"",ConstsLoginType.SOCIALSIGNON); + SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(instId,provider); + loginCredential.setProvider(socialSignOnProvider.getProviderName()); + + Authentication authentication = authenticationProvider.authenticate(loginCredential,true); + socialsAssociate.setSocialUserInfo(accountJsonString); + + this.socialsAssociateService.update(socialsAssociate); + return new Message<>(authTokenService.genAuthJwt(authentication)); + }else { + + } + }catch(Exception e) { + _logger.error("callback Exception ",e); + + } + return new Message<>(Message.ERROR); + } - /** - * 提供给第三方应用关联用户接口 - * @return - */ - @PostMapping("/workweixin/qr/auth/login") - public Message qrAuthLogin( - @RequestParam Map param, - HttpServletRequest request) { + /** + * 提供给第三方应用关联用户接口 + * @return + */ + @PostMapping("/workweixin/qr/auth/login") + public Message qrAuthLogin( + @RequestParam Map param, + HttpServletRequest request) { - try { - if (null == param){ - return new Message<>(Message.ERROR); - } - String token = param.get("token"); - String username = param.get("username"); - //判断token是否合法 - String redisusername = this.socialSignOnProviderService.getToken(token); - if (StringUtils.isNotEmpty(redisusername)){ - //设置token和用户绑定 - boolean flag = this.socialSignOnProviderService.bindtoken(token,username); - if (flag) { - return new Message<>(); - } - } else { - return new Message<>(Message.WARNING,"Invalid token"); - } - }catch(Exception e) { - _logger.error("qrAuthLogin Exception ",e); - } - return new Message<>(Message.ERROR); - } + try { + if (null == param){ + return new Message<>(Message.ERROR); + } + String token = param.get("token"); + String username = param.get("username"); + //判断token是否合法 + String redisusername = this.socialSignOnProviderService.getToken(token); + if (StringUtils.isNotEmpty(redisusername)){ + //设置token和用户绑定 + boolean flag = this.socialSignOnProviderService.bindtoken(token,username); + if (flag) { + return new Message<>(); + } + } else { + return new Message<>(Message.WARNING,"Invalid token"); + } + }catch(Exception e) { + _logger.error("qrAuthLogin Exception ",e); + } + return new Message<>(Message.ERROR); + } - /** - * maxkey 监听扫码回调 - * @param provider - * @param state - * @param request - * @return - */ - @PostMapping("/qrcallback/{provider}/{state}") - public Message qrcallback(@PathVariable("provider") String provider,@PathVariable("state") String state, - HttpServletRequest request) { - try { - //判断只有maxkey扫码 - if (!provider.equalsIgnoreCase(AuthMaxkeyRequest.KEY)) { - return new Message<>(Message.ERROR); - } + /** + * maxkey 监听扫码回调 + * @param provider + * @param state + * @param request + * @return + */ + @PostMapping("/qrcallback/{provider}/{state}") + public Message qrcallback(@PathVariable("provider") String provider,@PathVariable("state") String state, + HttpServletRequest request) { + try { + //判断只有maxkey扫码 + if (!provider.equalsIgnoreCase(AuthMaxkeyRequest.KEY)) { + return new Message<>(Message.ERROR); + } - String loginName = socialSignOnProviderService.getToken(state); - if (StringUtils.isEmpty(loginName)) { - //二维码过期 - return new Message<>(Message.PROMPT); - } - if("-1".equalsIgnoreCase(loginName)){ - //暂无用户扫码 - return new Message<>(Message.WARNING); - } - String instId = WebContext.getInst().getId(); + String loginName = socialSignOnProviderService.getToken(state); + if (StringUtils.isEmpty(loginName)) { + //二维码过期 + return new Message<>(Message.PROMPT); + } + if("-1".equalsIgnoreCase(loginName)){ + //暂无用户扫码 + return new Message<>(Message.WARNING); + } + String instId = WebContext.getInst().getId(); - SocialsAssociate socialsAssociate = new SocialsAssociate(); - socialsAssociate.setProvider(provider); - socialsAssociate.setSocialUserId(loginName); - socialsAssociate.setInstId(instId); + SocialsAssociate socialsAssociate = new SocialsAssociate(); + socialsAssociate.setProvider(provider); + socialsAssociate.setSocialUserId(loginName); + socialsAssociate.setInstId(instId); - socialsAssociate = this.socialsAssociateService.get(socialsAssociate); + socialsAssociate = this.socialsAssociateService.get(socialsAssociate); - _logger.debug("qrcallback Loaded SocialSignOn Socials Associate : {}",socialsAssociate); + _logger.debug("qrcallback Loaded SocialSignOn Socials Associate : {}",socialsAssociate); - if(null == socialsAssociate) { - return new Message<>(Message.ERROR); - } + if(null == socialsAssociate) { + return new Message<>(Message.ERROR); + } - LoginCredential loginCredential =new LoginCredential( - socialsAssociate.getUsername(),"",ConstsLoginType.SOCIALSIGNON); - SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(instId,provider); - loginCredential.setProvider(socialSignOnProvider.getProviderName()); + LoginCredential loginCredential =new LoginCredential( + socialsAssociate.getUsername(),"",ConstsLoginType.SOCIALSIGNON); + SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(instId,provider); + loginCredential.setProvider(socialSignOnProvider.getProviderName()); - Authentication authentication = authenticationProvider.authenticate(loginCredential,true); - socialsAssociate.setSocialUserInfo(accountJsonString); + Authentication authentication = authenticationProvider.authenticate(loginCredential,true); + socialsAssociate.setSocialUserInfo(accountJsonString); - this.socialsAssociateService.update(socialsAssociate); - return new Message<>(authTokenService.genAuthJwt(authentication)); - }catch(Exception e) { - _logger.error("qrcallback Exception ",e); - return new Message<>(Message.ERROR); - } - } + this.socialsAssociateService.update(socialsAssociate); + return new Message<>(authTokenService.genAuthJwt(authentication)); + }catch(Exception e) { + _logger.error("qrcallback Exception ",e); + return new Message<>(Message.ERROR); + } + } } diff --git a/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/service/JdbcSocialsAssociateService.java b/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/service/JdbcSocialsAssociateService.java index e7545a3ef..1fee48ffb 100644 --- a/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/service/JdbcSocialsAssociateService.java +++ b/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/service/JdbcSocialsAssociateService.java @@ -32,120 +32,120 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; public class JdbcSocialsAssociateService implements SocialsAssociateService{ - private static final Logger _logger = LoggerFactory.getLogger(JdbcSocialsAssociateService.class); - - private static final String DEFAULT_DEFAULT_INSERT_STATEMENT = "insert into mxk_socials_associate(id, userid , username , provider , socialuserid , accesstoken , socialuserinfo , exattribute , instid)values( ? , ? , ? , ? , ?, ? , ? , ?, ?)"; - - private static final String DEFAULT_DEFAULT_INSERT_STATEMENT_ORACLE = "insert into mxk_socials_associate(id, userid , username , provider , socialuserid , accesstoken , socialuserinfo , exattribute , instid)values( ? , ? , ? , ? , ?, ? , ? , ?, ?)"; + private static final Logger _logger = LoggerFactory.getLogger(JdbcSocialsAssociateService.class); + + private static final String DEFAULT_DEFAULT_INSERT_STATEMENT = "insert into mxk_socials_associate(id, userid , username , provider , socialuserid , accesstoken , socialuserinfo , exattribute , instid)values( ? , ? , ? , ? , ?, ? , ? , ?, ?)"; + + private static final String DEFAULT_DEFAULT_INSERT_STATEMENT_ORACLE = "insert into mxk_socials_associate(id, userid , username , provider , socialuserid , accesstoken , socialuserinfo , exattribute , instid)values( ? , ? , ? , ? , ?, ? , ? , ?, ?)"; - private static final String DEFAULT_DEFAULT_SIGNON_SELECT_STATEMENT = "select id, userid , username , provider , socialuserid , accesstoken , socialuserinfo , exattribute , createddate , updateddate , instid from mxk_socials_associate where provider = ? and socialuserid = ? and instId = ?"; + private static final String DEFAULT_DEFAULT_SIGNON_SELECT_STATEMENT = "select id, userid , username , provider , socialuserid , accesstoken , socialuserinfo , exattribute , createddate , updateddate , instid from mxk_socials_associate where provider = ? and socialuserid = ? and instId = ?"; - private static final String DEFAULT_DEFAULT_BIND_SELECT_STATEMENT = "select id, userid , username , provider , socialuserid , accesstoken , socialuserinfo , exattribute , createddate , updateddate , instid from mxk_socials_associate where userid = ?" ; - - private static final String DEFAULT_DEFAULT_DELETE_STATEMENT = "delete from mxk_socials_associate where userid = ? and provider = ?"; - - private static final String DEFAULT_DEFAULT_UPDATE_STATEMENT= "update mxk_socials_associate set accesstoken = ? , socialuserinfo = ? , exattribute = ? ,updateddate = ? where id = ?"; + private static final String DEFAULT_DEFAULT_BIND_SELECT_STATEMENT = "select id, userid , username , provider , socialuserid , accesstoken , socialuserinfo , exattribute , createddate , updateddate , instid from mxk_socials_associate where userid = ?" ; + + private static final String DEFAULT_DEFAULT_DELETE_STATEMENT = "delete from mxk_socials_associate where userid = ? and provider = ?"; + + private static final String DEFAULT_DEFAULT_UPDATE_STATEMENT= "update mxk_socials_associate set accesstoken = ? , socialuserinfo = ? , exattribute = ? ,updateddate = ? where id = ?"; - private final JdbcTemplate jdbcTemplate; - - public JdbcSocialsAssociateService(JdbcTemplate jdbcTemplate) { - this.jdbcTemplate=jdbcTemplate; - } + private final JdbcTemplate jdbcTemplate; + + public JdbcSocialsAssociateService(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate=jdbcTemplate; + } - @Override - public boolean insert(SocialsAssociate socialsAssociate) { - socialsAssociate.setId(socialsAssociate.generateId()); - jdbcTemplate.update( - WebContext.compare(ConstsDatabase.ORACLE)? - DEFAULT_DEFAULT_INSERT_STATEMENT_ORACLE:DEFAULT_DEFAULT_INSERT_STATEMENT, - new Object[] { - socialsAssociate.getId(), - socialsAssociate.getUserId(), - socialsAssociate.getUsername(), - socialsAssociate.getProvider(), - socialsAssociate.getSocialUserId(), - socialsAssociate.getAccessToken(), - socialsAssociate.getSocialUserInfo(), - socialsAssociate.getExAttribute(), - socialsAssociate.getInstId() - }, - new int[] { - Types.VARCHAR, Types.VARCHAR,Types.VARCHAR,Types.VARCHAR, - Types.VARCHAR,Types.VARCHAR, Types.VARCHAR,Types.VARCHAR, - Types.VARCHAR - }); - return true; - } + @Override + public boolean insert(SocialsAssociate socialsAssociate) { + socialsAssociate.setId(socialsAssociate.generateId()); + jdbcTemplate.update( + WebContext.compare(ConstsDatabase.ORACLE)? + DEFAULT_DEFAULT_INSERT_STATEMENT_ORACLE:DEFAULT_DEFAULT_INSERT_STATEMENT, + new Object[] { + socialsAssociate.getId(), + socialsAssociate.getUserId(), + socialsAssociate.getUsername(), + socialsAssociate.getProvider(), + socialsAssociate.getSocialUserId(), + socialsAssociate.getAccessToken(), + socialsAssociate.getSocialUserInfo(), + socialsAssociate.getExAttribute(), + socialsAssociate.getInstId() + }, + new int[] { + Types.VARCHAR, Types.VARCHAR,Types.VARCHAR,Types.VARCHAR, + Types.VARCHAR,Types.VARCHAR, Types.VARCHAR,Types.VARCHAR, + Types.VARCHAR + }); + return true; + } - @Override - public boolean delete(SocialsAssociate socialsAssociate) { - jdbcTemplate.update(DEFAULT_DEFAULT_DELETE_STATEMENT, - new Object[] { - socialsAssociate.getUserId(), - socialsAssociate.getProvider() - }, - new int[] {Types.VARCHAR, Types.VARCHAR}); - return true; - } + @Override + public boolean delete(SocialsAssociate socialsAssociate) { + jdbcTemplate.update(DEFAULT_DEFAULT_DELETE_STATEMENT, + new Object[] { + socialsAssociate.getUserId(), + socialsAssociate.getProvider() + }, + new int[] {Types.VARCHAR, Types.VARCHAR}); + return true; + } - @Override - public SocialsAssociate get(SocialsAssociate socialsAssociate) { - List listsocialsAssociate=jdbcTemplate.query( - DEFAULT_DEFAULT_SIGNON_SELECT_STATEMENT, - new SocialsAssociateRowMapper(), - socialsAssociate.getProvider(), - socialsAssociate.getSocialUserId(), - socialsAssociate.getInstId()); - _logger.debug("list socialsAssociate "+listsocialsAssociate); - return (listsocialsAssociate.size()>0)?listsocialsAssociate.get(0):null; - } - - @Override - public List query( - SocialsAssociate socialsAssociate) { - List listsocialsAssociate=jdbcTemplate.query( - DEFAULT_DEFAULT_BIND_SELECT_STATEMENT, - new SocialsAssociateRowMapper(), - socialsAssociate.getUserId()); - _logger.debug("query bind SocialSignOnUser "+listsocialsAssociate); - return listsocialsAssociate; - } + @Override + public SocialsAssociate get(SocialsAssociate socialsAssociate) { + List listsocialsAssociate=jdbcTemplate.query( + DEFAULT_DEFAULT_SIGNON_SELECT_STATEMENT, + new SocialsAssociateRowMapper(), + socialsAssociate.getProvider(), + socialsAssociate.getSocialUserId(), + socialsAssociate.getInstId()); + _logger.debug("list socialsAssociate "+listsocialsAssociate); + return (listsocialsAssociate.size()>0)?listsocialsAssociate.get(0):null; + } + + @Override + public List query( + SocialsAssociate socialsAssociate) { + List listsocialsAssociate=jdbcTemplate.query( + DEFAULT_DEFAULT_BIND_SELECT_STATEMENT, + new SocialsAssociateRowMapper(), + socialsAssociate.getUserId()); + _logger.debug("query bind SocialSignOnUser "+listsocialsAssociate); + return listsocialsAssociate; + } - @Override - public boolean update(SocialsAssociate socialsAssociate) { - jdbcTemplate.update(DEFAULT_DEFAULT_UPDATE_STATEMENT, - new Object[] { - socialsAssociate.getAccessToken(), - socialsAssociate.getSocialUserInfo(), - socialsAssociate.getExAttribute(), - new Date(), - socialsAssociate.getId() - }, - new int[] {Types.VARCHAR, Types.VARCHAR,Types.VARCHAR, Types.TIMESTAMP,Types.VARCHAR }); - return false; - } - - private final class SocialsAssociateRowMapper implements RowMapper { - @Override - public SocialsAssociate mapRow(ResultSet rs, int rowNum) - throws SQLException { - SocialsAssociate socialsAssociate=new SocialsAssociate(); - socialsAssociate.setId(rs.getString(1)); - socialsAssociate.setUserId(rs.getString(2)); - socialsAssociate.setUsername(rs.getString(3)); - socialsAssociate.setProvider(rs.getString(4)); - socialsAssociate.setSocialUserId(rs.getString(5)); - socialsAssociate.setAccessToken(rs.getString(6)); - socialsAssociate.setSocialUserInfo(rs.getString(7)); - socialsAssociate.setExAttribute(rs.getString(8)); - socialsAssociate.setCreatedDate(rs.getTimestamp(9)); - socialsAssociate.setUpdatedDate(rs.getTimestamp(10)); - socialsAssociate.setInstId(rs.getString(11)); - return socialsAssociate; - } - } - + @Override + public boolean update(SocialsAssociate socialsAssociate) { + jdbcTemplate.update(DEFAULT_DEFAULT_UPDATE_STATEMENT, + new Object[] { + socialsAssociate.getAccessToken(), + socialsAssociate.getSocialUserInfo(), + socialsAssociate.getExAttribute(), + new Date(), + socialsAssociate.getId() + }, + new int[] {Types.VARCHAR, Types.VARCHAR,Types.VARCHAR, Types.TIMESTAMP,Types.VARCHAR }); + return false; + } + + private final class SocialsAssociateRowMapper implements RowMapper { + @Override + public SocialsAssociate mapRow(ResultSet rs, int rowNum) + throws SQLException { + SocialsAssociate socialsAssociate=new SocialsAssociate(); + socialsAssociate.setId(rs.getString(1)); + socialsAssociate.setUserId(rs.getString(2)); + socialsAssociate.setUsername(rs.getString(3)); + socialsAssociate.setProvider(rs.getString(4)); + socialsAssociate.setSocialUserId(rs.getString(5)); + socialsAssociate.setAccessToken(rs.getString(6)); + socialsAssociate.setSocialUserInfo(rs.getString(7)); + socialsAssociate.setExAttribute(rs.getString(8)); + socialsAssociate.setCreatedDate(rs.getTimestamp(9)); + socialsAssociate.setUpdatedDate(rs.getTimestamp(10)); + socialsAssociate.setInstId(rs.getString(11)); + return socialsAssociate; + } + } + } diff --git a/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/service/SocialSignOnProviderService.java b/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/service/SocialSignOnProviderService.java index 91bbfa3fc..97b2ce7c1 100644 --- a/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/service/SocialSignOnProviderService.java +++ b/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/service/SocialSignOnProviderService.java @@ -43,73 +43,73 @@ import me.zhyd.oauth.model.AuthUser; import me.zhyd.oauth.request.*; public class SocialSignOnProviderService{ - private static final Logger _logger = LoggerFactory.getLogger(SocialSignOnProviderService.class); - - private static final String DEFAULT_SELECT_STATEMENT = "select * from mxk_socials_provider where instid = ? and status = 1 order by sortindex"; - - protected static final Cache socialsProviderLoginStore = + private static final Logger _logger = LoggerFactory.getLogger(SocialSignOnProviderService.class); + + private static final String DEFAULT_SELECT_STATEMENT = "select * from mxk_socials_provider where instid = ? and status = 1 order by sortindex"; + + protected static final Cache socialsProviderLoginStore = Caffeine.newBuilder() .expireAfterWrite(ConstsTimeInterval.ONE_HOUR, TimeUnit.MINUTES) .build(); - - HashMapsocialSignOnProviderMaps = new HashMap<>(); - - private final JdbcTemplate jdbcTemplate; + + HashMapsocialSignOnProviderMaps = new HashMap<>(); + + private final JdbcTemplate jdbcTemplate; - RedisTokenStore redisTokenStore; - - public SocialSignOnProviderService(JdbcTemplate jdbcTemplate) { + RedisTokenStore redisTokenStore; + + public SocialSignOnProviderService(JdbcTemplate jdbcTemplate) { this.jdbcTemplate=jdbcTemplate; } - public SocialsProvider get(String instId,String provider){ - return socialSignOnProviderMaps.get(instId + "_" + provider); - } - public void setToken(String token){ - this.redisTokenStore.store(token); - } + public SocialsProvider get(String instId,String provider){ + return socialSignOnProviderMaps.get(instId + "_" + provider); + } + public void setToken(String token){ + this.redisTokenStore.store(token); + } - public boolean bindtoken(String token,String loginName){ - return this.redisTokenStore.bindtoken(token,loginName); - } + public boolean bindtoken(String token,String loginName){ + return this.redisTokenStore.bindtoken(token,loginName); + } - public String getToken(String token){ - return this.redisTokenStore.get(token); - } - - public String getRedirectUri(String baseUri,String provider) { - return baseUri + "/passport/callback/"+provider; - } - - public AuthRequest getAuthRequest(String instId,String provider,String baseUri) throws Exception { - AuthRequest authRequest = null; - AuthConfig authConfig = AuthConfig.builder() - .clientId(this.get(instId,provider).getClientId()) - .clientSecret(this.get(instId,provider).getClientSecret()) - .redirectUri(getRedirectUri(baseUri , provider)) - .build(); - - if(provider.equalsIgnoreCase("WeChatOpen")) { - authRequest = new AuthWeChatOpenRequest(authConfig); - }else if(provider.equalsIgnoreCase("sinaweibo")) { - authRequest = new AuthWeiboRequest(authConfig); - }else if(provider.equalsIgnoreCase("qq")) { - authRequest = new AuthQqRequest(authConfig); - }else if(provider.equalsIgnoreCase("Alipay")) { - String alipayPublicKey = ""; - authRequest = new AuthAlipayRequest(authConfig,alipayPublicKey); - }else if(provider.equalsIgnoreCase("Twitter")) { - authRequest = new AuthTwitterRequest(authConfig); - }else if(provider.equalsIgnoreCase("google")) { - authRequest = new AuthGoogleRequest(authConfig); - }else if(provider.equalsIgnoreCase("microsoft")) { - authRequest = new AuthMicrosoftRequest(authConfig); - }else if(provider.equalsIgnoreCase("Linkedin")) { - authRequest = new AuthLinkedinRequest(authConfig); - }else if(provider.equalsIgnoreCase("DingTalk")) { - authRequest = new AuthDingTalkRequest(authConfig); - }else if(provider.equalsIgnoreCase("gitee")) { + public String getToken(String token){ + return this.redisTokenStore.get(token); + } + + public String getRedirectUri(String baseUri,String provider) { + return baseUri + "/passport/callback/"+provider; + } + + public AuthRequest getAuthRequest(String instId,String provider,String baseUri) throws Exception { + AuthRequest authRequest = null; + AuthConfig authConfig = AuthConfig.builder() + .clientId(this.get(instId,provider).getClientId()) + .clientSecret(this.get(instId,provider).getClientSecret()) + .redirectUri(getRedirectUri(baseUri , provider)) + .build(); + + if(provider.equalsIgnoreCase("WeChatOpen")) { + authRequest = new AuthWeChatOpenRequest(authConfig); + }else if(provider.equalsIgnoreCase("sinaweibo")) { + authRequest = new AuthWeiboRequest(authConfig); + }else if(provider.equalsIgnoreCase("qq")) { + authRequest = new AuthQqRequest(authConfig); + }else if(provider.equalsIgnoreCase("Alipay")) { + String alipayPublicKey = ""; + authRequest = new AuthAlipayRequest(authConfig,alipayPublicKey); + }else if(provider.equalsIgnoreCase("Twitter")) { + authRequest = new AuthTwitterRequest(authConfig); + }else if(provider.equalsIgnoreCase("google")) { + authRequest = new AuthGoogleRequest(authConfig); + }else if(provider.equalsIgnoreCase("microsoft")) { + authRequest = new AuthMicrosoftRequest(authConfig); + }else if(provider.equalsIgnoreCase("Linkedin")) { + authRequest = new AuthLinkedinRequest(authConfig); + }else if(provider.equalsIgnoreCase("DingTalk")) { + authRequest = new AuthDingTalkRequest(authConfig); + }else if(provider.equalsIgnoreCase("gitee")) { authRequest = new AuthGiteeRequest(authConfig); }else if(provider.equalsIgnoreCase("Baidu")) { authRequest = new AuthBaiduRequest(authConfig); @@ -119,7 +119,7 @@ public class SocialSignOnProviderService{ authRequest = new AuthElemeRequest(authConfig); }else if(provider.equalsIgnoreCase("Feishu")) { //authRequest = new AuthFeishuRequest(authConfig); - authRequest = new AuthFeishu2Request(authConfig); + authRequest = new AuthFeishu2Request(authConfig); }else if(provider.equalsIgnoreCase("Github")) { authRequest = new AuthGithubRequest(authConfig); }else if(provider.equalsIgnoreCase("Gitlab")) { @@ -145,89 +145,89 @@ public class SocialSignOnProviderService{ }else if(provider.equalsIgnoreCase("welink")) { authRequest = new AuthHuaweiWeLinkRequest(authConfig); }else if(provider.equalsIgnoreCase("maxkey")) { - authRequest = new AuthMaxkeyRequest(authConfig); - } + authRequest = new AuthMaxkeyRequest(authConfig); + } - return authRequest; - } - - public String getAccountId(String provider,AuthResponse authResponse) throws Exception { - if(authResponse.getData() != null) { - AuthUser authUser = (AuthUser)authResponse.getData(); - _logger.debug("AuthUser[{},{},{},{},{},{},{},{},{},{},{},{}]", - authUser.getUuid(), - authUser.getUsername(), - authUser.getNickname(), - authUser.getGender(), - authUser.getEmail(), - authUser.getCompany(), - authUser.getBlog(), - authUser.getLocation(), - authUser.getRemark(), - authUser.getSource(), - authUser.getBlog(), - authUser.getAvatar()); - _logger.debug("RawUserInfo {}",authUser.getRawUserInfo()); - if(provider.equalsIgnoreCase("WeChatOpen")) { - return authUser.getUuid(); - }else if(provider.equalsIgnoreCase("sinaweibo")) { - return authUser.getUuid(); - }else if(provider.equalsIgnoreCase("qq")) { - return authUser.getUuid(); - }else if(provider.equalsIgnoreCase("Alipay")) { - return authUser.getUuid(); - }else if(provider.equalsIgnoreCase("Twitter")) { - return authUser.getUuid(); - }else if(provider.equalsIgnoreCase("google")) { - return authUser.getUuid(); - }else if(provider.equalsIgnoreCase("microsoft")) { - return authUser.getUuid(); - }else if(provider.equalsIgnoreCase("Linkedin")) { - return authUser.getUuid(); - }else if(provider.equalsIgnoreCase("DingTalk")) { - return authUser.getUuid(); - }else { - return authUser.getUuid(); - } - } - return null; - } - - public SocialsProviderLogin loadSocials(String instId) { - SocialsProviderLogin socialsLogin = socialsProviderLoginStore.getIfPresent(instId); - if(socialsLogin == null) { - List listSocialsProvider = jdbcTemplate.query( - DEFAULT_SELECT_STATEMENT, - new SocialsProviderRowMapper(),instId); - _logger.trace("query SocialsProvider {}" , listSocialsProvider); - - List socialSignOnProviders = new ArrayList<>(); - socialsLogin = new SocialsProviderLogin(socialSignOnProviders); - for(SocialsProvider socialsProvider : listSocialsProvider){ - _logger.debug("Social Provider {} ({})" , - socialsProvider.getProvider() ,socialsProvider.getProviderName()); - - if(socialsProvider.getDisplay().equals("true")) { - socialSignOnProviders.add(new SocialsProvider(socialsProvider)); - } - - if(socialsProvider.getScanCode().equalsIgnoreCase("true")) { - socialsLogin.setQrScan(socialsProvider.getProvider()); - } - - //add to socialSignOnProviderMaps - socialSignOnProviderMaps.put(instId + "_" + socialsProvider.getProvider() , socialsProvider); - } - - _logger.debug("social SignOn Providers Login {}" , socialsLogin); - - socialsProviderLoginStore.put(instId, socialsLogin); - } + return authRequest; + } + + public String getAccountId(String provider,AuthResponse authResponse) throws Exception { + if(authResponse.getData() != null) { + AuthUser authUser = (AuthUser)authResponse.getData(); + _logger.debug("AuthUser[{},{},{},{},{},{},{},{},{},{},{},{}]", + authUser.getUuid(), + authUser.getUsername(), + authUser.getNickname(), + authUser.getGender(), + authUser.getEmail(), + authUser.getCompany(), + authUser.getBlog(), + authUser.getLocation(), + authUser.getRemark(), + authUser.getSource(), + authUser.getBlog(), + authUser.getAvatar()); + _logger.debug("RawUserInfo {}",authUser.getRawUserInfo()); + if(provider.equalsIgnoreCase("WeChatOpen")) { + return authUser.getUuid(); + }else if(provider.equalsIgnoreCase("sinaweibo")) { + return authUser.getUuid(); + }else if(provider.equalsIgnoreCase("qq")) { + return authUser.getUuid(); + }else if(provider.equalsIgnoreCase("Alipay")) { + return authUser.getUuid(); + }else if(provider.equalsIgnoreCase("Twitter")) { + return authUser.getUuid(); + }else if(provider.equalsIgnoreCase("google")) { + return authUser.getUuid(); + }else if(provider.equalsIgnoreCase("microsoft")) { + return authUser.getUuid(); + }else if(provider.equalsIgnoreCase("Linkedin")) { + return authUser.getUuid(); + }else if(provider.equalsIgnoreCase("DingTalk")) { + return authUser.getUuid(); + }else { + return authUser.getUuid(); + } + } + return null; + } + + public SocialsProviderLogin loadSocials(String instId) { + SocialsProviderLogin socialsLogin = socialsProviderLoginStore.getIfPresent(instId); + if(socialsLogin == null) { + List listSocialsProvider = jdbcTemplate.query( + DEFAULT_SELECT_STATEMENT, + new SocialsProviderRowMapper(),instId); + _logger.trace("query SocialsProvider {}" , listSocialsProvider); + + List socialSignOnProviders = new ArrayList<>(); + socialsLogin = new SocialsProviderLogin(socialSignOnProviders); + for(SocialsProvider socialsProvider : listSocialsProvider){ + _logger.debug("Social Provider {} ({})" , + socialsProvider.getProvider() ,socialsProvider.getProviderName()); + + if(socialsProvider.getDisplay().equals("true")) { + socialSignOnProviders.add(new SocialsProvider(socialsProvider)); + } + + if(socialsProvider.getScanCode().equalsIgnoreCase("true")) { + socialsLogin.setQrScan(socialsProvider.getProvider()); + } + + //add to socialSignOnProviderMaps + socialSignOnProviderMaps.put(instId + "_" + socialsProvider.getProvider() , socialsProvider); + } + + _logger.debug("social SignOn Providers Login {}" , socialsLogin); + + socialsProviderLoginStore.put(instId, socialsLogin); + } return socialsLogin; - } - - - private final class SocialsProviderRowMapper implements RowMapper { + } + + + private final class SocialsProviderRowMapper implements RowMapper { @Override public SocialsProvider mapRow(ResultSet rs, int rowNum) throws SQLException { @@ -251,7 +251,7 @@ public class SocialSignOnProviderService{ } - public void setRedisTokenStore(RedisTokenStore redisTokenStore) { - this.redisTokenStore = redisTokenStore; - } + public void setRedisTokenStore(RedisTokenStore redisTokenStore) { + this.redisTokenStore = redisTokenStore; + } } diff --git a/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/service/SocialsAssociateService.java b/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/service/SocialsAssociateService.java index 2c3fe0d25..7e23e8b80 100644 --- a/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/service/SocialsAssociateService.java +++ b/maxkey-starter/maxkey-starter-social/src/main/java/org/dromara/maxkey/authn/support/socialsignon/service/SocialsAssociateService.java @@ -24,14 +24,14 @@ import org.dromara.maxkey.entity.SocialsAssociate; public interface SocialsAssociateService{ - public boolean insert(SocialsAssociate socialsAssociate); - - public List query (SocialsAssociate socialsAssociate); - - public SocialsAssociate get (SocialsAssociate socialsAssociate); - - public boolean delete (SocialsAssociate socialsAssociate); - - public boolean update (SocialsAssociate socialsAssociate); - + public boolean insert(SocialsAssociate socialsAssociate); + + public List query (SocialsAssociate socialsAssociate); + + public SocialsAssociate get (SocialsAssociate socialsAssociate); + + public boolean delete (SocialsAssociate socialsAssociate); + + public boolean update (SocialsAssociate socialsAssociate); + } diff --git a/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/autoconfigure/ApplicationAutoConfiguration.java b/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/autoconfigure/ApplicationAutoConfiguration.java index 46d6e63bb..35e26df8f 100644 --- a/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/autoconfigure/ApplicationAutoConfiguration.java +++ b/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/autoconfigure/ApplicationAutoConfiguration.java @@ -72,7 +72,7 @@ public class ApplicationAutoConfiguration { @Bean PasswordEncoder passwordEncoder( @Value("${maxkey.crypto.password.encoder:bcrypt}") String idForEncode) { - Map encoders = new HashMap<>(); + Map encoders = new HashMap<>(); encoders.put("bcrypt", new BCryptPasswordEncoder()); encoders.put("plain", NoOpPasswordEncoder.getInstance()); encoders.put("pbkdf2", Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8()); @@ -95,10 +95,10 @@ public class ApplicationAutoConfiguration { new DelegatingPasswordEncoder(idForEncode, encoders); if(_logger.isTraceEnabled()) { - _logger.trace("Password Encoders :"); - for (Map.Entry entry : encoders.entrySet()) { - _logger.trace("{}= {}" ,String.format("%-10s", entry.getKey()), entry.getValue().getClass().getName()); - } + _logger.trace("Password Encoders :"); + for (Map.Entry entry : encoders.entrySet()) { + _logger.trace("{}= {}" ,String.format("%-10s", entry.getKey()), entry.getValue().getClass().getName()); + } } _logger.debug("{} is default encoder" , idForEncode); return passwordEncoder; @@ -156,10 +156,10 @@ public class ApplicationAutoConfiguration { @Value("${maxkey.id.strategy:SnowFlake}") String strategy, @Value("${maxkey.id.datacenterId:0}") int datacenterId, @Value("${maxkey.id.machineId:0}") int machineId) { - IdGenerator idGenerator = new IdGenerator(strategy); - SnowFlakeId snowFlakeId = new SnowFlakeId(datacenterId,machineId); - idGenerator.setSnowFlakeId(snowFlakeId); - WebContext.setIdGenerator(idGenerator); + IdGenerator idGenerator = new IdGenerator(strategy); + SnowFlakeId snowFlakeId = new SnowFlakeId(datacenterId,machineId); + idGenerator.setSnowFlakeId(snowFlakeId); + WebContext.setIdGenerator(idGenerator); return idGenerator; } @@ -168,13 +168,13 @@ public class ApplicationAutoConfiguration { MomentaryService momentaryService( RedisConnectionFactory redisConnFactory, @Value("${maxkey.server.persistence}") int persistence) { - MomentaryService momentaryService; - if (persistence == ConstsPersistence.REDIS) { - momentaryService = new RedisMomentaryService(redisConnFactory); - }else { - momentaryService = new InMemoryMomentaryService(); - } - return momentaryService; + MomentaryService momentaryService; + if (persistence == ConstsPersistence.REDIS) { + momentaryService = new RedisMomentaryService(redisConnFactory); + }else { + momentaryService = new InMemoryMomentaryService(); + } + return momentaryService; } } diff --git a/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/autoconfigure/MvcAutoConfiguration.java b/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/autoconfigure/MvcAutoConfiguration.java index 4d727b1c0..5aa3108d8 100644 --- a/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/autoconfigure/MvcAutoConfiguration.java +++ b/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/autoconfigure/MvcAutoConfiguration.java @@ -299,11 +299,11 @@ public class MvcAutoConfiguration implements WebMvcConfigurer { @Bean FilterRegistrationBean webInstRequestFilter( - InstitutionsService institutionsService, - ApplicationConfig applicationConfig) { + InstitutionsService institutionsService, + ApplicationConfig applicationConfig) { _logger.debug("WebInstRequestFilter init for /* "); FilterRegistrationBean registrationBean = - new FilterRegistrationBean<>(new WebInstRequestFilter(institutionsService,applicationConfig)); + new FilterRegistrationBean<>(new WebInstRequestFilter(institutionsService,applicationConfig)); registrationBean.addUrlPatterns("/*"); registrationBean.setName("webInstRequestFilter"); registrationBean.setOrder(4); diff --git a/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/autoconfigure/MvcResourceAutoConfiguration.java b/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/autoconfigure/MvcResourceAutoConfiguration.java index 34247f27d..826d252c4 100644 --- a/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/autoconfigure/MvcResourceAutoConfiguration.java +++ b/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/autoconfigure/MvcResourceAutoConfiguration.java @@ -31,8 +31,8 @@ public class MvcResourceAutoConfiguration implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { - logger.debug("add Resource Handlers"); - + logger.debug("add Resource Handlers"); + logger.debug("add statics"); registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/"); @@ -47,10 +47,10 @@ public class MvcResourceAutoConfiguration implements WebMvcConfigurer { logger.debug("add knife4j"); registry.addResourceHandler("doc.html") - .addResourceLocations("classpath:/META-INF/resources/"); + .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") - .addResourceLocations("classpath:/META-INF/resources/webjars/"); + .addResourceLocations("classpath:/META-INF/resources/webjars/"); logger.debug("add Resource Handler finished ."); } diff --git a/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/autoconfigure/SwaggerAutoConfiguration.java b/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/autoconfigure/SwaggerAutoConfiguration.java index 77ca95e77..87fddea7e 100644 --- a/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/autoconfigure/SwaggerAutoConfiguration.java +++ b/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/autoconfigure/SwaggerAutoConfiguration.java @@ -18,8 +18,8 @@ import io.swagger.v3.oas.models.info.License; @AutoConfiguration public class SwaggerAutoConfiguration { - static final Logger _logger = LoggerFactory.getLogger(SwaggerAutoConfiguration.class); - + static final Logger _logger = LoggerFactory.getLogger(SwaggerAutoConfiguration.class); + @Value("${maxkey.swagger.title}") String title; @@ -53,18 +53,18 @@ public class SwaggerAutoConfiguration { @Bean GroupedOpenApi userApi(){ String[] paths = { - "/login", - "/logout", - "/login/**", - "/logout/**", - "/authz/**", - "/authz/**/**", - "/metadata/saml20/**" , - "/onlineticket/validate/**", - "/api/connect/v10/userinfo", - "/api/oauth/v20/me" - - }; + "/login", + "/logout", + "/login/**", + "/logout/**", + "/authz/**", + "/authz/**/**", + "/metadata/saml20/**" , + "/onlineticket/validate/**", + "/api/connect/v10/userinfo", + "/api/oauth/v20/me" + + }; String[] packagedToMatch = { "org.dromara.maxkey.authz" }; return GroupedOpenApi.builder().group(title) .pathsToMatch(paths) @@ -73,23 +73,23 @@ public class SwaggerAutoConfiguration { @Bean OpenAPI docOpenAPI() { - return new OpenAPI() - .info( - new Info() - .title(title) - .description(description) - .version(version) - .termsOfService("https://www.maxkey.top/") - .license( - new License() - .name("Apache License, Version 2.0") - .url("http://www.apache.org/licenses/LICENSE-2.0") - ) - ). - externalDocs( - new ExternalDocumentation() - .description("MaxKey.top contact support@maxsso.net") - .url("https://www.maxkey.top/") - ); - } + return new OpenAPI() + .info( + new Info() + .title(title) + .description(description) + .version(version) + .termsOfService("https://www.maxkey.top/") + .license( + new License() + .name("Apache License, Version 2.0") + .url("http://www.apache.org/licenses/LICENSE-2.0") + ) + ). + externalDocs( + new ExternalDocumentation() + .description("MaxKey.top contact support@maxsso.net") + .url("https://www.maxkey.top/") + ); + } } diff --git a/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/web/WebInstRequestFilter.java b/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/web/WebInstRequestFilter.java index e06c6032d..91f64375b 100644 --- a/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/web/WebInstRequestFilter.java +++ b/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/web/WebInstRequestFilter.java @@ -35,58 +35,58 @@ import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; public class WebInstRequestFilter extends GenericFilterBean { - static final Logger _logger = LoggerFactory.getLogger(WebInstRequestFilter.class); - - public static final String HEADER_HOST = "host"; - - public static final String HEADER_HOSTNAME = "hostname"; - - public static final String HEADER_ORIGIN = "Origin"; - - InstitutionsService institutionsService; - - ApplicationConfig applicationConfig; - - @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) - throws IOException, ServletException { - _logger.trace("WebInstRequestFilter"); - HttpServletRequest request= ((HttpServletRequest)servletRequest); - - if(request.getSession().getAttribute(WebConstants.CURRENT_INST) == null) { - if(_logger.isTraceEnabled()) {WebContext.printRequest(request);} - String host = request.getHeader(HEADER_HOSTNAME); - _logger.trace("hostname {}",host); - if(StringUtils.isEmpty(host)) { - host = request.getHeader(HEADER_HOST); - _logger.trace("host {}",host); - } - if(StringUtils.isEmpty(host)) { - host = applicationConfig.getDomainName(); - _logger.trace("config domain {}",host); - } - if(host.indexOf(":")> -1 ) { - host = host.split(":")[0]; - _logger.trace("domain split {}",host); - } - _logger.trace("host {}",host); - Institutions institution = institutionsService.get(host); - _logger.trace("{}" ,institution); - request.getSession().setAttribute(WebConstants.CURRENT_INST, institution); - - String origin = request.getHeader(HEADER_ORIGIN); - if(StringUtils.isEmpty(origin)) { - origin = applicationConfig.getFrontendUri(); - } - _logger.trace("origin {}" ,origin); - } + static final Logger _logger = LoggerFactory.getLogger(WebInstRequestFilter.class); + + public static final String HEADER_HOST = "host"; + + public static final String HEADER_HOSTNAME = "hostname"; + + public static final String HEADER_ORIGIN = "Origin"; + + InstitutionsService institutionsService; + + ApplicationConfig applicationConfig; + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) + throws IOException, ServletException { + _logger.trace("WebInstRequestFilter"); + HttpServletRequest request= ((HttpServletRequest)servletRequest); + + if(request.getSession().getAttribute(WebConstants.CURRENT_INST) == null) { + if(_logger.isTraceEnabled()) {WebContext.printRequest(request);} + String host = request.getHeader(HEADER_HOSTNAME); + _logger.trace("hostname {}",host); + if(StringUtils.isEmpty(host)) { + host = request.getHeader(HEADER_HOST); + _logger.trace("host {}",host); + } + if(StringUtils.isEmpty(host)) { + host = applicationConfig.getDomainName(); + _logger.trace("config domain {}",host); + } + if(host.indexOf(":")> -1 ) { + host = host.split(":")[0]; + _logger.trace("domain split {}",host); + } + _logger.trace("host {}",host); + Institutions institution = institutionsService.get(host); + _logger.trace("{}" ,institution); + request.getSession().setAttribute(WebConstants.CURRENT_INST, institution); + + String origin = request.getHeader(HEADER_ORIGIN); + if(StringUtils.isEmpty(origin)) { + origin = applicationConfig.getFrontendUri(); + } + _logger.trace("origin {}" ,origin); + } chain.doFilter(servletRequest, servletResponse); - } + } - public WebInstRequestFilter(InstitutionsService institutionsService,ApplicationConfig applicationConfig) { - super(); - this.institutionsService = institutionsService; - this.applicationConfig = applicationConfig; - } + public WebInstRequestFilter(InstitutionsService institutionsService,ApplicationConfig applicationConfig) { + super(); + this.institutionsService = institutionsService; + this.applicationConfig = applicationConfig; + } } diff --git a/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/web/WebXssRequestFilter.java b/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/web/WebXssRequestFilter.java index 08fd0c6ca..9d914f655 100644 --- a/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/web/WebXssRequestFilter.java +++ b/maxkey-starter/maxkey-starter-web/src/main/java/org/dromara/maxkey/web/WebXssRequestFilter.java @@ -35,92 +35,92 @@ import jakarta.servlet.http.HttpServletRequest; public class WebXssRequestFilter extends GenericFilterBean { - static final Logger _logger = LoggerFactory.getLogger(WebXssRequestFilter.class); - - static final ConcurrentHashMap skipUrlMap = new ConcurrentHashMap <>(); - static final ConcurrentHashMap skipParameterName = new ConcurrentHashMap <>(); - - /** - * 特殊字符 ' -- # - */ - public final static Pattern specialCharacterRegex = Pattern.compile(".*((\\%27)|(')|(\\')|(--)|(\\-\\-)|(\\%23)|(#)).*", Pattern.CASE_INSENSITIVE); - - static { - //add or update - skipUrlMap.put("/notices/add", "/notices/add"); - skipUrlMap.put("/notices/update", "/notices/update"); - skipUrlMap.put("/institutions/update","/institutions/update"); - skipUrlMap.put("/localization/update","/localization/update"); - skipUrlMap.put("/apps/updateExtendAttr","/apps/updateExtendAttr"); - - //authz - skipUrlMap.put("/authz/cas", "/authz/cas"); - skipUrlMap.put("/authz/cas/", "/authz/cas/"); - skipUrlMap.put("/authz/cas/login", "/authz/cas/login"); - skipUrlMap.put("/authz/oauth/v20/authorize", "/authz/oauth/v20/authorize"); - //TENCENT_IOA - skipUrlMap.put("/oauth2/authorize", "/oauth2/authorize"); - - skipParameterName.put("relatedPassword", "relatedPassword"); - skipParameterName.put("oldPassword", "oldPassword"); - skipParameterName.put("password", "password"); - skipParameterName.put("confirmpassword", "confirmpassword"); - skipParameterName.put("credentials", "credentials"); - skipParameterName.put("clientSecret", "clientSecret"); - skipParameterName.put("appSecret", "appSecret"); - skipParameterName.put("sharedSecret", "sharedSecret"); - skipParameterName.put("secret", "secret"); - } - - @Override - public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) - throws IOException, ServletException { - _logger.trace("WebXssRequestFilter"); - boolean isWebXss = false; - HttpServletRequest request= ((HttpServletRequest)servletRequest); - if(_logger.isTraceEnabled()) {WebContext.printRequest(request);} - String requestURL =request.getRequestURI().substring(request.getContextPath().length()); - if(skipUrlMap.containsKey(requestURL)) { - _logger.trace("skip URL {}",requestURL); - }else { - Enumeration parameterNames = request.getParameterNames(); - while (parameterNames.hasMoreElements()) { - String key = parameterNames.nextElement(); - if(!skipParameterName.containsKey(key)) { - String value = request.getParameter(key); - _logger.trace("parameter name {} , value {}" , key, value); - String tempValue = value; - String lowerCaseTempValue = tempValue.toLowerCase(); - /** - * StringEscapeUtils.escapeHtml4 - * " 转义为 " - * & 转义为 & - * < 转义为 < - * > 转义为 > - * - * 以下符号过滤 - * ' - * -- - * # - * - * script - * eval - * - */ - if(!StringEscapeUtils.escapeHtml4(tempValue).equals(value) - ||specialCharacterRegex.matcher(value).matches() - ||lowerCaseTempValue.indexOf("script")>-1 - ||lowerCaseTempValue.replace(" ", "").indexOf("eval(")>-1) { - isWebXss = true; - _logger.error("dangerous ! parameter {} , value {}",key,value); - break; - } - } - } - } + static final Logger _logger = LoggerFactory.getLogger(WebXssRequestFilter.class); + + static final ConcurrentHashMap skipUrlMap = new ConcurrentHashMap <>(); + static final ConcurrentHashMap skipParameterName = new ConcurrentHashMap <>(); + + /** + * 特殊字符 ' -- # + */ + public final static Pattern specialCharacterRegex = Pattern.compile(".*((\\%27)|(')|(\\')|(--)|(\\-\\-)|(\\%23)|(#)).*", Pattern.CASE_INSENSITIVE); + + static { + //add or update + skipUrlMap.put("/notices/add", "/notices/add"); + skipUrlMap.put("/notices/update", "/notices/update"); + skipUrlMap.put("/institutions/update","/institutions/update"); + skipUrlMap.put("/localization/update","/localization/update"); + skipUrlMap.put("/apps/updateExtendAttr","/apps/updateExtendAttr"); + + //authz + skipUrlMap.put("/authz/cas", "/authz/cas"); + skipUrlMap.put("/authz/cas/", "/authz/cas/"); + skipUrlMap.put("/authz/cas/login", "/authz/cas/login"); + skipUrlMap.put("/authz/oauth/v20/authorize", "/authz/oauth/v20/authorize"); + //TENCENT_IOA + skipUrlMap.put("/oauth2/authorize", "/oauth2/authorize"); + + skipParameterName.put("relatedPassword", "relatedPassword"); + skipParameterName.put("oldPassword", "oldPassword"); + skipParameterName.put("password", "password"); + skipParameterName.put("confirmpassword", "confirmpassword"); + skipParameterName.put("credentials", "credentials"); + skipParameterName.put("clientSecret", "clientSecret"); + skipParameterName.put("appSecret", "appSecret"); + skipParameterName.put("sharedSecret", "sharedSecret"); + skipParameterName.put("secret", "secret"); + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + _logger.trace("WebXssRequestFilter"); + boolean isWebXss = false; + HttpServletRequest request= ((HttpServletRequest)servletRequest); + if(_logger.isTraceEnabled()) {WebContext.printRequest(request);} + String requestURL =request.getRequestURI().substring(request.getContextPath().length()); + if(skipUrlMap.containsKey(requestURL)) { + _logger.trace("skip URL {}",requestURL); + }else { + Enumeration parameterNames = request.getParameterNames(); + while (parameterNames.hasMoreElements()) { + String key = parameterNames.nextElement(); + if(!skipParameterName.containsKey(key)) { + String value = request.getParameter(key); + _logger.trace("parameter name {} , value {}" , key, value); + String tempValue = value; + String lowerCaseTempValue = tempValue.toLowerCase(); + /** + * StringEscapeUtils.escapeHtml4 + * " 转义为 " + * & 转义为 & + * < 转义为 < + * > 转义为 > + * + * 以下符号过滤 + * ' + * -- + * # + * + * script + * eval + * + */ + if(!StringEscapeUtils.escapeHtml4(tempValue).equals(value) + ||specialCharacterRegex.matcher(value).matches() + ||lowerCaseTempValue.indexOf("script")>-1 + ||lowerCaseTempValue.replace(" ", "").indexOf("eval(")>-1) { + isWebXss = true; + _logger.error("dangerous ! parameter {} , value {}",key,value); + break; + } + } + } + } if(!isWebXss) { - chain.doFilter(request, response); + chain.doFilter(request, response); } - } + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-activedirectory/src/main/java/org/dromara/maxkey/synchronizer/activedirectory/ActiveDirectoryOrganizationService.java b/maxkey-synchronizers/maxkey-synchronizer-activedirectory/src/main/java/org/dromara/maxkey/synchronizer/activedirectory/ActiveDirectoryOrganizationService.java index 928a03270..7fa50e2af 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-activedirectory/src/main/java/org/dromara/maxkey/synchronizer/activedirectory/ActiveDirectoryOrganizationService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-activedirectory/src/main/java/org/dromara/maxkey/synchronizer/activedirectory/ActiveDirectoryOrganizationService.java @@ -50,257 +50,257 @@ import static org.dromara.maxkey.synchronizer.utils.FieldUtil.setFieldValue; @Service public class ActiveDirectoryOrganizationService extends AbstractSynchronizerService implements ISynchronizerService{ - static final Logger _logger = LoggerFactory.getLogger(ActiveDirectoryOrganizationService.class); + static final Logger _logger = LoggerFactory.getLogger(ActiveDirectoryOrganizationService.class); - @Autowired - private SyncJobConfigFieldService syncJobConfigFieldService; - private static final Integer ORG_TYPE = 2; - ActiveDirectoryUtils ldapUtils; - - public void sync() { - loadOrgsByInstId(this.synchronizer.getInstId(),Organizations.ROOT_ORG_ID); - _logger.info("Sync ActiveDirectory Organizations ..."); - try { - ArrayList orgsList = queryActiveDirectory(); - int maxLevel = 0; - for(Organizations organization : orgsList) { - maxLevel = (maxLevel < organization.getLevel()) ? organization.getLevel() : maxLevel ; - } - - for (int level = 2 ; level <= maxLevel ; level++) { - for(Organizations organization : orgsList) { - if(organization.getLevel() == level) { - String parentNamePath= organization.getNamePath().substring(0, organization.getNamePath().lastIndexOf("/")); - - if(orgsNamePathMap.get(organization.getNamePath())!=null) { - _logger.info("org {} exists." , orgsNamePathMap.get(organization.getNamePath()).getNamePath()); - continue; - } - - Organizations parentOrg = orgsNamePathMap.get(parentNamePath); - if(parentOrg == null ) { - parentOrg = rootOrganization; - } - organization.setParentId(parentOrg.getId()); - organization.setParentName(parentOrg.getOrgName()); - organization.setCodePath(parentOrg.getCodePath()+"/"+organization.getId()); - _logger.info("parentNamePath {} , namePah {}" ,parentNamePath, organization.getNamePath()); - - //synchro Related - SynchroRelated synchroRelated = - synchroRelatedService.findByOriginId( - this.synchronizer,organization.getLdapDn(),Organizations.CLASS_TYPE ); - if(synchroRelated == null) { - organization.setId(organization.generateId()); - organizationsService.insert(organization); - _logger.debug("Organizations : {}" , organization); - - synchroRelated = buildSynchroRelated(organization,organization.getLdapDn(),organization.getOrgName()); - }else { - organization.setId(synchroRelated.getObjectId()); - organizationsService.update(organization); - } - - synchroRelatedService.updateSynchroRelated( - this.synchronizer,synchroRelated,Organizations.CLASS_TYPE); - - orgsNamePathMap.put(organization.getNamePath(), organization); - - HistorySynchronizer historySynchronizer - = new HistorySynchronizer(synchronizer.generateId(), - this.synchronizer.getId(), - this.synchronizer.getName(), - organization.getId(), - organization.getOrgName(), - Organizations.class.getSimpleName(), - "success", - synchronizer.getInstId()); - this.historySynchronizerService.insert(historySynchronizer); - } - } - } - - //ldapUtils.close(); - } catch (NamingException e) { - _logger.error("NamingException " , e); - } - - - } - - private ArrayList queryActiveDirectory() throws NamingException { - SearchControls constraints = new SearchControls(); - constraints.setSearchScope(ldapUtils.getSearchScope()); - String filter = "(&(objectClass=OrganizationalUnit))"; - if(StringUtils.isNotBlank(this.getSynchronizer().getOrgFilters())) { - //filter = this.getSynchronizer().getFilters(); - } - - NamingEnumeration results = - ldapUtils.getConnection().search(ldapUtils.getBaseDN(), filter, constraints); - - ArrayList orgsList = new ArrayList(); - long recordCount = 0; - while (null != results && results.hasMoreElements()) { - Object obj = results.nextElement(); - if (obj instanceof SearchResult) { - SearchResult sr = (SearchResult) obj; - if(sr.getNameInNamespace().contains("OU=Domain Controllers")||StringUtils.isEmpty(sr.getName())) { - _logger.info("Skip '' or 'OU=Domain Controllers' ."); - continue; - } - _logger.debug("Sync OrganizationalUnit {} , name [{}] , NameInNamespace [{}]" , - (++recordCount),sr.getName(),sr.getNameInNamespace()); - - HashMap attributeMap = new HashMap<>(); - NamingEnumeration attrs = sr.getAttributes().getAll(); - while (null != attrs && attrs.hasMoreElements()) { - Attribute objAttrs = attrs.nextElement(); - _logger.trace("attribute {} : {}" , - objAttrs.getID(), - ActiveDirectoryUtils.getAttrStringValue(objAttrs) - ); - attributeMap.put(objAttrs.getID().toLowerCase(), objAttrs); - } - - Organizations organization = buildOrganization(attributeMap,sr.getName(),sr.getNameInNamespace()); - if(organization != null) { - orgsList.add(organization); - } - } - } - return orgsList; - } - - public SynchroRelated buildSynchroRelated(Organizations organization,String ldapDN,String name) { - return new SynchroRelated( - organization.getId(), - organization.getOrgName(), - organization.getOrgName(), - Organizations.CLASS_TYPE, - synchronizer.getId(), - synchronizer.getName(), - ldapDN, - name, - "", - organization.getParentId(), - synchronizer.getInstId()); - } - - public Organizations buildOrganization(HashMap attributeMap,String name,String nameInNamespace) { - try { - Organizations org = new Organizations(); - org.setLdapDn(nameInNamespace); - String []namePaths = name.replaceAll(",OU=" , "/") - .replaceAll("OU=" , "/") - .replaceAll(",ou=" , "/") - .replaceAll("ou=" , "/") - .split("/"); - String namePah= "/"+rootOrganization.getOrgName(); - for(int i = namePaths.length -1 ; i >= 0 ; i --) { - namePah = namePah + "/" + namePaths[i]; - } - - namePah = namePah.substring(0, namePah.length() - 1); - - org.setId(org.generateId()); - org.setOrgCode(org.getId()); - org.setNamePath(namePah); - org.setLevel(namePaths.length); - org.setOrgName(LdapUtils.getAttributeStringValue(OrganizationalUnit.OU,attributeMap)); - org.setFullName(org.getOrgName()); - org.setType("department"); - org.setCountry(LdapUtils.getAttributeStringValue(OrganizationalUnit.CO,attributeMap)); - org.setRegion(LdapUtils.getAttributeStringValue(OrganizationalUnit.ST,attributeMap)); - org.setLocality(LdapUtils.getAttributeStringValue(OrganizationalUnit.L,attributeMap)); - org.setStreet(LdapUtils.getAttributeStringValue(OrganizationalUnit.STREET,attributeMap)); - org.setPostalCode(LdapUtils.getAttributeStringValue(OrganizationalUnit.POSTALCODE,attributeMap)); - org.setDescription(LdapUtils.getAttributeStringValue(OrganizationalUnit.DESCRIPTION,attributeMap)); - org.setInstId(this.synchronizer.getInstId()); - org.setStatus(ConstsStatus.ACTIVE); - - _logger.debug("Organization {}" , org); - return org; - } catch (NamingException e) { - _logger.error("NamingException " , e); - } - return null; - } + @Autowired + private SyncJobConfigFieldService syncJobConfigFieldService; + private static final Integer ORG_TYPE = 2; + ActiveDirectoryUtils ldapUtils; + + public void sync() { + loadOrgsByInstId(this.synchronizer.getInstId(),Organizations.ROOT_ORG_ID); + _logger.info("Sync ActiveDirectory Organizations ..."); + try { + ArrayList orgsList = queryActiveDirectory(); + int maxLevel = 0; + for(Organizations organization : orgsList) { + maxLevel = (maxLevel < organization.getLevel()) ? organization.getLevel() : maxLevel ; + } + + for (int level = 2 ; level <= maxLevel ; level++) { + for(Organizations organization : orgsList) { + if(organization.getLevel() == level) { + String parentNamePath= organization.getNamePath().substring(0, organization.getNamePath().lastIndexOf("/")); + + if(orgsNamePathMap.get(organization.getNamePath())!=null) { + _logger.info("org {} exists." , orgsNamePathMap.get(organization.getNamePath()).getNamePath()); + continue; + } + + Organizations parentOrg = orgsNamePathMap.get(parentNamePath); + if(parentOrg == null ) { + parentOrg = rootOrganization; + } + organization.setParentId(parentOrg.getId()); + organization.setParentName(parentOrg.getOrgName()); + organization.setCodePath(parentOrg.getCodePath()+"/"+organization.getId()); + _logger.info("parentNamePath {} , namePah {}" ,parentNamePath, organization.getNamePath()); + + //synchro Related + SynchroRelated synchroRelated = + synchroRelatedService.findByOriginId( + this.synchronizer,organization.getLdapDn(),Organizations.CLASS_TYPE ); + if(synchroRelated == null) { + organization.setId(organization.generateId()); + organizationsService.insert(organization); + _logger.debug("Organizations : {}" , organization); + + synchroRelated = buildSynchroRelated(organization,organization.getLdapDn(),organization.getOrgName()); + }else { + organization.setId(synchroRelated.getObjectId()); + organizationsService.update(organization); + } + + synchroRelatedService.updateSynchroRelated( + this.synchronizer,synchroRelated,Organizations.CLASS_TYPE); + + orgsNamePathMap.put(organization.getNamePath(), organization); + + HistorySynchronizer historySynchronizer + = new HistorySynchronizer(synchronizer.generateId(), + this.synchronizer.getId(), + this.synchronizer.getName(), + organization.getId(), + organization.getOrgName(), + Organizations.class.getSimpleName(), + "success", + synchronizer.getInstId()); + this.historySynchronizerService.insert(historySynchronizer); + } + } + } + + //ldapUtils.close(); + } catch (NamingException e) { + _logger.error("NamingException " , e); + } + + + } + + private ArrayList queryActiveDirectory() throws NamingException { + SearchControls constraints = new SearchControls(); + constraints.setSearchScope(ldapUtils.getSearchScope()); + String filter = "(&(objectClass=OrganizationalUnit))"; + if(StringUtils.isNotBlank(this.getSynchronizer().getOrgFilters())) { + //filter = this.getSynchronizer().getFilters(); + } + + NamingEnumeration results = + ldapUtils.getConnection().search(ldapUtils.getBaseDN(), filter, constraints); + + ArrayList orgsList = new ArrayList(); + long recordCount = 0; + while (null != results && results.hasMoreElements()) { + Object obj = results.nextElement(); + if (obj instanceof SearchResult) { + SearchResult sr = (SearchResult) obj; + if(sr.getNameInNamespace().contains("OU=Domain Controllers")||StringUtils.isEmpty(sr.getName())) { + _logger.info("Skip '' or 'OU=Domain Controllers' ."); + continue; + } + _logger.debug("Sync OrganizationalUnit {} , name [{}] , NameInNamespace [{}]" , + (++recordCount),sr.getName(),sr.getNameInNamespace()); + + HashMap attributeMap = new HashMap<>(); + NamingEnumeration attrs = sr.getAttributes().getAll(); + while (null != attrs && attrs.hasMoreElements()) { + Attribute objAttrs = attrs.nextElement(); + _logger.trace("attribute {} : {}" , + objAttrs.getID(), + ActiveDirectoryUtils.getAttrStringValue(objAttrs) + ); + attributeMap.put(objAttrs.getID().toLowerCase(), objAttrs); + } + + Organizations organization = buildOrganization(attributeMap,sr.getName(),sr.getNameInNamespace()); + if(organization != null) { + orgsList.add(organization); + } + } + } + return orgsList; + } + + public SynchroRelated buildSynchroRelated(Organizations organization,String ldapDN,String name) { + return new SynchroRelated( + organization.getId(), + organization.getOrgName(), + organization.getOrgName(), + Organizations.CLASS_TYPE, + synchronizer.getId(), + synchronizer.getName(), + ldapDN, + name, + "", + organization.getParentId(), + synchronizer.getInstId()); + } + + public Organizations buildOrganization(HashMap attributeMap,String name,String nameInNamespace) { + try { + Organizations org = new Organizations(); + org.setLdapDn(nameInNamespace); + String []namePaths = name.replaceAll(",OU=" , "/") + .replaceAll("OU=" , "/") + .replaceAll(",ou=" , "/") + .replaceAll("ou=" , "/") + .split("/"); + String namePah= "/"+rootOrganization.getOrgName(); + for(int i = namePaths.length -1 ; i >= 0 ; i --) { + namePah = namePah + "/" + namePaths[i]; + } + + namePah = namePah.substring(0, namePah.length() - 1); + + org.setId(org.generateId()); + org.setOrgCode(org.getId()); + org.setNamePath(namePah); + org.setLevel(namePaths.length); + org.setOrgName(LdapUtils.getAttributeStringValue(OrganizationalUnit.OU,attributeMap)); + org.setFullName(org.getOrgName()); + org.setType("department"); + org.setCountry(LdapUtils.getAttributeStringValue(OrganizationalUnit.CO,attributeMap)); + org.setRegion(LdapUtils.getAttributeStringValue(OrganizationalUnit.ST,attributeMap)); + org.setLocality(LdapUtils.getAttributeStringValue(OrganizationalUnit.L,attributeMap)); + org.setStreet(LdapUtils.getAttributeStringValue(OrganizationalUnit.STREET,attributeMap)); + org.setPostalCode(LdapUtils.getAttributeStringValue(OrganizationalUnit.POSTALCODE,attributeMap)); + org.setDescription(LdapUtils.getAttributeStringValue(OrganizationalUnit.DESCRIPTION,attributeMap)); + org.setInstId(this.synchronizer.getInstId()); + org.setStatus(ConstsStatus.ACTIVE); + + _logger.debug("Organization {}" , org); + return org; + } catch (NamingException e) { + _logger.error("NamingException " , e); + } + return null; + } - public Organizations buildOrgByFiledMap(HashMap attributeMap,String name,String nameInNamespace){ - Organizations org = new Organizations(); - Map filedMap = getFiledMap(Long.parseLong(synchronizer.getId())); - String []namePaths = name.replaceAll(",OU=" , "/") - .replaceAll("OU=" , "/") - .replaceAll(",ou=" , "/") - .replaceAll("ou=" , "/") - .split("/"); - String namePah= "/"+rootOrganization.getOrgName(); - for(int i = namePaths.length -1 ; i >= 0 ; i --) { - namePah = namePah + "/" + namePaths[i]; - } - namePah = namePah.substring(0, namePah.length() - 1); + public Organizations buildOrgByFiledMap(HashMap attributeMap,String name,String nameInNamespace){ + Organizations org = new Organizations(); + Map filedMap = getFiledMap(Long.parseLong(synchronizer.getId())); + String []namePaths = name.replaceAll(",OU=" , "/") + .replaceAll("OU=" , "/") + .replaceAll(",ou=" , "/") + .replaceAll("ou=" , "/") + .split("/"); + String namePah= "/"+rootOrganization.getOrgName(); + for(int i = namePaths.length -1 ; i >= 0 ; i --) { + namePah = namePah + "/" + namePaths[i]; + } + namePah = namePah.substring(0, namePah.length() - 1); - org.setLdapDn(nameInNamespace); - org.setNamePath(namePah); - org.setId(org.generateId()); - org.setLevel(namePaths.length); - org.setType("department"); - org.setInstId(this.synchronizer.getInstId()); - org.setStatus(ConstsStatus.ACTIVE); + org.setLdapDn(nameInNamespace); + org.setNamePath(namePah); + org.setId(org.generateId()); + org.setLevel(namePaths.length); + org.setType("department"); + org.setInstId(this.synchronizer.getInstId()); + org.setStatus(ConstsStatus.ACTIVE); - for (Map.Entry entry : filedMap.entrySet()) { - String orgProperty = entry.getKey(); - String sourceProperty = entry.getValue(); - try { - Object sourceValue = null; - if(attributeMap.keySet().contains(sourceProperty.toLowerCase())){ - sourceValue = LdapUtils.getAttributeStringValue(sourceProperty, attributeMap); - }else{ - sourceValue = getFieldValue(org, sourceProperty); - } - if (sourceValue != null) { - setFieldValue(org, orgProperty, sourceValue); - } - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | NamingException e) { - e.printStackTrace(); - } - } - org.setOrgCode(org.getId()); + for (Map.Entry entry : filedMap.entrySet()) { + String orgProperty = entry.getKey(); + String sourceProperty = entry.getValue(); + try { + Object sourceValue = null; + if(attributeMap.keySet().contains(sourceProperty.toLowerCase())){ + sourceValue = LdapUtils.getAttributeStringValue(sourceProperty, attributeMap); + }else{ + sourceValue = getFieldValue(org, sourceProperty); + } + if (sourceValue != null) { + setFieldValue(org, orgProperty, sourceValue); + } + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | NamingException e) { + e.printStackTrace(); + } + } + org.setOrgCode(org.getId()); - return org; - } + return org; + } - public Map getFiledMap(Long jobId){ - Map filedMap = new HashMap<>(); - //根据job id查询属性映射表 - List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); - //获取用户属性映射 - for(SyncJobConfigField element:syncJobConfigFieldList){ - if(Integer.parseInt(element.getObjectType()) == ORG_TYPE.intValue()){ - filedMap.put(element.getTargetField(),element.getSourceField()); - } - } - return filedMap; - } - - + public Map getFiledMap(Long jobId){ + Map filedMap = new HashMap<>(); + //根据job id查询属性映射表 + List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); + //获取用户属性映射 + for(SyncJobConfigField element:syncJobConfigFieldList){ + if(Integer.parseInt(element.getObjectType()) == ORG_TYPE.intValue()){ + filedMap.put(element.getTargetField(),element.getSourceField()); + } + } + return filedMap; + } + + - public ActiveDirectoryUtils getLdapUtils() { - return ldapUtils; - } + public ActiveDirectoryUtils getLdapUtils() { + return ldapUtils; + } - public void setLdapUtils(ActiveDirectoryUtils ldapUtils) { - this.ldapUtils = ldapUtils; - } + public void setLdapUtils(ActiveDirectoryUtils ldapUtils) { + this.ldapUtils = ldapUtils; + } - public SyncJobConfigFieldService getSyncJobConfigFieldService() { - return syncJobConfigFieldService; - } + public SyncJobConfigFieldService getSyncJobConfigFieldService() { + return syncJobConfigFieldService; + } - public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { - this.syncJobConfigFieldService = syncJobConfigFieldService; - } + public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { + this.syncJobConfigFieldService = syncJobConfigFieldService; + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-activedirectory/src/main/java/org/dromara/maxkey/synchronizer/activedirectory/ActiveDirectorySynchronizerService.java b/maxkey-synchronizers/maxkey-synchronizer-activedirectory/src/main/java/org/dromara/maxkey/synchronizer/activedirectory/ActiveDirectorySynchronizerService.java index d250e0fdd..4cd14cefd 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-activedirectory/src/main/java/org/dromara/maxkey/synchronizer/activedirectory/ActiveDirectorySynchronizerService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-activedirectory/src/main/java/org/dromara/maxkey/synchronizer/activedirectory/ActiveDirectorySynchronizerService.java @@ -27,63 +27,63 @@ import org.springframework.stereotype.Service; @Service public class ActiveDirectorySynchronizerService implements ISynchronizerService{ - static final Logger _logger = LoggerFactory.getLogger(ActiveDirectorySynchronizerService.class); - - Synchronizers synchronizer; - - @Autowired - ActiveDirectoryUsersService activeDirectoryUsersService; - - @Autowired - ActiveDirectoryOrganizationService activeDirectoryOrganizationService; - - public ActiveDirectorySynchronizerService() { - super(); - } + static final Logger _logger = LoggerFactory.getLogger(ActiveDirectorySynchronizerService.class); + + Synchronizers synchronizer; + + @Autowired + ActiveDirectoryUsersService activeDirectoryUsersService; + + @Autowired + ActiveDirectoryOrganizationService activeDirectoryOrganizationService; + + public ActiveDirectorySynchronizerService() { + super(); + } - public void sync() { - _logger.info("Sync ..."); - ActiveDirectoryUtils ldapUtils = new ActiveDirectoryUtils( - synchronizer.getProviderUrl(), - synchronizer.getPrincipal(), - synchronizer.getCredentials(), - synchronizer.getUserBasedn(), - synchronizer.getMsadDomain()); - ldapUtils.openConnection(); - - activeDirectoryOrganizationService.setSynchronizer(synchronizer); - activeDirectoryOrganizationService.setLdapUtils(ldapUtils); - activeDirectoryOrganizationService.sync(); - - activeDirectoryUsersService.setSynchronizer(synchronizer); - activeDirectoryUsersService.setLdapUtils(ldapUtils); - activeDirectoryUsersService.sync(); - - ldapUtils.close(); - } + public void sync() { + _logger.info("Sync ..."); + ActiveDirectoryUtils ldapUtils = new ActiveDirectoryUtils( + synchronizer.getProviderUrl(), + synchronizer.getPrincipal(), + synchronizer.getCredentials(), + synchronizer.getUserBasedn(), + synchronizer.getMsadDomain()); + ldapUtils.openConnection(); + + activeDirectoryOrganizationService.setSynchronizer(synchronizer); + activeDirectoryOrganizationService.setLdapUtils(ldapUtils); + activeDirectoryOrganizationService.sync(); + + activeDirectoryUsersService.setSynchronizer(synchronizer); + activeDirectoryUsersService.setLdapUtils(ldapUtils); + activeDirectoryUsersService.sync(); + + ldapUtils.close(); + } - public ActiveDirectoryUsersService getActiveDirectoryUsersService() { - return activeDirectoryUsersService; - } + public ActiveDirectoryUsersService getActiveDirectoryUsersService() { + return activeDirectoryUsersService; + } - public void setActiveDirectoryUsersService(ActiveDirectoryUsersService activeDirectoryUsersService) { - this.activeDirectoryUsersService = activeDirectoryUsersService; - } + public void setActiveDirectoryUsersService(ActiveDirectoryUsersService activeDirectoryUsersService) { + this.activeDirectoryUsersService = activeDirectoryUsersService; + } - public ActiveDirectoryOrganizationService getActiveDirectoryOrganizationService() { - return activeDirectoryOrganizationService; - } + public ActiveDirectoryOrganizationService getActiveDirectoryOrganizationService() { + return activeDirectoryOrganizationService; + } - public void setActiveDirectoryOrganizationService( - ActiveDirectoryOrganizationService activeDirectoryOrganizationService) { - this.activeDirectoryOrganizationService = activeDirectoryOrganizationService; - } + public void setActiveDirectoryOrganizationService( + ActiveDirectoryOrganizationService activeDirectoryOrganizationService) { + this.activeDirectoryOrganizationService = activeDirectoryOrganizationService; + } - @Override - public void setSynchronizer(Synchronizers synchronizer) { - this.synchronizer = synchronizer; - } + @Override + public void setSynchronizer(Synchronizers synchronizer) { + this.synchronizer = synchronizer; + } - + } diff --git a/maxkey-synchronizers/maxkey-synchronizer-activedirectory/src/main/java/org/dromara/maxkey/synchronizer/activedirectory/ActiveDirectoryUsersService.java b/maxkey-synchronizers/maxkey-synchronizer-activedirectory/src/main/java/org/dromara/maxkey/synchronizer/activedirectory/ActiveDirectoryUsersService.java index f2459b7d4..1cef616df 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-activedirectory/src/main/java/org/dromara/maxkey/synchronizer/activedirectory/ActiveDirectoryUsersService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-activedirectory/src/main/java/org/dromara/maxkey/synchronizer/activedirectory/ActiveDirectoryUsersService.java @@ -50,155 +50,155 @@ import static org.dromara.maxkey.synchronizer.utils.FieldUtil.setFieldValue; @Service public class ActiveDirectoryUsersService extends AbstractSynchronizerService implements ISynchronizerService{ - final static Logger _logger = LoggerFactory.getLogger(ActiveDirectoryUsersService.class); - @Autowired - private SyncJobConfigFieldService syncJobConfigFieldService; + final static Logger _logger = LoggerFactory.getLogger(ActiveDirectoryUsersService.class); + @Autowired + private SyncJobConfigFieldService syncJobConfigFieldService; - private static final Integer USER_TYPE = 1; - ActiveDirectoryUtils ldapUtils; - - public void sync() { - _logger.info("Sync ActiveDirectory Users..."); - loadOrgsByInstId(this.synchronizer.getInstId(),Organizations.ROOT_ORG_ID); - try { - SearchControls constraints = new SearchControls(); - constraints.setSearchScope(ldapUtils.getSearchScope()); - String filter = StringUtils.isNotBlank(this.getSynchronizer().getUserFilters())? - getSynchronizer().getUserFilters() : "(&(objectClass=User))"; - NamingEnumeration results = - ldapUtils.getConnection().search(ldapUtils.getBaseDN(), filter, constraints); - - long recordCount = 0; - while (null != results && results.hasMoreElements()) { - Object obj = results.nextElement(); - if (obj instanceof SearchResult) { - SearchResult sr = (SearchResult) obj; - if(sr.getNameInNamespace().contains("CN=Users,") - ||sr.getNameInNamespace().contains("OU=Domain Controllers,")) { - _logger.trace("Skip 'CN=Users' or 'OU=Domain Controllers' . "); - continue; - } - _logger.debug("Sync User {} , name [{}] , NameInNamespace [{}]" , - (++recordCount),sr.getName(),sr.getNameInNamespace()); - - HashMap attributeMap = new HashMap(); - NamingEnumeration attrs = sr.getAttributes().getAll(); - while (null != attrs && attrs.hasMoreElements()) { - Attribute objAttrs = attrs.nextElement(); - _logger.trace("attribute {} : {}" , - objAttrs.getID(), - ActiveDirectoryUtils.getAttrStringValue(objAttrs) - ); - attributeMap.put(objAttrs.getID().toLowerCase(), objAttrs); - } - - String originId = DigestUtils.md5B64(sr.getNameInNamespace()); - - UserInfo userInfo =buildUserInfo(attributeMap,sr.getName(),sr.getNameInNamespace()); - if(userInfo != null) { - userInfo.setPassword(userInfo.getUsername() + UserInfo.DEFAULT_PASSWORD_SUFFIX); - userInfoService.saveOrUpdate(userInfo); - _logger.info("userInfo " + userInfo); - - SynchroRelated synchroRelated = new SynchroRelated( - userInfo.getId(), - userInfo.getUsername(), - userInfo.getDisplayName(), - UserInfo.CLASS_TYPE, - synchronizer.getId(), - synchronizer.getName(), - originId, - userInfo.getDisplayName(), - "", - "", - synchronizer.getInstId()); - - synchroRelatedService.updateSynchroRelated( - this.synchronizer,synchroRelated,UserInfo.CLASS_TYPE); - } - } - } + private static final Integer USER_TYPE = 1; + ActiveDirectoryUtils ldapUtils; + + public void sync() { + _logger.info("Sync ActiveDirectory Users..."); + loadOrgsByInstId(this.synchronizer.getInstId(),Organizations.ROOT_ORG_ID); + try { + SearchControls constraints = new SearchControls(); + constraints.setSearchScope(ldapUtils.getSearchScope()); + String filter = StringUtils.isNotBlank(this.getSynchronizer().getUserFilters())? + getSynchronizer().getUserFilters() : "(&(objectClass=User))"; + NamingEnumeration results = + ldapUtils.getConnection().search(ldapUtils.getBaseDN(), filter, constraints); + + long recordCount = 0; + while (null != results && results.hasMoreElements()) { + Object obj = results.nextElement(); + if (obj instanceof SearchResult) { + SearchResult sr = (SearchResult) obj; + if(sr.getNameInNamespace().contains("CN=Users,") + ||sr.getNameInNamespace().contains("OU=Domain Controllers,")) { + _logger.trace("Skip 'CN=Users' or 'OU=Domain Controllers' . "); + continue; + } + _logger.debug("Sync User {} , name [{}] , NameInNamespace [{}]" , + (++recordCount),sr.getName(),sr.getNameInNamespace()); + + HashMap attributeMap = new HashMap(); + NamingEnumeration attrs = sr.getAttributes().getAll(); + while (null != attrs && attrs.hasMoreElements()) { + Attribute objAttrs = attrs.nextElement(); + _logger.trace("attribute {} : {}" , + objAttrs.getID(), + ActiveDirectoryUtils.getAttrStringValue(objAttrs) + ); + attributeMap.put(objAttrs.getID().toLowerCase(), objAttrs); + } + + String originId = DigestUtils.md5B64(sr.getNameInNamespace()); + + UserInfo userInfo =buildUserInfo(attributeMap,sr.getName(),sr.getNameInNamespace()); + if(userInfo != null) { + userInfo.setPassword(userInfo.getUsername() + UserInfo.DEFAULT_PASSWORD_SUFFIX); + userInfoService.saveOrUpdate(userInfo); + _logger.info("userInfo " + userInfo); + + SynchroRelated synchroRelated = new SynchroRelated( + userInfo.getId(), + userInfo.getUsername(), + userInfo.getDisplayName(), + UserInfo.CLASS_TYPE, + synchronizer.getId(), + synchronizer.getName(), + originId, + userInfo.getDisplayName(), + "", + "", + synchronizer.getInstId()); + + synchroRelatedService.updateSynchroRelated( + this.synchronizer,synchroRelated,UserInfo.CLASS_TYPE); + } + } + } - //ldapUtils.close(); - } catch (NamingException e) { - _logger.error("NamingException " , e); - } - - } + //ldapUtils.close(); + } catch (NamingException e) { + _logger.error("NamingException " , e); + } + + } - public UserInfo buildUserInfo(HashMap attributeMap,String name,String nameInNamespace) { - - UserInfo userInfo = new UserInfo(); - userInfo.setLdapDn(nameInNamespace); - String []namePaths = name.replaceAll(",OU=" , "/") - .replaceAll("OU=" , "/") - .replaceAll(",ou=" , "/") - .replaceAll("ou=" , "/") - .split("/"); - - String namePah= "/"+rootOrganization.getOrgName(); - for(int i = namePaths.length -1 ; i >= 0 ; i --) { - namePah = namePah + "/" + namePaths[i]; - } - + public UserInfo buildUserInfo(HashMap attributeMap,String name,String nameInNamespace) { + + UserInfo userInfo = new UserInfo(); + userInfo.setLdapDn(nameInNamespace); + String []namePaths = name.replaceAll(",OU=" , "/") + .replaceAll("OU=" , "/") + .replaceAll(",ou=" , "/") + .replaceAll("ou=" , "/") + .split("/"); + + String namePah= "/"+rootOrganization.getOrgName(); + for(int i = namePaths.length -1 ; i >= 0 ; i --) { + namePah = namePah + "/" + namePaths[i]; + } + namePah = namePah.substring(0, namePah.length()); String deptNamePath= namePah.substring(0, namePah.lastIndexOf("/")); _logger.info("deptNamePath " + deptNamePath); - + Organizations deptOrg = orgsNamePathMap.get(deptNamePath); if(deptOrg == null ) { - deptOrg = rootOrganization; - } + deptOrg = rootOrganization; + } userInfo.setDepartment(deptOrg.getOrgName()); userInfo.setDepartmentId(deptOrg.getId()); - try { - userInfo.setId(userInfo.generateId()); - userInfo.setFormattedName(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.CN,attributeMap));//cn - // - userInfo.setUsername(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.SAMACCOUNTNAME,attributeMap));//WindowsAccount - userInfo.setWindowsAccount(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.SAMACCOUNTNAME,attributeMap)); - //userInfo.setWindowsAccount(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.USERPRINCIPALNAME,attributeMap));// - - // - userInfo.setFamilyName(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.SN,attributeMap));//Last Name/SurName - userInfo.setGivenName(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.GIVENNAME,attributeMap));//First Name - userInfo.setNickName(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.INITIALS,attributeMap));//Initials - userInfo.setNameZhShortSpell(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.INITIALS,attributeMap));//Initials - userInfo.setDisplayName(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.DISPLAYNAME,attributeMap));// - userInfo.setDescription(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.DESCRIPTION,attributeMap));// - userInfo.setWorkPhoneNumber(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.TELEPHONENUMBER,attributeMap));// - userInfo.setWorkOfficeName(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.PHYSICALDELIVERYOFFICENAME,attributeMap));// - userInfo.setWorkEmail(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.MAIL,attributeMap));// - userInfo.setWebSite(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.WWWHOMEPAGE,attributeMap));// - // - userInfo.setWorkCountry(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.CO,attributeMap));// - userInfo.setWorkRegion(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.ST,attributeMap));// - userInfo.setWorkLocality(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.L,attributeMap));// - userInfo.setWorkStreetAddress(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.STREETADDRESS,attributeMap));// - userInfo.setWorkPostalCode(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.POSTALCODE,attributeMap));// - userInfo.setWorkAddressFormatted(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.POSTOFFICEBOX,attributeMap));// - - if(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.MOBILE,attributeMap).equals("")) { - userInfo.setMobile(userInfo.getId()); - }else { - userInfo.setMobile(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.MOBILE,attributeMap));// - } - userInfo.setHomePhoneNumber(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.HOMEPHONE,attributeMap));// - userInfo.setWorkFax(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.FACSIMILETELEPHONENUMBER,attributeMap));// - userInfo.setHomeAddressFormatted(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.INFO,attributeMap));// - - userInfo.setDivision(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.COMPANY,attributeMap)); // - //userInfo.setDepartment(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.DEPARTMENT,attributeMap)); // - //userInfo.setDepartmentId(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.DEPARTMENT,attributeMap)); // - userInfo.setJobTitle(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.TITLE,attributeMap));// - userInfo.setUserState("RESIDENT"); - userInfo.setUserType("EMPLOYEE"); - userInfo.setTimeZone("Asia/Shanghai"); - userInfo.setStatus(ConstsStatus.ACTIVE); - userInfo.setInstId(this.synchronizer.getInstId()); - - HistorySynchronizer historySynchronizer =new HistorySynchronizer(); + try { + userInfo.setId(userInfo.generateId()); + userInfo.setFormattedName(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.CN,attributeMap));//cn + // + userInfo.setUsername(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.SAMACCOUNTNAME,attributeMap));//WindowsAccount + userInfo.setWindowsAccount(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.SAMACCOUNTNAME,attributeMap)); + //userInfo.setWindowsAccount(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.USERPRINCIPALNAME,attributeMap));// + + // + userInfo.setFamilyName(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.SN,attributeMap));//Last Name/SurName + userInfo.setGivenName(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.GIVENNAME,attributeMap));//First Name + userInfo.setNickName(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.INITIALS,attributeMap));//Initials + userInfo.setNameZhShortSpell(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.INITIALS,attributeMap));//Initials + userInfo.setDisplayName(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.DISPLAYNAME,attributeMap));// + userInfo.setDescription(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.DESCRIPTION,attributeMap));// + userInfo.setWorkPhoneNumber(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.TELEPHONENUMBER,attributeMap));// + userInfo.setWorkOfficeName(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.PHYSICALDELIVERYOFFICENAME,attributeMap));// + userInfo.setWorkEmail(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.MAIL,attributeMap));// + userInfo.setWebSite(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.WWWHOMEPAGE,attributeMap));// + // + userInfo.setWorkCountry(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.CO,attributeMap));// + userInfo.setWorkRegion(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.ST,attributeMap));// + userInfo.setWorkLocality(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.L,attributeMap));// + userInfo.setWorkStreetAddress(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.STREETADDRESS,attributeMap));// + userInfo.setWorkPostalCode(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.POSTALCODE,attributeMap));// + userInfo.setWorkAddressFormatted(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.POSTOFFICEBOX,attributeMap));// + + if(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.MOBILE,attributeMap).equals("")) { + userInfo.setMobile(userInfo.getId()); + }else { + userInfo.setMobile(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.MOBILE,attributeMap));// + } + userInfo.setHomePhoneNumber(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.HOMEPHONE,attributeMap));// + userInfo.setWorkFax(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.FACSIMILETELEPHONENUMBER,attributeMap));// + userInfo.setHomeAddressFormatted(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.INFO,attributeMap));// + + userInfo.setDivision(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.COMPANY,attributeMap)); // + //userInfo.setDepartment(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.DEPARTMENT,attributeMap)); // + //userInfo.setDepartmentId(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.DEPARTMENT,attributeMap)); // + userInfo.setJobTitle(LdapUtils.getAttributeStringValue(ActiveDirectoryUser.TITLE,attributeMap));// + userInfo.setUserState("RESIDENT"); + userInfo.setUserType("EMPLOYEE"); + userInfo.setTimeZone("Asia/Shanghai"); + userInfo.setStatus(ConstsStatus.ACTIVE); + userInfo.setInstId(this.synchronizer.getInstId()); + + HistorySynchronizer historySynchronizer =new HistorySynchronizer(); historySynchronizer.setId(historySynchronizer.generateId()); historySynchronizer.setSyncId(this.synchronizer.getId()); historySynchronizer.setSyncName(this.synchronizer.getName()); @@ -209,121 +209,121 @@ public class ActiveDirectoryUsersService extends AbstractSynchronizerService historySynchronizer.setResult("success"); this.historySynchronizerService.insert(historySynchronizer); - } catch (NamingException e) { - e.printStackTrace(); - } - return userInfo; - } + } catch (NamingException e) { + e.printStackTrace(); + } + return userInfo; + } - public UserInfo buildUserInfoByFieldMap(HashMap attributeMap,String name,String nameInNamespace){ - UserInfo userInfo = new UserInfo(); - userInfo.setLdapDn(nameInNamespace); - userInfo.setId(userInfo.generateId()); - String []namePaths = name.replaceAll(",OU=" , "/") - .replaceAll("OU=" , "/") - .replaceAll(",ou=" , "/") - .replaceAll("ou=" , "/") - .split("/"); + public UserInfo buildUserInfoByFieldMap(HashMap attributeMap,String name,String nameInNamespace){ + UserInfo userInfo = new UserInfo(); + userInfo.setLdapDn(nameInNamespace); + userInfo.setId(userInfo.generateId()); + String []namePaths = name.replaceAll(",OU=" , "/") + .replaceAll("OU=" , "/") + .replaceAll(",ou=" , "/") + .replaceAll("ou=" , "/") + .split("/"); - String namePah= "/"+rootOrganization.getOrgName(); - for(int i = namePaths.length -1 ; i >= 0 ; i --) { - namePah = namePah + "/" + namePaths[i]; - } + String namePah= "/"+rootOrganization.getOrgName(); + for(int i = namePaths.length -1 ; i >= 0 ; i --) { + namePah = namePah + "/" + namePaths[i]; + } - namePah = namePah.substring(0, namePah.length()); - String deptNamePath= namePah.substring(0, namePah.lastIndexOf("/")); - _logger.info("deptNamePath " + deptNamePath); - - Organizations deptOrg = orgsNamePathMap.get(deptNamePath); - if(deptOrg == null ) { - deptOrg = rootOrganization; - } - Map fieldMap = getFieldMap(Long.parseLong(synchronizer.getId())); - for (Map.Entry entry : fieldMap.entrySet()) { - String userInfoProperty = entry.getKey(); - String sourceProperty = entry.getValue(); - try { - - if(sourceProperty.equals("orgName")){ - userInfo.setDepartment(deptOrg.getOrgName()); - continue; - } - if(sourceProperty.equals("id")){ - userInfo.setDepartmentId(deptOrg.getId()); - continue; - } - if(sourceProperty.equals("mobile")){ - userInfo.setMobile(LdapUtils.getAttributeStringValue(sourceProperty, attributeMap).equals("")? - userInfo.getId():LdapUtils.getAttributeStringValue(sourceProperty,attributeMap)); - continue; - } - // 获取源属性的值 - Object sourceValue = LdapUtils.getAttributeStringValue(sourceProperty, attributeMap); - // 设置到 UserInfo 对象 - if (sourceValue != null) { - setFieldValue(userInfo, userInfoProperty, sourceValue); - } - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } catch (NamingException e) { - e.printStackTrace(); - } - } + namePah = namePah.substring(0, namePah.length()); + String deptNamePath= namePah.substring(0, namePah.lastIndexOf("/")); + _logger.info("deptNamePath " + deptNamePath); + + Organizations deptOrg = orgsNamePathMap.get(deptNamePath); + if(deptOrg == null ) { + deptOrg = rootOrganization; + } + Map fieldMap = getFieldMap(Long.parseLong(synchronizer.getId())); + for (Map.Entry entry : fieldMap.entrySet()) { + String userInfoProperty = entry.getKey(); + String sourceProperty = entry.getValue(); + try { + + if(sourceProperty.equals("orgName")){ + userInfo.setDepartment(deptOrg.getOrgName()); + continue; + } + if(sourceProperty.equals("id")){ + userInfo.setDepartmentId(deptOrg.getId()); + continue; + } + if(sourceProperty.equals("mobile")){ + userInfo.setMobile(LdapUtils.getAttributeStringValue(sourceProperty, attributeMap).equals("")? + userInfo.getId():LdapUtils.getAttributeStringValue(sourceProperty,attributeMap)); + continue; + } + // 获取源属性的值 + Object sourceValue = LdapUtils.getAttributeStringValue(sourceProperty, attributeMap); + // 设置到 UserInfo 对象 + if (sourceValue != null) { + setFieldValue(userInfo, userInfoProperty, sourceValue); + } + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } catch (NamingException e) { + e.printStackTrace(); + } + } - try { - userInfo.setLdapDn(nameInNamespace); - userInfo.setUserState("RESIDENT"); - userInfo.setUserType("EMPLOYEE"); - userInfo.setTimeZone("Asia/Shanghai"); - userInfo.setStatus(ConstsStatus.ACTIVE); - userInfo.setInstId(this.synchronizer.getInstId()); + try { + userInfo.setLdapDn(nameInNamespace); + userInfo.setUserState("RESIDENT"); + userInfo.setUserType("EMPLOYEE"); + userInfo.setTimeZone("Asia/Shanghai"); + userInfo.setStatus(ConstsStatus.ACTIVE); + userInfo.setInstId(this.synchronizer.getInstId()); - - HistorySynchronizer historySynchronizer =new HistorySynchronizer(); - historySynchronizer.setId(historySynchronizer.generateId()); - historySynchronizer.setSyncId(this.synchronizer.getId()); - historySynchronizer.setSyncName(this.synchronizer.getName()); - historySynchronizer.setObjectId(userInfo.getId()); - historySynchronizer.setObjectName(userInfo.getUsername()); - historySynchronizer.setObjectType(Organizations.class.getSimpleName()); - historySynchronizer.setInstId(synchronizer.getInstId()); - historySynchronizer.setResult("success"); - this.historySynchronizerService.insert(historySynchronizer); - } catch (Exception e) { - e.printStackTrace(); - } + + HistorySynchronizer historySynchronizer =new HistorySynchronizer(); + historySynchronizer.setId(historySynchronizer.generateId()); + historySynchronizer.setSyncId(this.synchronizer.getId()); + historySynchronizer.setSyncName(this.synchronizer.getName()); + historySynchronizer.setObjectId(userInfo.getId()); + historySynchronizer.setObjectName(userInfo.getUsername()); + historySynchronizer.setObjectType(Organizations.class.getSimpleName()); + historySynchronizer.setInstId(synchronizer.getInstId()); + historySynchronizer.setResult("success"); + this.historySynchronizerService.insert(historySynchronizer); + } catch (Exception e) { + e.printStackTrace(); + } - return userInfo; - } + return userInfo; + } - public Map getFieldMap(Long jobId){ - Map fieldMap = new HashMap<>(); - //根据job id查询属性映射表 - List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); - //获取用户属性映射 - for(SyncJobConfigField element:syncJobConfigFieldList){ - if(Integer.parseInt(element.getObjectType()) == USER_TYPE.intValue()){ - fieldMap.put(element.getTargetField(), element.getSourceField()); - } - } - return fieldMap; - } + public Map getFieldMap(Long jobId){ + Map fieldMap = new HashMap<>(); + //根据job id查询属性映射表 + List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); + //获取用户属性映射 + for(SyncJobConfigField element:syncJobConfigFieldList){ + if(Integer.parseInt(element.getObjectType()) == USER_TYPE.intValue()){ + fieldMap.put(element.getTargetField(), element.getSourceField()); + } + } + return fieldMap; + } - public ActiveDirectoryUtils getLdapUtils() { - return ldapUtils; - } + public ActiveDirectoryUtils getLdapUtils() { + return ldapUtils; + } - public void setLdapUtils(ActiveDirectoryUtils ldapUtils) { - this.ldapUtils = ldapUtils; - } + public void setLdapUtils(ActiveDirectoryUtils ldapUtils) { + this.ldapUtils = ldapUtils; + } - public SyncJobConfigFieldService getSyncJobConfigFieldService() { - return syncJobConfigFieldService; - } + public SyncJobConfigFieldService getSyncJobConfigFieldService() { + return syncJobConfigFieldService; + } - public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { - this.syncJobConfigFieldService = syncJobConfigFieldService; - } + public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { + this.syncJobConfigFieldService = syncJobConfigFieldService; + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-dingtalk/src/main/java/org/dromara/maxkey/synchronizer/dingtalk/DingtalkAccessTokenService.java b/maxkey-synchronizers/maxkey-synchronizer-dingtalk/src/main/java/org/dromara/maxkey/synchronizer/dingtalk/DingtalkAccessTokenService.java index ab6e5c1b1..1035569a9 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-dingtalk/src/main/java/org/dromara/maxkey/synchronizer/dingtalk/DingtalkAccessTokenService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-dingtalk/src/main/java/org/dromara/maxkey/synchronizer/dingtalk/DingtalkAccessTokenService.java @@ -27,60 +27,60 @@ import com.dingtalk.api.response.OapiGettokenResponse; import com.taobao.api.ApiException; public class DingtalkAccessTokenService { - static final Logger _logger = LoggerFactory.getLogger(DingtalkAccessTokenService.class); - - String appkey; - - String appsecret; - - public DingtalkAccessTokenService() { - - } - public DingtalkAccessTokenService(String appkey, String appsecret) { - super(); - this.appkey = appkey; - this.appsecret = appsecret; - } + static final Logger _logger = LoggerFactory.getLogger(DingtalkAccessTokenService.class); + + String appkey; + + String appsecret; + + public DingtalkAccessTokenService() { + + } + public DingtalkAccessTokenService(String appkey, String appsecret) { + super(); + this.appkey = appkey; + this.appsecret = appsecret; + } - public String requestToken() throws ApiException { - DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken"); - OapiGettokenRequest request = new OapiGettokenRequest(); - request.setAppkey(appkey); - request.setAppsecret(appsecret); - request.setHttpMethod("GET"); - OapiGettokenResponse response = client.execute(request); - _logger.info("response : " + response.getBody()); - - if(response.getErrcode()== 0){ - return response.getAccessToken(); - } - return ""; - } - - - public String getAppkey() { - return appkey; - } + public String requestToken() throws ApiException { + DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken"); + OapiGettokenRequest request = new OapiGettokenRequest(); + request.setAppkey(appkey); + request.setAppsecret(appsecret); + request.setHttpMethod("GET"); + OapiGettokenResponse response = client.execute(request); + _logger.info("response : " + response.getBody()); + + if(response.getErrcode()== 0){ + return response.getAccessToken(); + } + return ""; + } + + + public String getAppkey() { + return appkey; + } - public void setAppkey(String appkey) { - this.appkey = appkey; - } + public void setAppkey(String appkey) { + this.appkey = appkey; + } - public String getAppsecret() { - return appsecret; - } + public String getAppsecret() { + return appsecret; + } - public void setAppsecret(String appsecret) { - this.appsecret = appsecret; - } + public void setAppsecret(String appsecret) { + this.appsecret = appsecret; + } - public static void main(String[] args) { + public static void main(String[] args) { - } + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-dingtalk/src/main/java/org/dromara/maxkey/synchronizer/dingtalk/DingtalkOrganizationService.java b/maxkey-synchronizers/maxkey-synchronizer-dingtalk/src/main/java/org/dromara/maxkey/synchronizer/dingtalk/DingtalkOrganizationService.java index 8188ace3e..911457881 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-dingtalk/src/main/java/org/dromara/maxkey/synchronizer/dingtalk/DingtalkOrganizationService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-dingtalk/src/main/java/org/dromara/maxkey/synchronizer/dingtalk/DingtalkOrganizationService.java @@ -48,199 +48,199 @@ import static org.dromara.maxkey.synchronizer.utils.FieldUtil.*; @Service public class DingtalkOrganizationService extends AbstractSynchronizerService implements ISynchronizerService{ - final static Logger _logger = LoggerFactory.getLogger(DingtalkOrganizationService.class); + final static Logger _logger = LoggerFactory.getLogger(DingtalkOrganizationService.class); - @Autowired - private SyncJobConfigFieldService syncJobConfigFieldService; - private static final Integer ORG_TYPE = 2; - - static Long ROOT_DEPT_ID = 1L; - - String access_token; - - public void sync() { - _logger.info("Sync Dingtalk Organizations ..."); - LinkedBlockingQueue deptsQueue = new LinkedBlockingQueue(); - deptsQueue.add(ROOT_DEPT_ID); - try { - //root - Organizations rootOrganization = organizationsService.get(Organizations.ROOT_ORG_ID); - OapiV2DepartmentGetResponse rootDeptRsp = requestDepartment(access_token,ROOT_DEPT_ID); - _logger.debug("root dept deptId {} , name {} , parentId {}" - ,rootDeptRsp.getResult().getDeptId(), - rootDeptRsp.getResult().getName(), - rootDeptRsp.getResult().getParentId()); - //root - SynchroRelated rootSynchroRelated = buildSynchroRelated(rootOrganization, - rootDeptRsp.getResult().getDeptId()+"", - rootDeptRsp.getResult().getName(), - rootDeptRsp.getResult().getParentId()+""); - - synchroRelatedService.updateSynchroRelated( - this.synchronizer,rootSynchroRelated,Organizations.CLASS_TYPE); - - while(deptsQueue.element() != null) { - OapiV2DepartmentListsubResponse rsp = requestDepartmentList(access_token,deptsQueue.poll()); - - for(DeptBaseResponse dept : rsp.getResult()) { - _logger.debug("dept deptId {} , name {} , parentId {} " , - dept.getDeptId(), - dept.getName(), - dept.getParentId()); - - deptsQueue.add(dept.getDeptId()); + @Autowired + private SyncJobConfigFieldService syncJobConfigFieldService; + private static final Integer ORG_TYPE = 2; + + static Long ROOT_DEPT_ID = 1L; + + String access_token; + + public void sync() { + _logger.info("Sync Dingtalk Organizations ..."); + LinkedBlockingQueue deptsQueue = new LinkedBlockingQueue(); + deptsQueue.add(ROOT_DEPT_ID); + try { + //root + Organizations rootOrganization = organizationsService.get(Organizations.ROOT_ORG_ID); + OapiV2DepartmentGetResponse rootDeptRsp = requestDepartment(access_token,ROOT_DEPT_ID); + _logger.debug("root dept deptId {} , name {} , parentId {}" + ,rootDeptRsp.getResult().getDeptId(), + rootDeptRsp.getResult().getName(), + rootDeptRsp.getResult().getParentId()); + //root + SynchroRelated rootSynchroRelated = buildSynchroRelated(rootOrganization, + rootDeptRsp.getResult().getDeptId()+"", + rootDeptRsp.getResult().getName(), + rootDeptRsp.getResult().getParentId()+""); + + synchroRelatedService.updateSynchroRelated( + this.synchronizer,rootSynchroRelated,Organizations.CLASS_TYPE); + + while(deptsQueue.element() != null) { + OapiV2DepartmentListsubResponse rsp = requestDepartmentList(access_token,deptsQueue.poll()); + + for(DeptBaseResponse dept : rsp.getResult()) { + _logger.debug("dept deptId {} , name {} , parentId {} " , + dept.getDeptId(), + dept.getName(), + dept.getParentId()); + + deptsQueue.add(dept.getDeptId()); - //synchro Related - SynchroRelated synchroRelated = - synchroRelatedService.findByOriginId( - this.synchronizer,dept.getDeptId() + "",Organizations.CLASS_TYPE ); - //Parent - SynchroRelated synchroRelatedParent = - synchroRelatedService.findByOriginId( - this.synchronizer,dept.getParentId() + "",Organizations.CLASS_TYPE); - Organizations organization = buildOrgByFieldMap(dept,synchroRelatedParent); - if(synchroRelated == null) { - organization.setId(organization.generateId()); - organizationsService.insert(organization); - _logger.debug("Organizations : " + organization); - - synchroRelated = buildSynchroRelated(organization, - dept.getDeptId() + "", - dept.getName(), - dept.getParentId() + ""); - - }else { - organization.setId(synchroRelated.getObjectId()); - organizationsService.update(organization); - } - - synchroRelatedService.updateSynchroRelated( - this.synchronizer,synchroRelated,Organizations.CLASS_TYPE); - - _logger.debug("Organizations : " + organization); - } - } - } catch (ApiException e) { - e.printStackTrace(); - }catch (NoSuchElementException e) { - _logger.debug("Sync Department successful ."); - } - - } - - public OapiV2DepartmentListsubResponse requestDepartmentList(String access_token,Long deptId) throws ApiException { - DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub"); - OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest(); - req.setDeptId(deptId); - req.setLanguage("zh_CN"); - OapiV2DepartmentListsubResponse rspDepts = client.execute(req, access_token); - _logger.trace("response : " + rspDepts.getBody()); - return rspDepts; - } - - public OapiV2DepartmentGetResponse requestDepartment(String access_token,Long deptId) throws ApiException { - DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/get"); - OapiV2DepartmentGetRequest req = new OapiV2DepartmentGetRequest(); - req.setDeptId(deptId); - req.setLanguage("zh_CN"); - OapiV2DepartmentGetResponse rspDepts = client.execute(req, access_token); - _logger.trace("response : " + rspDepts.getBody()); - return rspDepts; - } - - public SynchroRelated buildSynchroRelated(Organizations organization,String deptId,String name,String parentId) { - return new SynchroRelated( - organization.getId(), - organization.getOrgName(), - organization.getOrgName(), - Organizations.CLASS_TYPE, - synchronizer.getId(), - synchronizer.getName(), - deptId+"", - name, - "", - parentId, - synchronizer.getInstId()); - } - - public Organizations buildOrganization(DeptBaseResponse dept,SynchroRelated synchroRelatedParent) { + //synchro Related + SynchroRelated synchroRelated = + synchroRelatedService.findByOriginId( + this.synchronizer,dept.getDeptId() + "",Organizations.CLASS_TYPE ); + //Parent + SynchroRelated synchroRelatedParent = + synchroRelatedService.findByOriginId( + this.synchronizer,dept.getParentId() + "",Organizations.CLASS_TYPE); + Organizations organization = buildOrgByFieldMap(dept,synchroRelatedParent); + if(synchroRelated == null) { + organization.setId(organization.generateId()); + organizationsService.insert(organization); + _logger.debug("Organizations : " + organization); + + synchroRelated = buildSynchroRelated(organization, + dept.getDeptId() + "", + dept.getName(), + dept.getParentId() + ""); + + }else { + organization.setId(synchroRelated.getObjectId()); + organizationsService.update(organization); + } + + synchroRelatedService.updateSynchroRelated( + this.synchronizer,synchroRelated,Organizations.CLASS_TYPE); + + _logger.debug("Organizations : " + organization); + } + } + } catch (ApiException e) { + e.printStackTrace(); + }catch (NoSuchElementException e) { + _logger.debug("Sync Department successful ."); + } + + } + + public OapiV2DepartmentListsubResponse requestDepartmentList(String access_token,Long deptId) throws ApiException { + DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub"); + OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest(); + req.setDeptId(deptId); + req.setLanguage("zh_CN"); + OapiV2DepartmentListsubResponse rspDepts = client.execute(req, access_token); + _logger.trace("response : " + rspDepts.getBody()); + return rspDepts; + } + + public OapiV2DepartmentGetResponse requestDepartment(String access_token,Long deptId) throws ApiException { + DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/get"); + OapiV2DepartmentGetRequest req = new OapiV2DepartmentGetRequest(); + req.setDeptId(deptId); + req.setLanguage("zh_CN"); + OapiV2DepartmentGetResponse rspDepts = client.execute(req, access_token); + _logger.trace("response : " + rspDepts.getBody()); + return rspDepts; + } + + public SynchroRelated buildSynchroRelated(Organizations organization,String deptId,String name,String parentId) { + return new SynchroRelated( + organization.getId(), + organization.getOrgName(), + organization.getOrgName(), + Organizations.CLASS_TYPE, + synchronizer.getId(), + synchronizer.getName(), + deptId+"", + name, + "", + parentId, + synchronizer.getInstId()); + } + + public Organizations buildOrganization(DeptBaseResponse dept,SynchroRelated synchroRelatedParent) { - Organizations org = new Organizations(); - org.setId(dept.getDeptId()+""); - org.setOrgCode(dept.getDeptId()+""); - org.setOrgName(dept.getName()); - org.setParentCode(dept.getParentId()+""); - if(synchroRelatedParent != null) { - org.setParentId(synchroRelatedParent.getObjectId()); - org.setParentName(synchroRelatedParent.getObjectName()); - } - org.setInstId(this.synchronizer.getInstId()); - org.setStatus(ConstsStatus.ACTIVE); - org.setDescription("dingtalk"); - return org; - } + Organizations org = new Organizations(); + org.setId(dept.getDeptId()+""); + org.setOrgCode(dept.getDeptId()+""); + org.setOrgName(dept.getName()); + org.setParentCode(dept.getParentId()+""); + if(synchroRelatedParent != null) { + org.setParentId(synchroRelatedParent.getObjectId()); + org.setParentName(synchroRelatedParent.getObjectName()); + } + org.setInstId(this.synchronizer.getInstId()); + org.setStatus(ConstsStatus.ACTIVE); + org.setDescription("dingtalk"); + return org; + } - public Organizations buildOrgByFieldMap(DeptBaseResponse dept,SynchroRelated synchroRelatedParent){ - Organizations org = new Organizations(); - Map fieldMap = getFieldMap(Long.parseLong(synchronizer.getId())); + public Organizations buildOrgByFieldMap(DeptBaseResponse dept,SynchroRelated synchroRelatedParent){ + Organizations org = new Organizations(); + Map fieldMap = getFieldMap(Long.parseLong(synchronizer.getId())); - for (Map.Entry entry : fieldMap.entrySet()) { - String orgProperty = entry.getKey(); - String sourceProperty = entry.getValue(); - try { - Object sourceValue = null; + for (Map.Entry entry : fieldMap.entrySet()) { + String orgProperty = entry.getKey(); + String sourceProperty = entry.getValue(); + try { + Object sourceValue = null; - if (hasField(DeptBaseResponse.class, sourceProperty)) { - sourceValue = getFieldValue(dept, sourceProperty); - } - else if (synchroRelatedParent != null && hasField(SynchroRelated.class, sourceProperty)) { - sourceValue = getFieldValue(synchroRelatedParent, sourceProperty); - } - if (sourceValue != null) { - setFieldValue(org, orgProperty, sourceValue); - } - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } - } - org.setType("department"); - org.setInstId(this.synchronizer.getInstId()); - org.setStatus(ConstsStatus.ACTIVE); - org.setDescription("dingtalk"); - return org; - } + if (hasField(DeptBaseResponse.class, sourceProperty)) { + sourceValue = getFieldValue(dept, sourceProperty); + } + else if (synchroRelatedParent != null && hasField(SynchroRelated.class, sourceProperty)) { + sourceValue = getFieldValue(synchroRelatedParent, sourceProperty); + } + if (sourceValue != null) { + setFieldValue(org, orgProperty, sourceValue); + } + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + } + org.setType("department"); + org.setInstId(this.synchronizer.getInstId()); + org.setStatus(ConstsStatus.ACTIVE); + org.setDescription("dingtalk"); + return org; + } - public Map getFieldMap(Long jobId){ - Map FieldMap = new HashMap<>(); - //根据job id查询属性映射表 - List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); - //获取用户属性映射 - for(SyncJobConfigField element:syncJobConfigFieldList){ - if(Integer.parseInt(element.getObjectType()) == ORG_TYPE.intValue()){ - FieldMap.put(element.getTargetField(), element.getSourceField()); - } - } - return FieldMap; - } + public Map getFieldMap(Long jobId){ + Map FieldMap = new HashMap<>(); + //根据job id查询属性映射表 + List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); + //获取用户属性映射 + for(SyncJobConfigField element:syncJobConfigFieldList){ + if(Integer.parseInt(element.getObjectType()) == ORG_TYPE.intValue()){ + FieldMap.put(element.getTargetField(), element.getSourceField()); + } + } + return FieldMap; + } - public String getAccess_token() { - return access_token; - } + public String getAccess_token() { + return access_token; + } - public void setAccess_token(String access_token) { - this.access_token = access_token; - } + public void setAccess_token(String access_token) { + this.access_token = access_token; + } - public SyncJobConfigFieldService getSyncJobConfigFieldService() { - return syncJobConfigFieldService; - } + public SyncJobConfigFieldService getSyncJobConfigFieldService() { + return syncJobConfigFieldService; + } - public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { - this.syncJobConfigFieldService = syncJobConfigFieldService; - } - + public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { + this.syncJobConfigFieldService = syncJobConfigFieldService; + } + } diff --git a/maxkey-synchronizers/maxkey-synchronizer-dingtalk/src/main/java/org/dromara/maxkey/synchronizer/dingtalk/DingtalkSynchronizerService.java b/maxkey-synchronizers/maxkey-synchronizer-dingtalk/src/main/java/org/dromara/maxkey/synchronizer/dingtalk/DingtalkSynchronizerService.java index 7fc26a086..6f33d895f 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-dingtalk/src/main/java/org/dromara/maxkey/synchronizer/dingtalk/DingtalkSynchronizerService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-dingtalk/src/main/java/org/dromara/maxkey/synchronizer/dingtalk/DingtalkSynchronizerService.java @@ -28,70 +28,70 @@ import com.taobao.api.ApiException; @Service public class DingtalkSynchronizerService implements ISynchronizerService{ - static final Logger _logger = LoggerFactory.getLogger(DingtalkSynchronizerService.class); - Synchronizers synchronizer; - - @Autowired - DingtalkUsersService dingtalkUsersService; - - @Autowired - DingtalkOrganizationService dingtalkOrganizationService; - + static final Logger _logger = LoggerFactory.getLogger(DingtalkSynchronizerService.class); + Synchronizers synchronizer; + + @Autowired + DingtalkUsersService dingtalkUsersService; + + @Autowired + DingtalkOrganizationService dingtalkOrganizationService; + - DingtalkAccessTokenService dingtalkAccessTokenService = new DingtalkAccessTokenService(); - - public DingtalkSynchronizerService() { - super(); - } + DingtalkAccessTokenService dingtalkAccessTokenService = new DingtalkAccessTokenService(); + + public DingtalkSynchronizerService() { + super(); + } - public void sync() throws ApiException { - _logger.info("Sync ..."); - dingtalkAccessTokenService.setAppkey(synchronizer.getPrincipal()); - dingtalkAccessTokenService.setAppsecret(synchronizer.getCredentials()); - String access_token=dingtalkAccessTokenService.requestToken(); - - dingtalkOrganizationService.setSynchronizer(synchronizer); - dingtalkOrganizationService.setAccess_token(access_token); - dingtalkOrganizationService.sync(); - - dingtalkUsersService.setSynchronizer(synchronizer); - dingtalkUsersService.setAccess_token(access_token); - dingtalkUsersService.sync(); - } + public void sync() throws ApiException { + _logger.info("Sync ..."); + dingtalkAccessTokenService.setAppkey(synchronizer.getPrincipal()); + dingtalkAccessTokenService.setAppsecret(synchronizer.getCredentials()); + String access_token=dingtalkAccessTokenService.requestToken(); + + dingtalkOrganizationService.setSynchronizer(synchronizer); + dingtalkOrganizationService.setAccess_token(access_token); + dingtalkOrganizationService.sync(); + + dingtalkUsersService.setSynchronizer(synchronizer); + dingtalkUsersService.setAccess_token(access_token); + dingtalkUsersService.sync(); + } - public DingtalkUsersService getDingtalkUsersService() { - return dingtalkUsersService; - } + public DingtalkUsersService getDingtalkUsersService() { + return dingtalkUsersService; + } - public void setDingtalkUsersService(DingtalkUsersService dingtalkUsersService) { - this.dingtalkUsersService = dingtalkUsersService; - } + public void setDingtalkUsersService(DingtalkUsersService dingtalkUsersService) { + this.dingtalkUsersService = dingtalkUsersService; + } - public DingtalkOrganizationService getDingtalkOrganizationService() { - return dingtalkOrganizationService; - } + public DingtalkOrganizationService getDingtalkOrganizationService() { + return dingtalkOrganizationService; + } - public void setDingtalkOrganizationService(DingtalkOrganizationService dingtalkOrganizationService) { - this.dingtalkOrganizationService = dingtalkOrganizationService; - } + public void setDingtalkOrganizationService(DingtalkOrganizationService dingtalkOrganizationService) { + this.dingtalkOrganizationService = dingtalkOrganizationService; + } - public Synchronizers getSynchronizer() { - return synchronizer; - } + public Synchronizers getSynchronizer() { + return synchronizer; + } - public DingtalkAccessTokenService getDingtalkAccessTokenService() { - return dingtalkAccessTokenService; - } + public DingtalkAccessTokenService getDingtalkAccessTokenService() { + return dingtalkAccessTokenService; + } - public void setDingtalkAccessTokenService(DingtalkAccessTokenService dingtalkAccessTokenService) { - this.dingtalkAccessTokenService = dingtalkAccessTokenService; - } + public void setDingtalkAccessTokenService(DingtalkAccessTokenService dingtalkAccessTokenService) { + this.dingtalkAccessTokenService = dingtalkAccessTokenService; + } - @Override - public void setSynchronizer(Synchronizers synchronizer) { - this.synchronizer = synchronizer; - - } + @Override + public void setSynchronizer(Synchronizers synchronizer) { + this.synchronizer = synchronizer; + + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-dingtalk/src/main/java/org/dromara/maxkey/synchronizer/dingtalk/DingtalkUsersService.java b/maxkey-synchronizers/maxkey-synchronizer-dingtalk/src/main/java/org/dromara/maxkey/synchronizer/dingtalk/DingtalkUsersService.java index 585fb2429..2f5f02d03 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-dingtalk/src/main/java/org/dromara/maxkey/synchronizer/dingtalk/DingtalkUsersService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-dingtalk/src/main/java/org/dromara/maxkey/synchronizer/dingtalk/DingtalkUsersService.java @@ -46,179 +46,179 @@ import static org.dromara.maxkey.synchronizer.utils.FieldUtil.*; @Service public class DingtalkUsersService extends AbstractSynchronizerService implements ISynchronizerService{ - static final Logger _logger = LoggerFactory.getLogger(DingtalkUsersService.class); - - String access_token; + static final Logger _logger = LoggerFactory.getLogger(DingtalkUsersService.class); + + String access_token; - private static final Integer USER_TYPE = 1; + private static final Integer USER_TYPE = 1; - @Autowired - private SyncJobConfigFieldService syncJobConfigFieldService; + @Autowired + private SyncJobConfigFieldService syncJobConfigFieldService; - - public void sync() { - _logger.info("Sync Dingtalk Users..."); - try { - List synchroRelateds = - synchroRelatedService.findOrgs(this.synchronizer); - - for(SynchroRelated relatedOrg : synchroRelateds) { - DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list"); - OapiV2UserListRequest req = new OapiV2UserListRequest(); - _logger.debug("DingTalk deptId : {}" , relatedOrg.getOriginId()); - req.setDeptId(Long.parseLong(relatedOrg.getOriginId())); - req.setCursor(0L); - req.setSize(100L); - req.setOrderField("modify_desc"); - req.setContainAccessLimit(true); - req.setLanguage("zh_CN"); - OapiV2UserListResponse rsp = client.execute(req, access_token); - _logger.trace("response : {}" , rsp.getBody()); - - if(rsp.getErrcode()==0) { - for(ListUserResponse user :rsp.getResult().getList()) { - _logger.debug("name : {} , {} , {}", user.getName(),user.getLoginId(),user.getUserid()); - - UserInfo userInfo = buildUserInfoByFieldMap(user,relatedOrg); - _logger.trace("userInfo {}" , userInfo); - userInfo.setPassword(userInfo.getUsername() + UserInfo.DEFAULT_PASSWORD_SUFFIX); - userInfoService.saveOrUpdate(userInfo); - - SynchroRelated synchroRelated = new SynchroRelated( - userInfo.getId(), - userInfo.getUsername(), - userInfo.getDisplayName(), - UserInfo.CLASS_TYPE, - synchronizer.getId(), - synchronizer.getName(), - user.getUnionid(), - user.getName(), - user.getUserid(), - "", - synchronizer.getInstId()); - synchroRelatedService.updateSynchroRelated( - this.synchronizer,synchroRelated,UserInfo.CLASS_TYPE); - - socialsAssociate(synchroRelated,"dingtalk"); - } - } - } + + public void sync() { + _logger.info("Sync Dingtalk Users..."); + try { + List synchroRelateds = + synchroRelatedService.findOrgs(this.synchronizer); + + for(SynchroRelated relatedOrg : synchroRelateds) { + DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list"); + OapiV2UserListRequest req = new OapiV2UserListRequest(); + _logger.debug("DingTalk deptId : {}" , relatedOrg.getOriginId()); + req.setDeptId(Long.parseLong(relatedOrg.getOriginId())); + req.setCursor(0L); + req.setSize(100L); + req.setOrderField("modify_desc"); + req.setContainAccessLimit(true); + req.setLanguage("zh_CN"); + OapiV2UserListResponse rsp = client.execute(req, access_token); + _logger.trace("response : {}" , rsp.getBody()); + + if(rsp.getErrcode()==0) { + for(ListUserResponse user :rsp.getResult().getList()) { + _logger.debug("name : {} , {} , {}", user.getName(),user.getLoginId(),user.getUserid()); + + UserInfo userInfo = buildUserInfoByFieldMap(user,relatedOrg); + _logger.trace("userInfo {}" , userInfo); + userInfo.setPassword(userInfo.getUsername() + UserInfo.DEFAULT_PASSWORD_SUFFIX); + userInfoService.saveOrUpdate(userInfo); + + SynchroRelated synchroRelated = new SynchroRelated( + userInfo.getId(), + userInfo.getUsername(), + userInfo.getDisplayName(), + UserInfo.CLASS_TYPE, + synchronizer.getId(), + synchronizer.getName(), + user.getUnionid(), + user.getName(), + user.getUserid(), + "", + synchronizer.getInstId()); + synchroRelatedService.updateSynchroRelated( + this.synchronizer,synchroRelated,UserInfo.CLASS_TYPE); + + socialsAssociate(synchroRelated,"dingtalk"); + } + } + } - - } catch (Exception e) { - e.printStackTrace(); - } - - } + + } catch (Exception e) { + e.printStackTrace(); + } + + } - public UserInfo buildUserInfo(ListUserResponse user,SynchroRelated relatedOrg) { - UserInfo userInfo = new UserInfo(); + public UserInfo buildUserInfo(ListUserResponse user,SynchroRelated relatedOrg) { + UserInfo userInfo = new UserInfo(); - userInfo.setUsername(user.getUserid()); - userInfo.setNickName(user.getName()); - userInfo.setDisplayName(user.getName()); - userInfo.setFormattedName(user.getName()); - - userInfo.setEmail(StringUtils.isBlank(user.getEmail())? user.getUserid() +"@maxkey.top":user.getEmail()); - userInfo.setEntryDate(new DateTime(user.getHiredDate()).toString(DateTimeFormat.forPattern("yyyy-MM-dd"))); - userInfo.setMobile(user.getMobile()); - - userInfo.setDepartmentId(relatedOrg.getObjectId()+""); - userInfo.setDepartment(relatedOrg.getObjectName()); - userInfo.setEmployeeNumber(user.getJobNumber()); - userInfo.setJobTitle(user.getTitle()); - userInfo.setWorkEmail(user.getOrgEmail()); - userInfo.setWorkPhoneNumber(user.getTelephone()); - userInfo.setWorkOfficeName(user.getWorkPlace()); - if(user.getActive()) { - userInfo.setStatus(ConstsStatus.ACTIVE); - }else { - userInfo.setStatus(ConstsStatus.INACTIVE); - } + userInfo.setUsername(user.getUserid()); + userInfo.setNickName(user.getName()); + userInfo.setDisplayName(user.getName()); + userInfo.setFormattedName(user.getName()); + + userInfo.setEmail(StringUtils.isBlank(user.getEmail())? user.getUserid() +"@maxkey.top":user.getEmail()); + userInfo.setEntryDate(new DateTime(user.getHiredDate()).toString(DateTimeFormat.forPattern("yyyy-MM-dd"))); + userInfo.setMobile(user.getMobile()); + + userInfo.setDepartmentId(relatedOrg.getObjectId()+""); + userInfo.setDepartment(relatedOrg.getObjectName()); + userInfo.setEmployeeNumber(user.getJobNumber()); + userInfo.setJobTitle(user.getTitle()); + userInfo.setWorkEmail(user.getOrgEmail()); + userInfo.setWorkPhoneNumber(user.getTelephone()); + userInfo.setWorkOfficeName(user.getWorkPlace()); + if(user.getActive()) { + userInfo.setStatus(ConstsStatus.ACTIVE); + }else { + userInfo.setStatus(ConstsStatus.INACTIVE); + } - //userInfo.setInstId(this.synchronizer.getInstId()); - userInfo.setDescription("dingtalk "+user.getRemark()); - return userInfo; - } + //userInfo.setInstId(this.synchronizer.getInstId()); + userInfo.setDescription("dingtalk "+user.getRemark()); + return userInfo; + } - public UserInfo buildUserInfoByFieldMap(ListUserResponse user, SynchroRelated relatedOrg){ - UserInfo userInfo = new UserInfo(); - Map fieldMap = getFieldMap(Long.parseLong(synchronizer.getId())); - for (Map.Entry entry : fieldMap.entrySet()) { + public UserInfo buildUserInfoByFieldMap(ListUserResponse user, SynchroRelated relatedOrg){ + UserInfo userInfo = new UserInfo(); + Map fieldMap = getFieldMap(Long.parseLong(synchronizer.getId())); + for (Map.Entry entry : fieldMap.entrySet()) { - String userInfoProperty = entry.getKey(); - String sourceProperty = entry.getValue(); + String userInfoProperty = entry.getKey(); + String sourceProperty = entry.getValue(); - try { - Object sourceValue = null; + try { + Object sourceValue = null; - if(sourceProperty.equals("email")){ - userInfo.setEmail(StringUtils.isBlank(user.getEmail())? user.getUserid() +"@maxkey.top":user.getEmail()); - continue; - } - if(sourceProperty.equals("active")){ - userInfo.setStatus(user.getActive()?ConstsStatus.ACTIVE:ConstsStatus.INACTIVE); - continue; - } - if(sourceProperty.equals("remark")){ - userInfo.setDescription("dingtalk "+user.getRemark()); - continue; - } - if(sourceProperty.equals("hiredDate")){ - userInfo.setEntryDate(new DateTime(user.getHiredDate()).toString(DateTimeFormat.forPattern("yyyy-MM-dd"))); - continue; - } - if (hasField(OapiV2UserListResponse.ListUserResponse.class, sourceProperty)) { - sourceValue = getFieldValue(user, sourceProperty); - } + if(sourceProperty.equals("email")){ + userInfo.setEmail(StringUtils.isBlank(user.getEmail())? user.getUserid() +"@maxkey.top":user.getEmail()); + continue; + } + if(sourceProperty.equals("active")){ + userInfo.setStatus(user.getActive()?ConstsStatus.ACTIVE:ConstsStatus.INACTIVE); + continue; + } + if(sourceProperty.equals("remark")){ + userInfo.setDescription("dingtalk "+user.getRemark()); + continue; + } + if(sourceProperty.equals("hiredDate")){ + userInfo.setEntryDate(new DateTime(user.getHiredDate()).toString(DateTimeFormat.forPattern("yyyy-MM-dd"))); + continue; + } + if (hasField(OapiV2UserListResponse.ListUserResponse.class, sourceProperty)) { + sourceValue = getFieldValue(user, sourceProperty); + } - else if (hasField(SynchroRelated.class, sourceProperty)) { - sourceValue = getFieldValue(relatedOrg, sourceProperty); - } + else if (hasField(SynchroRelated.class, sourceProperty)) { + sourceValue = getFieldValue(relatedOrg, sourceProperty); + } - if (sourceValue != null) { - setFieldValue(userInfo, userInfoProperty, sourceValue); - } + if (sourceValue != null) { + setFieldValue(userInfo, userInfoProperty, sourceValue); + } - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } - } - userInfo.setInstId(this.synchronizer.getInstId()); - userInfo.setUserType("EMPLOYEE"); - userInfo.setUserState("RESIDENT"); - return userInfo; - } + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + } + userInfo.setInstId(this.synchronizer.getInstId()); + userInfo.setUserType("EMPLOYEE"); + userInfo.setUserState("RESIDENT"); + return userInfo; + } - public Map getFieldMap(Long jobId){ - Map userFieldMap = new HashMap<>(); - //根据job id查询属性映射表 - List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); - //获取用户属性映射 - for(SyncJobConfigField element:syncJobConfigFieldList){ - if(Integer.parseInt(element.getObjectType()) == USER_TYPE.intValue()){ - userFieldMap.put(element.getTargetField(), element.getSourceField()); - } - } - return userFieldMap; - } + public Map getFieldMap(Long jobId){ + Map userFieldMap = new HashMap<>(); + //根据job id查询属性映射表 + List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); + //获取用户属性映射 + for(SyncJobConfigField element:syncJobConfigFieldList){ + if(Integer.parseInt(element.getObjectType()) == USER_TYPE.intValue()){ + userFieldMap.put(element.getTargetField(), element.getSourceField()); + } + } + return userFieldMap; + } - public void setAccess_token(String access_token) { - this.access_token = access_token; - } + public void setAccess_token(String access_token) { + this.access_token = access_token; + } - public SyncJobConfigFieldService getSyncJobConfigFieldService() { - return syncJobConfigFieldService; - } + public SyncJobConfigFieldService getSyncJobConfigFieldService() { + return syncJobConfigFieldService; + } - public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { - this.syncJobConfigFieldService = syncJobConfigFieldService; - } + public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { + this.syncJobConfigFieldService = syncJobConfigFieldService; + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/FeishuAccessTokenService.java b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/FeishuAccessTokenService.java index 77eed1d22..6df0f0284 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/FeishuAccessTokenService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/FeishuAccessTokenService.java @@ -28,63 +28,63 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FeishuAccessTokenService { - static final Logger _logger = LoggerFactory.getLogger(FeishuAccessTokenService.class); - - String appId; - - String appSecret; - - public static String TOKEN_URL="https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"; + static final Logger _logger = LoggerFactory.getLogger(FeishuAccessTokenService.class); + + String appId; + + String appSecret; + + public static String TOKEN_URL="https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"; - public FeishuAccessTokenService() {} - - - public FeishuAccessTokenService(String appId, String appSecret) { - super(); - this.appId = appId; - this.appSecret = appSecret; - } + public FeishuAccessTokenService() {} + + + public FeishuAccessTokenService(String appId, String appSecret) { + super(); + this.appId = appId; + this.appSecret = appSecret; + } - public String requestToken() { - HttpRequestAdapter request =new HttpRequestAdapter(ContentType.APPLICATION_JSON); - Map parameterMap = new HashMap(); - parameterMap.put("app_id", appId); - parameterMap.put("app_secret", appSecret); - String responseBody = request.post(TOKEN_URL, parameterMap,null); - - AccessToken accessToken = JsonUtils.gsonStringToObject(responseBody, AccessToken.class); - _logger.debug("accessToken " + accessToken); - if(accessToken.getErrcode()== 0){ - return accessToken.getTenant_access_token(); - } - return ""; - } - - - public String getAppId() { - return appId; - } + public String requestToken() { + HttpRequestAdapter request =new HttpRequestAdapter(ContentType.APPLICATION_JSON); + Map parameterMap = new HashMap(); + parameterMap.put("app_id", appId); + parameterMap.put("app_secret", appSecret); + String responseBody = request.post(TOKEN_URL, parameterMap,null); + + AccessToken accessToken = JsonUtils.gsonStringToObject(responseBody, AccessToken.class); + _logger.debug("accessToken " + accessToken); + if(accessToken.getErrcode()== 0){ + return accessToken.getTenant_access_token(); + } + return ""; + } + + + public String getAppId() { + return appId; + } - public void setAppId(String appId) { - this.appId = appId; - } + public void setAppId(String appId) { + this.appId = appId; + } - public String getAppSecret() { - return appSecret; - } + public String getAppSecret() { + return appSecret; + } - public void setAppSecret(String appSecret) { - this.appSecret = appSecret; - } + public void setAppSecret(String appSecret) { + this.appSecret = appSecret; + } - public static void main(String[] args) { + public static void main(String[] args) { - } + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/FeishuOrganizationService.java b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/FeishuOrganizationService.java index 1ce168f7e..6fb5fcbdf 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/FeishuOrganizationService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/FeishuOrganizationService.java @@ -45,200 +45,200 @@ import static org.dromara.maxkey.synchronizer.utils.FieldUtil.*; @Service public class FeishuOrganizationService extends AbstractSynchronizerService implements ISynchronizerService{ - static final Logger _logger = LoggerFactory.getLogger(FeishuOrganizationService.class); - - String access_token; - private static final Integer ORG_TYPE = 2; + static final Logger _logger = LoggerFactory.getLogger(FeishuOrganizationService.class); + + String access_token; + private static final Integer ORG_TYPE = 2; - @Autowired - private SyncJobConfigFieldService syncJobConfigFieldService; - - static String DEPTS_URL = "https://open.feishu.cn/open-apis/contact/v3/departments/%s/children?page_size=50"; - static String ROOT_DEPT_URL = "https://open.feishu.cn/open-apis/contact/v3/departments/%s"; - static String ROOT_DEPT_ID = "0"; - public void sync() { - _logger.info("Sync Feishu Organizations ..."); + @Autowired + private SyncJobConfigFieldService syncJobConfigFieldService; + + static String DEPTS_URL = "https://open.feishu.cn/open-apis/contact/v3/departments/%s/children?page_size=50"; + static String ROOT_DEPT_URL = "https://open.feishu.cn/open-apis/contact/v3/departments/%s"; + static String ROOT_DEPT_ID = "0"; + public void sync() { + _logger.info("Sync Feishu Organizations ..."); - LinkedBlockingQueue deptsQueue = new LinkedBlockingQueue(); - - deptsQueue.add(ROOT_DEPT_ID); - //root - FeishuDeptsResponse rspRoot = requestDepartment(ROOT_DEPT_URL,ROOT_DEPT_ID,access_token); - Organizations rootOrganization = organizationsService.get(Organizations.ROOT_ORG_ID); - SynchroRelated rootSynchroRelated = buildSynchroRelated(rootOrganization,rspRoot.getData().getDepartment()); - - synchroRelatedService.updateSynchroRelated( - this.synchronizer,rootSynchroRelated,Organizations.CLASS_TYPE); - - //child - try { - while(deptsQueue.element() != null) { - FeishuDeptsResponse rsp = requestDepartmentList(access_token,deptsQueue.poll()); - if(rsp.getCode() == 0 && rsp.getData().getItems() != null) { - for(FeishuDepts dept : rsp.getData().getItems()) { - _logger.debug("dept : id {} , Parent {} , Name {} , od {}" , - dept.getDepartment_id(), - dept.getParent_department_id(), - dept.getName(), - dept.getOpen_department_id() - ); - deptsQueue.add(dept.getOpen_department_id()); - //synchro Related - SynchroRelated synchroRelated = - synchroRelatedService.findByOriginId( - this.synchronizer,dept.getOpen_department_id(),Organizations.CLASS_TYPE ); - //Parent - SynchroRelated synchroRelatedParent = - synchroRelatedService.findByOriginId( - this.synchronizer,dept.getParent_department_id(),Organizations.CLASS_TYPE); - Organizations organization = buildOrganizationByFieldMap(dept,synchroRelatedParent); - if(synchroRelated == null) { - organization.setId(organization.generateId()); - organizationsService.insert(organization); - _logger.debug("Organizations : " + organization); - synchroRelated = buildSynchroRelated(organization,dept); - - }else { - organization.setId(synchroRelated.getObjectId()); - organizationsService.update(organization); - } - - - synchroRelatedService.updateSynchroRelated( - this.synchronizer,synchroRelated,Organizations.CLASS_TYPE); - } - } - } - } catch (NoSuchElementException e) { - _logger.debug("Sync Department successful ."); - } - - } - - public FeishuDeptsResponse requestDepartmentList(String access_token,String deptId) { - HttpRequestAdapter request =new HttpRequestAdapter(); - HashMap headers =new HashMap(); - headers.put("Authorization", AuthorizationHeaderUtils.createBearer(access_token)); - String responseBody = request.get(String.format(DEPTS_URL, deptId),headers); - FeishuDeptsResponse deptsResponse =JsonUtils.gsonStringToObject(responseBody, FeishuDeptsResponse.class); - - _logger.trace("response : " + responseBody); + LinkedBlockingQueue deptsQueue = new LinkedBlockingQueue(); + + deptsQueue.add(ROOT_DEPT_ID); + //root + FeishuDeptsResponse rspRoot = requestDepartment(ROOT_DEPT_URL,ROOT_DEPT_ID,access_token); + Organizations rootOrganization = organizationsService.get(Organizations.ROOT_ORG_ID); + SynchroRelated rootSynchroRelated = buildSynchroRelated(rootOrganization,rspRoot.getData().getDepartment()); + + synchroRelatedService.updateSynchroRelated( + this.synchronizer,rootSynchroRelated,Organizations.CLASS_TYPE); + + //child + try { + while(deptsQueue.element() != null) { + FeishuDeptsResponse rsp = requestDepartmentList(access_token,deptsQueue.poll()); + if(rsp.getCode() == 0 && rsp.getData().getItems() != null) { + for(FeishuDepts dept : rsp.getData().getItems()) { + _logger.debug("dept : id {} , Parent {} , Name {} , od {}" , + dept.getDepartment_id(), + dept.getParent_department_id(), + dept.getName(), + dept.getOpen_department_id() + ); + deptsQueue.add(dept.getOpen_department_id()); + //synchro Related + SynchroRelated synchroRelated = + synchroRelatedService.findByOriginId( + this.synchronizer,dept.getOpen_department_id(),Organizations.CLASS_TYPE ); + //Parent + SynchroRelated synchroRelatedParent = + synchroRelatedService.findByOriginId( + this.synchronizer,dept.getParent_department_id(),Organizations.CLASS_TYPE); + Organizations organization = buildOrganizationByFieldMap(dept,synchroRelatedParent); + if(synchroRelated == null) { + organization.setId(organization.generateId()); + organizationsService.insert(organization); + _logger.debug("Organizations : " + organization); + synchroRelated = buildSynchroRelated(organization,dept); + + }else { + organization.setId(synchroRelated.getObjectId()); + organizationsService.update(organization); + } + + + synchroRelatedService.updateSynchroRelated( + this.synchronizer,synchroRelated,Organizations.CLASS_TYPE); + } + } + } + } catch (NoSuchElementException e) { + _logger.debug("Sync Department successful ."); + } + + } + + public FeishuDeptsResponse requestDepartmentList(String access_token,String deptId) { + HttpRequestAdapter request =new HttpRequestAdapter(); + HashMap headers =new HashMap(); + headers.put("Authorization", AuthorizationHeaderUtils.createBearer(access_token)); + String responseBody = request.get(String.format(DEPTS_URL, deptId),headers); + FeishuDeptsResponse deptsResponse =JsonUtils.gsonStringToObject(responseBody, FeishuDeptsResponse.class); + + _logger.trace("response : " + responseBody); - return deptsResponse; - } - - public FeishuDeptsResponse requestDepartment(String url ,String deptId ,String access_token) { - HttpRequestAdapter request =new HttpRequestAdapter(); - HashMap headers =new HashMap(); - headers.put("Authorization", AuthorizationHeaderUtils.createBearer(access_token)); - String responseBody = request.get(String.format(url, deptId),headers); - FeishuDeptsResponse deptsResponse =JsonUtils.gsonStringToObject(responseBody, FeishuDeptsResponse.class); - - _logger.trace("response : " + responseBody); + return deptsResponse; + } + + public FeishuDeptsResponse requestDepartment(String url ,String deptId ,String access_token) { + HttpRequestAdapter request =new HttpRequestAdapter(); + HashMap headers =new HashMap(); + headers.put("Authorization", AuthorizationHeaderUtils.createBearer(access_token)); + String responseBody = request.get(String.format(url, deptId),headers); + FeishuDeptsResponse deptsResponse =JsonUtils.gsonStringToObject(responseBody, FeishuDeptsResponse.class); + + _logger.trace("response : " + responseBody); - return deptsResponse; - } - - public SynchroRelated buildSynchroRelated(Organizations org,FeishuDepts dept) { - return new SynchroRelated( - org.getId(), - org.getOrgName(), - org.getOrgName(), - Organizations.CLASS_TYPE, - synchronizer.getId(), - synchronizer.getName(), - dept.getOpen_department_id(), - dept.getName(), - dept.getDepartment_id(), - dept.getParent_department_id(), - synchronizer.getInstId()); - } - - public Organizations buildOrganization(FeishuDepts dept,SynchroRelated synchroRelatedParent) { + return deptsResponse; + } + + public SynchroRelated buildSynchroRelated(Organizations org,FeishuDepts dept) { + return new SynchroRelated( + org.getId(), + org.getOrgName(), + org.getOrgName(), + Organizations.CLASS_TYPE, + synchronizer.getId(), + synchronizer.getName(), + dept.getOpen_department_id(), + dept.getName(), + dept.getDepartment_id(), + dept.getParent_department_id(), + synchronizer.getInstId()); + } + + public Organizations buildOrganization(FeishuDepts dept,SynchroRelated synchroRelatedParent) { - - Organizations org = new Organizations(); - org.setOrgCode(dept.getDepartment_id()+""); - org.setOrgName(dept.getName()); - org.setFullName(dept.getName()); - org.setParentId(synchroRelatedParent.getObjectId()); - org.setParentName(synchroRelatedParent.getObjectName()); - org.setSortIndex(Integer.parseInt(dept.getOrder())); - org.setInstId(this.synchronizer.getInstId()); - org.setStatus(ConstsStatus.ACTIVE); - org.setDescription("Feishu"); - return org; - } + + Organizations org = new Organizations(); + org.setOrgCode(dept.getDepartment_id()+""); + org.setOrgName(dept.getName()); + org.setFullName(dept.getName()); + org.setParentId(synchroRelatedParent.getObjectId()); + org.setParentName(synchroRelatedParent.getObjectName()); + org.setSortIndex(Integer.parseInt(dept.getOrder())); + org.setInstId(this.synchronizer.getInstId()); + org.setStatus(ConstsStatus.ACTIVE); + org.setDescription("Feishu"); + return org; + } - public Organizations buildOrganizationByFieldMap(FeishuDepts dept,SynchroRelated synchroRelatedParent){ - Map fieldMap = getFiledMap(Long.parseLong(synchronizer.getId())); - Organizations org = new Organizations(); - for (Map.Entry entry : fieldMap.entrySet()) { - String orgProperty = entry.getKey(); - String sourceProperty = entry.getValue(); - try { - Object sourceValue = null; + public Organizations buildOrganizationByFieldMap(FeishuDepts dept,SynchroRelated synchroRelatedParent){ + Map fieldMap = getFiledMap(Long.parseLong(synchronizer.getId())); + Organizations org = new Organizations(); + for (Map.Entry entry : fieldMap.entrySet()) { + String orgProperty = entry.getKey(); + String sourceProperty = entry.getValue(); + try { + Object sourceValue = null; - if (hasField(dept.getClass(), sourceProperty)) { - sourceValue = getFieldValue(dept, sourceProperty); - } - else if (synchroRelatedParent != null && hasField(SynchroRelated.class, sourceProperty)) { - sourceValue = getFieldValue(synchroRelatedParent, sourceProperty); - } - if (sourceValue != null) { - setFieldValue(org, orgProperty, sourceValue); - } - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } - } + if (hasField(dept.getClass(), sourceProperty)) { + sourceValue = getFieldValue(dept, sourceProperty); + } + else if (synchroRelatedParent != null && hasField(SynchroRelated.class, sourceProperty)) { + sourceValue = getFieldValue(synchroRelatedParent, sourceProperty); + } + if (sourceValue != null) { + setFieldValue(org, orgProperty, sourceValue); + } + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + } - // 额外处理特定逻辑:意味着这些属性不能出现在属性映射表中 - try { + // 额外处理特定逻辑:意味着这些属性不能出现在属性映射表中 + try { /*if (synchroRelatedParent != null) { setFieldValue(org, "parentId", synchroRelatedParent.getObjectId()); setFieldValue(org, "parentName", synchroRelatedParent.getObjectName()); }*/ - setFieldValue(org, "instId", this.synchronizer.getInstId()); - setFieldValue(org, "status", ConstsStatus.ACTIVE); - setFieldValue(org, "description", "Feishu"); - org.setType("department"); - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } - return org; - } + setFieldValue(org, "instId", this.synchronizer.getInstId()); + setFieldValue(org, "status", ConstsStatus.ACTIVE); + setFieldValue(org, "description", "Feishu"); + org.setType("department"); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + return org; + } - public Map getFiledMap(Long jobId){ - //key是maxkey的属性,value是其他应用的属性 - Map filedMap = new HashMap<>(); - //根据job id查询属性映射表 - List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); - //获取组织属性映射 - for(SyncJobConfigField element:syncJobConfigFieldList){ - if(Integer.parseInt(element.getObjectType()) == ORG_TYPE.intValue()){ - filedMap.put(element.getTargetField(), element.getSourceField()); - } - } - return filedMap; - } + public Map getFiledMap(Long jobId){ + //key是maxkey的属性,value是其他应用的属性 + Map filedMap = new HashMap<>(); + //根据job id查询属性映射表 + List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); + //获取组织属性映射 + for(SyncJobConfigField element:syncJobConfigFieldList){ + if(Integer.parseInt(element.getObjectType()) == ORG_TYPE.intValue()){ + filedMap.put(element.getTargetField(), element.getSourceField()); + } + } + return filedMap; + } - public String getAccess_token() { - return access_token; - } + public String getAccess_token() { + return access_token; + } - public void setAccess_token(String access_token) { - this.access_token = access_token; - } + public void setAccess_token(String access_token) { + this.access_token = access_token; + } - public SyncJobConfigFieldService getSyncJobConfigFieldService() { - return syncJobConfigFieldService; - } + public SyncJobConfigFieldService getSyncJobConfigFieldService() { + return syncJobConfigFieldService; + } - public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { - this.syncJobConfigFieldService = syncJobConfigFieldService; - } + public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { + this.syncJobConfigFieldService = syncJobConfigFieldService; + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/FeishuSynchronizerService.java b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/FeishuSynchronizerService.java index 4dd22d86a..a775e1857 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/FeishuSynchronizerService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/FeishuSynchronizerService.java @@ -26,50 +26,50 @@ import org.springframework.stereotype.Service; @Service public class FeishuSynchronizerService implements ISynchronizerService{ - static final Logger _logger = LoggerFactory.getLogger(FeishuSynchronizerService.class); - Synchronizers synchronizer; - - @Autowired - FeishuUsersService feishuUsersService; - - @Autowired - FeishuOrganizationService feishuOrganizationService; - + static final Logger _logger = LoggerFactory.getLogger(FeishuSynchronizerService.class); + Synchronizers synchronizer; + + @Autowired + FeishuUsersService feishuUsersService; + + @Autowired + FeishuOrganizationService feishuOrganizationService; + - FeishuAccessTokenService feishuAccessTokenService = new FeishuAccessTokenService(); - - public FeishuSynchronizerService() { - super(); - } + FeishuAccessTokenService feishuAccessTokenService = new FeishuAccessTokenService(); + + public FeishuSynchronizerService() { + super(); + } - public void sync() throws Exception { - _logger.info("Sync ..."); - feishuAccessTokenService.setAppId(synchronizer.getPrincipal()); - feishuAccessTokenService.setAppSecret(synchronizer.getCredentials()); - String access_token=feishuAccessTokenService.requestToken(); - - feishuOrganizationService.setSynchronizer(synchronizer); - feishuOrganizationService.setAccess_token(access_token); - feishuOrganizationService.sync(); - - feishuUsersService.setSynchronizer(synchronizer); - feishuUsersService.setAccess_token(access_token); - feishuUsersService.sync(); - } + public void sync() throws Exception { + _logger.info("Sync ..."); + feishuAccessTokenService.setAppId(synchronizer.getPrincipal()); + feishuAccessTokenService.setAppSecret(synchronizer.getCredentials()); + String access_token=feishuAccessTokenService.requestToken(); + + feishuOrganizationService.setSynchronizer(synchronizer); + feishuOrganizationService.setAccess_token(access_token); + feishuOrganizationService.sync(); + + feishuUsersService.setSynchronizer(synchronizer); + feishuUsersService.setAccess_token(access_token); + feishuUsersService.sync(); + } - public void setFeishuUsersService(FeishuUsersService feishuUsersService) { - this.feishuUsersService = feishuUsersService; - } + public void setFeishuUsersService(FeishuUsersService feishuUsersService) { + this.feishuUsersService = feishuUsersService; + } - public void setFeishuOrganizationService(FeishuOrganizationService feishuOrganizationService) { - this.feishuOrganizationService = feishuOrganizationService; - } + public void setFeishuOrganizationService(FeishuOrganizationService feishuOrganizationService) { + this.feishuOrganizationService = feishuOrganizationService; + } - @Override - public void setSynchronizer(Synchronizers synchronizer) { - this.synchronizer = synchronizer; - - } + @Override + public void setSynchronizer(Synchronizers synchronizer) { + this.synchronizer = synchronizer; + + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/FeishuUsersService.java b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/FeishuUsersService.java index 60b09ec56..bf208381e 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/FeishuUsersService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/FeishuUsersService.java @@ -44,172 +44,172 @@ import static org.dromara.maxkey.synchronizer.utils.FieldUtil.*; @Service public class FeishuUsersService extends AbstractSynchronizerService implements ISynchronizerService{ - final static Logger _logger = LoggerFactory.getLogger(FeishuUsersService.class); - @Autowired - private SyncJobConfigFieldService syncJobConfigFieldService; - String access_token; - private static final Integer USER_TYPE = 1; - - static String USERS_URL="https://open.feishu.cn/open-apis/contact/v3/users/find_by_department?department_id=%s&page_size=50"; - - public void sync() { - _logger.info("Sync Feishu Users..."); - try { - List synchroRelateds = - synchroRelatedService.findOrgs(this.synchronizer); - - for(SynchroRelated relatedOrg : synchroRelateds) { - HttpRequestAdapter request =new HttpRequestAdapter(); - HashMap headers =new HashMap(); - headers.put("Authorization", AuthorizationHeaderUtils.createBearer(access_token)); - String responseBody = request.get(String.format(USERS_URL,relatedOrg.getOriginId()),headers); - FeishuUsersResponse usersResponse =JsonUtils.gsonStringToObject(responseBody, FeishuUsersResponse.class); - _logger.trace("response : " + responseBody); - if(usersResponse.getCode() == 0 && usersResponse.getData().getItems() != null) { - for(FeishuUsers feiShuUser : usersResponse.getData().getItems()) { - UserInfo userInfo = buildUserInfoByFieldMapper(feiShuUser,relatedOrg); - _logger.debug("userInfo : " + userInfo); - userInfo.setPassword(userInfo.getUsername() + UserInfo.DEFAULT_PASSWORD_SUFFIX); - userInfoService.saveOrUpdate(userInfo); - - SynchroRelated synchroRelated = new SynchroRelated( - userInfo.getId(), - userInfo.getUsername(), - userInfo.getDisplayName(), - UserInfo.CLASS_TYPE, - synchronizer.getId(), - synchronizer.getName(), - feiShuUser.getOpen_id(), - feiShuUser.getName(), - feiShuUser.getUser_id(), - feiShuUser.getUnion_id(), - synchronizer.getInstId()); - synchroRelatedService.updateSynchroRelated( - this.synchronizer,synchroRelated,UserInfo.CLASS_TYPE); - - synchroRelated.setOriginId(feiShuUser.getUnion_id()); - socialsAssociate(synchroRelated,"feishu"); - - } - } - } - - } catch (Exception e) { - e.printStackTrace(); - } - - } + final static Logger _logger = LoggerFactory.getLogger(FeishuUsersService.class); + @Autowired + private SyncJobConfigFieldService syncJobConfigFieldService; + String access_token; + private static final Integer USER_TYPE = 1; + + static String USERS_URL="https://open.feishu.cn/open-apis/contact/v3/users/find_by_department?department_id=%s&page_size=50"; + + public void sync() { + _logger.info("Sync Feishu Users..."); + try { + List synchroRelateds = + synchroRelatedService.findOrgs(this.synchronizer); + + for(SynchroRelated relatedOrg : synchroRelateds) { + HttpRequestAdapter request =new HttpRequestAdapter(); + HashMap headers =new HashMap(); + headers.put("Authorization", AuthorizationHeaderUtils.createBearer(access_token)); + String responseBody = request.get(String.format(USERS_URL,relatedOrg.getOriginId()),headers); + FeishuUsersResponse usersResponse =JsonUtils.gsonStringToObject(responseBody, FeishuUsersResponse.class); + _logger.trace("response : " + responseBody); + if(usersResponse.getCode() == 0 && usersResponse.getData().getItems() != null) { + for(FeishuUsers feiShuUser : usersResponse.getData().getItems()) { + UserInfo userInfo = buildUserInfoByFieldMapper(feiShuUser,relatedOrg); + _logger.debug("userInfo : " + userInfo); + userInfo.setPassword(userInfo.getUsername() + UserInfo.DEFAULT_PASSWORD_SUFFIX); + userInfoService.saveOrUpdate(userInfo); + + SynchroRelated synchroRelated = new SynchroRelated( + userInfo.getId(), + userInfo.getUsername(), + userInfo.getDisplayName(), + UserInfo.CLASS_TYPE, + synchronizer.getId(), + synchronizer.getName(), + feiShuUser.getOpen_id(), + feiShuUser.getName(), + feiShuUser.getUser_id(), + feiShuUser.getUnion_id(), + synchronizer.getInstId()); + synchroRelatedService.updateSynchroRelated( + this.synchronizer,synchroRelated,UserInfo.CLASS_TYPE); + + synchroRelated.setOriginId(feiShuUser.getUnion_id()); + socialsAssociate(synchroRelated,"feishu"); + + } + } + } + + } catch (Exception e) { + e.printStackTrace(); + } + + } - - public void postSync(UserInfo userInfo) { - - } + + public void postSync(UserInfo userInfo) { + + } - public UserInfo buildUserInfo(FeishuUsers user,SynchroRelated relatedOrg) { - UserInfo userInfo = new UserInfo(); - userInfo.setId(userInfo.generateId()); - userInfo.setUsername(user.getUser_id());//账号 - userInfo.setNickName(user.getNickname());//名字 - userInfo.setDisplayName(user.getName());//名字 - - userInfo.setMobile(user.getMobile());//手机 - userInfo.setEmail(user.getEmail()); - userInfo.setGender(user.getGender()); - - userInfo.setEmployeeNumber(user.getEmployee_no()); - userInfo.setWorkPhoneNumber(user.getMobile());//工作电话 - - userInfo.setDepartmentId(relatedOrg.getObjectId()); - userInfo.setDepartment(relatedOrg.getObjectName()); - - userInfo.setJobTitle(user.getJob_title());//职务 - userInfo.setWorkAddressFormatted(user.getWork_station());//工作地点 + public UserInfo buildUserInfo(FeishuUsers user,SynchroRelated relatedOrg) { + UserInfo userInfo = new UserInfo(); + userInfo.setId(userInfo.generateId()); + userInfo.setUsername(user.getUser_id());//账号 + userInfo.setNickName(user.getNickname());//名字 + userInfo.setDisplayName(user.getName());//名字 + + userInfo.setMobile(user.getMobile());//手机 + userInfo.setEmail(user.getEmail()); + userInfo.setGender(user.getGender()); + + userInfo.setEmployeeNumber(user.getEmployee_no()); + userInfo.setWorkPhoneNumber(user.getMobile());//工作电话 + + userInfo.setDepartmentId(relatedOrg.getObjectId()); + userInfo.setDepartment(relatedOrg.getObjectName()); + + userInfo.setJobTitle(user.getJob_title());//职务 + userInfo.setWorkAddressFormatted(user.getWork_station());//工作地点 - //激活状态: 1=已激活,2=已禁用,4=未激活,5=退出企业。 - if(user.getStatus().isIs_activated() ) { - userInfo.setStatus(ConstsStatus.ACTIVE); - }else { - userInfo.setStatus(ConstsStatus.INACTIVE); - } - userInfo.setInstId(this.synchronizer.getInstId()); - return userInfo; - } + //激活状态: 1=已激活,2=已禁用,4=未激活,5=退出企业。 + if(user.getStatus().isIs_activated() ) { + userInfo.setStatus(ConstsStatus.ACTIVE); + }else { + userInfo.setStatus(ConstsStatus.INACTIVE); + } + userInfo.setInstId(this.synchronizer.getInstId()); + return userInfo; + } - public UserInfo buildUserInfoByFieldMapper(FeishuUsers user,SynchroRelated relatedOrg){ - UserInfo userInfo = new UserInfo(); - Map fieldMap = this.getFiledMap(Long.parseLong(synchronizer.getId())); - for (Map.Entry entry : fieldMap.entrySet()) { + public UserInfo buildUserInfoByFieldMapper(FeishuUsers user,SynchroRelated relatedOrg){ + UserInfo userInfo = new UserInfo(); + Map fieldMap = this.getFiledMap(Long.parseLong(synchronizer.getId())); + for (Map.Entry entry : fieldMap.entrySet()) { - String userInfoProperty = entry.getKey(); - String sourceProperty = entry.getValue(); + String userInfoProperty = entry.getKey(); + String sourceProperty = entry.getValue(); - try { - Object sourceValue = null; - if(sourceProperty.equals("status")){ - if (user.getStatus().isIs_activated()) { - setFieldValue(userInfo, "status", ConstsStatus.ACTIVE); - } else { - setFieldValue(userInfo, "status", ConstsStatus.INACTIVE); - } - continue; - } - if (hasField(user.getClass(), sourceProperty)) { - sourceValue = getFieldValue(user, sourceProperty); - } - else if (hasField(SynchroRelated.class, sourceProperty)) { - sourceValue = getFieldValue(relatedOrg, sourceProperty); - } + try { + Object sourceValue = null; + if(sourceProperty.equals("status")){ + if (user.getStatus().isIs_activated()) { + setFieldValue(userInfo, "status", ConstsStatus.ACTIVE); + } else { + setFieldValue(userInfo, "status", ConstsStatus.INACTIVE); + } + continue; + } + if (hasField(user.getClass(), sourceProperty)) { + sourceValue = getFieldValue(user, sourceProperty); + } + else if (hasField(SynchroRelated.class, sourceProperty)) { + sourceValue = getFieldValue(relatedOrg, sourceProperty); + } - if (sourceValue != null) { - setFieldValue(userInfo, userInfoProperty, sourceValue); - } + if (sourceValue != null) { + setFieldValue(userInfo, userInfoProperty, sourceValue); + } - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } - } - // 额外处理特定逻辑 :意味着这些属性映射不能保存在数据库中。 - try { - if(userInfo.getUsername() == null){ - userInfo.setUsername(user.getOpen_id()); - } - setFieldValue(userInfo, "id", userInfo.generateId()); - setFieldValue(userInfo, "instId", this.synchronizer.getInstId()); - userInfo.setUserType("EMPLOYEE"); - userInfo.setUserState("RESIDENT"); - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } - return userInfo; - } + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + } + // 额外处理特定逻辑 :意味着这些属性映射不能保存在数据库中。 + try { + if(userInfo.getUsername() == null){ + userInfo.setUsername(user.getOpen_id()); + } + setFieldValue(userInfo, "id", userInfo.generateId()); + setFieldValue(userInfo, "instId", this.synchronizer.getInstId()); + userInfo.setUserType("EMPLOYEE"); + userInfo.setUserState("RESIDENT"); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + return userInfo; + } - public Map getFiledMap(Long jobId){ - Map fieldMap = new HashMap<>(); - //根据job id查询属性映射表 - List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); - //获取用户属性映射 - for(SyncJobConfigField element:syncJobConfigFieldList){ - if(Integer.parseInt(element.getObjectType()) == USER_TYPE.intValue()){ - fieldMap.put(element.getTargetField(), element.getSourceField()); - } - } - return fieldMap; - } + public Map getFiledMap(Long jobId){ + Map fieldMap = new HashMap<>(); + //根据job id查询属性映射表 + List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); + //获取用户属性映射 + for(SyncJobConfigField element:syncJobConfigFieldList){ + if(Integer.parseInt(element.getObjectType()) == USER_TYPE.intValue()){ + fieldMap.put(element.getTargetField(), element.getSourceField()); + } + } + return fieldMap; + } - public void setAccess_token(String access_token) { - this.access_token = access_token; - } - public SyncJobConfigFieldService getSyncJobConfigFieldService() { - return syncJobConfigFieldService; - } + public void setAccess_token(String access_token) { + this.access_token = access_token; + } + public SyncJobConfigFieldService getSyncJobConfigFieldService() { + return syncJobConfigFieldService; + } - public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { - this.syncJobConfigFieldService = syncJobConfigFieldService; - } + public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { + this.syncJobConfigFieldService = syncJobConfigFieldService; + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuDeptStatus.java b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuDeptStatus.java index a235f7ffd..56dabb8cc 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuDeptStatus.java +++ b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuDeptStatus.java @@ -17,28 +17,28 @@ package org.dromara.maxkey.synchronizer.feishu.entity; public class FeishuDeptStatus { - boolean is_deleted; + boolean is_deleted; - public FeishuDeptStatus() { - super(); + public FeishuDeptStatus() { + super(); - } + } - public boolean isIs_deleted() { - return is_deleted; - } + public boolean isIs_deleted() { + return is_deleted; + } - public void setIs_deleted(boolean is_deleted) { - this.is_deleted = is_deleted; - } + public void setIs_deleted(boolean is_deleted) { + this.is_deleted = is_deleted; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("FeishuDeptStatus [is_deleted="); - builder.append(is_deleted); - builder.append("]"); - return builder.toString(); - } - + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("FeishuDeptStatus [is_deleted="); + builder.append(is_deleted); + builder.append("]"); + return builder.toString(); + } + } diff --git a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuDepts.java b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuDepts.java index 22a475df5..e71ee68e3 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuDepts.java +++ b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuDepts.java @@ -18,150 +18,150 @@ package org.dromara.maxkey.synchronizer.feishu.entity; public class FeishuDepts { - - String department_id; - String parent_department_id; - String open_department_id; - String name; - FeishuI18nName i18n_name; - String leader_user_id; - String chat_id; - String order; - int member_count; - FeishuDeptStatus status; - String is_deleted; - String create_group_chat; + + String department_id; + String parent_department_id; + String open_department_id; + String name; + FeishuI18nName i18n_name; + String leader_user_id; + String chat_id; + String order; + int member_count; + FeishuDeptStatus status; + String is_deleted; + String create_group_chat; - public FeishuDepts() { - super(); - } + public FeishuDepts() { + super(); + } - public String getDepartment_id() { - return department_id; - } + public String getDepartment_id() { + return department_id; + } - public void setDepartment_id(String department_id) { - this.department_id = department_id; - } + public void setDepartment_id(String department_id) { + this.department_id = department_id; + } - public String getParent_department_id() { - return parent_department_id; - } + public String getParent_department_id() { + return parent_department_id; + } - public void setParent_department_id(String parent_department_id) { - this.parent_department_id = parent_department_id; - } + public void setParent_department_id(String parent_department_id) { + this.parent_department_id = parent_department_id; + } - public String getOpen_department_id() { - return open_department_id; - } + public String getOpen_department_id() { + return open_department_id; + } - public void setOpen_department_id(String open_department_id) { - this.open_department_id = open_department_id; - } + public void setOpen_department_id(String open_department_id) { + this.open_department_id = open_department_id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public FeishuI18nName getI18n_name() { - return i18n_name; - } + public FeishuI18nName getI18n_name() { + return i18n_name; + } - public void setI18n_name(FeishuI18nName i18n_name) { - this.i18n_name = i18n_name; - } + public void setI18n_name(FeishuI18nName i18n_name) { + this.i18n_name = i18n_name; + } - public String getLeader_user_id() { - return leader_user_id; - } + public String getLeader_user_id() { + return leader_user_id; + } - public void setLeader_user_id(String leader_user_id) { - this.leader_user_id = leader_user_id; - } + public void setLeader_user_id(String leader_user_id) { + this.leader_user_id = leader_user_id; + } - public String getChat_id() { - return chat_id; - } + public String getChat_id() { + return chat_id; + } - public void setChat_id(String chat_id) { - this.chat_id = chat_id; - } + public void setChat_id(String chat_id) { + this.chat_id = chat_id; + } - public String getOrder() { - return order; - } + public String getOrder() { + return order; + } - public void setOrder(String order) { - this.order = order; - } + public void setOrder(String order) { + this.order = order; + } - public int getMember_count() { - return member_count; - } + public int getMember_count() { + return member_count; + } - public void setMember_count(int member_count) { - this.member_count = member_count; - } + public void setMember_count(int member_count) { + this.member_count = member_count; + } - public FeishuDeptStatus getStatus() { - return status; - } + public FeishuDeptStatus getStatus() { + return status; + } - public void setStatus(FeishuDeptStatus status) { - this.status = status; - } + public void setStatus(FeishuDeptStatus status) { + this.status = status; + } - public String getIs_deleted() { - return is_deleted; - } + public String getIs_deleted() { + return is_deleted; + } - public void setIs_deleted(String is_deleted) { - this.is_deleted = is_deleted; - } + public void setIs_deleted(String is_deleted) { + this.is_deleted = is_deleted; + } - public String getCreate_group_chat() { - return create_group_chat; - } + public String getCreate_group_chat() { + return create_group_chat; + } - public void setCreate_group_chat(String create_group_chat) { - this.create_group_chat = create_group_chat; - } + public void setCreate_group_chat(String create_group_chat) { + this.create_group_chat = create_group_chat; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("FeishuDepts [department_id="); - builder.append(department_id); - builder.append(", parent_department_id="); - builder.append(parent_department_id); - builder.append(", open_department_id="); - builder.append(open_department_id); - builder.append(", name="); - builder.append(name); - builder.append(", i18n_name="); - builder.append(i18n_name); - builder.append(", leader_user_id="); - builder.append(leader_user_id); - builder.append(", chat_id="); - builder.append(chat_id); - builder.append(", order="); - builder.append(order); - builder.append(", member_count="); - builder.append(member_count); - builder.append(", status="); - builder.append(status); - builder.append(", is_deleted="); - builder.append(is_deleted); - builder.append(", create_group_chat="); - builder.append(create_group_chat); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("FeishuDepts [department_id="); + builder.append(department_id); + builder.append(", parent_department_id="); + builder.append(parent_department_id); + builder.append(", open_department_id="); + builder.append(open_department_id); + builder.append(", name="); + builder.append(name); + builder.append(", i18n_name="); + builder.append(i18n_name); + builder.append(", leader_user_id="); + builder.append(leader_user_id); + builder.append(", chat_id="); + builder.append(chat_id); + builder.append(", order="); + builder.append(order); + builder.append(", member_count="); + builder.append(member_count); + builder.append(", status="); + builder.append(status); + builder.append(", is_deleted="); + builder.append(is_deleted); + builder.append(", create_group_chat="); + builder.append(create_group_chat); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuDeptsData.java b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuDeptsData.java index 6215f05e7..7d8431b8d 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuDeptsData.java +++ b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuDeptsData.java @@ -22,59 +22,59 @@ import org.dromara.maxkey.synchronizer.entity.ResponseData; public class FeishuDeptsData extends ResponseData { - boolean has_more; - String page_token; - ArrayList items; + boolean has_more; + String page_token; + ArrayList items; - FeishuDepts department; - - public boolean isHas_more() { - return has_more; - } + FeishuDepts department; + + public boolean isHas_more() { + return has_more; + } - public void setHas_more(boolean has_more) { - this.has_more = has_more; - } + public void setHas_more(boolean has_more) { + this.has_more = has_more; + } - public String getPage_token() { - return page_token; - } + public String getPage_token() { + return page_token; + } - public void setPage_token(String page_token) { - this.page_token = page_token; - } + public void setPage_token(String page_token) { + this.page_token = page_token; + } - public ArrayList getItems() { - return items; - } + public ArrayList getItems() { + return items; + } - public void setItems(ArrayList items) { - this.items = items; - } + public void setItems(ArrayList items) { + this.items = items; + } - public FeishuDepts getDepartment() { - return department; - } + public FeishuDepts getDepartment() { + return department; + } - public void setDepartment(FeishuDepts department) { - this.department = department; - } + public void setDepartment(FeishuDepts department) { + this.department = department; + } - public FeishuDeptsData() { - super(); - } + public FeishuDeptsData() { + super(); + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("FeishuDeptsResponse [has_more="); - builder.append(has_more); - builder.append(", page_token="); - builder.append(page_token); - builder.append(", items="); - builder.append(items); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("FeishuDeptsResponse [has_more="); + builder.append(has_more); + builder.append(", page_token="); + builder.append(page_token); + builder.append(", items="); + builder.append(items); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuDeptsResponse.java b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuDeptsResponse.java index 508244413..eb37a817b 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuDeptsResponse.java +++ b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuDeptsResponse.java @@ -20,31 +20,31 @@ import org.dromara.maxkey.synchronizer.entity.ResponseData; public class FeishuDeptsResponse extends ResponseData { - FeishuDeptsData data; + FeishuDeptsData data; - public FeishuDeptsResponse() { - super(); - } + public FeishuDeptsResponse() { + super(); + } - public FeishuDeptsData getData() { - return data; - } + public FeishuDeptsData getData() { + return data; + } - public void setData(FeishuDeptsData data) { - this.data = data; - } + public void setData(FeishuDeptsData data) { + this.data = data; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("FeishuDeptsResponse [data="); - builder.append(data); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("FeishuDeptsResponse [data="); + builder.append(data); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuI18nName.java b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuI18nName.java index 2e2439504..5697f4ebf 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuI18nName.java +++ b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuI18nName.java @@ -18,49 +18,49 @@ package org.dromara.maxkey.synchronizer.feishu.entity; public class FeishuI18nName { - String zh_cn; - String ja_jp; - String en_us; + String zh_cn; + String ja_jp; + String en_us; - public FeishuI18nName() { - super(); - } + public FeishuI18nName() { + super(); + } - public String getZh_cn() { - return zh_cn; - } + public String getZh_cn() { + return zh_cn; + } - public void setZh_cn(String zh_cn) { - this.zh_cn = zh_cn; - } + public void setZh_cn(String zh_cn) { + this.zh_cn = zh_cn; + } - public String getJa_jp() { - return ja_jp; - } + public String getJa_jp() { + return ja_jp; + } - public void setJa_jp(String ja_jp) { - this.ja_jp = ja_jp; - } + public void setJa_jp(String ja_jp) { + this.ja_jp = ja_jp; + } - public String getEn_us() { - return en_us; - } + public String getEn_us() { + return en_us; + } - public void setEn_us(String en_us) { - this.en_us = en_us; - } + public void setEn_us(String en_us) { + this.en_us = en_us; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("FeishuI18nName [zh_cn="); - builder.append(zh_cn); - builder.append(", ja_jp="); - builder.append(ja_jp); - builder.append(", en_us="); - builder.append(en_us); - builder.append("]"); - return builder.toString(); - } - + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("FeishuI18nName [zh_cn="); + builder.append(zh_cn); + builder.append(", ja_jp="); + builder.append(ja_jp); + builder.append(", en_us="); + builder.append(en_us); + builder.append("]"); + return builder.toString(); + } + } diff --git a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuUserStatus.java b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuUserStatus.java index a85a2cf91..d450350ed 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuUserStatus.java +++ b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuUserStatus.java @@ -17,71 +17,71 @@ package org.dromara.maxkey.synchronizer.feishu.entity; public class FeishuUserStatus { - boolean is_frozen; - boolean is_resigned; - boolean is_activated; - boolean is_exited; - boolean is_unjoin; + boolean is_frozen; + boolean is_resigned; + boolean is_activated; + boolean is_exited; + boolean is_unjoin; - public FeishuUserStatus() { - super(); - } + public FeishuUserStatus() { + super(); + } - public boolean isIs_frozen() { - return is_frozen; - } + public boolean isIs_frozen() { + return is_frozen; + } - public void setIs_frozen(boolean is_frozen) { - this.is_frozen = is_frozen; - } + public void setIs_frozen(boolean is_frozen) { + this.is_frozen = is_frozen; + } - public boolean isIs_resigned() { - return is_resigned; - } + public boolean isIs_resigned() { + return is_resigned; + } - public void setIs_resigned(boolean is_resigned) { - this.is_resigned = is_resigned; - } + public void setIs_resigned(boolean is_resigned) { + this.is_resigned = is_resigned; + } - public boolean isIs_activated() { - return is_activated; - } + public boolean isIs_activated() { + return is_activated; + } - public void setIs_activated(boolean is_activated) { - this.is_activated = is_activated; - } + public void setIs_activated(boolean is_activated) { + this.is_activated = is_activated; + } - public boolean isIs_exited() { - return is_exited; - } + public boolean isIs_exited() { + return is_exited; + } - public void setIs_exited(boolean is_exited) { - this.is_exited = is_exited; - } + public void setIs_exited(boolean is_exited) { + this.is_exited = is_exited; + } - public boolean isIs_unjoin() { - return is_unjoin; - } + public boolean isIs_unjoin() { + return is_unjoin; + } - public void setIs_unjoin(boolean is_unjoin) { - this.is_unjoin = is_unjoin; - } + public void setIs_unjoin(boolean is_unjoin) { + this.is_unjoin = is_unjoin; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("FeishuUserStatus [is_frozen="); - builder.append(is_frozen); - builder.append(", is_resigned="); - builder.append(is_resigned); - builder.append(", is_activated="); - builder.append(is_activated); - builder.append(", is_exited="); - builder.append(is_exited); - builder.append(", is_unjoin="); - builder.append(is_unjoin); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("FeishuUserStatus [is_frozen="); + builder.append(is_frozen); + builder.append(", is_resigned="); + builder.append(is_resigned); + builder.append(", is_activated="); + builder.append(is_activated); + builder.append(", is_exited="); + builder.append(is_exited); + builder.append(", is_unjoin="); + builder.append(is_unjoin); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuUsers.java b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuUsers.java index 9abf79af8..6bbe0c309 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuUsers.java +++ b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuUsers.java @@ -21,289 +21,289 @@ import java.util.Arrays; public class FeishuUsers { - String union_id; - String user_id; - String open_id; - String name; - String en_name; - String nickname; - String email; - String mobile; - boolean mobile_visible; - int gender; - String avatar_key; - FeishuUserStatus status; - String []department_ids; - String leader_user_id; - String city; - String country; - String work_station; - int join_time; - String is_tenant_manager; - String employee_no; - long employee_type; + String union_id; + String user_id; + String open_id; + String name; + String en_name; + String nickname; + String email; + String mobile; + boolean mobile_visible; + int gender; + String avatar_key; + FeishuUserStatus status; + String []department_ids; + String leader_user_id; + String city; + String country; + String work_station; + int join_time; + String is_tenant_manager; + String employee_no; + long employee_type; - String enterprise_email; - String job_title; - String is_frozen; + String enterprise_email; + String job_title; + String is_frozen; - public class ExtAttrs { + public class ExtAttrs { - String type; - String name; - String text; + String type; + String name; + String text; - } + } - public String getUnion_id() { - return union_id; - } + public String getUnion_id() { + return union_id; + } - public void setUnion_id(String union_id) { - this.union_id = union_id; - } + public void setUnion_id(String union_id) { + this.union_id = union_id; + } - public String getUser_id() { - return user_id; - } + public String getUser_id() { + return user_id; + } - public void setUser_id(String user_id) { - this.user_id = user_id; - } + public void setUser_id(String user_id) { + this.user_id = user_id; + } - public String getOpen_id() { - return open_id; - } + public String getOpen_id() { + return open_id; + } - public void setOpen_id(String open_id) { - this.open_id = open_id; - } + public void setOpen_id(String open_id) { + this.open_id = open_id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getEn_name() { - return en_name; - } + public String getEn_name() { + return en_name; + } - public void setEn_name(String en_name) { - this.en_name = en_name; - } + public void setEn_name(String en_name) { + this.en_name = en_name; + } - public String getNickname() { - return nickname; - } + public String getNickname() { + return nickname; + } - public void setNickname(String nickname) { - this.nickname = nickname; - } + public void setNickname(String nickname) { + this.nickname = nickname; + } - public String getEmail() { - return email; - } + public String getEmail() { + return email; + } - public void setEmail(String email) { - this.email = email; - } + public void setEmail(String email) { + this.email = email; + } - public String getMobile() { - return mobile; - } + public String getMobile() { + return mobile; + } - public void setMobile(String mobile) { - this.mobile = mobile; - } + public void setMobile(String mobile) { + this.mobile = mobile; + } - public boolean isMobile_visible() { - return mobile_visible; - } + public boolean isMobile_visible() { + return mobile_visible; + } - public void setMobile_visible(boolean mobile_visible) { - this.mobile_visible = mobile_visible; - } + public void setMobile_visible(boolean mobile_visible) { + this.mobile_visible = mobile_visible; + } - public int getGender() { - return gender; - } + public int getGender() { + return gender; + } - public void setGender(int gender) { - this.gender = gender; - } + public void setGender(int gender) { + this.gender = gender; + } - public String getAvatar_key() { - return avatar_key; - } + public String getAvatar_key() { + return avatar_key; + } - public void setAvatar_key(String avatar_key) { - this.avatar_key = avatar_key; - } + public void setAvatar_key(String avatar_key) { + this.avatar_key = avatar_key; + } - public FeishuUserStatus getStatus() { - return status; - } + public FeishuUserStatus getStatus() { + return status; + } - public void setStatus(FeishuUserStatus status) { - this.status = status; - } + public void setStatus(FeishuUserStatus status) { + this.status = status; + } - public String[] getDepartment_ids() { - return department_ids; - } + public String[] getDepartment_ids() { + return department_ids; + } - public void setDepartment_ids(String[] department_ids) { - this.department_ids = department_ids; - } + public void setDepartment_ids(String[] department_ids) { + this.department_ids = department_ids; + } - public String getLeader_user_id() { - return leader_user_id; - } + public String getLeader_user_id() { + return leader_user_id; + } - public void setLeader_user_id(String leader_user_id) { - this.leader_user_id = leader_user_id; - } + public void setLeader_user_id(String leader_user_id) { + this.leader_user_id = leader_user_id; + } - public String getCity() { - return city; - } + public String getCity() { + return city; + } - public void setCity(String city) { - this.city = city; - } + public void setCity(String city) { + this.city = city; + } - public String getCountry() { - return country; - } + public String getCountry() { + return country; + } - public void setCountry(String country) { - this.country = country; - } + public void setCountry(String country) { + this.country = country; + } - public String getWork_station() { - return work_station; - } + public String getWork_station() { + return work_station; + } - public void setWork_station(String work_station) { - this.work_station = work_station; - } + public void setWork_station(String work_station) { + this.work_station = work_station; + } - public int getJoin_time() { - return join_time; - } + public int getJoin_time() { + return join_time; + } - public void setJoin_time(int join_time) { - this.join_time = join_time; - } + public void setJoin_time(int join_time) { + this.join_time = join_time; + } - public String getIs_tenant_manager() { - return is_tenant_manager; - } + public String getIs_tenant_manager() { + return is_tenant_manager; + } - public void setIs_tenant_manager(String is_tenant_manager) { - this.is_tenant_manager = is_tenant_manager; - } + public void setIs_tenant_manager(String is_tenant_manager) { + this.is_tenant_manager = is_tenant_manager; + } - public String getEmployee_no() { - return employee_no; - } + public String getEmployee_no() { + return employee_no; + } - public void setEmployee_no(String employee_no) { - this.employee_no = employee_no; - } + public void setEmployee_no(String employee_no) { + this.employee_no = employee_no; + } - public long getEmployee_type() { - return employee_type; - } + public long getEmployee_type() { + return employee_type; + } - public void setEmployee_type(long employee_type) { - this.employee_type = employee_type; - } + public void setEmployee_type(long employee_type) { + this.employee_type = employee_type; + } - public String getEnterprise_email() { - return enterprise_email; - } + public String getEnterprise_email() { + return enterprise_email; + } - public void setEnterprise_email(String enterprise_email) { - this.enterprise_email = enterprise_email; - } + public void setEnterprise_email(String enterprise_email) { + this.enterprise_email = enterprise_email; + } - public String getJob_title() { - return job_title; - } + public String getJob_title() { + return job_title; + } - public void setJob_title(String job_title) { - this.job_title = job_title; - } + public void setJob_title(String job_title) { + this.job_title = job_title; + } - public String getIs_frozen() { - return is_frozen; - } + public String getIs_frozen() { + return is_frozen; + } - public void setIs_frozen(String is_frozen) { - this.is_frozen = is_frozen; - } + public void setIs_frozen(String is_frozen) { + this.is_frozen = is_frozen; + } - public FeishuUsers() { - super(); - } + public FeishuUsers() { + super(); + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("FeishuUsers [union_id="); - builder.append(union_id); - builder.append(", user_id="); - builder.append(user_id); - builder.append(", open_id="); - builder.append(open_id); - builder.append(", name="); - builder.append(name); - builder.append(", en_name="); - builder.append(en_name); - builder.append(", nickname="); - builder.append(nickname); - builder.append(", email="); - builder.append(email); - builder.append(", mobile="); - builder.append(mobile); - builder.append(", mobile_visible="); - builder.append(mobile_visible); - builder.append(", gender="); - builder.append(gender); - builder.append(", avatar_key="); - builder.append(avatar_key); - builder.append(", status="); - builder.append(status); - builder.append(", department_ids="); - builder.append(Arrays.toString(department_ids)); - builder.append(", leader_user_id="); - builder.append(leader_user_id); - builder.append(", city="); - builder.append(city); - builder.append(", country="); - builder.append(country); - builder.append(", work_station="); - builder.append(work_station); - builder.append(", join_time="); - builder.append(join_time); - builder.append(", is_tenant_manager="); - builder.append(is_tenant_manager); - builder.append(", employee_no="); - builder.append(employee_no); - builder.append(", employee_type="); - builder.append(employee_type); - builder.append(", enterprise_email="); - builder.append(enterprise_email); - builder.append(", job_title="); - builder.append(job_title); - builder.append(", is_frozen="); - builder.append(is_frozen); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("FeishuUsers [union_id="); + builder.append(union_id); + builder.append(", user_id="); + builder.append(user_id); + builder.append(", open_id="); + builder.append(open_id); + builder.append(", name="); + builder.append(name); + builder.append(", en_name="); + builder.append(en_name); + builder.append(", nickname="); + builder.append(nickname); + builder.append(", email="); + builder.append(email); + builder.append(", mobile="); + builder.append(mobile); + builder.append(", mobile_visible="); + builder.append(mobile_visible); + builder.append(", gender="); + builder.append(gender); + builder.append(", avatar_key="); + builder.append(avatar_key); + builder.append(", status="); + builder.append(status); + builder.append(", department_ids="); + builder.append(Arrays.toString(department_ids)); + builder.append(", leader_user_id="); + builder.append(leader_user_id); + builder.append(", city="); + builder.append(city); + builder.append(", country="); + builder.append(country); + builder.append(", work_station="); + builder.append(work_station); + builder.append(", join_time="); + builder.append(join_time); + builder.append(", is_tenant_manager="); + builder.append(is_tenant_manager); + builder.append(", employee_no="); + builder.append(employee_no); + builder.append(", employee_type="); + builder.append(employee_type); + builder.append(", enterprise_email="); + builder.append(enterprise_email); + builder.append(", job_title="); + builder.append(job_title); + builder.append(", is_frozen="); + builder.append(is_frozen); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuUsersData.java b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuUsersData.java index eaa2f3577..8e1598723 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuUsersData.java +++ b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuUsersData.java @@ -20,59 +20,59 @@ package org.dromara.maxkey.synchronizer.feishu.entity; import java.util.ArrayList; public class FeishuUsersData { - boolean has_more; - String page_token; - - ArrayListitems; - - - public FeishuUsersData() { - super(); - } + boolean has_more; + String page_token; + + ArrayListitems; + + + public FeishuUsersData() { + super(); + } - public boolean isHas_more() { - return has_more; - } + public boolean isHas_more() { + return has_more; + } - public void setHas_more(boolean has_more) { - this.has_more = has_more; - } + public void setHas_more(boolean has_more) { + this.has_more = has_more; + } - public String getPage_token() { - return page_token; - } + public String getPage_token() { + return page_token; + } - public void setPage_token(String page_token) { - this.page_token = page_token; - } + public void setPage_token(String page_token) { + this.page_token = page_token; + } - public ArrayList getItems() { - return items; - } + public ArrayList getItems() { + return items; + } - public void setItems(ArrayList items) { - this.items = items; - } + public void setItems(ArrayList items) { + this.items = items; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("FeishuUsersData [has_more="); - builder.append(has_more); - builder.append(", page_token="); - builder.append(page_token); - builder.append(", items="); - builder.append(items); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("FeishuUsersData [has_more="); + builder.append(has_more); + builder.append(", page_token="); + builder.append(page_token); + builder.append(", items="); + builder.append(items); + builder.append("]"); + return builder.toString(); + } diff --git a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuUsersResponse.java b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuUsersResponse.java index 0f428aedb..0246fe279 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuUsersResponse.java +++ b/maxkey-synchronizers/maxkey-synchronizer-feishu/src/main/java/org/dromara/maxkey/synchronizer/feishu/entity/FeishuUsersResponse.java @@ -21,29 +21,29 @@ import org.dromara.maxkey.synchronizer.entity.ResponseData; public class FeishuUsersResponse extends ResponseData{ - FeishuUsersData data; + FeishuUsersData data; - public FeishuUsersResponse() { - super(); - } + public FeishuUsersResponse() { + super(); + } - public FeishuUsersData getData() { - return data; - } + public FeishuUsersData getData() { + return data; + } - public void setData(FeishuUsersData data) { - this.data = data; - } + public void setData(FeishuUsersData data) { + this.data = data; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("FeishuUsersResponse [data="); - builder.append(data); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("FeishuUsersResponse [data="); + builder.append(data); + builder.append("]"); + return builder.toString(); + } - + } diff --git a/maxkey-synchronizers/maxkey-synchronizer-jdbc/src/main/java/org/dromara/maxkey/synchronizer/jdbc/ColumnFieldMapper.java b/maxkey-synchronizers/maxkey-synchronizer-jdbc/src/main/java/org/dromara/maxkey/synchronizer/jdbc/ColumnFieldMapper.java index e688504d6..5bec252d8 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-jdbc/src/main/java/org/dromara/maxkey/synchronizer/jdbc/ColumnFieldMapper.java +++ b/maxkey-synchronizers/maxkey-synchronizer-jdbc/src/main/java/org/dromara/maxkey/synchronizer/jdbc/ColumnFieldMapper.java @@ -20,19 +20,19 @@ package org.dromara.maxkey.synchronizer.jdbc; import org.dromara.maxkey.entity.DbTableColumn; public class ColumnFieldMapper extends DbTableColumn{ - String field; - - public ColumnFieldMapper(String column, String field, String type) { - super(column, type, 0, 0); - this.field = field; - } + String field; + + public ColumnFieldMapper(String column, String field, String type) { + super(column, type, 0, 0); + this.field = field; + } - public String getField() { - return field; - } + public String getField() { + return field; + } - public void setField(String field) { - this.field = field; - } - + public void setField(String field) { + this.field = field; + } + } diff --git a/maxkey-synchronizers/maxkey-synchronizer-jdbc/src/main/java/org/dromara/maxkey/synchronizer/jdbc/JdbcOrganizationService.java b/maxkey-synchronizers/maxkey-synchronizer-jdbc/src/main/java/org/dromara/maxkey/synchronizer/jdbc/JdbcOrganizationService.java index 08b055bec..f01da563b 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-jdbc/src/main/java/org/dromara/maxkey/synchronizer/jdbc/JdbcOrganizationService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-jdbc/src/main/java/org/dromara/maxkey/synchronizer/jdbc/JdbcOrganizationService.java @@ -168,7 +168,7 @@ public class JdbcOrganizationService extends AbstractSynchronizerService impleme historySynchronizer.setInstId(synchronizer.getInstId()); historySynchronizer.setResult("success"); historySynchronizerService.insert(historySynchronizer); - + return org; } diff --git a/maxkey-synchronizers/maxkey-synchronizer-jdbc/src/main/java/org/dromara/maxkey/synchronizer/jdbc/JdbcSynchronizerService.java b/maxkey-synchronizers/maxkey-synchronizer-jdbc/src/main/java/org/dromara/maxkey/synchronizer/jdbc/JdbcSynchronizerService.java index 109ebc853..b01137196 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-jdbc/src/main/java/org/dromara/maxkey/synchronizer/jdbc/JdbcSynchronizerService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-jdbc/src/main/java/org/dromara/maxkey/synchronizer/jdbc/JdbcSynchronizerService.java @@ -26,43 +26,43 @@ import org.springframework.stereotype.Service; @Service public class JdbcSynchronizerService implements ISynchronizerService{ - static final Logger _logger = LoggerFactory.getLogger(JdbcSynchronizerService.class); - - Synchronizers synchronizer; - - @Autowired - JdbcUsersService jdbcUsersService; - - @Autowired - JdbcOrganizationService jdbcOrganizationService; - - public JdbcSynchronizerService() { - super(); - } + static final Logger _logger = LoggerFactory.getLogger(JdbcSynchronizerService.class); + + Synchronizers synchronizer; + + @Autowired + JdbcUsersService jdbcUsersService; + + @Autowired + JdbcOrganizationService jdbcOrganizationService; + + public JdbcSynchronizerService() { + super(); + } - public void sync() { - _logger.info("Sync ..."); - jdbcOrganizationService.setSynchronizer(synchronizer); - jdbcOrganizationService.sync(); - - jdbcUsersService.setSynchronizer(synchronizer); - jdbcUsersService.sync(); - - } + public void sync() { + _logger.info("Sync ..."); + jdbcOrganizationService.setSynchronizer(synchronizer); + jdbcOrganizationService.sync(); + + jdbcUsersService.setSynchronizer(synchronizer); + jdbcUsersService.sync(); + + } - public void setJdbcUsersService(JdbcUsersService jdbcUsersService) { - this.jdbcUsersService = jdbcUsersService; - } + public void setJdbcUsersService(JdbcUsersService jdbcUsersService) { + this.jdbcUsersService = jdbcUsersService; + } - public void setJdbcOrganizationService(JdbcOrganizationService jdbcOrganizationService) { - this.jdbcOrganizationService = jdbcOrganizationService; - } + public void setJdbcOrganizationService(JdbcOrganizationService jdbcOrganizationService) { + this.jdbcOrganizationService = jdbcOrganizationService; + } - @Override - public void setSynchronizer(Synchronizers synchronizer) { - this.synchronizer = synchronizer; - } + @Override + public void setSynchronizer(Synchronizers synchronizer) { + this.synchronizer = synchronizer; + } - + } diff --git a/maxkey-synchronizers/maxkey-synchronizer-jdbc/src/main/java/org/dromara/maxkey/synchronizer/jdbc/JdbcUsersService.java b/maxkey-synchronizers/maxkey-synchronizer-jdbc/src/main/java/org/dromara/maxkey/synchronizer/jdbc/JdbcUsersService.java index 5c3bcfee9..ef8c2dbc3 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-jdbc/src/main/java/org/dromara/maxkey/synchronizer/jdbc/JdbcUsersService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-jdbc/src/main/java/org/dromara/maxkey/synchronizer/jdbc/JdbcUsersService.java @@ -47,9 +47,9 @@ import static org.dromara.maxkey.synchronizer.utils.FieldUtil.setFieldValue; @Service public class JdbcUsersService extends AbstractSynchronizerService implements ISynchronizerService { - static final Logger _logger = LoggerFactory.getLogger(JdbcUsersService.class); + static final Logger _logger = LoggerFactory.getLogger(JdbcUsersService.class); - @Autowired + @Autowired public SyncJobConfigFieldService syncJobConfigFieldService; private static final Integer USER_TYPE = 1; diff --git a/maxkey-synchronizers/maxkey-synchronizer-ldap/src/main/java/org/dromara/maxkey/synchronizer/ldap/LdapOrganizationService.java b/maxkey-synchronizers/maxkey-synchronizer-ldap/src/main/java/org/dromara/maxkey/synchronizer/ldap/LdapOrganizationService.java index 3ffb99629..964124044 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-ldap/src/main/java/org/dromara/maxkey/synchronizer/ldap/LdapOrganizationService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-ldap/src/main/java/org/dromara/maxkey/synchronizer/ldap/LdapOrganizationService.java @@ -50,259 +50,259 @@ import static org.dromara.maxkey.synchronizer.utils.FieldUtil.setFieldValue; @Service public class LdapOrganizationService extends AbstractSynchronizerService implements ISynchronizerService{ - final static Logger _logger = LoggerFactory.getLogger(LdapOrganizationService.class); - @Autowired - private SyncJobConfigFieldService syncJobConfigFieldService; + final static Logger _logger = LoggerFactory.getLogger(LdapOrganizationService.class); + @Autowired + private SyncJobConfigFieldService syncJobConfigFieldService; - private static final Integer ORG_TYPE = 2; - LdapUtils ldapUtils; - - public void sync() { - _logger.info("Sync Ldap Organizations ..."); - loadOrgsByInstId(this.synchronizer.getInstId(),Organizations.ROOT_ORG_ID); - try { - ArrayList orgsList = queryLdap(); - int maxLevel = 0; - for(Organizations organization : orgsList) { - maxLevel = (maxLevel < organization.getLevel()) ? organization.getLevel() : maxLevel ; - } - - for (int level = 2 ; level <= maxLevel ; level++) { - for(Organizations organization : orgsList) { - if(organization.getLevel() == level) { - String parentNamePath= organization.getNamePath().substring(0, organization.getNamePath().lastIndexOf("/")); - - if(orgsNamePathMap.get(organization.getNamePath())!=null) { - _logger.info("org " + orgsNamePathMap.get(organization.getNamePath()).getNamePath()+" exists."); - continue; - } - - Organizations parentOrg = orgsNamePathMap.get(parentNamePath); - if(parentOrg == null ) { - parentOrg = rootOrganization; - } - organization.setParentId(parentOrg.getId()); - organization.setParentName(parentOrg.getOrgName()); - organization.setCodePath(parentOrg.getCodePath()+"/"+organization.getId()); - _logger.info("parentNamePath " + parentNamePath+" , namePah " + organization.getNamePath()); - - //synchro Related - SynchroRelated synchroRelated = - synchroRelatedService.findByOriginId( - this.synchronizer,organization.getLdapDn(),Organizations.CLASS_TYPE ); - if(synchroRelated == null) { - organization.setId(organization.generateId()); - organizationsService.insert(organization); - _logger.debug("Organizations : " + organization); - - synchroRelated = buildSynchroRelated(organization,organization.getLdapDn(),organization.getOrgName()); - }else { - organization.setId(synchroRelated.getObjectId()); - organizationsService.update(organization); - } - - synchroRelatedService.updateSynchroRelated( - this.synchronizer,synchroRelated,Organizations.CLASS_TYPE); - - orgsNamePathMap.put(organization.getNamePath(), organization); - - _logger.info("Organizations " + organization); - HistorySynchronizer historySynchronizer =new HistorySynchronizer(); - historySynchronizer.setId(historySynchronizer.generateId()); - historySynchronizer.setSyncId(this.synchronizer.getId()); - historySynchronizer.setSyncName(this.synchronizer.getName()); - historySynchronizer.setObjectId(organization.getId()); - historySynchronizer.setObjectName(organization.getOrgName()); - historySynchronizer.setObjectType(Organizations.class.getSimpleName()); - historySynchronizer.setInstId(synchronizer.getInstId()); - historySynchronizer.setResult("success"); - this.historySynchronizerService.insert(historySynchronizer); - } - } - } - //ldapUtils.close(); - } catch (NamingException e) { - e.printStackTrace(); - } - - } - - private ArrayList queryLdap() throws NamingException { - SearchControls constraints = new SearchControls(); - constraints.setSearchScope(ldapUtils.getSearchScope()); - String filter = "(&(objectClass=OrganizationalUnit))"; - if(StringUtils.isNotBlank(this.getSynchronizer().getOrgFilters())) { - filter = this.getSynchronizer().getOrgFilters(); - } - NamingEnumeration results = - ldapUtils.getConnection().search(ldapUtils.getBaseDN(), filter , constraints); - - ArrayList orgsList = new ArrayList(); - - long recordCount = 0; - while (null != results && results.hasMoreElements()) { - Object obj = results.nextElement(); - if (obj instanceof SearchResult) { - SearchResult sr = (SearchResult) obj; - _logger.debug("Sync OrganizationalUnit {} , name [{}] , NameInNamespace [{}]" , - (++recordCount),sr.getName(),sr.getNameInNamespace()); - - HashMap attributeMap = new HashMap(); - NamingEnumeration attrs = sr.getAttributes().getAll(); - while (null != attrs && attrs.hasMoreElements()) { - Attribute objAttrs = attrs.nextElement(); - _logger.trace("attribute {} : {}" , - objAttrs.getID(), - LdapUtils.getAttrStringValue(objAttrs) - ); - attributeMap.put(objAttrs.getID().toLowerCase(), objAttrs); - } - - Organizations organization = buildOrganization(attributeMap,sr.getName(),sr.getNameInNamespace()); - if(organization != null) { - orgsList.add(organization); - } - } - } - return orgsList; - } - - public SynchroRelated buildSynchroRelated(Organizations organization,String ldapDN,String name) { - return new SynchroRelated( - organization.getId(), - organization.getOrgName(), - organization.getOrgName(), - Organizations.CLASS_TYPE, - synchronizer.getId(), - synchronizer.getName(), - ldapDN, - name, - "", - organization.getParentId(), - synchronizer.getInstId()); - } - - public Organizations buildOrganization(HashMap attributeMap,String name,String nameInNamespace) { - try { - Organizations org = new Organizations(); - org.setLdapDn(nameInNamespace); - String []namePaths = name.replaceAll(",OU=" , "/") - .replaceAll("OU=" , "/") - .replaceAll(",ou=" , "/") - .replaceAll("ou=" , "/") - .split("/"); - - String namePah= "/"+rootOrganization.getOrgName(); - for(int i = namePaths.length -1 ; i >= 0 ; i --) { - namePah = namePah + "/" + namePaths[i]; - } - - namePah = namePah.substring(0, namePah.length() - 1); + private static final Integer ORG_TYPE = 2; + LdapUtils ldapUtils; + + public void sync() { + _logger.info("Sync Ldap Organizations ..."); + loadOrgsByInstId(this.synchronizer.getInstId(),Organizations.ROOT_ORG_ID); + try { + ArrayList orgsList = queryLdap(); + int maxLevel = 0; + for(Organizations organization : orgsList) { + maxLevel = (maxLevel < organization.getLevel()) ? organization.getLevel() : maxLevel ; + } + + for (int level = 2 ; level <= maxLevel ; level++) { + for(Organizations organization : orgsList) { + if(organization.getLevel() == level) { + String parentNamePath= organization.getNamePath().substring(0, organization.getNamePath().lastIndexOf("/")); + + if(orgsNamePathMap.get(organization.getNamePath())!=null) { + _logger.info("org " + orgsNamePathMap.get(organization.getNamePath()).getNamePath()+" exists."); + continue; + } + + Organizations parentOrg = orgsNamePathMap.get(parentNamePath); + if(parentOrg == null ) { + parentOrg = rootOrganization; + } + organization.setParentId(parentOrg.getId()); + organization.setParentName(parentOrg.getOrgName()); + organization.setCodePath(parentOrg.getCodePath()+"/"+organization.getId()); + _logger.info("parentNamePath " + parentNamePath+" , namePah " + organization.getNamePath()); + + //synchro Related + SynchroRelated synchroRelated = + synchroRelatedService.findByOriginId( + this.synchronizer,organization.getLdapDn(),Organizations.CLASS_TYPE ); + if(synchroRelated == null) { + organization.setId(organization.generateId()); + organizationsService.insert(organization); + _logger.debug("Organizations : " + organization); + + synchroRelated = buildSynchroRelated(organization,organization.getLdapDn(),organization.getOrgName()); + }else { + organization.setId(synchroRelated.getObjectId()); + organizationsService.update(organization); + } + + synchroRelatedService.updateSynchroRelated( + this.synchronizer,synchroRelated,Organizations.CLASS_TYPE); + + orgsNamePathMap.put(organization.getNamePath(), organization); + + _logger.info("Organizations " + organization); + HistorySynchronizer historySynchronizer =new HistorySynchronizer(); + historySynchronizer.setId(historySynchronizer.generateId()); + historySynchronizer.setSyncId(this.synchronizer.getId()); + historySynchronizer.setSyncName(this.synchronizer.getName()); + historySynchronizer.setObjectId(organization.getId()); + historySynchronizer.setObjectName(organization.getOrgName()); + historySynchronizer.setObjectType(Organizations.class.getSimpleName()); + historySynchronizer.setInstId(synchronizer.getInstId()); + historySynchronizer.setResult("success"); + this.historySynchronizerService.insert(historySynchronizer); + } + } + } + //ldapUtils.close(); + } catch (NamingException e) { + e.printStackTrace(); + } + + } + + private ArrayList queryLdap() throws NamingException { + SearchControls constraints = new SearchControls(); + constraints.setSearchScope(ldapUtils.getSearchScope()); + String filter = "(&(objectClass=OrganizationalUnit))"; + if(StringUtils.isNotBlank(this.getSynchronizer().getOrgFilters())) { + filter = this.getSynchronizer().getOrgFilters(); + } + NamingEnumeration results = + ldapUtils.getConnection().search(ldapUtils.getBaseDN(), filter , constraints); + + ArrayList orgsList = new ArrayList(); + + long recordCount = 0; + while (null != results && results.hasMoreElements()) { + Object obj = results.nextElement(); + if (obj instanceof SearchResult) { + SearchResult sr = (SearchResult) obj; + _logger.debug("Sync OrganizationalUnit {} , name [{}] , NameInNamespace [{}]" , + (++recordCount),sr.getName(),sr.getNameInNamespace()); + + HashMap attributeMap = new HashMap(); + NamingEnumeration attrs = sr.getAttributes().getAll(); + while (null != attrs && attrs.hasMoreElements()) { + Attribute objAttrs = attrs.nextElement(); + _logger.trace("attribute {} : {}" , + objAttrs.getID(), + LdapUtils.getAttrStringValue(objAttrs) + ); + attributeMap.put(objAttrs.getID().toLowerCase(), objAttrs); + } + + Organizations organization = buildOrganization(attributeMap,sr.getName(),sr.getNameInNamespace()); + if(organization != null) { + orgsList.add(organization); + } + } + } + return orgsList; + } + + public SynchroRelated buildSynchroRelated(Organizations organization,String ldapDN,String name) { + return new SynchroRelated( + organization.getId(), + organization.getOrgName(), + organization.getOrgName(), + Organizations.CLASS_TYPE, + synchronizer.getId(), + synchronizer.getName(), + ldapDN, + name, + "", + organization.getParentId(), + synchronizer.getInstId()); + } + + public Organizations buildOrganization(HashMap attributeMap,String name,String nameInNamespace) { + try { + Organizations org = new Organizations(); + org.setLdapDn(nameInNamespace); + String []namePaths = name.replaceAll(",OU=" , "/") + .replaceAll("OU=" , "/") + .replaceAll(",ou=" , "/") + .replaceAll("ou=" , "/") + .split("/"); + + String namePah= "/"+rootOrganization.getOrgName(); + for(int i = namePaths.length -1 ; i >= 0 ; i --) { + namePah = namePah + "/" + namePaths[i]; + } + + namePah = namePah.substring(0, namePah.length() - 1); - org.setId(org.generateId()); - org.setOrgCode(org.getId()); - org.setNamePath(namePah); - org.setLevel(namePaths.length); - org.setOrgName(LdapUtils.getAttributeStringValue(OrganizationalUnit.OU,attributeMap)); - org.setFullName(org.getOrgName()); - org.setType("department"); - //org.setCountry(LdapUtils.getAttributeStringValue(OrganizationalUnit.CO,attributeMap)); - org.setRegion(LdapUtils.getAttributeStringValue(OrganizationalUnit.ST,attributeMap)); - org.setLocality(LdapUtils.getAttributeStringValue(OrganizationalUnit.L,attributeMap)); - org.setStreet(LdapUtils.getAttributeStringValue(OrganizationalUnit.STREET,attributeMap)); - org.setPostalCode(LdapUtils.getAttributeStringValue(OrganizationalUnit.POSTALCODE,attributeMap)); - org.setAddress(LdapUtils.getAttributeStringValue(OrganizationalUnit.POSTALADDRESS,attributeMap)); - org.setPhone(LdapUtils.getAttributeStringValue(OrganizationalUnit.TELEPHONENUMBER,attributeMap)); - org.setFax(LdapUtils.getAttributeStringValue(OrganizationalUnit.FACSIMILETELEPHONENUMBER,attributeMap)); - org.setDescription(LdapUtils.getAttributeStringValue(OrganizationalUnit.DESCRIPTION,attributeMap)); - org.setInstId(this.synchronizer.getInstId()); - org.setStatus(ConstsStatus.ACTIVE); + org.setId(org.generateId()); + org.setOrgCode(org.getId()); + org.setNamePath(namePah); + org.setLevel(namePaths.length); + org.setOrgName(LdapUtils.getAttributeStringValue(OrganizationalUnit.OU,attributeMap)); + org.setFullName(org.getOrgName()); + org.setType("department"); + //org.setCountry(LdapUtils.getAttributeStringValue(OrganizationalUnit.CO,attributeMap)); + org.setRegion(LdapUtils.getAttributeStringValue(OrganizationalUnit.ST,attributeMap)); + org.setLocality(LdapUtils.getAttributeStringValue(OrganizationalUnit.L,attributeMap)); + org.setStreet(LdapUtils.getAttributeStringValue(OrganizationalUnit.STREET,attributeMap)); + org.setPostalCode(LdapUtils.getAttributeStringValue(OrganizationalUnit.POSTALCODE,attributeMap)); + org.setAddress(LdapUtils.getAttributeStringValue(OrganizationalUnit.POSTALADDRESS,attributeMap)); + org.setPhone(LdapUtils.getAttributeStringValue(OrganizationalUnit.TELEPHONENUMBER,attributeMap)); + org.setFax(LdapUtils.getAttributeStringValue(OrganizationalUnit.FACSIMILETELEPHONENUMBER,attributeMap)); + org.setDescription(LdapUtils.getAttributeStringValue(OrganizationalUnit.DESCRIPTION,attributeMap)); + org.setInstId(this.synchronizer.getInstId()); + org.setStatus(ConstsStatus.ACTIVE); _logger.info("org " + org); return org; - } catch (NamingException e) { - _logger.error("NamingException " , e); - } - return null; - } + } catch (NamingException e) { + _logger.error("NamingException " , e); + } + return null; + } - public Organizations buildOrgByFieldMap(HashMap attributeMap,String name,String nameInNamespace){ - Organizations org = new Organizations(); - String []namePaths = name.replaceAll(",OU=" , "/") - .replaceAll("OU=" , "/") - .replaceAll(",ou=" , "/") - .replaceAll("ou=" , "/") - .split("/"); + public Organizations buildOrgByFieldMap(HashMap attributeMap,String name,String nameInNamespace){ + Organizations org = new Organizations(); + String []namePaths = name.replaceAll(",OU=" , "/") + .replaceAll("OU=" , "/") + .replaceAll(",ou=" , "/") + .replaceAll("ou=" , "/") + .split("/"); - String namePah= "/"+rootOrganization.getOrgName(); - for(int i = namePaths.length -1 ; i >= 0 ; i --) { - namePah = namePah + "/" + namePaths[i]; - } + String namePah= "/"+rootOrganization.getOrgName(); + for(int i = namePaths.length -1 ; i >= 0 ; i --) { + namePah = namePah + "/" + namePaths[i]; + } - namePah = namePah.substring(0, namePah.length() - 1); - org.setLdapDn(nameInNamespace); - org.setId(org.generateId()); - org.setNamePath(namePah); - org.setLevel(namePaths.length); - org.setType("department"); + namePah = namePah.substring(0, namePah.length() - 1); + org.setLdapDn(nameInNamespace); + org.setId(org.generateId()); + org.setNamePath(namePah); + org.setLevel(namePaths.length); + org.setType("department"); - Map fieldMap = getFieldMap(Long.parseLong(synchronizer.getId())); - for(Map.Entry entry:fieldMap.entrySet()){ - String orgProperty = entry.getKey(); - String sourceProperty = entry.getValue(); - try { - String fieldValue = null; - if(!attributeMap.keySet().contains(sourceProperty.toLowerCase())){ - fieldValue = (String) getFieldValue(org, sourceProperty); - }else { - fieldValue = LdapUtils.getAttributeStringValue(sourceProperty,attributeMap); - } - if(fieldValue!=null){ - setFieldValue(org,orgProperty,fieldValue); - } - } catch (InvocationTargetException e) { - throw new RuntimeException(e); - } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } catch (NamingException e) { - throw new RuntimeException(e); - } - org.setInstId(this.synchronizer.getInstId()); - org.setStatus(ConstsStatus.ACTIVE); + Map fieldMap = getFieldMap(Long.parseLong(synchronizer.getId())); + for(Map.Entry entry:fieldMap.entrySet()){ + String orgProperty = entry.getKey(); + String sourceProperty = entry.getValue(); + try { + String fieldValue = null; + if(!attributeMap.keySet().contains(sourceProperty.toLowerCase())){ + fieldValue = (String) getFieldValue(org, sourceProperty); + }else { + fieldValue = LdapUtils.getAttributeStringValue(sourceProperty,attributeMap); + } + if(fieldValue!=null){ + setFieldValue(org,orgProperty,fieldValue); + } + } catch (InvocationTargetException e) { + throw new RuntimeException(e); + } catch (NoSuchMethodException e) { + throw new RuntimeException(e); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } catch (NamingException e) { + throw new RuntimeException(e); + } + org.setInstId(this.synchronizer.getInstId()); + org.setStatus(ConstsStatus.ACTIVE); - } - return org; - } + } + return org; + } - public Map getFieldMap(Long jobId){ - Map userFiledMap = new HashMap<>(); - //根据job id查询属性映射表 - List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); - //获取用户属性映射 - for(SyncJobConfigField element:syncJobConfigFieldList){ - if(Integer.parseInt(element.getObjectType()) == ORG_TYPE.intValue()){ - userFiledMap.put(element.getTargetField(), element.getSourceField()); - } - } - return userFiledMap; - } - + public Map getFieldMap(Long jobId){ + Map userFiledMap = new HashMap<>(); + //根据job id查询属性映射表 + List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); + //获取用户属性映射 + for(SyncJobConfigField element:syncJobConfigFieldList){ + if(Integer.parseInt(element.getObjectType()) == ORG_TYPE.intValue()){ + userFiledMap.put(element.getTargetField(), element.getSourceField()); + } + } + return userFiledMap; + } + - public LdapUtils getLdapUtils() { - return ldapUtils; - } + public LdapUtils getLdapUtils() { + return ldapUtils; + } - public void setLdapUtils(LdapUtils ldapUtils) { - this.ldapUtils = ldapUtils; - } + public void setLdapUtils(LdapUtils ldapUtils) { + this.ldapUtils = ldapUtils; + } - public SyncJobConfigFieldService getSyncJobConfigFieldService() { - return syncJobConfigFieldService; - } + public SyncJobConfigFieldService getSyncJobConfigFieldService() { + return syncJobConfigFieldService; + } - public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { - this.syncJobConfigFieldService = syncJobConfigFieldService; - } + public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { + this.syncJobConfigFieldService = syncJobConfigFieldService; + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-ldap/src/main/java/org/dromara/maxkey/synchronizer/ldap/LdapSynchronizerService.java b/maxkey-synchronizers/maxkey-synchronizer-ldap/src/main/java/org/dromara/maxkey/synchronizer/ldap/LdapSynchronizerService.java index 33a6a1bb3..affb7c631 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-ldap/src/main/java/org/dromara/maxkey/synchronizer/ldap/LdapSynchronizerService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-ldap/src/main/java/org/dromara/maxkey/synchronizer/ldap/LdapSynchronizerService.java @@ -27,63 +27,63 @@ import org.springframework.stereotype.Service; @Service public class LdapSynchronizerService implements ISynchronizerService{ - static final Logger _logger = LoggerFactory.getLogger(LdapSynchronizerService.class); - - Synchronizers synchronizer; - - @Autowired - LdapUsersService ldapUsersService; - - @Autowired - LdapOrganizationService ldapOrganizationService; - - public LdapSynchronizerService() { - super(); - } + static final Logger _logger = LoggerFactory.getLogger(LdapSynchronizerService.class); + + Synchronizers synchronizer; + + @Autowired + LdapUsersService ldapUsersService; + + @Autowired + LdapOrganizationService ldapOrganizationService; + + public LdapSynchronizerService() { + super(); + } - public void sync() { - _logger.info("Sync ..."); - LdapUtils ldapUtils = new LdapUtils( - synchronizer.getProviderUrl(), - synchronizer.getPrincipal(), - synchronizer.getCredentials(), - synchronizer.getUserBasedn()); - ldapUtils.openConnection(); - - ldapOrganizationService.setSynchronizer(synchronizer); - ldapUsersService.setSynchronizer(synchronizer); - - ldapOrganizationService.setLdapUtils(ldapUtils); - ldapUsersService.setLdapUtils(ldapUtils); - - - ldapOrganizationService.sync(); - ldapUsersService.sync(); - - ldapUtils.close(); - } + public void sync() { + _logger.info("Sync ..."); + LdapUtils ldapUtils = new LdapUtils( + synchronizer.getProviderUrl(), + synchronizer.getPrincipal(), + synchronizer.getCredentials(), + synchronizer.getUserBasedn()); + ldapUtils.openConnection(); + + ldapOrganizationService.setSynchronizer(synchronizer); + ldapUsersService.setSynchronizer(synchronizer); + + ldapOrganizationService.setLdapUtils(ldapUtils); + ldapUsersService.setLdapUtils(ldapUtils); + + + ldapOrganizationService.sync(); + ldapUsersService.sync(); + + ldapUtils.close(); + } - public LdapUsersService getLdapUsersService() { - return ldapUsersService; - } + public LdapUsersService getLdapUsersService() { + return ldapUsersService; + } - public void setLdapUsersService(LdapUsersService ldapUsersService) { - this.ldapUsersService = ldapUsersService; - } + public void setLdapUsersService(LdapUsersService ldapUsersService) { + this.ldapUsersService = ldapUsersService; + } - public LdapOrganizationService getLdapOrganizationService() { - return ldapOrganizationService; - } + public LdapOrganizationService getLdapOrganizationService() { + return ldapOrganizationService; + } - public void setLdapOrganizationService(LdapOrganizationService ldapOrganizationService) { - this.ldapOrganizationService = ldapOrganizationService; - } + public void setLdapOrganizationService(LdapOrganizationService ldapOrganizationService) { + this.ldapOrganizationService = ldapOrganizationService; + } - @Override - public void setSynchronizer(Synchronizers synchronizer) { - this.synchronizer = synchronizer; - - } + @Override + public void setSynchronizer(Synchronizers synchronizer) { + this.synchronizer = synchronizer; + + } - + } diff --git a/maxkey-synchronizers/maxkey-synchronizer-ldap/src/main/java/org/dromara/maxkey/synchronizer/ldap/LdapUsersService.java b/maxkey-synchronizers/maxkey-synchronizer-ldap/src/main/java/org/dromara/maxkey/synchronizer/ldap/LdapUsersService.java index c7c0af565..881e634d7 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-ldap/src/main/java/org/dromara/maxkey/synchronizer/ldap/LdapUsersService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-ldap/src/main/java/org/dromara/maxkey/synchronizer/ldap/LdapUsersService.java @@ -49,161 +49,161 @@ import static org.dromara.maxkey.synchronizer.utils.FieldUtil.setFieldValue; @Service public class LdapUsersService extends AbstractSynchronizerService implements ISynchronizerService{ - final static Logger _logger = LoggerFactory.getLogger(LdapUsersService.class); - @Autowired - public SyncJobConfigFieldService syncJobConfigFieldService; + final static Logger _logger = LoggerFactory.getLogger(LdapUsersService.class); + @Autowired + public SyncJobConfigFieldService syncJobConfigFieldService; - private static final Integer USER_TYPE = 1; - LdapUtils ldapUtils; - - public void sync() { - _logger.info("Sync Ldap Users ..."); - loadOrgsByInstId(this.synchronizer.getInstId(),Organizations.ROOT_ORG_ID); - try { - SearchControls constraints = new SearchControls(); - constraints.setSearchScope(ldapUtils.getSearchScope()); - String filter = StringUtils.isNotBlank(this.getSynchronizer().getUserFilters()) ? - getSynchronizer().getUserFilters() : "(&(objectClass=inetOrgPerson))"; - _logger.debug(" User filter {} ",filter); - NamingEnumeration results = - ldapUtils.getConnection().search(ldapUtils.getBaseDN(), filter, constraints); - - long recordCount = 0; - while (null != results && results.hasMoreElements()) { - Object obj = results.nextElement(); - if (obj instanceof SearchResult) { - SearchResult sr = (SearchResult) obj; - _logger.debug("Sync User {} , name [{}] , NameInNamespace [{}]" , - (++recordCount),sr.getName(),sr.getNameInNamespace()); - - HashMap attributeMap = new HashMap(); - NamingEnumeration attrs = sr.getAttributes().getAll(); - while (null != attrs && attrs.hasMoreElements()) { - Attribute objAttrs = attrs.nextElement(); - _logger.trace("attribute {} : {}" , - objAttrs.getID(), - LdapUtils.getAttrStringValue(objAttrs) - ); - attributeMap.put(objAttrs.getID(), objAttrs); - } - String originId = DigestUtils.md5B64(sr.getNameInNamespace()); - UserInfo userInfo = buildUserInfo(attributeMap,sr.getName(),sr.getNameInNamespace()); - userInfo.setPassword(userInfo.getUsername() + UserInfo.DEFAULT_PASSWORD_SUFFIX); - userInfoService.saveOrUpdate(userInfo); - SynchroRelated synchroRelated = new SynchroRelated( - userInfo.getId(), - userInfo.getUsername(), - userInfo.getDisplayName(), - UserInfo.CLASS_TYPE, - synchronizer.getId(), - synchronizer.getName(), - originId, - userInfo.getDisplayName(), - "", - "", - synchronizer.getInstId()); - - synchroRelatedService.updateSynchroRelated( - this.synchronizer,synchroRelated,UserInfo.CLASS_TYPE); - _logger.info("userInfo " + userInfo); - } - } + private static final Integer USER_TYPE = 1; + LdapUtils ldapUtils; + + public void sync() { + _logger.info("Sync Ldap Users ..."); + loadOrgsByInstId(this.synchronizer.getInstId(),Organizations.ROOT_ORG_ID); + try { + SearchControls constraints = new SearchControls(); + constraints.setSearchScope(ldapUtils.getSearchScope()); + String filter = StringUtils.isNotBlank(this.getSynchronizer().getUserFilters()) ? + getSynchronizer().getUserFilters() : "(&(objectClass=inetOrgPerson))"; + _logger.debug(" User filter {} ",filter); + NamingEnumeration results = + ldapUtils.getConnection().search(ldapUtils.getBaseDN(), filter, constraints); + + long recordCount = 0; + while (null != results && results.hasMoreElements()) { + Object obj = results.nextElement(); + if (obj instanceof SearchResult) { + SearchResult sr = (SearchResult) obj; + _logger.debug("Sync User {} , name [{}] , NameInNamespace [{}]" , + (++recordCount),sr.getName(),sr.getNameInNamespace()); + + HashMap attributeMap = new HashMap(); + NamingEnumeration attrs = sr.getAttributes().getAll(); + while (null != attrs && attrs.hasMoreElements()) { + Attribute objAttrs = attrs.nextElement(); + _logger.trace("attribute {} : {}" , + objAttrs.getID(), + LdapUtils.getAttrStringValue(objAttrs) + ); + attributeMap.put(objAttrs.getID(), objAttrs); + } + String originId = DigestUtils.md5B64(sr.getNameInNamespace()); + UserInfo userInfo = buildUserInfo(attributeMap,sr.getName(),sr.getNameInNamespace()); + userInfo.setPassword(userInfo.getUsername() + UserInfo.DEFAULT_PASSWORD_SUFFIX); + userInfoService.saveOrUpdate(userInfo); + SynchroRelated synchroRelated = new SynchroRelated( + userInfo.getId(), + userInfo.getUsername(), + userInfo.getDisplayName(), + UserInfo.CLASS_TYPE, + synchronizer.getId(), + synchronizer.getName(), + originId, + userInfo.getDisplayName(), + "", + "", + synchronizer.getInstId()); + + synchroRelatedService.updateSynchroRelated( + this.synchronizer,synchroRelated,UserInfo.CLASS_TYPE); + _logger.info("userInfo " + userInfo); + } + } - //ldapUtils.close(); - } catch (NamingException e) { - e.printStackTrace(); - } - - } - - public void postSync(UserInfo userInfo) { - - } + //ldapUtils.close(); + } catch (NamingException e) { + e.printStackTrace(); + } + + } + + public void postSync(UserInfo userInfo) { + + } - public UserInfo buildUserInfo(HashMap attributeMap,String name,String nameInNamespace) { - UserInfo userInfo = new UserInfo(); - userInfo.setLdapDn(nameInNamespace); - String []namePaths = name.replaceAll(",OU=" , "/") - .replaceAll("OU=" , "/") - .replaceAll(",ou=" , "/") - .replaceAll("ou=" , "/") - .split("/"); - String namePah= "/"+rootOrganization.getOrgName(); - for(int i = namePaths.length -1 ; i >= 0 ; i --) { - namePah = namePah + "/" + namePaths[i]; - } - + public UserInfo buildUserInfo(HashMap attributeMap,String name,String nameInNamespace) { + UserInfo userInfo = new UserInfo(); + userInfo.setLdapDn(nameInNamespace); + String []namePaths = name.replaceAll(",OU=" , "/") + .replaceAll("OU=" , "/") + .replaceAll(",ou=" , "/") + .replaceAll("ou=" , "/") + .split("/"); + String namePah= "/"+rootOrganization.getOrgName(); + for(int i = namePaths.length -1 ; i >= 0 ; i --) { + namePah = namePah + "/" + namePaths[i]; + } + namePah = namePah.substring(0, namePah.length()); String deptNamePath= namePah.substring(0, namePah.lastIndexOf("/")); _logger.info("deptNamePath " + deptNamePath); - + Organizations deptOrg = orgsNamePathMap.get(deptNamePath); userInfo.setDepartment(deptOrg.getOrgName()); userInfo.setDepartmentId(deptOrg.getId()); - try { - userInfo.setId(userInfo.generateId()); - String cn = LdapUtils.getAttributeStringValue(InetOrgPerson.CN,attributeMap); - String uid = LdapUtils.getAttributeStringValue(InetOrgPerson.UID,attributeMap); - String sn = LdapUtils.getAttributeStringValue(InetOrgPerson.SN,attributeMap); - String givenName = LdapUtils.getAttributeStringValue(InetOrgPerson.GIVENNAME,attributeMap); - String initials = LdapUtils.getAttributeStringValue(InetOrgPerson.INITIALS,attributeMap); - String displayName = LdapUtils.getAttributeStringValue(InetOrgPerson.DISPLAYNAME,attributeMap); - userInfo.setFormattedName(sn + givenName); - if(StringUtils.isBlank(uid)) { - userInfo.setUsername(cn); - userInfo.setWindowsAccount(cn); - }else { - userInfo.setUsername(uid); - userInfo.setWindowsAccount(uid); - } - userInfo.setFamilyName(sn); - userInfo.setGivenName(givenName); - if(StringUtils.isBlank(initials)) { - userInfo.setNickName(sn + givenName); - userInfo.setNameZhShortSpell(sn + givenName); - }else { - userInfo.setNickName(initials); - userInfo.setNameZhShortSpell(initials); - } - if(StringUtils.isBlank(displayName)) { - userInfo.setDisplayName(sn + givenName); - }else { - userInfo.setDisplayName(displayName); - } - - userInfo.setEmployeeNumber(LdapUtils.getAttributeStringValue(InetOrgPerson.EMPLOYEENUMBER,attributeMap)); - //userInfo.setDepartment(LdapUtils.getAttributeStringValue(InetOrgPerson.OU,attributeMap)); - //userInfo.setDepartmentId(LdapUtils.getAttributeStringValue(InetOrgPerson.DEPARTMENTNUMBER,attributeMap)); - userInfo.setJobTitle(LdapUtils.getAttributeStringValue(InetOrgPerson.TITLE,attributeMap)); - userInfo.setWorkOfficeName(LdapUtils.getAttributeStringValue(InetOrgPerson.PHYSICALDELIVERYOFFICENAME,attributeMap)); - userInfo.setWorkEmail(LdapUtils.getAttributeStringValue(InetOrgPerson.MAIL,attributeMap)); - userInfo.setWorkRegion(LdapUtils.getAttributeStringValue(InetOrgPerson.ST,attributeMap)); - userInfo.setWorkLocality(LdapUtils.getAttributeStringValue(InetOrgPerson.L,attributeMap)); - userInfo.setWorkStreetAddress(LdapUtils.getAttributeStringValue(InetOrgPerson.STREET,attributeMap)); - userInfo.setWorkPostalCode(LdapUtils.getAttributeStringValue(InetOrgPerson.POSTALCODE,attributeMap)); - userInfo.setWorkAddressFormatted(LdapUtils.getAttributeStringValue(InetOrgPerson.POSTOFFICEBOX,attributeMap)); - userInfo.setWorkFax(LdapUtils.getAttributeStringValue(InetOrgPerson.FACSIMILETELEPHONENUMBER,attributeMap)); - - userInfo.setHomePhoneNumber(LdapUtils.getAttributeStringValue(InetOrgPerson.HOMEPHONE,attributeMap)); - userInfo.setHomeAddressFormatted(LdapUtils.getAttributeStringValue(InetOrgPerson.HOMEPOSTALADDRESS,attributeMap)); - - if(LdapUtils.getAttributeStringValue(InetOrgPerson.MOBILE,attributeMap).equals("")) { - userInfo.setMobile(userInfo.getId()); - }else { - userInfo.setMobile(LdapUtils.getAttributeStringValue(InetOrgPerson.MOBILE,attributeMap)); + try { + userInfo.setId(userInfo.generateId()); + String cn = LdapUtils.getAttributeStringValue(InetOrgPerson.CN,attributeMap); + String uid = LdapUtils.getAttributeStringValue(InetOrgPerson.UID,attributeMap); + String sn = LdapUtils.getAttributeStringValue(InetOrgPerson.SN,attributeMap); + String givenName = LdapUtils.getAttributeStringValue(InetOrgPerson.GIVENNAME,attributeMap); + String initials = LdapUtils.getAttributeStringValue(InetOrgPerson.INITIALS,attributeMap); + String displayName = LdapUtils.getAttributeStringValue(InetOrgPerson.DISPLAYNAME,attributeMap); + userInfo.setFormattedName(sn + givenName); + if(StringUtils.isBlank(uid)) { + userInfo.setUsername(cn); + userInfo.setWindowsAccount(cn); + }else { + userInfo.setUsername(uid); + userInfo.setWindowsAccount(uid); } - - userInfo.setPreferredLanguage(LdapUtils.getAttributeStringValue(InetOrgPerson.PREFERREDLANGUAGE,attributeMap)); - - userInfo.setDescription(LdapUtils.getAttributeStringValue(InetOrgPerson.DESCRIPTION,attributeMap)); - userInfo.setUserState("RESIDENT"); - userInfo.setUserType("EMPLOYEE"); - userInfo.setTimeZone("Asia/Shanghai"); - userInfo.setStatus(1); - userInfo.setInstId(this.synchronizer.getInstId()); - - HistorySynchronizer historySynchronizer =new HistorySynchronizer(); + userInfo.setFamilyName(sn); + userInfo.setGivenName(givenName); + if(StringUtils.isBlank(initials)) { + userInfo.setNickName(sn + givenName); + userInfo.setNameZhShortSpell(sn + givenName); + }else { + userInfo.setNickName(initials); + userInfo.setNameZhShortSpell(initials); + } + if(StringUtils.isBlank(displayName)) { + userInfo.setDisplayName(sn + givenName); + }else { + userInfo.setDisplayName(displayName); + } + + userInfo.setEmployeeNumber(LdapUtils.getAttributeStringValue(InetOrgPerson.EMPLOYEENUMBER,attributeMap)); + //userInfo.setDepartment(LdapUtils.getAttributeStringValue(InetOrgPerson.OU,attributeMap)); + //userInfo.setDepartmentId(LdapUtils.getAttributeStringValue(InetOrgPerson.DEPARTMENTNUMBER,attributeMap)); + userInfo.setJobTitle(LdapUtils.getAttributeStringValue(InetOrgPerson.TITLE,attributeMap)); + userInfo.setWorkOfficeName(LdapUtils.getAttributeStringValue(InetOrgPerson.PHYSICALDELIVERYOFFICENAME,attributeMap)); + userInfo.setWorkEmail(LdapUtils.getAttributeStringValue(InetOrgPerson.MAIL,attributeMap)); + userInfo.setWorkRegion(LdapUtils.getAttributeStringValue(InetOrgPerson.ST,attributeMap)); + userInfo.setWorkLocality(LdapUtils.getAttributeStringValue(InetOrgPerson.L,attributeMap)); + userInfo.setWorkStreetAddress(LdapUtils.getAttributeStringValue(InetOrgPerson.STREET,attributeMap)); + userInfo.setWorkPostalCode(LdapUtils.getAttributeStringValue(InetOrgPerson.POSTALCODE,attributeMap)); + userInfo.setWorkAddressFormatted(LdapUtils.getAttributeStringValue(InetOrgPerson.POSTOFFICEBOX,attributeMap)); + userInfo.setWorkFax(LdapUtils.getAttributeStringValue(InetOrgPerson.FACSIMILETELEPHONENUMBER,attributeMap)); + + userInfo.setHomePhoneNumber(LdapUtils.getAttributeStringValue(InetOrgPerson.HOMEPHONE,attributeMap)); + userInfo.setHomeAddressFormatted(LdapUtils.getAttributeStringValue(InetOrgPerson.HOMEPOSTALADDRESS,attributeMap)); + + if(LdapUtils.getAttributeStringValue(InetOrgPerson.MOBILE,attributeMap).equals("")) { + userInfo.setMobile(userInfo.getId()); + }else { + userInfo.setMobile(LdapUtils.getAttributeStringValue(InetOrgPerson.MOBILE,attributeMap)); + } + + userInfo.setPreferredLanguage(LdapUtils.getAttributeStringValue(InetOrgPerson.PREFERREDLANGUAGE,attributeMap)); + + userInfo.setDescription(LdapUtils.getAttributeStringValue(InetOrgPerson.DESCRIPTION,attributeMap)); + userInfo.setUserState("RESIDENT"); + userInfo.setUserType("EMPLOYEE"); + userInfo.setTimeZone("Asia/Shanghai"); + userInfo.setStatus(1); + userInfo.setInstId(this.synchronizer.getInstId()); + + HistorySynchronizer historySynchronizer =new HistorySynchronizer(); historySynchronizer.setId(historySynchronizer.generateId()); historySynchronizer.setSyncId(this.synchronizer.getId()); historySynchronizer.setSyncName(this.synchronizer.getName()); @@ -214,143 +214,143 @@ public class LdapUsersService extends AbstractSynchronizerService implements IS historySynchronizer.setResult("success"); this.historySynchronizerService.insert(historySynchronizer); - } catch (NamingException e) { - e.printStackTrace(); - } - return userInfo; - } + } catch (NamingException e) { + e.printStackTrace(); + } + return userInfo; + } - public UserInfo buildUserInfoByFieldMap(HashMap attributeMap,String name,String nameInNamespace){ - UserInfo userInfo = new UserInfo(); - Map fieldMap = getFieldMap(Long.parseLong(synchronizer.getId())); - String []namePaths = name.replaceAll(",OU=" , "/") - .replaceAll("OU=" , "/") - .replaceAll(",ou=" , "/") + public UserInfo buildUserInfoByFieldMap(HashMap attributeMap,String name,String nameInNamespace){ + UserInfo userInfo = new UserInfo(); + Map fieldMap = getFieldMap(Long.parseLong(synchronizer.getId())); + String []namePaths = name.replaceAll(",OU=" , "/") + .replaceAll("OU=" , "/") + .replaceAll(",ou=" , "/") - .replaceAll("ou=" , "/") - .split("/"); - String namePah= "/"+rootOrganization.getOrgName(); - for(int i = namePaths.length -1 ; i >= 0 ; i --) { - namePah = namePah + "/" + namePaths[i]; - } + .replaceAll("ou=" , "/") + .split("/"); + String namePah= "/"+rootOrganization.getOrgName(); + for(int i = namePaths.length -1 ; i >= 0 ; i --) { + namePah = namePah + "/" + namePaths[i]; + } - namePah = namePah.substring(0, namePah.length()); - String deptNamePath= namePah.substring(0, namePah.lastIndexOf("/")); - _logger.info("deptNamePath " + deptNamePath); - - Organizations deptOrg = orgsNamePathMap.get(deptNamePath); + namePah = namePah.substring(0, namePah.length()); + String deptNamePath= namePah.substring(0, namePah.lastIndexOf("/")); + _logger.info("deptNamePath " + deptNamePath); + + Organizations deptOrg = orgsNamePathMap.get(deptNamePath); - userInfo.setLdapDn(nameInNamespace); - userInfo.setId(userInfo.generateId()); - userInfo.setUserState("RESIDENT"); - userInfo.setUserType("EMPLOYEE"); - userInfo.setTimeZone("Asia/Shanghai"); - userInfo.setStatus(1); - userInfo.setInstId(this.synchronizer.getInstId()); + userInfo.setLdapDn(nameInNamespace); + userInfo.setId(userInfo.generateId()); + userInfo.setUserState("RESIDENT"); + userInfo.setUserType("EMPLOYEE"); + userInfo.setTimeZone("Asia/Shanghai"); + userInfo.setStatus(1); + userInfo.setInstId(this.synchronizer.getInstId()); - for (Map.Entry entry : fieldMap.entrySet()) { - String targetAttr = entry.getKey(); - String sourceAttr = entry.getValue(); - String value = null; - try { - - if(!attributeMap.keySet().contains(sourceAttr.toLowerCase())){ - value = (String) getFieldValue(deptOrg, sourceAttr); - if(value!=null){ - setFieldValue(userInfo,targetAttr,value); - continue; - } - } - value = LdapUtils.getAttributeStringValue(sourceAttr,attributeMap); - if(targetAttr.equals("formattedName")){ - userInfo.setFormattedName(LdapUtils.getAttributeStringValue(InetOrgPerson.SN,attributeMap)+ - LdapUtils.getAttributeStringValue(InetOrgPerson.GIVENNAME,attributeMap)); - continue; - } - //只配置 username 到 uid 的映射关系 - ///只配置 windowsAccount 到 uid 的映射关系 - if (targetAttr.equals("username") || targetAttr.equals("windowsAccount")) { - if (sourceAttr.equals("uid") && StringUtils.isBlank(value)) { - value = LdapUtils.getAttributeStringValue(InetOrgPerson.CN,attributeMap); - }else{ - value = LdapUtils.getAttributeStringValue(InetOrgPerson.UID,attributeMap); - } - //只配置 nickName 到 initials 的映射关系 - //只配置 nameZhShortSpell 到 initials 的映射关系 - } else if (targetAttr.equals("nickName") || targetAttr.equals("nameZhShortSpell")) { - if (sourceAttr.equals("initials") && StringUtils.isBlank(value)) { - value = LdapUtils.getAttributeStringValue(InetOrgPerson.SN,attributeMap) + - LdapUtils.getAttributeStringValue(InetOrgPerson.GIVENNAME,attributeMap); - }else{ - value = LdapUtils.getAttributeStringValue(InetOrgPerson.INITIALS,attributeMap); - } + for (Map.Entry entry : fieldMap.entrySet()) { + String targetAttr = entry.getKey(); + String sourceAttr = entry.getValue(); + String value = null; + try { + + if(!attributeMap.keySet().contains(sourceAttr.toLowerCase())){ + value = (String) getFieldValue(deptOrg, sourceAttr); + if(value!=null){ + setFieldValue(userInfo,targetAttr,value); + continue; + } + } + value = LdapUtils.getAttributeStringValue(sourceAttr,attributeMap); + if(targetAttr.equals("formattedName")){ + userInfo.setFormattedName(LdapUtils.getAttributeStringValue(InetOrgPerson.SN,attributeMap)+ + LdapUtils.getAttributeStringValue(InetOrgPerson.GIVENNAME,attributeMap)); + continue; + } + //只配置 username 到 uid 的映射关系 + ///只配置 windowsAccount 到 uid 的映射关系 + if (targetAttr.equals("username") || targetAttr.equals("windowsAccount")) { + if (sourceAttr.equals("uid") && StringUtils.isBlank(value)) { + value = LdapUtils.getAttributeStringValue(InetOrgPerson.CN,attributeMap); + }else{ + value = LdapUtils.getAttributeStringValue(InetOrgPerson.UID,attributeMap); + } + //只配置 nickName 到 initials 的映射关系 + //只配置 nameZhShortSpell 到 initials 的映射关系 + } else if (targetAttr.equals("nickName") || targetAttr.equals("nameZhShortSpell")) { + if (sourceAttr.equals("initials") && StringUtils.isBlank(value)) { + value = LdapUtils.getAttributeStringValue(InetOrgPerson.SN,attributeMap) + + LdapUtils.getAttributeStringValue(InetOrgPerson.GIVENNAME,attributeMap); + }else{ + value = LdapUtils.getAttributeStringValue(InetOrgPerson.INITIALS,attributeMap); + } - //只配置 displayName 到 displayName 的映射关系 - } else if (targetAttr.equals("displayName")) { - if (sourceAttr.equals("displayName") && StringUtils.isBlank(value)) { - value = LdapUtils.getAttributeStringValue(InetOrgPerson.SN,attributeMap) + - LdapUtils.getAttributeStringValue(InetOrgPerson.GIVENNAME,attributeMap); - }else { - value = LdapUtils.getAttributeStringValue(InetOrgPerson.DISPLAYNAME,attributeMap); - } - } else if (targetAttr.equals("mobile")) { - if (sourceAttr.equals("mobile") && StringUtils.isBlank(value)) { - value = (String) getFieldValue(userInfo,"id"); - }else { - value = LdapUtils.getAttributeStringValue(InetOrgPerson.MOBILE,attributeMap); - } - } + //只配置 displayName 到 displayName 的映射关系 + } else if (targetAttr.equals("displayName")) { + if (sourceAttr.equals("displayName") && StringUtils.isBlank(value)) { + value = LdapUtils.getAttributeStringValue(InetOrgPerson.SN,attributeMap) + + LdapUtils.getAttributeStringValue(InetOrgPerson.GIVENNAME,attributeMap); + }else { + value = LdapUtils.getAttributeStringValue(InetOrgPerson.DISPLAYNAME,attributeMap); + } + } else if (targetAttr.equals("mobile")) { + if (sourceAttr.equals("mobile") && StringUtils.isBlank(value)) { + value = (String) getFieldValue(userInfo,"id"); + }else { + value = LdapUtils.getAttributeStringValue(InetOrgPerson.MOBILE,attributeMap); + } + } - setFieldValue(userInfo, targetAttr,value); - }catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } catch (NamingException e) { - throw new RuntimeException(e); - } + setFieldValue(userInfo, targetAttr,value); + }catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } catch (NamingException e) { + throw new RuntimeException(e); + } - } - HistorySynchronizer historySynchronizer =new HistorySynchronizer(); - historySynchronizer.setId(historySynchronizer.generateId()); - historySynchronizer.setSyncId(this.synchronizer.getId()); - historySynchronizer.setSyncName(this.synchronizer.getName()); - historySynchronizer.setObjectId(userInfo.getId()); - historySynchronizer.setObjectName(userInfo.getUsername()); - historySynchronizer.setObjectType(Organizations.class.getSimpleName()); - historySynchronizer.setInstId(synchronizer.getInstId()); - historySynchronizer.setResult("success"); - this.historySynchronizerService.insert(historySynchronizer); + } + HistorySynchronizer historySynchronizer =new HistorySynchronizer(); + historySynchronizer.setId(historySynchronizer.generateId()); + historySynchronizer.setSyncId(this.synchronizer.getId()); + historySynchronizer.setSyncName(this.synchronizer.getName()); + historySynchronizer.setObjectId(userInfo.getId()); + historySynchronizer.setObjectName(userInfo.getUsername()); + historySynchronizer.setObjectType(Organizations.class.getSimpleName()); + historySynchronizer.setInstId(synchronizer.getInstId()); + historySynchronizer.setResult("success"); + this.historySynchronizerService.insert(historySynchronizer); - return userInfo; - } + return userInfo; + } - public Map getFieldMap(Long jobId){ - Map userFieldMap = new HashMap<>(); - //根据job id查询属性映射表 - List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); - //获取用户属性映射 - for(SyncJobConfigField element:syncJobConfigFieldList){ - if(Integer.parseInt(element.getObjectType()) == USER_TYPE.intValue()){ - userFieldMap.put(element.getTargetField(), element.getSourceField()); - } - } - return userFieldMap; - } + public Map getFieldMap(Long jobId){ + Map userFieldMap = new HashMap<>(); + //根据job id查询属性映射表 + List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); + //获取用户属性映射 + for(SyncJobConfigField element:syncJobConfigFieldList){ + if(Integer.parseInt(element.getObjectType()) == USER_TYPE.intValue()){ + userFieldMap.put(element.getTargetField(), element.getSourceField()); + } + } + return userFieldMap; + } - - public LdapUtils getLdapUtils() { - return ldapUtils; - } + + public LdapUtils getLdapUtils() { + return ldapUtils; + } - public void setLdapUtils(LdapUtils ldapUtils) { - this.ldapUtils = ldapUtils; - } + public void setLdapUtils(LdapUtils ldapUtils) { + this.ldapUtils = ldapUtils; + } - public SyncJobConfigFieldService getSyncJobConfigFieldService() { - return syncJobConfigFieldService; - } + public SyncJobConfigFieldService getSyncJobConfigFieldService() { + return syncJobConfigFieldService; + } - public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { - this.syncJobConfigFieldService = syncJobConfigFieldService; - } + public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { + this.syncJobConfigFieldService = syncJobConfigFieldService; + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/WorkweixinAccessTokenService.java b/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/WorkweixinAccessTokenService.java index be781aafe..2db62b477 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/WorkweixinAccessTokenService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/WorkweixinAccessTokenService.java @@ -24,62 +24,62 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WorkweixinAccessTokenService { - static final Logger _logger = LoggerFactory.getLogger(WorkweixinAccessTokenService.class); - - String corpid; - - String corpsecret; - - public static String TOKEN_URL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s"; + static final Logger _logger = LoggerFactory.getLogger(WorkweixinAccessTokenService.class); + + String corpid; + + String corpsecret; + + public static String TOKEN_URL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s"; - public WorkweixinAccessTokenService() {} - - - public WorkweixinAccessTokenService(String corpid, String corpsecret) { - super(); - this.corpid = corpid; - this.corpsecret = corpsecret; - } + public WorkweixinAccessTokenService() {} + + + public WorkweixinAccessTokenService(String corpid, String corpsecret) { + super(); + this.corpid = corpid; + this.corpsecret = corpsecret; + } - public String requestToken() { - HttpRequestAdapter request =new HttpRequestAdapter(); - String responseBody = request.get(String.format(TOKEN_URL, corpid,corpsecret)); - - AccessToken accessToken = JsonUtils.gsonStringToObject(responseBody, AccessToken.class); - _logger.debug("accessToken " + accessToken); - if(accessToken.getErrcode()== 0){ - return accessToken.getAccess_token(); - } - return ""; - } - - + public String requestToken() { + HttpRequestAdapter request =new HttpRequestAdapter(); + String responseBody = request.get(String.format(TOKEN_URL, corpid,corpsecret)); + + AccessToken accessToken = JsonUtils.gsonStringToObject(responseBody, AccessToken.class); + _logger.debug("accessToken " + accessToken); + if(accessToken.getErrcode()== 0){ + return accessToken.getAccess_token(); + } + return ""; + } + + - public String getCorpid() { - return corpid; - } + public String getCorpid() { + return corpid; + } - public void setCorpid(String corpid) { - this.corpid = corpid; - } + public void setCorpid(String corpid) { + this.corpid = corpid; + } - public String getCorpsecret() { - return corpsecret; - } + public String getCorpsecret() { + return corpsecret; + } - public void setCorpsecret(String corpsecret) { - this.corpsecret = corpsecret; - } + public void setCorpsecret(String corpsecret) { + this.corpsecret = corpsecret; + } - public static void main(String[] args) { + public static void main(String[] args) { - } + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/WorkweixinOrganizationService.java b/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/WorkweixinOrganizationService.java index 1f8206f63..7564722f1 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/WorkweixinOrganizationService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/WorkweixinOrganizationService.java @@ -42,166 +42,166 @@ import static org.dromara.maxkey.synchronizer.utils.FieldUtil.*; @Service public class WorkweixinOrganizationService extends AbstractSynchronizerService implements ISynchronizerService{ - static final Logger _logger = LoggerFactory.getLogger(WorkweixinOrganizationService.class); - - String access_token; - @Autowired - private SyncJobConfigFieldService syncJobConfigFieldService; - private static final Integer ORG_TYPE = 2; - static String DEPTS_URL="https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=%s"; - static long ROOT_DEPT_ID = 1; - - public void sync() { - _logger.info("Sync Workweixin Organizations ..."); + static final Logger _logger = LoggerFactory.getLogger(WorkweixinOrganizationService.class); + + String access_token; + @Autowired + private SyncJobConfigFieldService syncJobConfigFieldService; + private static final Integer ORG_TYPE = 2; + static String DEPTS_URL="https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=%s"; + static long ROOT_DEPT_ID = 1; + + public void sync() { + _logger.info("Sync Workweixin Organizations ..."); - try { - WorkWeixinDeptsResponse rsp = requestDepartmentList(access_token); - - for(WorkWeixinDepts dept : rsp.getDepartment()) { - _logger.debug("dept : " + dept.getId()+" "+ dept.getName()+" "+ dept.getParentid()); - //root - if(dept.getId() == ROOT_DEPT_ID) { - Organizations rootOrganization = organizationsService.get(Organizations.ROOT_ORG_ID); - SynchroRelated rootSynchroRelated = buildSynchroRelated(rootOrganization,dept); - synchroRelatedService.updateSynchroRelated( - this.synchronizer,rootSynchroRelated,Organizations.CLASS_TYPE); - }else { - //synchro Related - SynchroRelated synchroRelated = - synchroRelatedService.findByOriginId( - this.synchronizer,dept.getId() + "",Organizations.CLASS_TYPE ); - //Parent - SynchroRelated synchroRelatedParent = - synchroRelatedService.findByOriginId( - this.synchronizer,dept.getParentid() + "",Organizations.CLASS_TYPE); - Organizations organization = buildOrgByFiledMap(dept,synchroRelatedParent); - if(synchroRelated == null) { - organization.setId(organization.generateId()); - organizationsService.insert(organization); - _logger.debug("Organizations : " + organization); - - synchroRelated = buildSynchroRelated(organization,dept); - }else { - organization.setId(synchroRelated.getObjectId()); - organizationsService.update(organization); - } - - synchroRelatedService.updateSynchroRelated( - this.synchronizer,synchroRelated,Organizations.CLASS_TYPE); - } - } + try { + WorkWeixinDeptsResponse rsp = requestDepartmentList(access_token); + + for(WorkWeixinDepts dept : rsp.getDepartment()) { + _logger.debug("dept : " + dept.getId()+" "+ dept.getName()+" "+ dept.getParentid()); + //root + if(dept.getId() == ROOT_DEPT_ID) { + Organizations rootOrganization = organizationsService.get(Organizations.ROOT_ORG_ID); + SynchroRelated rootSynchroRelated = buildSynchroRelated(rootOrganization,dept); + synchroRelatedService.updateSynchroRelated( + this.synchronizer,rootSynchroRelated,Organizations.CLASS_TYPE); + }else { + //synchro Related + SynchroRelated synchroRelated = + synchroRelatedService.findByOriginId( + this.synchronizer,dept.getId() + "",Organizations.CLASS_TYPE ); + //Parent + SynchroRelated synchroRelatedParent = + synchroRelatedService.findByOriginId( + this.synchronizer,dept.getParentid() + "",Organizations.CLASS_TYPE); + Organizations organization = buildOrgByFiledMap(dept,synchroRelatedParent); + if(synchroRelated == null) { + organization.setId(organization.generateId()); + organizationsService.insert(organization); + _logger.debug("Organizations : " + organization); + + synchroRelated = buildSynchroRelated(organization,dept); + }else { + organization.setId(synchroRelated.getObjectId()); + organizationsService.update(organization); + } + + synchroRelatedService.updateSynchroRelated( + this.synchronizer,synchroRelated,Organizations.CLASS_TYPE); + } + } - } catch (Exception e) { - e.printStackTrace(); - } - - } - - public SynchroRelated buildSynchroRelated(Organizations organization,WorkWeixinDepts dept) { - return new SynchroRelated( - organization.getId(), - organization.getOrgName(), - organization.getOrgName(), - Organizations.CLASS_TYPE, - synchronizer.getId(), - synchronizer.getName(), - dept.getId()+"", - dept.getName(), - "", - dept.getParentid()+"", - synchronizer.getInstId()); - } - - public WorkWeixinDeptsResponse requestDepartmentList(String access_token) { - HttpRequestAdapter request =new HttpRequestAdapter(); - String responseBody = request.get(String.format(DEPTS_URL, access_token)); - WorkWeixinDeptsResponse deptsResponse =JsonUtils.gsonStringToObject(responseBody, WorkWeixinDeptsResponse.class); - - _logger.trace("response : " + responseBody); - for(WorkWeixinDepts dept : deptsResponse.getDepartment()) { - _logger.debug("WorkWeixinDepts : " + dept); - } - return deptsResponse; - } - - public Organizations buildOrganization(WorkWeixinDepts dept,SynchroRelated synchroRelatedParent) { + } catch (Exception e) { + e.printStackTrace(); + } + + } + + public SynchroRelated buildSynchroRelated(Organizations organization,WorkWeixinDepts dept) { + return new SynchroRelated( + organization.getId(), + organization.getOrgName(), + organization.getOrgName(), + Organizations.CLASS_TYPE, + synchronizer.getId(), + synchronizer.getName(), + dept.getId()+"", + dept.getName(), + "", + dept.getParentid()+"", + synchronizer.getInstId()); + } + + public WorkWeixinDeptsResponse requestDepartmentList(String access_token) { + HttpRequestAdapter request =new HttpRequestAdapter(); + String responseBody = request.get(String.format(DEPTS_URL, access_token)); + WorkWeixinDeptsResponse deptsResponse =JsonUtils.gsonStringToObject(responseBody, WorkWeixinDeptsResponse.class); + + _logger.trace("response : " + responseBody); + for(WorkWeixinDepts dept : deptsResponse.getDepartment()) { + _logger.debug("WorkWeixinDepts : " + dept); + } + return deptsResponse; + } + + public Organizations buildOrganization(WorkWeixinDepts dept,SynchroRelated synchroRelatedParent) { - Organizations org = new Organizations(); - org.setOrgName(dept.getName()); - org.setOrgCode(dept.getId()+""); - org.setParentId(synchroRelatedParent.getObjectId()); - org.setParentName(synchroRelatedParent.getObjectName()); - org.setSortIndex(dept.getOrder()); - org.setInstId(this.synchronizer.getInstId()); - org.setStatus(ConstsStatus.ACTIVE); - org.setDescription("WorkWeixin"); - return org; - } + Organizations org = new Organizations(); + org.setOrgName(dept.getName()); + org.setOrgCode(dept.getId()+""); + org.setParentId(synchroRelatedParent.getObjectId()); + org.setParentName(synchroRelatedParent.getObjectName()); + org.setSortIndex(dept.getOrder()); + org.setInstId(this.synchronizer.getInstId()); + org.setStatus(ConstsStatus.ACTIVE); + org.setDescription("WorkWeixin"); + return org; + } - public Organizations buildOrgByFiledMap(WorkWeixinDepts dept, SynchroRelated synchroRelatedParent){ - Organizations org = new Organizations(); - //fieldMap - Map fieldMap = getFieldMap(Long.parseLong(synchronizer.getId())); + public Organizations buildOrgByFiledMap(WorkWeixinDepts dept, SynchroRelated synchroRelatedParent){ + Organizations org = new Organizations(); + //fieldMap + Map fieldMap = getFieldMap(Long.parseLong(synchronizer.getId())); - for (Map.Entry entry : fieldMap.entrySet()) { - String orgProperty = entry.getKey(); - String sourceProperty = entry.getValue(); - try { - Object sourceValue = null; + for (Map.Entry entry : fieldMap.entrySet()) { + String orgProperty = entry.getKey(); + String sourceProperty = entry.getValue(); + try { + Object sourceValue = null; - if (hasField(dept.getClass(), sourceProperty)) { - sourceValue = getFieldValue(dept, sourceProperty); - } - else if (synchroRelatedParent != null && hasField(SynchroRelated.class, sourceProperty)) { - sourceValue = getFieldValue(synchroRelatedParent, sourceProperty); - } - if (sourceValue != null) { - setFieldValue(org, orgProperty, sourceValue); - } - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } - } - org.setInstId(this.synchronizer.getInstId()); - org.setStatus(ConstsStatus.ACTIVE); - org.setDescription("WorkWeixin"); - org.setType("department"); - return org; + if (hasField(dept.getClass(), sourceProperty)) { + sourceValue = getFieldValue(dept, sourceProperty); + } + else if (synchroRelatedParent != null && hasField(SynchroRelated.class, sourceProperty)) { + sourceValue = getFieldValue(synchroRelatedParent, sourceProperty); + } + if (sourceValue != null) { + setFieldValue(org, orgProperty, sourceValue); + } + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + } + org.setInstId(this.synchronizer.getInstId()); + org.setStatus(ConstsStatus.ACTIVE); + org.setDescription("WorkWeixin"); + org.setType("department"); + return org; - } + } - public Map getFieldMap(Long jobId){ - Map filedMap = new HashMap<>(); - //根据job id查询属性映射表 - List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); - //获取组织属性映射 - for(SyncJobConfigField element:syncJobConfigFieldList){ - if(Integer.parseInt(element.getObjectType()) == ORG_TYPE.intValue()){ - filedMap.put(element.getTargetField(), element.getSourceField()); - } - } - return filedMap; - } + public Map getFieldMap(Long jobId){ + Map filedMap = new HashMap<>(); + //根据job id查询属性映射表 + List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); + //获取组织属性映射 + for(SyncJobConfigField element:syncJobConfigFieldList){ + if(Integer.parseInt(element.getObjectType()) == ORG_TYPE.intValue()){ + filedMap.put(element.getTargetField(), element.getSourceField()); + } + } + return filedMap; + } - public String getAccess_token() { - return access_token; - } + public String getAccess_token() { + return access_token; + } - public void setAccess_token(String access_token) { - this.access_token = access_token; - } + public void setAccess_token(String access_token) { + this.access_token = access_token; + } - public SyncJobConfigFieldService getSyncJobConfigFieldService() { - return syncJobConfigFieldService; - } + public SyncJobConfigFieldService getSyncJobConfigFieldService() { + return syncJobConfigFieldService; + } - public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { - this.syncJobConfigFieldService = syncJobConfigFieldService; - } + public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { + this.syncJobConfigFieldService = syncJobConfigFieldService; + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/WorkweixinSynchronizerService.java b/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/WorkweixinSynchronizerService.java index 5e22c5a6b..ac07f2fc2 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/WorkweixinSynchronizerService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/WorkweixinSynchronizerService.java @@ -26,65 +26,65 @@ import org.springframework.stereotype.Service; @Service public class WorkweixinSynchronizerService implements ISynchronizerService{ - static final Logger _logger = LoggerFactory.getLogger(WorkweixinSynchronizerService.class); - Synchronizers synchronizer; - - @Autowired - WorkweixinUsersService workweixinUsersService; - - @Autowired - WorkweixinOrganizationService workweixinOrganizationService; - + static final Logger _logger = LoggerFactory.getLogger(WorkweixinSynchronizerService.class); + Synchronizers synchronizer; + + @Autowired + WorkweixinUsersService workweixinUsersService; + + @Autowired + WorkweixinOrganizationService workweixinOrganizationService; + - WorkweixinAccessTokenService workweixinAccessTokenService = new WorkweixinAccessTokenService(); - - public WorkweixinSynchronizerService() { - super(); - } + WorkweixinAccessTokenService workweixinAccessTokenService = new WorkweixinAccessTokenService(); + + public WorkweixinSynchronizerService() { + super(); + } - public void sync() throws Exception { - _logger.info("Sync ..."); - workweixinAccessTokenService.setCorpid(synchronizer.getPrincipal()); - workweixinAccessTokenService.setCorpsecret(synchronizer.getCredentials()); - String access_token=workweixinAccessTokenService.requestToken(); - - workweixinOrganizationService.setSynchronizer(synchronizer); - workweixinOrganizationService.setAccess_token(access_token); - workweixinOrganizationService.sync(); - - workweixinUsersService.setSynchronizer(synchronizer); - workweixinUsersService.setAccess_token(access_token); - workweixinUsersService.sync(); - } + public void sync() throws Exception { + _logger.info("Sync ..."); + workweixinAccessTokenService.setCorpid(synchronizer.getPrincipal()); + workweixinAccessTokenService.setCorpsecret(synchronizer.getCredentials()); + String access_token=workweixinAccessTokenService.requestToken(); + + workweixinOrganizationService.setSynchronizer(synchronizer); + workweixinOrganizationService.setAccess_token(access_token); + workweixinOrganizationService.sync(); + + workweixinUsersService.setSynchronizer(synchronizer); + workweixinUsersService.setAccess_token(access_token); + workweixinUsersService.sync(); + } - public WorkweixinUsersService getWorkweixinUsersService() { - return workweixinUsersService; - } + public WorkweixinUsersService getWorkweixinUsersService() { + return workweixinUsersService; + } - public void setWorkweixinUsersService(WorkweixinUsersService workweixinUsersService) { - this.workweixinUsersService = workweixinUsersService; - } + public void setWorkweixinUsersService(WorkweixinUsersService workweixinUsersService) { + this.workweixinUsersService = workweixinUsersService; + } - public WorkweixinOrganizationService getWorkweixinOrganizationService() { - return workweixinOrganizationService; - } + public WorkweixinOrganizationService getWorkweixinOrganizationService() { + return workweixinOrganizationService; + } - public void setWorkweixinOrganizationService(WorkweixinOrganizationService workweixinOrganizationService) { - this.workweixinOrganizationService = workweixinOrganizationService; - } + public void setWorkweixinOrganizationService(WorkweixinOrganizationService workweixinOrganizationService) { + this.workweixinOrganizationService = workweixinOrganizationService; + } - public WorkweixinAccessTokenService getWorkweixinAccessTokenService() { - return workweixinAccessTokenService; - } + public WorkweixinAccessTokenService getWorkweixinAccessTokenService() { + return workweixinAccessTokenService; + } - public void setWorkweixinAccessTokenService(WorkweixinAccessTokenService workweixinAccessTokenService) { - this.workweixinAccessTokenService = workweixinAccessTokenService; - } + public void setWorkweixinAccessTokenService(WorkweixinAccessTokenService workweixinAccessTokenService) { + this.workweixinAccessTokenService = workweixinAccessTokenService; + } - @Override - public void setSynchronizer(Synchronizers synchronizer) { - this.synchronizer = synchronizer; - - } + @Override + public void setSynchronizer(Synchronizers synchronizer) { + this.synchronizer = synchronizer; + + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/WorkweixinUsersService.java b/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/WorkweixinUsersService.java index 3ee68a0b7..3c86ecedf 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/WorkweixinUsersService.java +++ b/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/WorkweixinUsersService.java @@ -42,141 +42,141 @@ import static org.dromara.maxkey.synchronizer.utils.FieldUtil.*; @Service public class WorkweixinUsersService extends AbstractSynchronizerService implements ISynchronizerService{ - final static Logger _logger = LoggerFactory.getLogger(WorkweixinUsersService.class); + final static Logger _logger = LoggerFactory.getLogger(WorkweixinUsersService.class); - @Autowired - public SyncJobConfigFieldService syncJobConfigFieldService; - private static final Integer USER_TYPE = 1; - String access_token; - - static String USERS_URL="https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=%s&department_id=%s&fetch_child=0"; - - public void sync() { - _logger.info("Sync Workweixin Users..."); - try { - List synchroRelateds = - synchroRelatedService.findOrgs(this.synchronizer); - - for(SynchroRelated relatedOrg : synchroRelateds) { - HttpRequestAdapter request =new HttpRequestAdapter(); - String responseBody = request.get(String.format(USERS_URL, access_token,relatedOrg.getOriginId())); - WorkWeixinUsersResponse usersResponse =JsonUtils.gsonStringToObject(responseBody, WorkWeixinUsersResponse.class); - _logger.trace("response : " + responseBody); - - for(WorkWeixinUsers user : usersResponse.getUserlist()) { - UserInfo userInfo = buildUserInfoByFiledMap(user); - _logger.debug("userInfo : " + userInfo); - userInfo.setPassword(userInfo.getUsername() + UserInfo.DEFAULT_PASSWORD_SUFFIX); - userInfoService.saveOrUpdate(userInfo); - - SynchroRelated synchroRelated = new SynchroRelated( - userInfo.getId(), - userInfo.getUsername(), - userInfo.getDisplayName(), - UserInfo.CLASS_TYPE, - synchronizer.getId(), - synchronizer.getName(), - user.getUserid(), - user.getName(), - user.getUserid(), - "", - synchronizer.getInstId()); - - synchroRelatedService.updateSynchroRelated( - this.synchronizer,synchroRelated,UserInfo.CLASS_TYPE); - - socialsAssociate(synchroRelated,"workweixin"); - } - } - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - public void postSync(UserInfo userInfo) { - - } + @Autowired + public SyncJobConfigFieldService syncJobConfigFieldService; + private static final Integer USER_TYPE = 1; + String access_token; + + static String USERS_URL="https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=%s&department_id=%s&fetch_child=0"; + + public void sync() { + _logger.info("Sync Workweixin Users..."); + try { + List synchroRelateds = + synchroRelatedService.findOrgs(this.synchronizer); + + for(SynchroRelated relatedOrg : synchroRelateds) { + HttpRequestAdapter request =new HttpRequestAdapter(); + String responseBody = request.get(String.format(USERS_URL, access_token,relatedOrg.getOriginId())); + WorkWeixinUsersResponse usersResponse =JsonUtils.gsonStringToObject(responseBody, WorkWeixinUsersResponse.class); + _logger.trace("response : " + responseBody); + + for(WorkWeixinUsers user : usersResponse.getUserlist()) { + UserInfo userInfo = buildUserInfoByFiledMap(user); + _logger.debug("userInfo : " + userInfo); + userInfo.setPassword(userInfo.getUsername() + UserInfo.DEFAULT_PASSWORD_SUFFIX); + userInfoService.saveOrUpdate(userInfo); + + SynchroRelated synchroRelated = new SynchroRelated( + userInfo.getId(), + userInfo.getUsername(), + userInfo.getDisplayName(), + UserInfo.CLASS_TYPE, + synchronizer.getId(), + synchronizer.getName(), + user.getUserid(), + user.getName(), + user.getUserid(), + "", + synchronizer.getInstId()); + + synchroRelatedService.updateSynchroRelated( + this.synchronizer,synchroRelated,UserInfo.CLASS_TYPE); + + socialsAssociate(synchroRelated,"workweixin"); + } + } + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + public void postSync(UserInfo userInfo) { + + } - public UserInfo buildUserInfo(WorkWeixinUsers user) { - UserInfo userInfo = new UserInfo(); - userInfo.setUsername(user.getUserid());//账号 - userInfo.setNickName(user.getAlias());//名字 - userInfo.setDisplayName(user.getName());//名字 - - userInfo.setMobile(user.getMobile());//手机 - userInfo.setEmail(user.getEmail()); - userInfo.setGender(Integer.parseInt(user.getGender())); - - userInfo.setWorkPhoneNumber(user.getTelephone());//工作电话 - userInfo.setDepartmentId(user.getMain_department()+""); - userInfo.setJobTitle(user.getPosition());//职务 - userInfo.setWorkAddressFormatted(user.getAddress());//工作地点 + public UserInfo buildUserInfo(WorkWeixinUsers user) { + UserInfo userInfo = new UserInfo(); + userInfo.setUsername(user.getUserid());//账号 + userInfo.setNickName(user.getAlias());//名字 + userInfo.setDisplayName(user.getName());//名字 + + userInfo.setMobile(user.getMobile());//手机 + userInfo.setEmail(user.getEmail()); + userInfo.setGender(Integer.parseInt(user.getGender())); + + userInfo.setWorkPhoneNumber(user.getTelephone());//工作电话 + userInfo.setDepartmentId(user.getMain_department()+""); + userInfo.setJobTitle(user.getPosition());//职务 + userInfo.setWorkAddressFormatted(user.getAddress());//工作地点 - //激活状态: 1=已激活,2=已禁用,4=未激活,5=退出企业。 - if(user.getStatus() == 1) { - userInfo.setStatus(ConstsStatus.ACTIVE); - }else { - userInfo.setStatus(ConstsStatus.INACTIVE); - } - userInfo.setInstId(this.synchronizer.getInstId()); - return userInfo; - } + //激活状态: 1=已激活,2=已禁用,4=未激活,5=退出企业。 + if(user.getStatus() == 1) { + userInfo.setStatus(ConstsStatus.ACTIVE); + }else { + userInfo.setStatus(ConstsStatus.INACTIVE); + } + userInfo.setInstId(this.synchronizer.getInstId()); + return userInfo; + } - public UserInfo buildUserInfoByFiledMap(WorkWeixinUsers user){ - UserInfo userInfo = new UserInfo(); - Map fieldMap = getFieldMap(Long.parseLong(synchronizer.getId())); - for (Map.Entry entry : fieldMap.entrySet()) { + public UserInfo buildUserInfoByFiledMap(WorkWeixinUsers user){ + UserInfo userInfo = new UserInfo(); + Map fieldMap = getFieldMap(Long.parseLong(synchronizer.getId())); + for (Map.Entry entry : fieldMap.entrySet()) { - String userInfoProperty = entry.getKey(); - String sourceProperty = entry.getValue(); + String userInfoProperty = entry.getKey(); + String sourceProperty = entry.getValue(); - try { - Object sourceValue = null; - if(sourceProperty.equals("status")){ - userInfo.setStatus(user.getStatus() == 1?ConstsStatus.ACTIVE:ConstsStatus.INACTIVE); - continue; - } - if (hasField(user.getClass(), sourceProperty)) { - sourceValue = getFieldValue(user, sourceProperty); - } - if (sourceValue != null) { - setFieldValue(userInfo, userInfoProperty, sourceValue); - } + try { + Object sourceValue = null; + if(sourceProperty.equals("status")){ + userInfo.setStatus(user.getStatus() == 1?ConstsStatus.ACTIVE:ConstsStatus.INACTIVE); + continue; + } + if (hasField(user.getClass(), sourceProperty)) { + sourceValue = getFieldValue(user, sourceProperty); + } + if (sourceValue != null) { + setFieldValue(userInfo, userInfoProperty, sourceValue); + } - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - e.printStackTrace(); - } - } + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + } - userInfo.setUserType("EMPLOYEE"); - userInfo.setUserState("RESIDENT"); - userInfo.setInstId(this.synchronizer.getInstId()); - return userInfo; - } + userInfo.setUserType("EMPLOYEE"); + userInfo.setUserState("RESIDENT"); + userInfo.setInstId(this.synchronizer.getInstId()); + return userInfo; + } - public Map getFieldMap(Long jobId){ - Map userFieldMap = new HashMap<>(); - //根据job id查询属性映射表 - List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); - //获取用户属性映射 - for(SyncJobConfigField element:syncJobConfigFieldList){ - if(Integer.parseInt(element.getObjectType()) == USER_TYPE.intValue()){ - userFieldMap.put(element.getTargetField(), element.getSourceField()); - } - } - return userFieldMap; - } + public Map getFieldMap(Long jobId){ + Map userFieldMap = new HashMap<>(); + //根据job id查询属性映射表 + List syncJobConfigFieldList = syncJobConfigFieldService.findByJobId(jobId); + //获取用户属性映射 + for(SyncJobConfigField element:syncJobConfigFieldList){ + if(Integer.parseInt(element.getObjectType()) == USER_TYPE.intValue()){ + userFieldMap.put(element.getTargetField(), element.getSourceField()); + } + } + return userFieldMap; + } - public void setAccess_token(String access_token) { - this.access_token = access_token; - } - public SyncJobConfigFieldService getSyncJobConfigFieldService() { - return syncJobConfigFieldService; - } + public void setAccess_token(String access_token) { + this.access_token = access_token; + } + public SyncJobConfigFieldService getSyncJobConfigFieldService() { + return syncJobConfigFieldService; + } - public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { - this.syncJobConfigFieldService = syncJobConfigFieldService; - } + public void setSyncJobConfigFieldService(SyncJobConfigFieldService syncJobConfigFieldService) { + this.syncJobConfigFieldService = syncJobConfigFieldService; + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/entity/WorkWeixinDepts.java b/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/entity/WorkWeixinDepts.java index f6685423a..a5377018d 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/entity/WorkWeixinDepts.java +++ b/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/entity/WorkWeixinDepts.java @@ -18,55 +18,55 @@ package org.dromara.maxkey.synchronizer.workweixin.entity; public class WorkWeixinDepts { - - long id; - String name; - String name_en; - long parentid; - long order; + + long id; + String name; + String name_en; + long parentid; + long order; - public WorkWeixinDepts() { - super(); - } + public WorkWeixinDepts() { + super(); + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(long id) { - this.id = id; - } + public void setId(long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getName_en() { - return name_en; - } + public String getName_en() { + return name_en; + } - public void setName_en(String name_en) { - this.name_en = name_en; - } + public void setName_en(String name_en) { + this.name_en = name_en; + } - public long getParentid() { - return parentid; - } + public long getParentid() { + return parentid; + } - public void setParentid(long parentid) { - this.parentid = parentid; - } + public void setParentid(long parentid) { + this.parentid = parentid; + } - public long getOrder() { - return order; - } + public long getOrder() { + return order; + } - public void setOrder(long order) { - this.order = order; - } + public void setOrder(long order) { + this.order = order; + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/entity/WorkWeixinDeptsResponse.java b/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/entity/WorkWeixinDeptsResponse.java index 11db91b0e..b2ec0018c 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/entity/WorkWeixinDeptsResponse.java +++ b/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/entity/WorkWeixinDeptsResponse.java @@ -23,18 +23,18 @@ import org.dromara.maxkey.synchronizer.entity.ResponseData; public class WorkWeixinDeptsResponse extends ResponseData{ - ArrayList department; + ArrayList department; - public ArrayList getDepartment() { - return department; - } + public ArrayList getDepartment() { + return department; + } - public void setDepartment(ArrayList department) { - this.department = department; - } + public void setDepartment(ArrayList department) { + this.department = department; + } - public WorkWeixinDeptsResponse() { - super(); - } + public WorkWeixinDeptsResponse() { + super(); + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/entity/WorkWeixinUsers.java b/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/entity/WorkWeixinUsers.java index 501b17490..089dc513c 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/entity/WorkWeixinUsers.java +++ b/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/entity/WorkWeixinUsers.java @@ -19,227 +19,227 @@ package org.dromara.maxkey.synchronizer.workweixin.entity; public class WorkWeixinUsers { - String userid; - String name; - String mobile; - long[] department; - long[] order; - String position; - String gender; - String email; - long[] is_leader_in_dept; - String avatar; - String thumb_avatar; - String telephone; - String alias; - int status; - int isleader; - int enable; - String address; - int hide_mobile; - String english_name; - String open_userid; - long main_department; + String userid; + String name; + String mobile; + long[] department; + long[] order; + String position; + String gender; + String email; + long[] is_leader_in_dept; + String avatar; + String thumb_avatar; + String telephone; + String alias; + int status; + int isleader; + int enable; + String address; + int hide_mobile; + String english_name; + String open_userid; + long main_department; - String qr_code; - String external_position; + String qr_code; + String external_position; - public class ExtAttrs { + public class ExtAttrs { - String type; - String name; - String text; + String type; + String name; + String text; - } + } - public String getUserid() { - return userid; - } + public String getUserid() { + return userid; + } - public void setUserid(String userid) { - this.userid = userid; - } + public void setUserid(String userid) { + this.userid = userid; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getMobile() { - return mobile; - } + public String getMobile() { + return mobile; + } - public void setMobile(String mobile) { - this.mobile = mobile; - } + public void setMobile(String mobile) { + this.mobile = mobile; + } - public long[] getDepartment() { - return department; - } + public long[] getDepartment() { + return department; + } - public void setDepartment(long[] department) { - this.department = department; - } + public void setDepartment(long[] department) { + this.department = department; + } - public long[] getOrder() { - return order; - } + public long[] getOrder() { + return order; + } - public void setOrder(long[] order) { - this.order = order; - } + public void setOrder(long[] order) { + this.order = order; + } - public String getPosition() { - return position; - } + public String getPosition() { + return position; + } - public void setPosition(String position) { - this.position = position; - } + public void setPosition(String position) { + this.position = position; + } - public String getGender() { - return gender; - } + public String getGender() { + return gender; + } - public void setGender(String gender) { - this.gender = gender; - } + public void setGender(String gender) { + this.gender = gender; + } - public String getEmail() { - return email; - } + public String getEmail() { + return email; + } - public void setEmail(String email) { - this.email = email; - } + public void setEmail(String email) { + this.email = email; + } - public long[] getIs_leader_in_dept() { - return is_leader_in_dept; - } + public long[] getIs_leader_in_dept() { + return is_leader_in_dept; + } - public void setIs_leader_in_dept(long[] is_leader_in_dept) { - this.is_leader_in_dept = is_leader_in_dept; - } + public void setIs_leader_in_dept(long[] is_leader_in_dept) { + this.is_leader_in_dept = is_leader_in_dept; + } - public String getAvatar() { - return avatar; - } + public String getAvatar() { + return avatar; + } - public void setAvatar(String avatar) { - this.avatar = avatar; - } + public void setAvatar(String avatar) { + this.avatar = avatar; + } - public String getThumb_avatar() { - return thumb_avatar; - } + public String getThumb_avatar() { + return thumb_avatar; + } - public void setThumb_avatar(String thumb_avatar) { - this.thumb_avatar = thumb_avatar; - } + public void setThumb_avatar(String thumb_avatar) { + this.thumb_avatar = thumb_avatar; + } - public String getTelephone() { - return telephone; - } + public String getTelephone() { + return telephone; + } - public void setTelephone(String telephone) { - this.telephone = telephone; - } + public void setTelephone(String telephone) { + this.telephone = telephone; + } - public String getAlias() { - return alias; - } + public String getAlias() { + return alias; + } - public void setAlias(String alias) { - this.alias = alias; - } + public void setAlias(String alias) { + this.alias = alias; + } - public int getStatus() { - return status; - } + public int getStatus() { + return status; + } - public void setStatus(int status) { - this.status = status; - } + public void setStatus(int status) { + this.status = status; + } - public String getAddress() { - return address; - } + public String getAddress() { + return address; + } - public void setAddress(String address) { - this.address = address; - } + public void setAddress(String address) { + this.address = address; + } - public int getHide_mobile() { - return hide_mobile; - } + public int getHide_mobile() { + return hide_mobile; + } - public void setHide_mobile(int hide_mobile) { - this.hide_mobile = hide_mobile; - } + public void setHide_mobile(int hide_mobile) { + this.hide_mobile = hide_mobile; + } - public String getEnglish_name() { - return english_name; - } + public String getEnglish_name() { + return english_name; + } - public void setEnglish_name(String english_name) { - this.english_name = english_name; - } + public void setEnglish_name(String english_name) { + this.english_name = english_name; + } - public String getOpen_userid() { - return open_userid; - } + public String getOpen_userid() { + return open_userid; + } - public void setOpen_userid(String open_userid) { - this.open_userid = open_userid; - } + public void setOpen_userid(String open_userid) { + this.open_userid = open_userid; + } - public long getMain_department() { - return main_department; - } + public long getMain_department() { + return main_department; + } - public void setMain_department(long main_department) { - this.main_department = main_department; - } + public void setMain_department(long main_department) { + this.main_department = main_department; + } - public String getQr_code() { - return qr_code; - } + public String getQr_code() { + return qr_code; + } - public void setQr_code(String qr_code) { - this.qr_code = qr_code; - } + public void setQr_code(String qr_code) { + this.qr_code = qr_code; + } - public String getExternal_position() { - return external_position; - } + public String getExternal_position() { + return external_position; + } - public void setExternal_position(String external_position) { - this.external_position = external_position; - } + public void setExternal_position(String external_position) { + this.external_position = external_position; + } - public int getIsleader() { - return isleader; - } + public int getIsleader() { + return isleader; + } - public void setIsleader(int isleader) { - this.isleader = isleader; - } + public void setIsleader(int isleader) { + this.isleader = isleader; + } - public int getEnable() { - return enable; - } + public int getEnable() { + return enable; + } - public void setEnable(int enable) { - this.enable = enable; - } + public void setEnable(int enable) { + this.enable = enable; + } - public WorkWeixinUsers() { - super(); - } + public WorkWeixinUsers() { + super(); + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/entity/WorkWeixinUsersResponse.java b/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/entity/WorkWeixinUsersResponse.java index 331a1dbcb..4a5bf79b0 100644 --- a/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/entity/WorkWeixinUsersResponse.java +++ b/maxkey-synchronizers/maxkey-synchronizer-workweixin/src/main/java/org/dromara/maxkey/synchronizer/workweixin/entity/WorkWeixinUsersResponse.java @@ -23,19 +23,19 @@ import org.dromara.maxkey.synchronizer.entity.ResponseData; public class WorkWeixinUsersResponse extends ResponseData{ - - ArrayListuserlist; + + ArrayListuserlist; - public WorkWeixinUsersResponse() { - super(); - } + public WorkWeixinUsersResponse() { + super(); + } - public ArrayList getUserlist() { - return userlist; - } + public ArrayList getUserlist() { + return userlist; + } - public void setUserlist(ArrayList userlist) { - this.userlist = userlist; - } - + public void setUserlist(ArrayList userlist) { + this.userlist = userlist; + } + } diff --git a/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/autoconfigure/SynchronizerAutoConfiguration.java b/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/autoconfigure/SynchronizerAutoConfiguration.java index 4e5b53be9..185521461 100644 --- a/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/autoconfigure/SynchronizerAutoConfiguration.java +++ b/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/autoconfigure/SynchronizerAutoConfiguration.java @@ -45,8 +45,8 @@ import org.springframework.scheduling.quartz.SchedulerFactoryBean; @AutoConfiguration public class SynchronizerAutoConfiguration implements InitializingBean { - private static final Logger _logger = LoggerFactory.getLogger(SynchronizerAutoConfiguration.class); - public static final String SYNCHRONIZERS_SELECT_STATEMENT = "select * from mxk_synchronizers where status ='1'"; + private static final Logger _logger = LoggerFactory.getLogger(SynchronizerAutoConfiguration.class); + public static final String SYNCHRONIZERS_SELECT_STATEMENT = "select * from mxk_synchronizers where status ='1'"; @Bean(name = "schedulerSynchronizerJobs") String schedulerSynchronizerJobs( @@ -54,80 +54,80 @@ public class SynchronizerAutoConfiguration implements InitializingBean { SchedulerFactoryBean schedulerFactoryBean, @Value("${maxkey.job.cron.enable}") boolean jobCronEnable ) throws SchedulerException { - - Scheduler scheduler = schedulerFactoryBean.getScheduler(); - if(jobCronEnable) { - List synchronizerList = querySynchronizers(jdbcTemplate); - for(Synchronizers synchronizer : synchronizerList) { - if(synchronizer.getScheduler()!=null - && !synchronizer.getScheduler().equals("") - && CronExpression.isValidExpression(synchronizer.getScheduler())) { - _logger.debug("synchronizer details : {}" , synchronizer); - buildJob(scheduler,synchronizer); - } - } - } - return "schedulerSynchronizerJobs"; - } - - - private void buildJob(Scheduler scheduler , - Synchronizers synchronizer) throws SchedulerException { - JobDetail jobDetail = - JobBuilder.newJob(SynchronizerJob.class) - .withIdentity(synchronizer.getService()+"_Job", "SynchronizerGroups") - .build(); - - JobDataMap jobDataMap = new JobDataMap(); - jobDataMap.put("synchronizer", synchronizer); - _logger.debug("synchronizer : {}" , synchronizer.getName()+"("+synchronizer.getId()+"_"+synchronizer.getSourceType()+")"); - _logger.debug("synchronizer service : {}", synchronizer.getService()); - _logger.debug("synchronizer Scheduler : {} " ,synchronizer.getScheduler()); - CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(synchronizer.getScheduler()); - CronTrigger cronTrigger = - TriggerBuilder.newTrigger() - .withIdentity("trigger_"+synchronizer.getService(), "SynchronizerGroups") - .usingJobData(jobDataMap) - .withSchedule(scheduleBuilder) - .build(); - scheduler.scheduleJob(jobDetail,cronTrigger); - } + + Scheduler scheduler = schedulerFactoryBean.getScheduler(); + if(jobCronEnable) { + List synchronizerList = querySynchronizers(jdbcTemplate); + for(Synchronizers synchronizer : synchronizerList) { + if(synchronizer.getScheduler()!=null + && !synchronizer.getScheduler().equals("") + && CronExpression.isValidExpression(synchronizer.getScheduler())) { + _logger.debug("synchronizer details : {}" , synchronizer); + buildJob(scheduler,synchronizer); + } + } + } + return "schedulerSynchronizerJobs"; + } + + + private void buildJob(Scheduler scheduler , + Synchronizers synchronizer) throws SchedulerException { + JobDetail jobDetail = + JobBuilder.newJob(SynchronizerJob.class) + .withIdentity(synchronizer.getService()+"_Job", "SynchronizerGroups") + .build(); + + JobDataMap jobDataMap = new JobDataMap(); + jobDataMap.put("synchronizer", synchronizer); + _logger.debug("synchronizer : {}" , synchronizer.getName()+"("+synchronizer.getId()+"_"+synchronizer.getSourceType()+")"); + _logger.debug("synchronizer service : {}", synchronizer.getService()); + _logger.debug("synchronizer Scheduler : {} " ,synchronizer.getScheduler()); + CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(synchronizer.getScheduler()); + CronTrigger cronTrigger = + TriggerBuilder.newTrigger() + .withIdentity("trigger_"+synchronizer.getService(), "SynchronizerGroups") + .usingJobData(jobDataMap) + .withSchedule(scheduleBuilder) + .build(); + scheduler.scheduleJob(jobDetail,cronTrigger); + } - public List querySynchronizers(JdbcTemplate jdbcTemplate) { - return jdbcTemplate.query(SYNCHRONIZERS_SELECT_STATEMENT, new RowMapper() { - @Override - public Synchronizers mapRow(ResultSet rs, int rowNum) throws SQLException { - Synchronizers synchronizer = new Synchronizers(); - synchronizer.setId( rs.getString("id")); - synchronizer.setName( rs.getString("name")); - synchronizer.setScheduler( rs.getString("scheduler")); - synchronizer.setSourceType( rs.getString("sourcetype")); - synchronizer.setProviderUrl(rs.getString("providerurl")); - synchronizer.setDriverClass(rs.getString("driverclass")); - synchronizer.setPrincipal( rs.getString("principal")); - synchronizer.setCredentials( - PasswordReciprocal.getInstance().decoder(rs.getString("credentials"))); - synchronizer.setResumeTime( rs.getString("resumetime")); - synchronizer.setSuspendTime(rs.getString("suspendtime")); - synchronizer.setUserFilters( rs.getString("userfilters")); - synchronizer.setUserBasedn( rs.getString("userbasedn")); - synchronizer.setOrgFilters( rs.getString("orgfilters")); - synchronizer.setOrgBasedn( rs.getString("orgbasedn")); - synchronizer.setMsadDomain( rs.getString("msaddomain")); - synchronizer.setSslSwitch( rs.getString("sslswitch")); - synchronizer.setTrustStore( rs.getString("truststore")); - synchronizer.setStatus( rs.getString("status")); - synchronizer.setDescription(rs.getString("description")); - synchronizer.setSyncStartTime(rs.getInt("syncstarttime")); - synchronizer.setService(rs.getString("service")); + public List querySynchronizers(JdbcTemplate jdbcTemplate) { + return jdbcTemplate.query(SYNCHRONIZERS_SELECT_STATEMENT, new RowMapper() { + @Override + public Synchronizers mapRow(ResultSet rs, int rowNum) throws SQLException { + Synchronizers synchronizer = new Synchronizers(); + synchronizer.setId( rs.getString("id")); + synchronizer.setName( rs.getString("name")); + synchronizer.setScheduler( rs.getString("scheduler")); + synchronizer.setSourceType( rs.getString("sourcetype")); + synchronizer.setProviderUrl(rs.getString("providerurl")); + synchronizer.setDriverClass(rs.getString("driverclass")); + synchronizer.setPrincipal( rs.getString("principal")); + synchronizer.setCredentials( + PasswordReciprocal.getInstance().decoder(rs.getString("credentials"))); + synchronizer.setResumeTime( rs.getString("resumetime")); + synchronizer.setSuspendTime(rs.getString("suspendtime")); + synchronizer.setUserFilters( rs.getString("userfilters")); + synchronizer.setUserBasedn( rs.getString("userbasedn")); + synchronizer.setOrgFilters( rs.getString("orgfilters")); + synchronizer.setOrgBasedn( rs.getString("orgbasedn")); + synchronizer.setMsadDomain( rs.getString("msaddomain")); + synchronizer.setSslSwitch( rs.getString("sslswitch")); + synchronizer.setTrustStore( rs.getString("truststore")); + synchronizer.setStatus( rs.getString("status")); + synchronizer.setDescription(rs.getString("description")); + synchronizer.setSyncStartTime(rs.getInt("syncstarttime")); + synchronizer.setService(rs.getString("service")); - return synchronizer; - } - }); - } - - @Override - public void afterPropertiesSet() throws Exception { - - } + return synchronizer; + } + }); + } + + @Override + public void afterPropertiesSet() throws Exception { + + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/AbstractSynchronizerService.java b/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/AbstractSynchronizerService.java index 2352c0226..3b615e660 100644 --- a/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/AbstractSynchronizerService.java +++ b/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/AbstractSynchronizerService.java @@ -59,7 +59,7 @@ public abstract class AbstractSynchronizerService { public HashMap loadOrgsByInstId(String instId,String rootOrgId) { List orgsList = organizationsService.find("instid = '" + instId + "'"); if(rootOrgId== null || rootOrgId.equals("")) { - rootOrgId="1"; + rootOrgId="1"; } for(Organizations org : orgsList) { @@ -83,24 +83,24 @@ public abstract class AbstractSynchronizerService { } public void socialsAssociate(SynchroRelated synchroRelated,String provider) { - SocialsAssociate socialsAssociate = - socialsAssociatesService.findOne("instid = ? and userid = ? and socialuserid = ? and provider = ? ", - new Object[] { - synchroRelated.getInstId(), - synchroRelated.getObjectId(), - synchroRelated.getOriginId(), - provider - }, - new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,Types.VARCHAR}); - if(socialsAssociate == null) { - socialsAssociate = new SocialsAssociate(); - socialsAssociate.setUserId(synchroRelated.getObjectId()); - socialsAssociate.setUsername(synchroRelated.getObjectName()); - socialsAssociate.setInstId(synchroRelated.getInstId()); - socialsAssociate.setProvider(provider); - socialsAssociate.setSocialUserId(synchroRelated.getOriginId()); - socialsAssociatesService.insert(socialsAssociate); - } + SocialsAssociate socialsAssociate = + socialsAssociatesService.findOne("instid = ? and userid = ? and socialuserid = ? and provider = ? ", + new Object[] { + synchroRelated.getInstId(), + synchroRelated.getObjectId(), + synchroRelated.getOriginId(), + provider + }, + new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,Types.VARCHAR}); + if(socialsAssociate == null) { + socialsAssociate = new SocialsAssociate(); + socialsAssociate.setUserId(synchroRelated.getObjectId()); + socialsAssociate.setUsername(synchroRelated.getObjectName()); + socialsAssociate.setInstId(synchroRelated.getInstId()); + socialsAssociate.setProvider(provider); + socialsAssociate.setSocialUserId(synchroRelated.getOriginId()); + socialsAssociatesService.insert(socialsAssociate); + } } public void push(HashMap orgsNamePathMap, List orgsList, @@ -169,13 +169,13 @@ public abstract class AbstractSynchronizerService { this.historySynchronizerService = historySynchronizerService; } - public SynchroRelatedService getSynchroRelatedService() { - return synchroRelatedService; - } + public SynchroRelatedService getSynchroRelatedService() { + return synchroRelatedService; + } - public void setSynchroRelatedService(SynchroRelatedService synchroRelatedService) { - this.synchroRelatedService = synchroRelatedService; - } + public void setSynchroRelatedService(SynchroRelatedService synchroRelatedService) { + this.synchroRelatedService = synchroRelatedService; + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/ISynchronizerService.java b/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/ISynchronizerService.java index be54d1ebd..a9c18ae66 100644 --- a/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/ISynchronizerService.java +++ b/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/ISynchronizerService.java @@ -21,7 +21,7 @@ import org.dromara.maxkey.entity.Synchronizers; public interface ISynchronizerService { - public void sync() throws Exception ; - - public void setSynchronizer(Synchronizers synchronizer); + public void sync() throws Exception ; + + public void setSynchronizer(Synchronizers synchronizer); } diff --git a/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/SynchronizerJob.java b/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/SynchronizerJob.java index d1aaffa04..e2a73e9e2 100644 --- a/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/SynchronizerJob.java +++ b/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/SynchronizerJob.java @@ -28,7 +28,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SynchronizerJob implements Job { - static final Logger logger = LoggerFactory.getLogger(SynchronizerJob.class); + static final Logger logger = LoggerFactory.getLogger(SynchronizerJob.class); public static class JOBSTATUS{ public static final int STOP = 0; @@ -36,17 +36,17 @@ public class SynchronizerJob implements Job { public static final int FINISHED = 2; } - SynchronizersService synchronizersService; - + SynchronizersService synchronizersService; + private static HashMap jobStatus = new HashMap<>(); @Override public void execute(JobExecutionContext context){ - Synchronizers synchronizer = readSynchronizer(context); - if(jobStatus.get(synchronizer.getId()) ==null ) { - //init - jobStatus.put(synchronizer.getId(), JOBSTATUS.STOP) ; - }else if(jobStatus.get(synchronizer.getId())== JOBSTATUS.RUNNING) { + Synchronizers synchronizer = readSynchronizer(context); + if(jobStatus.get(synchronizer.getId()) ==null ) { + //init + jobStatus.put(synchronizer.getId(), JOBSTATUS.STOP) ; + }else if(jobStatus.get(synchronizer.getId())== JOBSTATUS.RUNNING) { logger.info("SynchronizerJob is in running . " ); return; } @@ -54,14 +54,14 @@ public class SynchronizerJob implements Job { logger.debug("SynchronizerJob is running ... " ); jobStatus.put(synchronizer.getId(), JOBSTATUS.RUNNING) ; try { - - logger.debug("synchronizer : {}" , synchronizer.getName()+"("+synchronizer.getId()+"_"+synchronizer.getSourceType()+")"); - logger.debug("synchronizer service : {}" , synchronizer.getService()); - logger.debug("synchronizer Scheduler : {}" , synchronizer.getScheduler()); - ISynchronizerService service = (ISynchronizerService)WebContext.getBean(synchronizer.getService()); - service.setSynchronizer(synchronizer); - service.sync(); - jobStatus.put(synchronizer.getId(), JOBSTATUS.FINISHED); + + logger.debug("synchronizer : {}" , synchronizer.getName()+"("+synchronizer.getId()+"_"+synchronizer.getSourceType()+")"); + logger.debug("synchronizer service : {}" , synchronizer.getService()); + logger.debug("synchronizer Scheduler : {}" , synchronizer.getScheduler()); + ISynchronizerService service = (ISynchronizerService)WebContext.getBean(synchronizer.getService()); + service.setSynchronizer(synchronizer); + service.sync(); + jobStatus.put(synchronizer.getId(), JOBSTATUS.FINISHED); logger.debug("SynchronizerJob is success " ); }catch(Exception e) { logger.error("Exception " ,e); @@ -72,14 +72,14 @@ public class SynchronizerJob implements Job { public Synchronizers readSynchronizer(JobExecutionContext context) { - Synchronizers jobSynchronizer = (Synchronizers)context.getMergedJobDataMap().get("synchronizer"); - if(synchronizersService == null) { - synchronizersService = (SynchronizersService)WebContext.getBean("synchronizersService"); - } - //read synchronizer by id from database - Synchronizers synchronizer = synchronizersService.get(jobSynchronizer.getId()); - logger.trace("synchronizer {}" , synchronizer); - return synchronizer; + Synchronizers jobSynchronizer = (Synchronizers)context.getMergedJobDataMap().get("synchronizer"); + if(synchronizersService == null) { + synchronizersService = (SynchronizersService)WebContext.getBean("synchronizersService"); + } + //read synchronizer by id from database + Synchronizers synchronizer = synchronizersService.get(jobSynchronizer.getId()); + logger.trace("synchronizer {}" , synchronizer); + return synchronizer; } diff --git a/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/entity/AccessToken.java b/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/entity/AccessToken.java index d54bb9a01..8436bb3d3 100644 --- a/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/entity/AccessToken.java +++ b/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/entity/AccessToken.java @@ -19,70 +19,70 @@ package org.dromara.maxkey.synchronizer.entity; public class AccessToken { - int errcode; - String errmsg; - String access_token; - //feishu access_token - String tenant_access_token; - String expires_in; + int errcode; + String errmsg; + String access_token; + //feishu access_token + String tenant_access_token; + String expires_in; - public AccessToken() { - super(); - } + public AccessToken() { + super(); + } - public int getErrcode() { - return errcode; - } + public int getErrcode() { + return errcode; + } - public void setErrcode(int errcode) { - this.errcode = errcode; - } + public void setErrcode(int errcode) { + this.errcode = errcode; + } - public String getErrmsg() { - return errmsg; - } + public String getErrmsg() { + return errmsg; + } - public void setErrmsg(String errmsg) { - this.errmsg = errmsg; - } + public void setErrmsg(String errmsg) { + this.errmsg = errmsg; + } - public String getAccess_token() { - return access_token; - } + public String getAccess_token() { + return access_token; + } - public void setAccess_token(String access_token) { - this.access_token = access_token; - } + public void setAccess_token(String access_token) { + this.access_token = access_token; + } - public String getTenant_access_token() { - return tenant_access_token; - } + public String getTenant_access_token() { + return tenant_access_token; + } - public void setTenant_access_token(String tenant_access_token) { - this.tenant_access_token = tenant_access_token; - } + public void setTenant_access_token(String tenant_access_token) { + this.tenant_access_token = tenant_access_token; + } - public String getExpires_in() { - return expires_in; - } + public String getExpires_in() { + return expires_in; + } - public void setExpires_in(String expires_in) { - this.expires_in = expires_in; - } + public void setExpires_in(String expires_in) { + this.expires_in = expires_in; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("AccessToken [errcode="); - builder.append(errcode); - builder.append(", errmsg="); - builder.append(errmsg); - builder.append(", access_token="); - builder.append(access_token); - builder.append(", expires_in="); - builder.append(expires_in); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("AccessToken [errcode="); + builder.append(errcode); + builder.append(", errmsg="); + builder.append(errmsg); + builder.append(", access_token="); + builder.append(access_token); + builder.append(", expires_in="); + builder.append(expires_in); + builder.append("]"); + return builder.toString(); + } } diff --git a/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/entity/ResponseData.java b/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/entity/ResponseData.java index 105f2887d..a73f4a8c6 100644 --- a/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/entity/ResponseData.java +++ b/maxkey-synchronizers/maxkey-synchronizer/src/main/java/org/dromara/maxkey/synchronizer/entity/ResponseData.java @@ -19,55 +19,55 @@ package org.dromara.maxkey.synchronizer.entity; public class ResponseData { - protected long errcode; - protected long code; + protected long errcode; + protected long code; - protected String errmsg; - protected String msg; - protected String message; + protected String errmsg; + protected String msg; + protected String message; - public long getErrcode() { - return errcode; - } + public long getErrcode() { + return errcode; + } - public void setErrcode(long errcode) { - this.errcode = errcode; - } + public void setErrcode(long errcode) { + this.errcode = errcode; + } - public String getErrmsg() { - return errmsg; - } + public String getErrmsg() { + return errmsg; + } - public void setErrmsg(String errmsg) { - this.errmsg = errmsg; - } + public void setErrmsg(String errmsg) { + this.errmsg = errmsg; + } - public long getCode() { - return code; - } + public long getCode() { + return code; + } - public void setCode(long code) { - this.code = code; - } + public void setCode(long code) { + this.code = code; + } - public String getMsg() { - return msg; - } + public String getMsg() { + return msg; + } - public void setMsg(String msg) { - this.msg = msg; - } + public void setMsg(String msg) { + this.msg = msg; + } - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } - public void setMessage(String message) { - this.message = message; - } + public void setMessage(String message) { + this.message = message; + } - public ResponseData() { - super(); - } + public ResponseData() { + super(); + } } diff --git a/maxkey-web-apis/maxkey-web-api-rest/src/main/java/org/dromara/maxkey/web/apis/identity/rest/RestOrganizationController.java b/maxkey-web-apis/maxkey-web-api-rest/src/main/java/org/dromara/maxkey/web/apis/identity/rest/RestOrganizationController.java index 2b55dfcd9..3331e566f 100644 --- a/maxkey-web-apis/maxkey-web-api-rest/src/main/java/org/dromara/maxkey/web/apis/identity/rest/RestOrganizationController.java +++ b/maxkey-web-apis/maxkey-web-api-rest/src/main/java/org/dromara/maxkey/web/apis/identity/rest/RestOrganizationController.java @@ -43,15 +43,15 @@ import org.springframework.web.util.UriComponentsBuilder; @RestController @RequestMapping(value={"/api/idm/Organization"}) public class RestOrganizationController { - static final Logger _logger = LoggerFactory.getLogger(RestOrganizationController.class); - + static final Logger _logger = LoggerFactory.getLogger(RestOrganizationController.class); + @Autowired OrganizationsService organizationsService; @GetMapping(value = "/{id}") public Organizations getUser(@PathVariable String id, @RequestParam(required = false) String attributes) { - _logger.debug("Organizations id {} , attributes {}", id , attributes); + _logger.debug("Organizations id {} , attributes {}", id , attributes); return organizationsService.get(id); } @@ -59,7 +59,7 @@ public class RestOrganizationController { public Organizations create(@RequestBody Organizations org, @RequestParam(required = false) String attributes, UriComponentsBuilder builder) { - _logger.debug("Organizations content {} , attributes {}", org , attributes); + _logger.debug("Organizations content {} , attributes {}", org , attributes); Organizations loadOrg = organizationsService.get(org.getId()); if(loadOrg == null) { organizationsService.insert(org); @@ -73,7 +73,7 @@ public class RestOrganizationController { public Organizations replace(@PathVariable String id, @RequestBody Organizations org, @RequestParam(required = false) String attributes) { - _logger.debug("Organizations id {} , content {} , attributes {}", id , org , attributes); + _logger.debug("Organizations id {} , content {} , attributes {}", id , org , attributes); Organizations loadOrg = organizationsService.get(id); if(loadOrg == null) { organizationsService.insert(org); @@ -87,19 +87,19 @@ public class RestOrganizationController { @DeleteMapping(value = "/{id}") @ResponseStatus(HttpStatus.OK) public void delete(@PathVariable final String id) { - _logger.debug("Organizations id {} ", id ); + _logger.debug("Organizations id {} ", id ); organizationsService.delete(id); } @GetMapping(value = { "/.search" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message> search(@ModelAttribute Organizations org) { - if(StringUtils.isBlank(org.getInstId())){ - org.setInstId("1"); - } - _logger.debug("Organizations {}" , org); - return new Message<>(organizationsService.fetchPageResults(org)); - } + public Message> search(@ModelAttribute Organizations org) { + if(StringUtils.isBlank(org.getInstId())){ + org.setInstId("1"); + } + _logger.debug("Organizations {}" , org); + return new Message<>(organizationsService.fetchPageResults(org)); + } } diff --git a/maxkey-web-apis/maxkey-web-api-rest/src/main/java/org/dromara/maxkey/web/apis/identity/rest/RestResourcesController.java b/maxkey-web-apis/maxkey-web-api-rest/src/main/java/org/dromara/maxkey/web/apis/identity/rest/RestResourcesController.java index 20255ea69..14d0f97f6 100644 --- a/maxkey-web-apis/maxkey-web-api-rest/src/main/java/org/dromara/maxkey/web/apis/identity/rest/RestResourcesController.java +++ b/maxkey-web-apis/maxkey-web-api-rest/src/main/java/org/dromara/maxkey/web/apis/identity/rest/RestResourcesController.java @@ -45,7 +45,7 @@ import io.swagger.v3.oas.annotations.Operation; @RestController @RequestMapping("/api/idm/Resources") public class RestResourcesController { - static final Logger logger = LoggerFactory.getLogger(RestResourcesController.class); + static final Logger logger = LoggerFactory.getLogger(RestResourcesController.class); @Autowired UserInfoService userInfoService; @@ -59,27 +59,27 @@ public class RestResourcesController { @Operation(summary = "获取应用功能权限清单", description = "获取应用功能权限清单",method="GET") @GetMapping("/functionList") public Message getFunctionList(@RequestParam("userId") String userId) { - logger.debug("userId {} ", userId); + logger.debug("userId {} ", userId); UserInfo user = userInfoService.get(userId); ///获取appId登录 User principal = (User)AuthorizationUtils.getAuthentication().getPrincipal(); Apps app = appsService.get(principal.getUsername(),true); - logger.debug("appId {} " , app.getId()); - Apps relatedApp = new Apps(); - if(user != null) { - relatedApp.setId(app.getId()); - relatedApp.setAppName(app.getAppName()); - relatedApp.setLoginUrl(app.getLoginUrl()); - relatedApp.setLogoutUrl(app.getLogoutUrl()); - relatedApp.setProtocol(app.getProtocol()); - relatedApp.setCategory(app.getCategory()); - relatedApp.setVendor(app.getVendor()); - relatedApp.setVendorUrl(app.getVendorUrl()); - relatedApp.setDescription(app.getDescription()); - Set functions = authzResourceService.getResourcesBySubject(user,app); - return new Message<>(new AppResourcesVo(relatedApp,functions)); - }else { - return new Message<>(new AppResourcesVo(relatedApp,new HashSet<>())); - } + logger.debug("appId {} " , app.getId()); + Apps relatedApp = new Apps(); + if(user != null) { + relatedApp.setId(app.getId()); + relatedApp.setAppName(app.getAppName()); + relatedApp.setLoginUrl(app.getLoginUrl()); + relatedApp.setLogoutUrl(app.getLogoutUrl()); + relatedApp.setProtocol(app.getProtocol()); + relatedApp.setCategory(app.getCategory()); + relatedApp.setVendor(app.getVendor()); + relatedApp.setVendorUrl(app.getVendorUrl()); + relatedApp.setDescription(app.getDescription()); + Set functions = authzResourceService.getResourcesBySubject(user,app); + return new Message<>(new AppResourcesVo(relatedApp,functions)); + }else { + return new Message<>(new AppResourcesVo(relatedApp,new HashSet<>())); + } } } diff --git a/maxkey-web-apis/maxkey-web-api-rest/src/main/java/org/dromara/maxkey/web/apis/identity/rest/RestUserInfoController.java b/maxkey-web-apis/maxkey-web-api-rest/src/main/java/org/dromara/maxkey/web/apis/identity/rest/RestUserInfoController.java index 49327f5d2..fadcc02c2 100644 --- a/maxkey-web-apis/maxkey-web-api-rest/src/main/java/org/dromara/maxkey/web/apis/identity/rest/RestUserInfoController.java +++ b/maxkey-web-apis/maxkey-web-api-rest/src/main/java/org/dromara/maxkey/web/apis/identity/rest/RestUserInfoController.java @@ -43,9 +43,9 @@ import org.springframework.web.util.UriComponentsBuilder; @RestController @RequestMapping(value={"/api/idm/Users"}) public class RestUserInfoController { - - static final Logger _logger = LoggerFactory.getLogger(RestUserInfoController.class); - + + static final Logger _logger = LoggerFactory.getLogger(RestUserInfoController.class); + @Autowired UserInfoService userInfoService; @@ -53,7 +53,7 @@ public class RestUserInfoController { public UserInfo getUser( @PathVariable String id, @RequestParam(required = false) String attributes) { - _logger.debug("UserInfo id {} , attributes {}", id , attributes); + _logger.debug("UserInfo id {} , attributes {}", id , attributes); UserInfo loadUserInfo = userInfoService.get(id); loadUserInfo.setDecipherable(null); return loadUserInfo; @@ -63,7 +63,7 @@ public class RestUserInfoController { public UserInfo create(@RequestBody UserInfo userInfo, @RequestParam(required = false) String attributes, UriComponentsBuilder builder) { - _logger.debug("UserInfo content {} , attributes {}", userInfo , attributes); + _logger.debug("UserInfo content {} , attributes {}", userInfo , attributes); UserInfo loadUserInfo = userInfoService.findByUsername(userInfo.getUsername()); if(loadUserInfo != null) { userInfoService.update(userInfo); @@ -77,7 +77,7 @@ public class RestUserInfoController { public UserInfo replace(@PathVariable String id, @RequestBody UserInfo userInfo, @RequestParam(required = false) String attributes) { - _logger.debug("UserInfo content {} , attributes {}", userInfo , attributes); + _logger.debug("UserInfo content {} , attributes {}", userInfo , attributes); UserInfo loadUserInfo = userInfoService.findByUsername(userInfo.getUsername()); if(loadUserInfo != null) { userInfoService.update(userInfo); @@ -90,17 +90,17 @@ public class RestUserInfoController { @DeleteMapping(value = "/{id}") @ResponseStatus(HttpStatus.OK) public void delete(@PathVariable final String id) { - _logger.debug("UserInfo id {} ", id ); + _logger.debug("UserInfo id {} ", id ); userInfoService.delete(id); } @GetMapping(value = { "/.search" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message> search(@ModelAttribute UserInfo userInfo) { - _logger.debug("UserInfo {}",userInfo); - if(StringUtils.isBlank(userInfo.getInstId())){ - userInfo.setInstId("1"); - } - return new Message<>(userInfoService.fetchPageResults(userInfo)); - } + public Message> search(@ModelAttribute UserInfo userInfo) { + _logger.debug("UserInfo {}",userInfo); + if(StringUtils.isBlank(userInfo.getInstId())){ + userInfo.setInstId("1"); + } + return new Message<>(userInfoService.fetchPageResults(userInfo)); + } } diff --git a/maxkey-web-apis/maxkey-web-api-rest/src/main/java/org/dromara/maxkey/web/apis/identity/rest/RestUserPasswordController.java b/maxkey-web-apis/maxkey-web-api-rest/src/main/java/org/dromara/maxkey/web/apis/identity/rest/RestUserPasswordController.java index e2dbd5817..5f90b75c3 100644 --- a/maxkey-web-apis/maxkey-web-api-rest/src/main/java/org/dromara/maxkey/web/apis/identity/rest/RestUserPasswordController.java +++ b/maxkey-web-apis/maxkey-web-api-rest/src/main/java/org/dromara/maxkey/web/apis/identity/rest/RestUserPasswordController.java @@ -35,9 +35,9 @@ import org.springframework.web.util.UriComponentsBuilder; @Controller @RequestMapping(value={"/api/idm/Users"}) public class RestUserPasswordController { - - static final Logger _logger = LoggerFactory.getLogger(RestUserPasswordController.class); - + + static final Logger _logger = LoggerFactory.getLogger(RestUserPasswordController.class); + @Autowired UserInfoService userInfoService; @@ -47,14 +47,14 @@ public class RestUserPasswordController { public String changePassword(@RequestParam(required = true) String username, @RequestParam(required = true) String password, UriComponentsBuilder builder) throws IOException { - - _logger.debug("UserInfo username {} , password {}", username , password); - - UserInfo loadUserInfo = userInfoService.findByUsername(username); + + _logger.debug("UserInfo username {} , password {}", username , password); + + UserInfo loadUserInfo = userInfoService.findByUsername(username); if(loadUserInfo != null) { - ChangePassword changePassword = new ChangePassword(loadUserInfo); - changePassword.setPassword(password); - changePassword.setDecipherable(loadUserInfo.getDecipherable()); + ChangePassword changePassword = new ChangePassword(loadUserInfo); + changePassword.setPassword(password); + changePassword.setDecipherable(loadUserInfo.getDecipherable()); userInfoService.changePassword(changePassword,true); } return "true"; diff --git a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/ScimGroupController.java b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/ScimGroupController.java index ba20bb590..6dbf117cc 100644 --- a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/ScimGroupController.java +++ b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/ScimGroupController.java @@ -51,28 +51,28 @@ import org.springframework.web.util.UriComponentsBuilder; @RestController @RequestMapping(value = "/api/idm/SCIM/v2/Groups") public class ScimGroupController { - static final Logger _logger = LoggerFactory.getLogger(ScimGroupController.class); - - @Autowired - GroupsService groupsService; - - @Autowired - GroupMemberService groupMemberService; - + static final Logger _logger = LoggerFactory.getLogger(ScimGroupController.class); + + @Autowired + GroupsService groupsService; + + @Autowired + GroupMemberService groupMemberService; + @RequestMapping(value = "/{id}", method = RequestMethod.GET) public MappingJacksonValue get(@PathVariable String id, @RequestParam(required = false) String attributes) { - _logger.debug("ScimGroup id {} , attributes {}", id , attributes); - Groups group = groupsService.get(id); - ScimGroup scimGroup = group2ScimGroup(group); - List userList = groupMemberService.queryMemberByGroupId(id); - if(userList != null && userList.size() > 0) { - Set members = new HashSet(); - for (UserInfo user : userList) { - members.add(new ScimMemberRef(user.getDisplayName(),user.getId())); - } - scimGroup.setMembers(members); - } + _logger.debug("ScimGroup id {} , attributes {}", id , attributes); + Groups group = groupsService.get(id); + ScimGroup scimGroup = group2ScimGroup(group); + List userList = groupMemberService.queryMemberByGroupId(id); + if(userList != null && userList.size() > 0) { + Set members = new HashSet(); + for (UserInfo user : userList) { + members.add(new ScimMemberRef(user.getDisplayName(),user.getId())); + } + scimGroup.setMembers(members); + } return new MappingJacksonValue(scimGroup); } @@ -80,9 +80,9 @@ public class ScimGroupController { public MappingJacksonValue create(@RequestBody ScimGroup scimGroup, @RequestParam(required = false) String attributes, UriComponentsBuilder builder) throws IOException { - _logger.debug("ScimGroup content {} , attributes {}", scimGroup , attributes); - Groups group =scimGroup2Role(scimGroup); - groupsService.insert(group); + _logger.debug("ScimGroup content {} , attributes {}", scimGroup , attributes); + Groups group =scimGroup2Role(scimGroup); + groupsService.insert(group); return get(group.getId(),attributes); } @@ -90,18 +90,18 @@ public class ScimGroupController { public MappingJacksonValue replace(@PathVariable String id, @RequestBody ScimGroup scimGroup, @RequestParam(required = false) String attributes) - throws IOException { - _logger.debug("ScimGroup content {} , attributes {}", scimGroup , attributes); - Groups group =scimGroup2Role(scimGroup); - groupsService.update(group); + throws IOException { + _logger.debug("ScimGroup content {} , attributes {}", scimGroup , attributes); + Groups group =scimGroup2Role(scimGroup); + groupsService.update(group); return get(group.getId(),attributes); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) public void delete(@PathVariable final String id) { - _logger.debug("ScimGroup id {} " , id); - groupsService.delete(id); + _logger.debug("ScimGroup id {} " , id); + groupsService.delete(id); } @RequestMapping(method = RequestMethod.GET) @@ -111,48 +111,48 @@ public class ScimGroupController { @RequestMapping(value = "/.search", method = RequestMethod.POST) public MappingJacksonValue searchWithPost(@ModelAttribute ScimParameters requestParameters) { - requestParameters.parse(); - _logger.debug("requestParameters {} ",requestParameters); - Groups queryModel = new Groups(); - queryModel.setPageSize(requestParameters.getCount()); - queryModel.calculate(requestParameters.getStartIndex()); + requestParameters.parse(); + _logger.debug("requestParameters {} ",requestParameters); + Groups queryModel = new Groups(); + queryModel.setPageSize(requestParameters.getCount()); + queryModel.calculate(requestParameters.getStartIndex()); JpaPageResults orgResults = groupsService.fetchPageResults(queryModel); List resultList = new ArrayList(); for(Groups group : orgResults.getRows()) { - resultList.add(group2ScimGroup(group)); + resultList.add(group2ScimGroup(group)); } ScimSearchResult scimSearchResult = - new ScimSearchResult( - resultList, - orgResults.getRecords(), - queryModel.getPageSize(), - requestParameters.getStartIndex()); + new ScimSearchResult( + resultList, + orgResults.getRecords(), + queryModel.getPageSize(), + requestParameters.getStartIndex()); return new MappingJacksonValue(scimSearchResult); } public ScimGroup group2ScimGroup(Groups group) { - ScimGroup scimGroup = new ScimGroup(); - scimGroup.setId(group.getId()); - scimGroup.setExternalId(group.getId()); - scimGroup.setDisplayName(group.getGroupName()); - - ScimMeta meta = new ScimMeta("Group"); + ScimGroup scimGroup = new ScimGroup(); + scimGroup.setId(group.getId()); + scimGroup.setExternalId(group.getId()); + scimGroup.setDisplayName(group.getGroupName()); + + ScimMeta meta = new ScimMeta("Group"); if(group.getCreatedDate()!= null){ - meta.setCreated(group.getCreatedDate()); + meta.setCreated(group.getCreatedDate()); } if(group.getModifiedDate()!= null){ - meta.setLastModified(group.getModifiedDate()); + meta.setLastModified(group.getModifiedDate()); } scimGroup.setMeta(meta); - return scimGroup; + return scimGroup; } public Groups scimGroup2Role(ScimGroup scimGroup) { - Groups group = new Groups(); - group.setId(scimGroup.getId()); - group.setGroupName(scimGroup.getDisplayName()); - return group; + Groups group = new Groups(); + group.setId(scimGroup.getId()); + group.setGroupName(scimGroup.getDisplayName()); + return group; } } diff --git a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/ScimOrganizationController.java b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/ScimOrganizationController.java index 731775848..7a5cbf27f 100644 --- a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/ScimOrganizationController.java +++ b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/ScimOrganizationController.java @@ -56,17 +56,17 @@ import org.springframework.web.util.UriComponentsBuilder; @RestController @RequestMapping(value = "/api/idm/SCIM/v2/Organizations") public class ScimOrganizationController { - static final Logger _logger = LoggerFactory.getLogger(ScimOrganizationController.class); - - @Autowired - OrganizationsService organizationsService; - + static final Logger _logger = LoggerFactory.getLogger(ScimOrganizationController.class); + + @Autowired + OrganizationsService organizationsService; + @RequestMapping(value = "/{id}", method = RequestMethod.GET) public MappingJacksonValue get(@PathVariable String id, @RequestParam(required = false) String attributes) { - _logger.debug("ScimOrganization id {} , attributes {}", id , attributes); - Organizations org = organizationsService.get(id); - ScimOrganization scimOrg = org2ScimOrg(org); + _logger.debug("ScimOrganization id {} , attributes {}", id , attributes); + Organizations org = organizationsService.get(id); + ScimOrganization scimOrg = org2ScimOrg(org); return new MappingJacksonValue(scimOrg); } @@ -75,7 +75,7 @@ public class ScimOrganizationController { public MappingJacksonValue create(@RequestBody ScimOrganization scimOrg, @RequestParam(required = false) String attributes, UriComponentsBuilder builder) throws IOException { - _logger.debug("ScimOrganization content {} , attributes {}", scimOrg , attributes); + _logger.debug("ScimOrganization content {} , attributes {}", scimOrg , attributes); Organizations createOrg = scimOrg2Org(scimOrg); organizationsService.insert(createOrg); return get(createOrg.getId(), attributes); @@ -85,17 +85,17 @@ public class ScimOrganizationController { public MappingJacksonValue replace(@PathVariable String id, @RequestBody ScimOrganization scimOrg, @RequestParam(required = false) String attributes)throws IOException { - _logger.debug("ScimOrganization content {} , attributes {}", scimOrg , attributes); - Organizations updateOrg = scimOrg2Org(scimOrg); - organizationsService.update(updateOrg); + _logger.debug("ScimOrganization content {} , attributes {}", scimOrg , attributes); + Organizations updateOrg = scimOrg2Org(scimOrg); + organizationsService.update(updateOrg); return get(id, attributes); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) public void delete(@PathVariable final String id) { - _logger.debug("ScimOrganization id {}", id ); - organizationsService.delete(id); + _logger.debug("ScimOrganization id {}", id ); + organizationsService.delete(id); } @RequestMapping(method = RequestMethod.GET) @@ -105,8 +105,8 @@ public class ScimOrganizationController { @RequestMapping(value = "/.search", method = RequestMethod.POST) public MappingJacksonValue searchWithPost(@ModelAttribute ScimParameters requestParameters) { - requestParameters.parse(); - _logger.debug("requestParameters {} ",requestParameters); + requestParameters.parse(); + _logger.debug("requestParameters {} ",requestParameters); Organizations queryModel = new Organizations(); queryModel.setPageSize(requestParameters.getCount()); queryModel.calculate(requestParameters.getStartIndex()); @@ -114,20 +114,20 @@ public class ScimOrganizationController { JpaPageResults orgResults = organizationsService.fetchPageResults(queryModel); List resultList = new ArrayList(); for(Organizations org : orgResults.getRows()) { - resultList.add(org2ScimOrg(org)); + resultList.add(org2ScimOrg(org)); } ScimSearchResult scimSearchResult = - new ScimSearchResult( - resultList, - orgResults.getRecords(), - queryModel.getPageSize(), - requestParameters.getStartIndex()); + new ScimSearchResult( + resultList, + orgResults.getRecords(), + queryModel.getPageSize(), + requestParameters.getStartIndex()); return new MappingJacksonValue(scimSearchResult); } public ScimOrganization org2ScimOrg(Organizations org) { - ScimOrganization scimOrg = new ScimOrganization(); + ScimOrganization scimOrg = new ScimOrganization(); scimOrg.setId(org.getId()); scimOrg.setCode(org.getOrgCode()); scimOrg.setName(org.getOrgName()); @@ -148,38 +148,38 @@ public class ScimOrganizationController { scimOrg.setParentName(org.getParentName()); if(StringUtils.isNotBlank(org.getSortOrder())) { - scimOrg.setOrder(Long.parseLong(org.getSortOrder())); + scimOrg.setOrder(Long.parseLong(org.getSortOrder())); }else { - scimOrg.setOrder(1); + scimOrg.setOrder(1); } scimOrg.setExternalId(org.getId()); ScimMeta meta = new ScimMeta("Organization"); if(org.getCreatedDate()!= null){ - meta.setCreated(org.getCreatedDate()); + meta.setCreated(org.getCreatedDate()); } if(org.getModifiedDate()!= null){ - meta.setLastModified(org.getModifiedDate()); + meta.setLastModified(org.getModifiedDate()); } scimOrg.setMeta(meta); return scimOrg; } - public Organizations scimOrg2Org(ScimOrganization scimOrg) { - Organizations org = new Organizations(); - org.setId(scimOrg.getId()); - org.setOrgCode(scimOrg.getCode()); - org.setFullName(scimOrg.getFullName()); - org.setOrgName(StringUtils.isNotBlank(scimOrg.getName()) ? scimOrg.getName():scimOrg.getDisplayName()); - org.setParentId(StringUtils.isNotBlank(scimOrg.getParentId())? scimOrg.getParentId():scimOrg.getParent()); - org.setParentCode(scimOrg.getParentCode()); - org.setParentName(scimOrg.getParentName()); - org.setSortOrder(StringUtils.isNotBlank(scimOrg.getSortOrder() )?scimOrg.getSortOrder():scimOrg.getOrder()+""); - org.setLevel(scimOrg.getLevel()); - org.setType(scimOrg.getType()); - org.setDivision(scimOrg.getDivision()); - org.setDescription(scimOrg.getDescription()); - return org; + public Organizations scimOrg2Org(ScimOrganization scimOrg) { + Organizations org = new Organizations(); + org.setId(scimOrg.getId()); + org.setOrgCode(scimOrg.getCode()); + org.setFullName(scimOrg.getFullName()); + org.setOrgName(StringUtils.isNotBlank(scimOrg.getName()) ? scimOrg.getName():scimOrg.getDisplayName()); + org.setParentId(StringUtils.isNotBlank(scimOrg.getParentId())? scimOrg.getParentId():scimOrg.getParent()); + org.setParentCode(scimOrg.getParentCode()); + org.setParentName(scimOrg.getParentName()); + org.setSortOrder(StringUtils.isNotBlank(scimOrg.getSortOrder() )?scimOrg.getSortOrder():scimOrg.getOrder()+""); + org.setLevel(scimOrg.getLevel()); + org.setType(scimOrg.getType()); + org.setDivision(scimOrg.getDivision()); + org.setDescription(scimOrg.getDescription()); + return org; } } diff --git a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/ScimUserController.java b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/ScimUserController.java index fe998fc82..55776bff4 100644 --- a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/ScimUserController.java +++ b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/ScimUserController.java @@ -67,17 +67,17 @@ import org.springframework.web.util.UriComponentsBuilder; @RestController @RequestMapping(value = "/api/idm/SCIM/v2/Users") public class ScimUserController { - static final Logger _logger = LoggerFactory.getLogger(ScimUserController.class); - @Autowired - UserInfoService userInfoService; - - @Autowired - GroupsService groupsService; - + static final Logger _logger = LoggerFactory.getLogger(ScimUserController.class); + @Autowired + UserInfoService userInfoService; + + @Autowired + GroupsService groupsService; + @RequestMapping(value = "/{id}", method = RequestMethod.GET) public MappingJacksonValue get(@PathVariable String id, @RequestParam(required = false) String attributes) { - _logger.debug("ScimUser id {} , attributes {}", id , attributes); + _logger.debug("ScimUser id {} , attributes {}", id , attributes); UserInfo userInfo = userInfoService.get(id); ScimUser scimUser = userInfo2ScimUser(userInfo); return new MappingJacksonValue(scimUser); @@ -87,9 +87,9 @@ public class ScimUserController { public MappingJacksonValue create(@RequestBody ScimUser user, @RequestParam(required = false) String attributes, UriComponentsBuilder builder) throws IOException { - _logger.debug("ScimUser {} , attributes {}", user , attributes); - UserInfo userInfo = scimUser2UserInfo(user); - userInfoService.insert(userInfo); + _logger.debug("ScimUser {} , attributes {}", user , attributes); + UserInfo userInfo = scimUser2UserInfo(user); + userInfoService.insert(userInfo); return get(userInfo.getId(),attributes); } @@ -98,17 +98,17 @@ public class ScimUserController { @RequestBody ScimUser user, @RequestParam(required = false) String attributes) throws IOException { - _logger.debug("ScimUser {} , attributes {}", user , attributes); - UserInfo userInfo = scimUser2UserInfo(user); - userInfoService.update(userInfo); + _logger.debug("ScimUser {} , attributes {}", user , attributes); + UserInfo userInfo = scimUser2UserInfo(user); + userInfoService.update(userInfo); return get(id,attributes); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) public void delete(@PathVariable final String id) { - _logger.debug("ScimUser id {} ", id ); - userInfoService.delete(id); + _logger.debug("ScimUser id {} ", id ); + userInfoService.delete(id); } @RequestMapping(method = RequestMethod.GET) @@ -118,119 +118,119 @@ public class ScimUserController { @RequestMapping(value = "/.search", method = RequestMethod.POST) public MappingJacksonValue searchWithPost(@ModelAttribute ScimParameters requestParameters) { - requestParameters.parse(); - _logger.debug("requestParameters {} ",requestParameters); - UserInfo queryModel = new UserInfo(); - queryModel.setPageSize(requestParameters.getCount()); - queryModel.calculate(requestParameters.getStartIndex()); + requestParameters.parse(); + _logger.debug("requestParameters {} ",requestParameters); + UserInfo queryModel = new UserInfo(); + queryModel.setPageSize(requestParameters.getCount()); + queryModel.calculate(requestParameters.getStartIndex()); JpaPageResults orgResults = userInfoService.fetchPageResults(queryModel); List resultList = new ArrayList(); for(UserInfo user : orgResults.getRows()) { - resultList.add(userInfo2ScimUser(user)); + resultList.add(userInfo2ScimUser(user)); } ScimSearchResult scimSearchResult = - new ScimSearchResult( - resultList, - orgResults.getRecords(), - queryModel.getPageSize(), - requestParameters.getStartIndex()); + new ScimSearchResult( + resultList, + orgResults.getRecords(), + queryModel.getPageSize(), + requestParameters.getStartIndex()); return new MappingJacksonValue(scimSearchResult); } public ScimUser userInfo2ScimUser(UserInfo userInfo) { - ScimUser scimUser =new ScimUser(); - scimUser.setId(userInfo.getId()); - scimUser.setExternalId(userInfo.getId()); - scimUser.setDisplayName(userInfo.getDisplayName()); - scimUser.setUserName(userInfo.getUsername()); - scimUser.setName(new ScimFormattedName( - userInfo.getFormattedName(), - userInfo.getFamilyName(), - userInfo.getGivenName(), - userInfo.getMiddleName(), - userInfo.getHonorificPrefix(), - userInfo.getHonorificSuffix() - ) - ); - scimUser.setNickName(userInfo.getNickName()); - scimUser.setTitle(userInfo.getJobTitle()); - scimUser.setUserType(userInfo.getUserType()); - - ScimEnterprise enterprise = new ScimEnterprise(); - enterprise.setDepartmentId(userInfo.getDepartmentId()); - enterprise.setDepartment(userInfo.getDepartment()); - enterprise.setCostCenter(userInfo.getCostCenter()); - enterprise.setManager(new ScimManager(userInfo.getManagerId(),userInfo.getManager())); - enterprise.setDivision(userInfo.getDivision()); - enterprise.setEmployeeNumber(userInfo.getEmployeeNumber()); - scimUser.setEnterprise(enterprise); - - List organizationsList=new ArrayList(); - organizationsList.add(userInfo.getDepartmentId()); - scimUser.setOrganization(organizationsList); - - List groupsList=new ArrayList(); - List groups = new ArrayList(); - for(Groups group : groupsService.queryByUserId(userInfo.getId())){ - groupsList.add(group.getId()); - groups.add(new ScimGroupRef(group.getId(),group.getGroupName())); - - } - scimUser.setGroup(groupsList); - scimUser.setGroups(groups); - - scimUser.setTimezone(userInfo.getTimeZone()); - scimUser.setLocale(userInfo.getLocale()); - scimUser.setPreferredLanguage(userInfo.getPreferredLanguage()); - scimUser.setActive(userInfo.getStatus() == ConstsStatus.ACTIVE); - - List emails = new ArrayList(); - if(StringUtils.isNotBlank(userInfo.getEmail())){ - emails.add(new ScimUserEmail(userInfo.getEmail(),UserEmailType.OTHER,true)); - } - if(StringUtils.isNotBlank(userInfo.getWorkEmail())){ - emails.add(new ScimUserEmail(userInfo.getEmail(),UserEmailType.WORK,false)); - } - if(StringUtils.isNotBlank(userInfo.getHomeEmail())){ - emails.add(new ScimUserEmail(userInfo.getEmail(),UserEmailType.HOME,false)); - } - - if(emails.size() > 0) { - scimUser.setEmails(emails); - } - - List phoneNumbers = new ArrayList(); - if(StringUtils.isNotBlank(userInfo.getMobile())){ - phoneNumbers.add(new ScimUserPhoneNumber(userInfo.getMobile(),UserPhoneNumberType.MOBILE,true)); - } - if(StringUtils.isNotBlank(userInfo.getWorkPhoneNumber())){ - phoneNumbers.add(new ScimUserPhoneNumber(userInfo.getWorkPhoneNumber(),UserPhoneNumberType.WORK,false)); - } - - if(StringUtils.isNotBlank(userInfo.getHomePhoneNumber())){ - phoneNumbers.add(new ScimUserPhoneNumber(userInfo.getHomePhoneNumber(),UserPhoneNumberType.HOME,false)); - } - - if(phoneNumbers.size() > 0) { - scimUser.setPhoneNumbers(phoneNumbers); - } - + ScimUser scimUser =new ScimUser(); + scimUser.setId(userInfo.getId()); + scimUser.setExternalId(userInfo.getId()); + scimUser.setDisplayName(userInfo.getDisplayName()); + scimUser.setUserName(userInfo.getUsername()); + scimUser.setName(new ScimFormattedName( + userInfo.getFormattedName(), + userInfo.getFamilyName(), + userInfo.getGivenName(), + userInfo.getMiddleName(), + userInfo.getHonorificPrefix(), + userInfo.getHonorificSuffix() + ) + ); + scimUser.setNickName(userInfo.getNickName()); + scimUser.setTitle(userInfo.getJobTitle()); + scimUser.setUserType(userInfo.getUserType()); + + ScimEnterprise enterprise = new ScimEnterprise(); + enterprise.setDepartmentId(userInfo.getDepartmentId()); + enterprise.setDepartment(userInfo.getDepartment()); + enterprise.setCostCenter(userInfo.getCostCenter()); + enterprise.setManager(new ScimManager(userInfo.getManagerId(),userInfo.getManager())); + enterprise.setDivision(userInfo.getDivision()); + enterprise.setEmployeeNumber(userInfo.getEmployeeNumber()); + scimUser.setEnterprise(enterprise); + + List organizationsList=new ArrayList(); + organizationsList.add(userInfo.getDepartmentId()); + scimUser.setOrganization(organizationsList); + + List groupsList=new ArrayList(); + List groups = new ArrayList(); + for(Groups group : groupsService.queryByUserId(userInfo.getId())){ + groupsList.add(group.getId()); + groups.add(new ScimGroupRef(group.getId(),group.getGroupName())); + + } + scimUser.setGroup(groupsList); + scimUser.setGroups(groups); + + scimUser.setTimezone(userInfo.getTimeZone()); + scimUser.setLocale(userInfo.getLocale()); + scimUser.setPreferredLanguage(userInfo.getPreferredLanguage()); + scimUser.setActive(userInfo.getStatus() == ConstsStatus.ACTIVE); + + List emails = new ArrayList(); + if(StringUtils.isNotBlank(userInfo.getEmail())){ + emails.add(new ScimUserEmail(userInfo.getEmail(),UserEmailType.OTHER,true)); + } + if(StringUtils.isNotBlank(userInfo.getWorkEmail())){ + emails.add(new ScimUserEmail(userInfo.getEmail(),UserEmailType.WORK,false)); + } + if(StringUtils.isNotBlank(userInfo.getHomeEmail())){ + emails.add(new ScimUserEmail(userInfo.getEmail(),UserEmailType.HOME,false)); + } + + if(emails.size() > 0) { + scimUser.setEmails(emails); + } + + List phoneNumbers = new ArrayList(); + if(StringUtils.isNotBlank(userInfo.getMobile())){ + phoneNumbers.add(new ScimUserPhoneNumber(userInfo.getMobile(),UserPhoneNumberType.MOBILE,true)); + } + if(StringUtils.isNotBlank(userInfo.getWorkPhoneNumber())){ + phoneNumbers.add(new ScimUserPhoneNumber(userInfo.getWorkPhoneNumber(),UserPhoneNumberType.WORK,false)); + } + + if(StringUtils.isNotBlank(userInfo.getHomePhoneNumber())){ + phoneNumbers.add(new ScimUserPhoneNumber(userInfo.getHomePhoneNumber(),UserPhoneNumberType.HOME,false)); + } + + if(phoneNumbers.size() > 0) { + scimUser.setPhoneNumbers(phoneNumbers); + } + ScimMeta meta = new ScimMeta("User"); if(userInfo.getCreatedDate()!= null){ - meta.setCreated(userInfo.getCreatedDate()); + meta.setCreated(userInfo.getCreatedDate()); } if(userInfo.getModifiedDate()!= null){ - meta.setLastModified(userInfo.getModifiedDate()); + meta.setLastModified(userInfo.getModifiedDate()); } scimUser.setMeta(meta); - return scimUser; + return scimUser; } public UserInfo scimUser2UserInfo(ScimUser scimUser) { - UserInfo userInfo = new UserInfo(); - userInfo.setId(scimUser.getId()); - userInfo.setUsername(scimUser.getUserName()); - return userInfo; + UserInfo userInfo = new UserInfo(); + userInfo.setId(scimUser.getId()); + userInfo.setUsername(scimUser.getUserName()); + return userInfo; } } diff --git a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimEnterprise.java b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimEnterprise.java index 0037b9994..e9eb2256c 100644 --- a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimEnterprise.java +++ b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimEnterprise.java @@ -56,12 +56,12 @@ public class ScimEnterprise implements Serializable { } public String getDepartmentId() { - return departmentId; - } - public void setDepartmentId(String departmentId) { - this.departmentId = departmentId; - } - public String getDepartment() { + return departmentId; + } + public void setDepartmentId(String departmentId) { + this.departmentId = departmentId; + } + public String getDepartment() { return department; } public void setDepartment(String department) { diff --git a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimGroupRef.java b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimGroupRef.java index bd45917d9..e452c5dc1 100644 --- a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimGroupRef.java +++ b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimGroupRef.java @@ -24,13 +24,13 @@ public class ScimGroupRef extends ScimMultiValuedAttribute{ */ private static final long serialVersionUID = 7069453283024141999L; - public ScimGroupRef() { - super(); - } + public ScimGroupRef() { + super(); + } - public ScimGroupRef(String value,String display) { - super(); - this.value = value; - this.display = display; - } + public ScimGroupRef(String value,String display) { + super(); + this.value = value; + this.display = display; + } } diff --git a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimMemberRef.java b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimMemberRef.java index 5c9b7df29..190f3a916 100644 --- a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimMemberRef.java +++ b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimMemberRef.java @@ -28,7 +28,7 @@ public class ScimMemberRef extends ScimMultiValuedAttribute{ } public ScimMemberRef(String display,String value) { - this.display = display; - this.value = value; + this.display = display; + this.value = value; } } diff --git a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimMeta.java b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimMeta.java index bb570b93a..bb4d4a0b3 100644 --- a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimMeta.java +++ b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimMeta.java @@ -92,8 +92,8 @@ public class ScimMeta implements Serializable { } public ScimMeta(String resourceType) { - this.resourceType = resourceType; - this.version = "1.0"; + this.resourceType = resourceType; + this.version = "1.0"; } public ScimMeta(String resourceType, Date created, Date lastModified, String location, String version, diff --git a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimOrganization.java b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimOrganization.java index 7ec1436a0..24428ef8b 100644 --- a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimOrganization.java +++ b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimOrganization.java @@ -60,10 +60,10 @@ public class ScimOrganization extends ScimResource{ private String description; // T/IDAC 002—2021 - private String displayName; //name - private long order; //sortOrder - private String parent; //parentId - private String parentCode; //parent code + private String displayName; //name + private long order; //sortOrder + private String parent; //parentId + private String parentCode; //parent code public String getCode() { @@ -188,38 +188,38 @@ public class ScimOrganization extends ScimResource{ public String getDisplayName() { - return displayName; - } + return displayName; + } - public void setDisplayName(String displayName) { - this.displayName = displayName; - } + public void setDisplayName(String displayName) { + this.displayName = displayName; + } - public long getOrder() { - return order; - } + public long getOrder() { + return order; + } - public void setOrder(long order) { - this.order = order; - } + public void setOrder(long order) { + this.order = order; + } - public String getParent() { - return parent; - } + public String getParent() { + return parent; + } - public void setParent(String parent) { - this.parent = parent; - } + public void setParent(String parent) { + this.parent = parent; + } - public String getParentCode() { - return parentCode; - } + public String getParentCode() { + return parentCode; + } - public void setParentCode(String parentCode) { - this.parentCode = parentCode; - } + public void setParentCode(String parentCode) { + this.parentCode = parentCode; + } - public ScimOrganization() { + public ScimOrganization() { schemas =new HashSet(); schemas.add(SCHEMA); diff --git a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimParameters.java b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimParameters.java index 06f3dc48e..b66b7d269 100644 --- a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimParameters.java +++ b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimParameters.java @@ -20,83 +20,83 @@ package org.dromara.maxkey.web.apis.identity.scim.resources; import org.dromara.maxkey.web.apis.identity.scim.ScimServiceProviderConfigController; public class ScimParameters { - int startIndex = 1; - int count = ScimServiceProviderConfigController.MAX_RESULTS; - String filter; - String sortBy; - String sortOrder = "ascending"; - String attributes; + int startIndex = 1; + int count = ScimServiceProviderConfigController.MAX_RESULTS; + String filter; + String sortBy; + String sortOrder = "ascending"; + String attributes; - public ScimParameters() { - } + public ScimParameters() { + } - public void parse() { - if(startIndex == -1) { - count = ScimServiceProviderConfigController.MAX_RESULTS_LIMIT; - } - - if(startIndex <= 0) { - startIndex = 1; - } - - if(count > ScimServiceProviderConfigController.MAX_RESULTS - && count != ScimServiceProviderConfigController.MAX_RESULTS_LIMIT) { - count = ScimServiceProviderConfigController.MAX_RESULTS; - } - } - - public int getCount() { - return count; - } + public void parse() { + if(startIndex == -1) { + count = ScimServiceProviderConfigController.MAX_RESULTS_LIMIT; + } + + if(startIndex <= 0) { + startIndex = 1; + } + + if(count > ScimServiceProviderConfigController.MAX_RESULTS + && count != ScimServiceProviderConfigController.MAX_RESULTS_LIMIT) { + count = ScimServiceProviderConfigController.MAX_RESULTS; + } + } + + public int getCount() { + return count; + } - public void setCount(int count) { - this.count = count; - } + public void setCount(int count) { + this.count = count; + } - public int getStartIndex() { - return startIndex; - } + public int getStartIndex() { + return startIndex; + } - public void setStartIndex(int startIndex) { - this.startIndex = startIndex; - } + public void setStartIndex(int startIndex) { + this.startIndex = startIndex; + } - public String getfilter() { - return filter; - } + public String getfilter() { + return filter; + } - public void setfilter(String filter) { - this.filter = filter; - } + public void setfilter(String filter) { + this.filter = filter; + } - public String getSortBy() { - return sortBy; - } + public String getSortBy() { + return sortBy; + } - public void setSortBy(String sortBy) { - this.sortBy = sortBy; - } + public void setSortBy(String sortBy) { + this.sortBy = sortBy; + } - public String getSortOrder() { - return sortOrder; - } + public String getSortOrder() { + return sortOrder; + } - public void setSortOrder(String sortOrder) { - this.sortOrder = sortOrder; - } + public void setSortOrder(String sortOrder) { + this.sortOrder = sortOrder; + } - public String getAttributes() { - return attributes; - } + public String getAttributes() { + return attributes; + } - public void setAttributes(String attributes) { - this.attributes = attributes; - } + public void setAttributes(String attributes) { + this.attributes = attributes; + } - @Override - public String toString() { - return "ScimParameters [count=" + count + ", startIndex=" + startIndex + ", filter=" + filter + ", sortBy=" - + sortBy + ", sortOrder=" + sortOrder + ", attributes=" + attributes + "]"; - } + @Override + public String toString() { + return "ScimParameters [count=" + count + ", startIndex=" + startIndex + ", filter=" + filter + ", sortBy=" + + sortBy + ", sortOrder=" + sortOrder + ", attributes=" + attributes + "]"; + } } diff --git a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimSearchResult.java b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimSearchResult.java index 2275c0cf5..c8520add8 100644 --- a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimSearchResult.java +++ b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimSearchResult.java @@ -27,14 +27,14 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class ScimSearchResult { - public static class Constants{ - public static final String FILTER = "filter"; - public static final String SORTBY = "sortBy"; - public static final String COUNT = "count"; - public static final String STARTINDEX = "startIndex"; - - - } + public static class Constants{ + public static final String FILTER = "filter"; + public static final String SORTBY = "sortBy"; + public static final String COUNT = "count"; + public static final String STARTINDEX = "startIndex"; + + + } public static final String SCHEMA = "urn:ietf:params:scim:api:messages:2.0:ListResponse"; public static final int MAX_RESULTS = 100; private long totalResults; diff --git a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimUser.java b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimUser.java index 236269107..5ed024d1f 100644 --- a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimUser.java +++ b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimUser.java @@ -208,25 +208,25 @@ public class ScimUser extends ScimResource{ public ScimEnterprise getEnterprise() { - return enterprise; - } - public void setEnterprise(ScimEnterprise enterprise) { - this.enterprise = enterprise; - } + return enterprise; + } + public void setEnterprise(ScimEnterprise enterprise) { + this.enterprise = enterprise; + } - public List getOrganization() { - return organization; - } - public void setOrganization(List organization) { - this.organization = organization; - } - public List getGroup() { - return group; - } - public void setGroup(List group) { - this.group = group; - } - public ScimUser() { + public List getOrganization() { + return organization; + } + public void setOrganization(List organization) { + this.organization = organization; + } + public List getGroup() { + return group; + } + public void setGroup(List group) { + this.group = group; + } + public ScimUser() { schemas =new HashSet(); schemas.add(SCHEMA); } diff --git a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimUserOrganization.java b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimUserOrganization.java index c11e4c584..54aaa4ace 100644 --- a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimUserOrganization.java +++ b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimUserOrganization.java @@ -27,10 +27,10 @@ public class ScimUserOrganization extends ScimMultiValuedAttribute implements Se private static final long serialVersionUID = 3201987266085144715L; public ScimUserOrganization() { - super(); - } + super(); + } - public ScimUserOrganization(String value, String display, boolean primary) { + public ScimUserOrganization(String value, String display, boolean primary) { super(); this.value = value; this.display = display; diff --git a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimUserPhoneNumber.java b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimUserPhoneNumber.java index 1cc0e2dc6..c8eb73d91 100644 --- a/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimUserPhoneNumber.java +++ b/maxkey-web-apis/maxkey-web-api-scim/src/main/java/org/dromara/maxkey/web/apis/identity/scim/resources/ScimUserPhoneNumber.java @@ -37,10 +37,10 @@ public class ScimUserPhoneNumber extends ScimMultiValuedAttribute implements Ser } public ScimUserPhoneNumber() { - super(); - } + super(); + } - public ScimUserPhoneNumber(String value, String type, boolean primary) { + public ScimUserPhoneNumber(String value, String type, boolean primary) { super(); this.value = value; this.type = type; diff --git a/maxkey-webs/maxkey-gataway/src/main/java/org/dromara/maxkey/gateway/MaxKeyGatewayApplication.java b/maxkey-webs/maxkey-gataway/src/main/java/org/dromara/maxkey/gateway/MaxKeyGatewayApplication.java index 3ff2fdb9c..250a28ebd 100644 --- a/maxkey-webs/maxkey-gataway/src/main/java/org/dromara/maxkey/gateway/MaxKeyGatewayApplication.java +++ b/maxkey-webs/maxkey-gataway/src/main/java/org/dromara/maxkey/gateway/MaxKeyGatewayApplication.java @@ -31,7 +31,7 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @EnableDiscoveryClient public class MaxKeyGatewayApplication { - public static void main(String[] args) { - SpringApplication.run(MaxKeyGatewayApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(MaxKeyGatewayApplication.class, args); + } } diff --git a/maxkey-webs/maxkey-gataway/src/main/java/org/dromara/maxkey/gateway/filter/AuthAndLogFilter.java b/maxkey-webs/maxkey-gataway/src/main/java/org/dromara/maxkey/gateway/filter/AuthAndLogFilter.java index a5a968603..7401df55a 100644 --- a/maxkey-webs/maxkey-gataway/src/main/java/org/dromara/maxkey/gateway/filter/AuthAndLogFilter.java +++ b/maxkey-webs/maxkey-gataway/src/main/java/org/dromara/maxkey/gateway/filter/AuthAndLogFilter.java @@ -29,16 +29,16 @@ import reactor.core.publisher.Mono; @Component public class AuthAndLogFilter implements GlobalFilter, Ordered { - private final Logger logger = LoggerFactory.getLogger(getClass()); + private final Logger logger = LoggerFactory.getLogger(getClass()); - @Override - public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { - return chain.filter(exchange.mutate().build()); - } + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + return chain.filter(exchange.mutate().build()); + } - @Override - public int getOrder() { - logger.trace(" -20"); - return -20; - } + @Override + public int getOrder() { + logger.trace(" -20"); + return -20; + } } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/MaxKeyApplication.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/MaxKeyApplication.java index 70c3f04f8..d0f46f872 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/MaxKeyApplication.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/MaxKeyApplication.java @@ -41,7 +41,7 @@ public class MaxKeyApplication extends SpringBootServletInitializer { * @param args start parameter */ public static void main(String[] args) { - _logger.info("Start MaxKey Application ..."); + _logger.info("Start MaxKey Application ..."); ProductEnvironment.listEnvVars(); ConfigurableApplicationContext applicationContext = SpringApplication.run(MaxKeyApplication.class, args); diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyConfig.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyConfig.java index aaeaab5ec..9e0547f3f 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyConfig.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyConfig.java @@ -96,17 +96,17 @@ public class MaxKeyConfig { JdbcTemplate jdbcTemplate, MailOtpAuthnService otpAuthnService, CnfLdapContextService ldapContextService) { - LdapAuthenticationRealmService ldapRealmService = new LdapAuthenticationRealmService(ldapContextService); + LdapAuthenticationRealmService ldapRealmService = new LdapAuthenticationRealmService(ldapContextService); return new JdbcAuthenticationRealm( - passwordEncoder, - passwordPolicyValidatorService, - loginService, - historyLoginService, - userInfoService, - ipLocationParser, - jdbcTemplate, - ldapRealmService - ); + passwordEncoder, + passwordPolicyValidatorService, + loginService, + historyLoginService, + userInfoService, + ipLocationParser, + jdbcTemplate, + ldapRealmService + ); } @Bean @@ -115,8 +115,8 @@ public class MaxKeyConfig { int digits, @Value("${maxkey.otp.policy.period:30}") int period) { - TimeBasedOtpAuthn tfaOtpAuthn = new TimeBasedOtpAuthn(digits , period); - logger.debug("TimeBasedOtpAuthn inited."); + TimeBasedOtpAuthn tfaOtpAuthn = new TimeBasedOtpAuthn(digits , period); + logger.debug("TimeBasedOtpAuthn inited."); return tfaOtpAuthn; } @@ -206,17 +206,17 @@ public class MaxKeyConfig { Scheduler scheduler, ApplicationConfig applicationConfig, SessionManager sessionManager) throws SchedulerException { - if(applicationConfig.isPersistenceInmemory()) { - new ScheduleAdapterBuilder() - .setScheduler(scheduler) - .setCron("0 0/10 * * * ?") - .setJobClass(SessionListenerAdapter.class) - .setJobData("sessionManager",sessionManager) - .setJobData("category", SessionCategory.SIGN) - .build(); - logger.debug("Session ListenerAdapter inited ."); - } - return "sessionListenerAdapter"; + if(applicationConfig.isPersistenceInmemory()) { + new ScheduleAdapterBuilder() + .setScheduler(scheduler) + .setCron("0 0/10 * * * ?") + .setJobClass(SessionListenerAdapter.class) + .setJobData("sessionManager",sessionManager) + .setJobData("category", SessionCategory.SIGN) + .build(); + logger.debug("Session ListenerAdapter inited ."); + } + return "sessionListenerAdapter"; } } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyMvcConfig.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyMvcConfig.java index fbdd4124e..018831d7c 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyMvcConfig.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyMvcConfig.java @@ -50,7 +50,7 @@ public class MaxKeyMvcConfig implements WebMvcConfigurer { private String httpHeaderName; @Autowired - ApplicationConfig applicationConfig; + ApplicationConfig applicationConfig; @Autowired AbstractAuthenticationProvider authenticationProvider ; @@ -74,8 +74,8 @@ public class MaxKeyMvcConfig implements WebMvcConfigurer { logger.debug("add Http Kerberos Entry Point"); registry.addInterceptor(new HttpKerberosEntryPoint( - authenticationProvider,kerberosService,applicationConfig,true)) - .addPathPatterns("/login"); + authenticationProvider,kerberosService,applicationConfig,true)) + .addPathPatterns("/login"); if(httpHeaderEnable) { @@ -102,9 +102,9 @@ public class MaxKeyMvcConfig implements WebMvcConfigurer { .addPathPatterns("/socialsignon/**") .addPathPatterns("/authz/credential/**") .addPathPatterns("/authz/oauth/v20/approval_confirm/**") - .addPathPatterns("/authz/oauth/v20/authorize/approval/**") - .addPathPatterns("/logon/oauth20/bind/**") - .addPathPatterns("/logout") + .addPathPatterns("/authz/oauth/v20/authorize/approval/**") + .addPathPatterns("/logon/oauth20/bind/**") + .addPathPatterns("/logout") .addPathPatterns("/logout/**") .addPathPatterns("/authz/refused") .excludePathPatterns("/logon/oauth20/**/**") diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/access/contorller/LoginSessionController.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/access/contorller/LoginSessionController.java index 26cdcf153..5fdb56eec 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/access/contorller/LoginSessionController.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/access/contorller/LoginSessionController.java @@ -68,14 +68,14 @@ public class LoginSessionController { */ @GetMapping(value = { "/fetch" }) public Message> fetch( - @ModelAttribute("historyLogin") HistoryLogin historyLogin, - @CurrentUser UserInfo currentUser) { + @ModelAttribute("historyLogin") HistoryLogin historyLogin, + @CurrentUser UserInfo currentUser) { logger.debug("history/session/fetch {}" , historyLogin); historyLogin.setUserId(currentUser.getId()); historyLogin.setInstId(currentUser.getInstId()); return new Message>( - historyLoginService.queryOnlineSession(historyLogin) - ); + historyLoginService.queryOnlineSession(historyLogin) + ); } @DeleteMapping(value="/terminate") @@ -90,9 +90,9 @@ public class LoginSessionController { } sessionManager.terminate( - sessionId, - currentUser.getId(), - currentUser.getUsername()); + sessionId, + currentUser.getId(), + currentUser.getUsername()); } isTerminated = true; }catch(Exception e) { @@ -100,9 +100,9 @@ public class LoginSessionController { } if(isTerminated) { - return new Message<>(Message.SUCCESS); + return new Message<>(Message.SUCCESS); } else { - return new Message<>(Message.ERROR); + return new Message<>(Message.ERROR); } } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/AppListController.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/AppListController.java index e0a64656f..a8692890b 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/AppListController.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/AppListController.java @@ -66,7 +66,7 @@ public class AppListController { * @return */ @GetMapping(value = { "/appList" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message> appList( + public Message> appList( @RequestParam(value = "gridList", required = false) String gridList, @CurrentUser UserInfo currentUser) { userInfoService.updateGridList(gridList,currentUser); @@ -75,39 +75,39 @@ public class AppListController { userApps.setInstId(currentUser.getInstId()); List appList = appsService.queryMyApps(userApps); for (UserApps app : appList) { - app.transIconBase64(); + app.transIconBase64(); } return new Message<>(appList); } @GetMapping(value = { "/account/get" }) - public Message getAccount( - @RequestParam("credential") String credential, - @RequestParam("appId") String appId, - @CurrentUser UserInfo currentUser) { + public Message getAccount( + @RequestParam("credential") String credential, + @RequestParam("appId") String appId, + @CurrentUser UserInfo currentUser) { Accounts account = null ; if (credential.equalsIgnoreCase(Apps.CREDENTIALS.USER_DEFINED)) { - account = accountsService.get(Query.builder().eq("appId", appId).eq("userid", currentUser.getId())); - account.setRelatedPassword( - PasswordReciprocal.getInstance().decoder( - account.getRelatedPassword())); + account = accountsService.get(Query.builder().eq("appId", appId).eq("userid", currentUser.getId())); + account.setRelatedPassword( + PasswordReciprocal.getInstance().decoder( + account.getRelatedPassword())); }else { - account = new Accounts(); - account.setAppId(appId); - account.setUserId(currentUser.getId()); - account.setUsername(currentUser.getUsername()); - account.setDisplayName(currentUser.getDisplayName()); + account = new Accounts(); + account.setAppId(appId); + account.setUserId(currentUser.getId()); + account.setUsername(currentUser.getUsername()); + account.setDisplayName(currentUser.getDisplayName()); } return new Message<>(account); } @PutMapping(value = { "/account/update" }) - public Message updateAccount( - @RequestParam("credential") String credential, - @ModelAttribute Accounts account, + public Message updateAccount( + @RequestParam("credential") String credential, + @ModelAttribute Accounts account, @CurrentUser UserInfo currentUser) { Accounts appUsers = new Accounts(); if (credential.equalsIgnoreCase(Apps.CREDENTIALS.USER_DEFINED)) { @@ -120,14 +120,14 @@ public class AppListController { appUsers.setDisplayName(currentUser.getDisplayName()); appUsers.setRelatedPassword( - PasswordReciprocal.getInstance().encode(account.getRelatedPassword())); + PasswordReciprocal.getInstance().encode(account.getRelatedPassword())); appUsers.setInstId(currentUser.getInstId()); appUsers.setStatus(ConstsStatus.ACTIVE); accountsService.insert(appUsers); } else { appUsers.setRelatedUsername(account.getRelatedUsername()); appUsers.setRelatedPassword( - PasswordReciprocal.getInstance().encode(account.getRelatedPassword())); + PasswordReciprocal.getInstance().encode(account.getRelatedPassword())); accountsService.update(appUsers); } } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/ChangePasswodController.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/ChangePasswodController.java index 98190e987..acb99e5b7 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/ChangePasswodController.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/ChangePasswodController.java @@ -39,49 +39,49 @@ import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value={"/users"}) public class ChangePasswodController { - static final Logger logger = LoggerFactory.getLogger(ChangePasswodController.class); + static final Logger logger = LoggerFactory.getLogger(ChangePasswodController.class); - @Autowired - UserInfoService userInfoService; + @Autowired + UserInfoService userInfoService; - @Autowired - HistorySystemLogsService systemLog; + @Autowired + HistorySystemLogsService systemLog; - @Autowired - CnfPasswordPolicyService passwordPolicyService; + @Autowired + CnfPasswordPolicyService passwordPolicyService; - @GetMapping(value={"/passwordpolicy"}) - public Message passwordpolicy(@CurrentUser UserInfo currentUser){ - CnfPasswordPolicy passwordPolicy = passwordPolicyService.get(currentUser.getInstId()); - //构建密码强度说明 - passwordPolicyService.buildTipMessage(passwordPolicy); - return new Message<>(passwordPolicy); - } + @GetMapping(value={"/passwordpolicy"}) + public Message passwordpolicy(@CurrentUser UserInfo currentUser){ + CnfPasswordPolicy passwordPolicy = passwordPolicyService.get(currentUser.getInstId()); + //构建密码强度说明 + passwordPolicyService.buildTipMessage(passwordPolicy); + return new Message<>(passwordPolicy); + } - @PutMapping(value = { "/changePassword" }) - public Message changePasswod( - @RequestBody ChangePassword changePassword, - @CurrentUser UserInfo currentUser) { - if(!currentUser.getId().equals(changePassword.getId())){ - return null; - } - changePassword.setUserId(currentUser.getId()); - changePassword.setUsername(currentUser.getUsername()); - changePassword.setInstId(currentUser.getInstId()); - changePassword.setPasswordSetType(ConstsPasswordSetType.PASSWORD_NORMAL); - if(userInfoService.changePassword(changePassword)) { - systemLog.insert( - ConstsEntryType.USERINFO, - changePassword, - ConstsAct.CHANGE_PASSWORD, - ConstsActResult.SUCCESS, - currentUser); - return new Message<>(); - }else { - String message = (String) WebContext.getAttribute(PasswordPolicyValidatorServiceImpl.PASSWORD_POLICY_VALIDATE_RESULT); - logger.info("-message: {}",message); - return new Message<>(Message.ERROR,message); - } - } + @PutMapping(value = { "/changePassword" }) + public Message changePasswod( + @RequestBody ChangePassword changePassword, + @CurrentUser UserInfo currentUser) { + if(!currentUser.getId().equals(changePassword.getId())){ + return null; + } + changePassword.setUserId(currentUser.getId()); + changePassword.setUsername(currentUser.getUsername()); + changePassword.setInstId(currentUser.getInstId()); + changePassword.setPasswordSetType(ConstsPasswordSetType.PASSWORD_NORMAL); + if(userInfoService.changePassword(changePassword)) { + systemLog.insert( + ConstsEntryType.USERINFO, + changePassword, + ConstsAct.CHANGE_PASSWORD, + ConstsActResult.SUCCESS, + currentUser); + return new Message<>(); + }else { + String message = (String) WebContext.getAttribute(PasswordPolicyValidatorServiceImpl.PASSWORD_POLICY_VALIDATE_RESULT); + logger.info("-message: {}",message); + return new Message<>(Message.ERROR,message); + } + } } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/ForgotPasswordContorller.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/ForgotPasswordContorller.java index 3c61a674a..02c805ecf 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/ForgotPasswordContorller.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/ForgotPasswordContorller.java @@ -50,20 +50,20 @@ public class ForgotPasswordContorller { EmailConfig emailConfig; public class ForgotType{ - public static final int NOTFOUND = 1; - public static final int EMAIL = 2; - public static final int MOBILE = 3; - public static final int CAPTCHAERROR = 4; + public static final int NOTFOUND = 1; + public static final int EMAIL = 2; + public static final int MOBILE = 3; + public static final int CAPTCHAERROR = 4; } public class PasswordResetResult{ - public static final int SUCCESS = 1; - public static final int CAPTCHAERROR = 2; - public static final int PASSWORDERROR = 3; + public static final int SUCCESS = 1; + public static final int CAPTCHAERROR = 2; + public static final int PASSWORDERROR = 3; } @Autowired - AuthTokenService authTokenService; + AuthTokenService authTokenService; @Autowired UserInfoService userInfoService; @@ -75,129 +75,129 @@ public class ForgotPasswordContorller { SmsOtpAuthnService smsOtpAuthnService; @Autowired - HistorySystemLogsService historySystemLogsService; + HistorySystemLogsService historySystemLogsService; - @Autowired - CnfPasswordPolicyService passwordPolicyService; + @Autowired + CnfPasswordPolicyService passwordPolicyService; - @GetMapping(value={"/passwordpolicy"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message passwordpolicy(){ - CnfPasswordPolicy passwordPolicy = passwordPolicyService.get(WebContext.getInst().getId()); - //构建密码强度说明 - passwordPolicyService.buildTipMessage(passwordPolicy); - return new Message<>(passwordPolicy); - } + @GetMapping(value={"/passwordpolicy"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message passwordpolicy(){ + CnfPasswordPolicy passwordPolicy = passwordPolicyService.get(WebContext.getInst().getId()); + //构建密码强度说明 + passwordPolicyService.buildTipMessage(passwordPolicy); + return new Message<>(passwordPolicy); + } - @GetMapping(value = { "/validateCaptcha" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message validateCaptcha( - @RequestParam String userId, - @RequestParam String state, - @RequestParam String captcha, - @RequestParam String otpCaptcha) { - logger.debug("forgotpassword /forgotpassword/validateCaptcha."); - logger.debug(" userId {}: " ,userId); - UserInfo userInfo = userInfoService.get(userId); - if(userInfo != null) { - AbstractOtpAuthn smsOtpAuthn = smsOtpAuthnService.getByInstId(userInfo.getInstId()); - if (otpCaptcha == null || !smsOtpAuthn.validate(userInfo, otpCaptcha)) { - return new Message<>(Message.FAIL); - } - return new Message<>(Message.SUCCESS); - } - return new Message<>(Message.FAIL); - } + @GetMapping(value = { "/validateCaptcha" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message validateCaptcha( + @RequestParam String userId, + @RequestParam String state, + @RequestParam String captcha, + @RequestParam String otpCaptcha) { + logger.debug("forgotpassword /forgotpassword/validateCaptcha."); + logger.debug(" userId {}: " ,userId); + UserInfo userInfo = userInfoService.get(userId); + if(userInfo != null) { + AbstractOtpAuthn smsOtpAuthn = smsOtpAuthnService.getByInstId(userInfo.getInstId()); + if (otpCaptcha == null || !smsOtpAuthn.validate(userInfo, otpCaptcha)) { + return new Message<>(Message.FAIL); + } + return new Message<>(Message.SUCCESS); + } + return new Message<>(Message.FAIL); + } - @GetMapping(value = { "/produceOtp" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + @GetMapping(value = { "/produceOtp" }, produces = {MediaType.APPLICATION_JSON_VALUE}) public Message produceOtp( - @RequestParam String mobile, - @RequestParam String state, - @RequestParam String captcha) { + @RequestParam String mobile, + @RequestParam String state, + @RequestParam String captcha) { logger.debug("forgotpassword /forgotpassword/produceOtp."); logger.debug(" Mobile {}: " ,mobile); if (!authTokenService.validateCaptcha(state,captcha)) { - logger.debug("login captcha valid error."); - return new Message<>(Message.FAIL); + logger.debug("login captcha valid error."); + return new Message<>(Message.FAIL); } - ChangePassword change = null; - logger.debug("Mobile Regex matches {}",ConstsRegex.MOBILE_PATTERN.matcher(mobile).matches()); - if(StringUtils.isNotBlank(mobile) && ConstsRegex.MOBILE_PATTERN.matcher(mobile).matches()) { - UserInfo userInfo = userInfoService.findByEmailMobile(mobile); - if(userInfo != null) { - change = new ChangePassword(userInfo); - change.clearPassword(); - AbstractOtpAuthn smsOtpAuthn = smsOtpAuthnService.getByInstId(userInfo.getInstId()); - smsOtpAuthn.produce(userInfo); - return new Message<>(change); - } + ChangePassword change = null; + logger.debug("Mobile Regex matches {}",ConstsRegex.MOBILE_PATTERN.matcher(mobile).matches()); + if(StringUtils.isNotBlank(mobile) && ConstsRegex.MOBILE_PATTERN.matcher(mobile).matches()) { + UserInfo userInfo = userInfoService.findByEmailMobile(mobile); + if(userInfo != null) { + change = new ChangePassword(userInfo); + change.clearPassword(); + AbstractOtpAuthn smsOtpAuthn = smsOtpAuthnService.getByInstId(userInfo.getInstId()); + smsOtpAuthn.produce(userInfo); + return new Message<>(change); + } } return new Message<>(Message.FAIL); } - @GetMapping(value = { "/produceEmailOtp" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + @GetMapping(value = { "/produceEmailOtp" }, produces = {MediaType.APPLICATION_JSON_VALUE}) public Message produceEmailOtp( - @RequestParam String email, - @RequestParam String state, - @RequestParam String captcha) { + @RequestParam String email, + @RequestParam String state, + @RequestParam String captcha) { logger.debug("/forgotpassword/produceEmailOtp Email {} : " , email); if (!authTokenService.validateCaptcha(state,captcha)) { - logger.debug("captcha valid error."); - return new Message<>(Message.FAIL); + logger.debug("captcha valid error."); + return new Message<>(Message.FAIL); } - ChangePassword change = null; - if(StringUtils.isNotBlank(email) && ConstsRegex.EMAIL_PATTERN.matcher(email).matches()) { - UserInfo userInfo = userInfoService.findByEmailMobile(email); - if(userInfo != null) { - change = new ChangePassword(userInfo); - change.clearPassword(); - AbstractOtpAuthn mailOtpAuthn = mailOtpAuthnService.getMailOtpAuthn(userInfo.getInstId()); - mailOtpAuthn.produce(userInfo); - return new Message<>(change); - } - } + ChangePassword change = null; + if(StringUtils.isNotBlank(email) && ConstsRegex.EMAIL_PATTERN.matcher(email).matches()) { + UserInfo userInfo = userInfoService.findByEmailMobile(email); + if(userInfo != null) { + change = new ChangePassword(userInfo); + change.clearPassword(); + AbstractOtpAuthn mailOtpAuthn = mailOtpAuthnService.getMailOtpAuthn(userInfo.getInstId()); + mailOtpAuthn.produce(userInfo); + return new Message<>(change); + } + } return new Message<>(Message.FAIL); } @GetMapping({ "/setpassword" }) public Message setPassWord( - @ModelAttribute ChangePassword changePassword, - @RequestParam String forgotType, + @ModelAttribute ChangePassword changePassword, + @RequestParam String forgotType, @RequestParam String otpCaptcha, @RequestParam String state) { logger.debug("forgotPassword /forgotpassword/setpassword."); if (StringUtils.isNotBlank(changePassword.getPassword() ) - && changePassword.getPassword().equals(changePassword.getConfirmPassword())) { + && changePassword.getPassword().equals(changePassword.getConfirmPassword())) { UserInfo loadedUserInfo = userInfoService.get(changePassword.getUserId()); if(loadedUserInfo != null) { - AbstractOtpAuthn smsOtpAuthn = smsOtpAuthnService.getByInstId(loadedUserInfo.getInstId()); - AbstractOtpAuthn mailOtpAuthn = mailOtpAuthnService.getMailOtpAuthn(loadedUserInfo.getInstId()); - if ( - (forgotType.equalsIgnoreCase("email") - && mailOtpAuthn !=null - && mailOtpAuthn.validate(loadedUserInfo, otpCaptcha)) - || - (forgotType.equalsIgnoreCase("mobile") - && smsOtpAuthn !=null - && smsOtpAuthn.validate(loadedUserInfo, otpCaptcha)) - ) { - - if(userInfoService.changePassword(changePassword,true)) { - historySystemLogsService.insert( - ConstsEntryType.USERINFO, - changePassword, - ConstsAct.FORGOT_PASSWORD, - ConstsActResult.SUCCESS, - loadedUserInfo); - return new Message<>(Message.SUCCESS); - }else { - return new Message<>(Message.FAIL); - } - } else { - return new Message<>(Message.FAIL); - } - } + AbstractOtpAuthn smsOtpAuthn = smsOtpAuthnService.getByInstId(loadedUserInfo.getInstId()); + AbstractOtpAuthn mailOtpAuthn = mailOtpAuthnService.getMailOtpAuthn(loadedUserInfo.getInstId()); + if ( + (forgotType.equalsIgnoreCase("email") + && mailOtpAuthn !=null + && mailOtpAuthn.validate(loadedUserInfo, otpCaptcha)) + || + (forgotType.equalsIgnoreCase("mobile") + && smsOtpAuthn !=null + && smsOtpAuthn.validate(loadedUserInfo, otpCaptcha)) + ) { + + if(userInfoService.changePassword(changePassword,true)) { + historySystemLogsService.insert( + ConstsEntryType.USERINFO, + changePassword, + ConstsAct.FORGOT_PASSWORD, + ConstsActResult.SUCCESS, + loadedUserInfo); + return new Message<>(Message.SUCCESS); + }else { + return new Message<>(Message.FAIL); + } + } else { + return new Message<>(Message.FAIL); + } + } } return new Message<>(Message.FAIL); } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/LoginEntryPoint.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/LoginEntryPoint.java index 50ef20ce8..242e866ae 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/LoginEntryPoint.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/LoginEntryPoint.java @@ -66,205 +66,205 @@ import jakarta.servlet.http.HttpServletResponse; @RestController @RequestMapping(value = "/login") public class LoginEntryPoint { - private static Logger logger = LoggerFactory.getLogger(LoginEntryPoint.class); + private static Logger logger = LoggerFactory.getLogger(LoginEntryPoint.class); - @Autowired - AuthTokenService authTokenService; + @Autowired + AuthTokenService authTokenService; - @Autowired - ApplicationConfig applicationConfig; - - @Autowired + @Autowired + ApplicationConfig applicationConfig; + + @Autowired PasskeyProperties passkeyProperties; - @Autowired - AbstractAuthenticationProvider authenticationProvider ; + @Autowired + AbstractAuthenticationProvider authenticationProvider ; - @Autowired - SocialSignOnProviderService socialSignOnProviderService; + @Autowired + SocialSignOnProviderService socialSignOnProviderService; - @Autowired - SocialsAssociatesService socialsAssociatesService; + @Autowired + SocialsAssociatesService socialsAssociatesService; - @Autowired - KerberosService kerberosService; + @Autowired + KerberosService kerberosService; - @Autowired - UserInfoService userInfoService; + @Autowired + UserInfoService userInfoService; - @Autowired + @Autowired AbstractOtpAuthn tfaOtpAuthn; - @Autowired + @Autowired SmsOtpAuthnService smsAuthnService; - @Autowired - AbstractRemeberMeManager remeberMeManager; + @Autowired + AbstractRemeberMeManager remeberMeManager; - @Autowired - SessionManager sessionManager; + @Autowired + SessionManager sessionManager; - /** - * init login - * @return - */ - @Operation(summary = "登录接口", description = "用户登录地址",method="GET") - @GetMapping(value={"/get"}) - public Message get(@RequestParam(value = "remember_me", required = false) String rememberMeJwt) { - logger.debug("/get."); - //Remember Me - if(authTokenService.validateJwtToken(rememberMeJwt)) { - try { - RemeberMe remeberMe = remeberMeManager.resolve(rememberMeJwt); - if(remeberMe != null) { - LoginCredential credential = new LoginCredential(); - String remeberMeJwt = remeberMeManager.updateRemeberMe(remeberMe); - credential.setUsername(remeberMe.getUsername()); - Authentication authentication = authenticationProvider.authenticate(credential,true); - if(authentication != null) { - AuthJwt authJwt = authTokenService.genAuthJwt(authentication); - authJwt.setRemeberMe(remeberMeJwt); - return new Message(authJwt); - } - } - } catch (ParseException e) { - } - } - //for normal login - HashMap model = new HashMap<>(); - model.put("isRemeberMe", applicationConfig.getLoginConfig().isRemeberMe()); - model.put("isKerberos", applicationConfig.getLoginConfig().isKerberos()); - if(applicationConfig.getLoginConfig().isMfa()) { - model.put("otpType", tfaOtpAuthn.getOtpType()); - model.put("otpInterval", tfaOtpAuthn.getInterval()); - } - model.put("passkeyEnabled", passkeyProperties.isEnabled()); - model.put("passkeyAllowedOrigins", passkeyProperties.getRelyingParty().getAllowedOrigins()); + /** + * init login + * @return + */ + @Operation(summary = "登录接口", description = "用户登录地址",method="GET") + @GetMapping(value={"/get"}) + public Message get(@RequestParam(value = "remember_me", required = false) String rememberMeJwt) { + logger.debug("/get."); + //Remember Me + if(authTokenService.validateJwtToken(rememberMeJwt)) { + try { + RemeberMe remeberMe = remeberMeManager.resolve(rememberMeJwt); + if(remeberMe != null) { + LoginCredential credential = new LoginCredential(); + String remeberMeJwt = remeberMeManager.updateRemeberMe(remeberMe); + credential.setUsername(remeberMe.getUsername()); + Authentication authentication = authenticationProvider.authenticate(credential,true); + if(authentication != null) { + AuthJwt authJwt = authTokenService.genAuthJwt(authentication); + authJwt.setRemeberMe(remeberMeJwt); + return new Message(authJwt); + } + } + } catch (ParseException e) { + } + } + //for normal login + HashMap model = new HashMap<>(); + model.put("isRemeberMe", applicationConfig.getLoginConfig().isRemeberMe()); + model.put("isKerberos", applicationConfig.getLoginConfig().isKerberos()); + if(applicationConfig.getLoginConfig().isMfa()) { + model.put("otpType", tfaOtpAuthn.getOtpType()); + model.put("otpInterval", tfaOtpAuthn.getInterval()); + } + model.put("passkeyEnabled", passkeyProperties.isEnabled()); + model.put("passkeyAllowedOrigins", passkeyProperties.getRelyingParty().getAllowedOrigins()); - if( applicationConfig.getLoginConfig().isKerberos()){ - model.put("userDomainUrlJson", kerberosService.buildKerberosProxys()); - } + if( applicationConfig.getLoginConfig().isKerberos()){ + model.put("userDomainUrlJson", kerberosService.buildKerberosProxys()); + } - Institutions inst = (Institutions)WebContext.getAttribute(WebConstants.CURRENT_INST); - model.put("inst", inst); - if(applicationConfig.getLoginConfig().isCaptcha()) { - model.put("captcha", applicationConfig.getLoginConfig().getCaptchaType()); - }else { - model.put("captcha", "NONE"); - } - model.put("state", authTokenService.genRandomJwt()); - //load Social Sign On Providers - model.put("socials", socialSignOnProviderService.loadSocials(inst.getId())); + Institutions inst = (Institutions)WebContext.getAttribute(WebConstants.CURRENT_INST); + model.put("inst", inst); + if(applicationConfig.getLoginConfig().isCaptcha()) { + model.put("captcha", applicationConfig.getLoginConfig().getCaptchaType()); + }else { + model.put("captcha", "NONE"); + } + model.put("state", authTokenService.genRandomJwt()); + //load Social Sign On Providers + model.put("socials", socialSignOnProviderService.loadSocials(inst.getId())); - return new Message>(model); - } + return new Message>(model); + } - @RequestMapping(value={"/sendotp/{mobile}"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + @RequestMapping(value={"/sendotp/{mobile}"}, produces = {MediaType.APPLICATION_JSON_VALUE}) public Message produceOtp(@PathVariable("mobile") String mobile) { UserInfo userInfo=userInfoService.findByEmailMobile(mobile); if(userInfo != null) { - smsAuthnService.getByInstId(WebContext.getInst().getId()).produce(userInfo); - return new Message(Message.SUCCESS); + smsAuthnService.getByInstId(WebContext.getInst().getId()).produce(userInfo); + return new Message(Message.SUCCESS); } return new Message(Message.FAIL); } - @PostMapping(value={"/signin/bindusersocials"}) - public Message bindusersocials(@RequestBody LoginCredential credential) { - //短信验证码 - String code = credential.getCode(); - //映射社交服务的账号 - String username = credential.getUsername(); - //maxkey存储的手机号 - String mobile = credential.getMobile(); - //社交服务类型 - String authType = credential.getAuthType(); + @PostMapping(value={"/signin/bindusersocials"}) + public Message bindusersocials(@RequestBody LoginCredential credential) { + //短信验证码 + String code = credential.getCode(); + //映射社交服务的账号 + String username = credential.getUsername(); + //maxkey存储的手机号 + String mobile = credential.getMobile(); + //社交服务类型 + String authType = credential.getAuthType(); - UserInfo userInfo = userInfoService.findByEmailMobile(mobile); - //验证码验证是否合法 - if (smsAuthnService.getByInstId(WebContext.getInst().getId()).validate(userInfo,code)) { - //合法进行用户绑定 - SocialsAssociate socialsAssociate = new SocialsAssociate(); - socialsAssociate.setUserId(userInfo.getId()); - socialsAssociate.setUsername(userInfo.getUsername()); - socialsAssociate.setProvider(authType); - socialsAssociate.setSocialUserId(username); - socialsAssociate.setInstId(userInfo.getInstId()); - //插入Maxkey和社交服务的用户映射表 - socialsAssociatesService.insert(socialsAssociate); + UserInfo userInfo = userInfoService.findByEmailMobile(mobile); + //验证码验证是否合法 + if (smsAuthnService.getByInstId(WebContext.getInst().getId()).validate(userInfo,code)) { + //合法进行用户绑定 + SocialsAssociate socialsAssociate = new SocialsAssociate(); + socialsAssociate.setUserId(userInfo.getId()); + socialsAssociate.setUsername(userInfo.getUsername()); + socialsAssociate.setProvider(authType); + socialsAssociate.setSocialUserId(username); + socialsAssociate.setInstId(userInfo.getInstId()); + //插入Maxkey和社交服务的用户映射表 + socialsAssociatesService.insert(socialsAssociate); - //设置完成后,进行登录认证 - LoginCredential loginCredential =new LoginCredential( - socialsAssociate.getUsername(),"", ConstsLoginType.SOCIALSIGNON); + //设置完成后,进行登录认证 + LoginCredential loginCredential =new LoginCredential( + socialsAssociate.getUsername(),"", ConstsLoginType.SOCIALSIGNON); - SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(socialsAssociate.getInstId(),socialsAssociate.getProvider()); + SocialsProvider socialSignOnProvider = socialSignOnProviderService.get(socialsAssociate.getInstId(),socialsAssociate.getProvider()); - loginCredential.setProvider(socialSignOnProvider.getProviderName()); + loginCredential.setProvider(socialSignOnProvider.getProviderName()); - Authentication authentication = authenticationProvider.authenticate(loginCredential,true); + Authentication authentication = authenticationProvider.authenticate(loginCredential,true); - return new Message(authTokenService.genAuthJwt(authentication)); + return new Message(authTokenService.genAuthJwt(authentication)); - } - return new Message(Message.FAIL); - } + } + return new Message(Message.FAIL); + } - /** - * normal - * @param credential - * @return - */ - @Operation(summary = "登录接口", description = "登录接口",method="POST") - @PostMapping(value={"/signin"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message signin( HttpServletRequest request, HttpServletResponse response,@RequestBody LoginCredential credential) { - Message authJwtMessage = new Message<>(Message.FAIL); - if(authTokenService.validateJwtToken(credential.getState())){ - String authType = credential.getAuthType(); - logger.debug("Login AuthN Type {}" , authType); - if (StringUtils.isNotBlank(authType)){ - Authentication authentication = authenticationProvider.authenticate(credential); - if(authentication != null) { - AuthJwt authJwt = authTokenService.genAuthJwt(authentication); - if(StringUtils.isNotBlank(credential.getRemeberMe()) - &&credential.getRemeberMe().equalsIgnoreCase("true")) { - String remeberMe = remeberMeManager.createRemeberMe(authentication, request, response); - authJwt.setRemeberMe(remeberMe); - } - if(WebContext.getAttribute(WebConstants.CURRENT_USER_PASSWORD_SET_TYPE)!=null) { - authJwt.setPasswordSetType( - (Integer)WebContext.getAttribute(WebConstants.CURRENT_USER_PASSWORD_SET_TYPE)); - } - authJwtMessage = new Message<>(authJwt); + /** + * normal + * @param credential + * @return + */ + @Operation(summary = "登录接口", description = "登录接口",method="POST") + @PostMapping(value={"/signin"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message signin( HttpServletRequest request, HttpServletResponse response,@RequestBody LoginCredential credential) { + Message authJwtMessage = new Message<>(Message.FAIL); + if(authTokenService.validateJwtToken(credential.getState())){ + String authType = credential.getAuthType(); + logger.debug("Login AuthN Type {}" , authType); + if (StringUtils.isNotBlank(authType)){ + Authentication authentication = authenticationProvider.authenticate(credential); + if(authentication != null) { + AuthJwt authJwt = authTokenService.genAuthJwt(authentication); + if(StringUtils.isNotBlank(credential.getRemeberMe()) + &&credential.getRemeberMe().equalsIgnoreCase("true")) { + String remeberMe = remeberMeManager.createRemeberMe(authentication, request, response); + authJwt.setRemeberMe(remeberMe); + } + if(WebContext.getAttribute(WebConstants.CURRENT_USER_PASSWORD_SET_TYPE)!=null) { + authJwt.setPasswordSetType( + (Integer)WebContext.getAttribute(WebConstants.CURRENT_USER_PASSWORD_SET_TYPE)); + } + authJwtMessage = new Message<>(authJwt); - }else {//fail - String errorMsg = WebContext.getAttribute(WebConstants.LOGIN_ERROR_SESSION_MESSAGE) == null ? - "" : WebContext.getAttribute(WebConstants.LOGIN_ERROR_SESSION_MESSAGE).toString(); - authJwtMessage.setMessage(errorMsg); - logger.debug("login fail , message {}",errorMsg); - } - }else { - logger.error("Login AuthN type must eq normal , tfa or mobile . "); - } - } - return authJwtMessage; - } + }else {//fail + String errorMsg = WebContext.getAttribute(WebConstants.LOGIN_ERROR_SESSION_MESSAGE) == null ? + "" : WebContext.getAttribute(WebConstants.LOGIN_ERROR_SESSION_MESSAGE).toString(); + authJwtMessage.setMessage(errorMsg); + logger.debug("login fail , message {}",errorMsg); + } + }else { + logger.error("Login AuthN type must eq normal , tfa or mobile . "); + } + } + return authJwtMessage; + } - /** - * for congress - * @param credential - * @return - */ - @PostMapping(value={"/congress"}) - public Message congress( @RequestBody LoginCredential credential) { - if(StringUtils.isNotBlank(credential.getCongress())){ - AuthJwt authJwt = authTokenService.consumeCongress(credential.getCongress()); - if(authJwt != null) { - return new Message<>(authJwt); - } - } - return new Message<>(Message.FAIL); - } + /** + * for congress + * @param credential + * @return + */ + @PostMapping(value={"/congress"}) + public Message congress( @RequestBody LoginCredential credential) { + if(StringUtils.isNotBlank(credential.getCongress())){ + AuthJwt authJwt = authTokenService.consumeCongress(credential.getCongress()); + if(authJwt != null) { + return new Message<>(authJwt); + } + } + return new Message<>(Message.FAIL); + } } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/LoginScanCodeEndpoint.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/LoginScanCodeEndpoint.java index 8c7002674..f32ffd2ef 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/LoginScanCodeEndpoint.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/LoginScanCodeEndpoint.java @@ -59,83 +59,83 @@ import io.swagger.v3.oas.annotations.tags.Tag; @RestController @RequestMapping(value = "/login") public class LoginScanCodeEndpoint { - private static Logger logger = LoggerFactory.getLogger(LoginScanCodeEndpoint.class); + private static Logger logger = LoggerFactory.getLogger(LoginScanCodeEndpoint.class); - @Autowired - AuthTokenService authTokenService; + @Autowired + AuthTokenService authTokenService; - @Autowired - AbstractAuthenticationProvider authenticationProvider ; + @Autowired + AbstractAuthenticationProvider authenticationProvider ; - @Autowired - ScanCodeService scanCodeService; + @Autowired + ScanCodeService scanCodeService; - @Autowired - SessionManager sessionManager; + @Autowired + SessionManager sessionManager; - @Operation(summary = "生成登录扫描二维码", description = "生成登录扫描二维码", method = "GET") - @GetMapping("/genScanCode") - public Message> genScanCode() { - logger.debug("/genScanCode."); - String ticket = scanCodeService.createTicket(); - logger.debug("ticket: {}",ticket); - String encodeTicket = PasswordReciprocal.getInstance().encode(ticket); - BufferedImage bufferedImage = QRCodeUtils.write2BufferedImage(encodeTicket, "gif", 300, 300); - String rqCode = Base64Utils.encodeImage(bufferedImage); - HashMap codeMap = new HashMap<>(); - codeMap.put("rqCode", rqCode); - codeMap.put("ticket", encodeTicket); - return new Message<>(Message.SUCCESS, codeMap); - } + @Operation(summary = "生成登录扫描二维码", description = "生成登录扫描二维码", method = "GET") + @GetMapping("/genScanCode") + public Message> genScanCode() { + logger.debug("/genScanCode."); + String ticket = scanCodeService.createTicket(); + logger.debug("ticket: {}",ticket); + String encodeTicket = PasswordReciprocal.getInstance().encode(ticket); + BufferedImage bufferedImage = QRCodeUtils.write2BufferedImage(encodeTicket, "gif", 300, 300); + String rqCode = Base64Utils.encodeImage(bufferedImage); + HashMap codeMap = new HashMap<>(); + codeMap.put("rqCode", rqCode); + codeMap.put("ticket", encodeTicket); + return new Message<>(Message.SUCCESS, codeMap); + } - @Operation(summary = "web二维码登录", description = "web二维码登录", method = "POST") - @PostMapping("/sign/qrcode") - public Message signByQrcode(@Validated @RequestBody ScanCode scanCode) { - LoginCredential loginCredential = new LoginCredential(); - loginCredential.setAuthType(scanCode.getAuthType()); - loginCredential.setUsername(scanCode.getCode()); + @Operation(summary = "web二维码登录", description = "web二维码登录", method = "POST") + @PostMapping("/sign/qrcode") + public Message signByQrcode(@Validated @RequestBody ScanCode scanCode) { + LoginCredential loginCredential = new LoginCredential(); + loginCredential.setAuthType(scanCode.getAuthType()); + loginCredential.setUsername(scanCode.getCode()); - if(authTokenService.validateJwtToken(scanCode.getState())){ - try { - Authentication authentication = authenticationProvider.authenticate(loginCredential); - if (Objects.nonNull(authentication)) { - //success - AuthJwt authJwt = authTokenService.genAuthJwt(authentication); - return new Message<>(authJwt); - } else { - return new Message<>(Message.FAIL, "尚未扫码"); - } - } catch (BusinessException businessException) { - return new Message<>(businessException.getCode(), businessException.getMessage()); - } - } else { - return new Message<>(20005, "state失效重新获取"); - } - } + if(authTokenService.validateJwtToken(scanCode.getState())){ + try { + Authentication authentication = authenticationProvider.authenticate(loginCredential); + if (Objects.nonNull(authentication)) { + //success + AuthJwt authJwt = authTokenService.genAuthJwt(authentication); + return new Message<>(authJwt); + } else { + return new Message<>(Message.FAIL, "尚未扫码"); + } + } catch (BusinessException businessException) { + return new Message<>(businessException.getCode(), businessException.getMessage()); + } + } else { + return new Message<>(20005, "state失效重新获取"); + } + } - @Operation(summary = "app扫描二维码", description = "扫描二维码登录", method = "POST") - @PostMapping("/scanCode") - public Message scanCode(@Validated @RequestBody QrCodeCredentialDto credentialDto) throws ParseException { - logger.debug("/scanCode."); - String jwtToken = credentialDto.getJwtToken(); - String code = credentialDto.getCode(); - try { - //获取登录会话 - Session session = AuthorizationUtils.getSession(sessionManager, jwtToken); - if (Objects.isNull(session)) { - return new Message<>(Message.FAIL, "登录会话失效,请重新登录"); - } - //查询二维码是否过期 - String ticketString = PasswordReciprocal.getInstance().decoder(code); - boolean codeResult = scanCodeService.validateTicket(ticketString, session); - if (!codeResult) { - return new Message<>(Message.FAIL, "二维码已过期,请重新获取"); - } + @Operation(summary = "app扫描二维码", description = "扫描二维码登录", method = "POST") + @PostMapping("/scanCode") + public Message scanCode(@Validated @RequestBody QrCodeCredentialDto credentialDto) throws ParseException { + logger.debug("/scanCode."); + String jwtToken = credentialDto.getJwtToken(); + String code = credentialDto.getCode(); + try { + //获取登录会话 + Session session = AuthorizationUtils.getSession(sessionManager, jwtToken); + if (Objects.isNull(session)) { + return new Message<>(Message.FAIL, "登录会话失效,请重新登录"); + } + //查询二维码是否过期 + String ticketString = PasswordReciprocal.getInstance().decoder(code); + boolean codeResult = scanCodeService.validateTicket(ticketString, session); + if (!codeResult) { + return new Message<>(Message.FAIL, "二维码已过期,请重新获取"); + } - } catch (ParseException e) { - logger.error("ParseException.",e); - return new Message<>(Message.FAIL, "token格式错误"); - } - return new Message<>(Message.SUCCESS, "成功"); - } + } catch (ParseException e) { + logger.error("ParseException.",e); + return new Message<>(Message.FAIL, "token格式错误"); + } + return new Message<>(Message.SUCCESS, "成功"); + } } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/LogoutEndpoint.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/LogoutEndpoint.java index f86f904bd..77b813878 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/LogoutEndpoint.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/LogoutEndpoint.java @@ -52,79 +52,79 @@ import jakarta.servlet.http.HttpServletRequest; @Tag(name = "1-3-单点注销接口文档模块") @Controller public class LogoutEndpoint { - private static Logger logger = LoggerFactory.getLogger(LogoutEndpoint.class); + private static Logger logger = LoggerFactory.getLogger(LogoutEndpoint.class); - @Autowired + @Autowired ApplicationConfig applicationConfig; - - @Autowired + + @Autowired SessionManager sessionManager; - - @Autowired - DefaultTokenServices oauth20TokenServices; - - /** - * for front end - * @param currentUser - * @return ResponseEntity - */ - @Operation(summary = "前端注销接口", description = "前端注销接口",method="GET") - @GetMapping(value={"/logout"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - @ResponseBody - public Message logout(@CurrentUser UserInfo currentUser){ - //if logined in have onlineTicket ,need remove or logout back - String sessionId = currentUser.getSessionId(); - Session session = sessionManager.get(sessionId); - if(session != null) { - logger.debug("/logout frontend clean Session id {}",session.getId()); - Set> entrySet = session.getVisited().entrySet(); - - Iterator> iterator = entrySet.iterator(); - while (iterator.hasNext()) { - Entry mapEntry = iterator.next(); - VisitedDto visited = mapEntry.getValue(); - logger.debug("App Id : {} , {} " , mapEntry.getKey() ,mapEntry.getValue()); - if( mapEntry.getValue().getLogoutType() == LogoutType.BACK_CHANNEL){ - SingleLogout singleLogout; - if(mapEntry.getValue().getProtocol().equalsIgnoreCase(ConstsProtocols.CAS)) { - singleLogout =new SamlSingleLogout(); - }else { - singleLogout = new DefaultSingleLogout(); - } - singleLogout.sendRequest(session.getAuthentication(), visited); - } - //oauth , oidc revoke token - if(visited.getProtocol().equalsIgnoreCase(ConstsProtocols.OAUTH20) - ||visited.getProtocol().equalsIgnoreCase(ConstsProtocols.OAUTH21) - ||visited.getProtocol().equalsIgnoreCase(ConstsProtocols.OPEN_ID_CONNECT10)) { - oauth20TokenServices.revokeToken(visited.getToken()); - logger.debug("revoke token"); - } - } - //terminate session - sessionManager.terminate( - session.getId(), - currentUser.getId(), - currentUser.getUsername()); - } - return new Message(); - } - - @Operation(summary = "单点注销接口", description = "redirect_uri跳转地址",method="GET") - @GetMapping({"/force/logout"}) - public ModelAndView forceLogout(HttpServletRequest request, - @RequestParam(value = "redirect_uri",required = false) String redirect_uri){ - //invalidate http session - logger.debug("/force/logout http Session id {}",request.getSession().getId()); - request.getSession().invalidate(); - StringBuffer logoutUrl = new StringBuffer(""); - logoutUrl.append(applicationConfig.getFrontendUri()).append("/#/passport/logout"); - if(StringUtils.isNotBlank(redirect_uri)) { - logoutUrl.append("?") - .append("redirect_uri=").append(redirect_uri); - } - ModelAndView modelAndView=new ModelAndView("redirect"); - modelAndView.addObject("redirect_uri", logoutUrl); - return modelAndView; - } + + @Autowired + DefaultTokenServices oauth20TokenServices; + + /** + * for front end + * @param currentUser + * @return ResponseEntity + */ + @Operation(summary = "前端注销接口", description = "前端注销接口",method="GET") + @GetMapping(value={"/logout"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + @ResponseBody + public Message logout(@CurrentUser UserInfo currentUser){ + //if logined in have onlineTicket ,need remove or logout back + String sessionId = currentUser.getSessionId(); + Session session = sessionManager.get(sessionId); + if(session != null) { + logger.debug("/logout frontend clean Session id {}",session.getId()); + Set> entrySet = session.getVisited().entrySet(); + + Iterator> iterator = entrySet.iterator(); + while (iterator.hasNext()) { + Entry mapEntry = iterator.next(); + VisitedDto visited = mapEntry.getValue(); + logger.debug("App Id : {} , {} " , mapEntry.getKey() ,mapEntry.getValue()); + if( mapEntry.getValue().getLogoutType() == LogoutType.BACK_CHANNEL){ + SingleLogout singleLogout; + if(mapEntry.getValue().getProtocol().equalsIgnoreCase(ConstsProtocols.CAS)) { + singleLogout =new SamlSingleLogout(); + }else { + singleLogout = new DefaultSingleLogout(); + } + singleLogout.sendRequest(session.getAuthentication(), visited); + } + //oauth , oidc revoke token + if(visited.getProtocol().equalsIgnoreCase(ConstsProtocols.OAUTH20) + ||visited.getProtocol().equalsIgnoreCase(ConstsProtocols.OAUTH21) + ||visited.getProtocol().equalsIgnoreCase(ConstsProtocols.OPEN_ID_CONNECT10)) { + oauth20TokenServices.revokeToken(visited.getToken()); + logger.debug("revoke token"); + } + } + //terminate session + sessionManager.terminate( + session.getId(), + currentUser.getId(), + currentUser.getUsername()); + } + return new Message(); + } + + @Operation(summary = "单点注销接口", description = "redirect_uri跳转地址",method="GET") + @GetMapping({"/force/logout"}) + public ModelAndView forceLogout(HttpServletRequest request, + @RequestParam(value = "redirect_uri",required = false) String redirect_uri){ + //invalidate http session + logger.debug("/force/logout http Session id {}",request.getSession().getId()); + request.getSession().invalidate(); + StringBuffer logoutUrl = new StringBuffer(""); + logoutUrl.append(applicationConfig.getFrontendUri()).append("/#/passport/logout"); + if(StringUtils.isNotBlank(redirect_uri)) { + logoutUrl.append("?") + .append("redirect_uri=").append(redirect_uri); + } + ModelAndView modelAndView=new ModelAndView("redirect"); + modelAndView.addObject("redirect_uri", logoutUrl); + return modelAndView; + } } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/OneTimePasswordController.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/OneTimePasswordController.java index 1c1c35ae5..b24b64703 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/OneTimePasswordController.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/OneTimePasswordController.java @@ -64,52 +64,52 @@ public class OneTimePasswordController { @GetMapping(value = {"/view"}) public Message view(@CurrentUser UserInfo currentUser) { - UserInfo user = userInfoService.get(currentUser.getId()); - String sharedSecret = ""; - String qrCode = ""; - if(StringUtils.isNotBlank(user.getSharedSecret())) { - sharedSecret = PasswordReciprocal.getInstance().decoder(user.getSharedSecret()); - qrCode = genQRCode(sharedSecret,currentUser.getUsername()); - } + UserInfo user = userInfoService.get(currentUser.getId()); + String sharedSecret = ""; + String qrCode = ""; + if(StringUtils.isNotBlank(user.getSharedSecret())) { + sharedSecret = PasswordReciprocal.getInstance().decoder(user.getSharedSecret()); + qrCode = genQRCode(sharedSecret,currentUser.getUsername()); + } return new Message<>( - new TimeBasedDto( - user.getDisplayName(), - user.getUsername(), - otpKeyUriFormat.getDigits(), - otpKeyUriFormat.getPeriod(), - sharedSecret, - qrCode, - "" - )); + new TimeBasedDto( + user.getDisplayName(), + user.getUsername(), + otpKeyUriFormat.getDigits(), + otpKeyUriFormat.getPeriod(), + sharedSecret, + qrCode, + "" + )); } @GetMapping(value = {"/generate"}) public Message generate(@CurrentUser UserInfo currentUser) { - //generate + //generate byte[] byteSharedSecret = OtpSecret.generate(otpKeyUriFormat.getCrypto()); String sharedSecret = Base32Utils.encode(byteSharedSecret); String qrCode = genQRCode(sharedSecret,currentUser.getUsername()); - return new Message<>( - new TimeBasedDto( - currentUser.getDisplayName(), - currentUser.getUsername(), - otpKeyUriFormat.getDigits(), - otpKeyUriFormat.getPeriod(), - sharedSecret, - qrCode, - "" - )); + return new Message<>( + new TimeBasedDto( + currentUser.getDisplayName(), + currentUser.getUsername(), + otpKeyUriFormat.getDigits(), + otpKeyUriFormat.getPeriod(), + sharedSecret, + qrCode, + "" + )); } @PutMapping(value = {"/update"}) public Message update(@RequestBody TimeBasedDto timeBasedDto , @CurrentUser UserInfo currentUser) { // 从当前用户信息中获取共享密钥 - UserInfo user = new UserInfo(); - user.setId(currentUser.getId()); - user.setSharedSecret(PasswordReciprocal.getInstance().encode(timeBasedDto.sharedSecret())); + UserInfo user = new UserInfo(); + user.setId(currentUser.getId()); + user.setSharedSecret(PasswordReciprocal.getInstance().encode(timeBasedDto.sharedSecret())); // 计算当前时间对应的动态密码 if (StringUtils.isNotBlank(timeBasedDto.otpCode()) && timeBasedOtpAuthn.validate(user, timeBasedDto.otpCode())) { - userInfoService.updateSharedSecret(user); + userInfoService.updateSharedSecret(user); return new Message<>(Message.SUCCESS); } else { return new Message<>(Message.FAIL); @@ -117,16 +117,16 @@ public class OneTimePasswordController { } public String genQRCode(String sharedSecret,String username) { - otpKeyUriFormat.setSecret(sharedSecret); + otpKeyUriFormat.setSecret(sharedSecret); String otpauth = otpKeyUriFormat.format(username); BufferedImage bufferedImage = QRCodeUtils.write2BufferedImage(otpauth, "gif", 300, 300); - return Base64Utils.encodeImage(bufferedImage); + return Base64Utils.encodeImage(bufferedImage); } @GetMapping("/verify") public Message verify(@RequestParam("otpCode") String otpCode, @CurrentUser UserInfo currentUser) { // 从当前用户信息中获取共享密钥 - UserInfo user = userInfoService.get(currentUser.getId()); + UserInfo user = userInfoService.get(currentUser.getId()); // 计算当前时间对应的动态密码 boolean validate = timeBasedOtpAuthn.validate(user, otpCode); if (validate) { diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/ProfileController.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/ProfileController.java index 75f4c6bdb..5c0e4d1b4 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/ProfileController.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/ProfileController.java @@ -43,12 +43,12 @@ public class ProfileController { UserInfoService userInfoService; @Autowired - FileUploadService fileUploadService; + FileUploadService fileUploadService; @GetMapping(value = { "/get" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@CurrentUser UserInfo currentUser) { + public Message get(@CurrentUser UserInfo currentUser) { UserInfo userInfo = userInfoService.findByUsername(currentUser.getUsername()); - userInfo.trans(); + userInfo.trans(); return new Message<>(userInfo); } @@ -59,51 +59,51 @@ public class ProfileController { * @param result * @return */ - @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update( - @RequestBody UserInfo userInfo, - @CurrentUser UserInfo currentUser, + @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update( + @RequestBody UserInfo userInfo, + @CurrentUser UserInfo currentUser, BindingResult result) { logger.debug(userInfo.toString()); if(!currentUser.getId().equals(userInfo.getId())){ return null; } -// if(userInfo.getExtraAttributeValue()!=null){ -// String []extraAttributeLabel=userInfo.getExtraAttributeName().split(","); -// String []extraAttributeValue=userInfo.getExtraAttributeValue().split(","); -// Map extraAttributeMap=new HashMap (); -// for(int i=0;i extraAttributeMap=new HashMap (); +// for(int i=0;i 0) { - return new Message(Message.SUCCESS); + return new Message(Message.SUCCESS); } return new Message(Message.FAIL); } - - /** + + /** * AuthnType. * * @param userInfo * @param result * @return */ - @PutMapping("/updateAuthnType") - public Message updateAuthnType(@RequestBody UserInfo userInfo,@CurrentUser UserInfo currentUser) { - userInfo.setId(currentUser.getId()); + @PutMapping("/updateAuthnType") + public Message updateAuthnType(@RequestBody UserInfo userInfo,@CurrentUser UserInfo currentUser) { + userInfo.setId(currentUser.getId()); logger.debug("updateAuthnType {}",userInfo); if (userInfoService.updateAuthnType(userInfo)) { - return new Message<>(Message.SUCCESS); + return new Message<>(Message.SUCCESS); } return new Message<>(Message.FAIL); } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/RegisterController.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/RegisterController.java index 1d13b4ea3..b14e4db2a 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/RegisterController.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/RegisterController.java @@ -49,75 +49,75 @@ import jakarta.servlet.ServletException; @RestController @RequestMapping(value={"/signup"}) public class RegisterController { - private static Logger logger = LoggerFactory.getLogger(RegisterController.class); + private static Logger logger = LoggerFactory.getLogger(RegisterController.class); - @Autowired - AuthTokenService authTokenService; - - @Autowired - ApplicationConfig applicationConfig; - - @Autowired - UserInfoService userInfoService; - - @Autowired + @Autowired + AuthTokenService authTokenService; + + @Autowired + ApplicationConfig applicationConfig; + + @Autowired + UserInfoService userInfoService; + + @Autowired SmsOtpAuthnService smsOtpAuthnService; - - @Autowired - PasswordEncoder passwordEncoder; - - @GetMapping(value = { "/produceOtp" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message produceOtp(@RequestParam String mobile) { + + @Autowired + PasswordEncoder passwordEncoder; + + @GetMapping(value = { "/produceOtp" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message produceOtp(@RequestParam String mobile) { logger.debug("/signup/produceOtp Mobile {}: " ,mobile); - logger.debug("Mobile Regex matches {}",ConstsRegex.MOBILE_PATTERN.matcher(mobile).matches()); - if(StringUtils.isNotBlank(mobile) && ConstsRegex.MOBILE_PATTERN.matcher(mobile).matches()) { - UserInfo userInfo = new UserInfo(); - userInfo.setUsername(mobile); - userInfo.setMobile(mobile); - AbstractOtpAuthn smsOtpAuthn = smsOtpAuthnService.getByInstId(WebContext.getInst().getId()); - smsOtpAuthn.produce(userInfo); - return new Message(userInfo); + logger.debug("Mobile Regex matches {}",ConstsRegex.MOBILE_PATTERN.matcher(mobile).matches()); + if(StringUtils.isNotBlank(mobile) && ConstsRegex.MOBILE_PATTERN.matcher(mobile).matches()) { + UserInfo userInfo = new UserInfo(); + userInfo.setUsername(mobile); + userInfo.setMobile(mobile); + AbstractOtpAuthn smsOtpAuthn = smsOtpAuthnService.getByInstId(WebContext.getInst().getId()); + smsOtpAuthn.produce(userInfo); + return new Message(userInfo); } return new Message(Message.FAIL); } - - //直接注册 - @PostMapping(value={"/register"}) - public Message register(@ModelAttribute UserInfo userInfo , @RequestParam String captcha) throws ServletException, IOException { - UserInfo validateUserInfo = new UserInfo(); - validateUserInfo.setUsername(userInfo.getMobile()); - validateUserInfo.setMobile(userInfo.getMobile()); - AbstractOtpAuthn smsOtpAuthn = smsOtpAuthnService.getByInstId(WebContext.getInst().getId()); - if (smsOtpAuthn !=null - && smsOtpAuthn.validate(validateUserInfo, captcha)){ - UserInfo temp = userInfoService.findByEmailMobile(userInfo.getEmail()); - - if(temp != null) { - return new Message(Message.FAIL); - } - - temp = userInfoService.findByUsername(userInfo.getUsername()); - if(temp != null) { - return new Message(Message.FAIL); - } - - //default InstId - if(StringUtils.isEmpty(userInfo.getInstId())) { - userInfo.setInstId("1"); - } - String password = userInfo.getPassword(); - userInfo.setDecipherable(PasswordReciprocal.getInstance().encode(password)); - password = passwordEncoder.encode(password ); - userInfo.setPassword(password); - userInfo.setStatus(ConstsStatus.INACTIVE); - - if(userInfoService.insert(userInfo)) { - return new Message(); - } - } - return new Message(Message.FAIL); - } + + //直接注册 + @PostMapping(value={"/register"}) + public Message register(@ModelAttribute UserInfo userInfo , @RequestParam String captcha) throws ServletException, IOException { + UserInfo validateUserInfo = new UserInfo(); + validateUserInfo.setUsername(userInfo.getMobile()); + validateUserInfo.setMobile(userInfo.getMobile()); + AbstractOtpAuthn smsOtpAuthn = smsOtpAuthnService.getByInstId(WebContext.getInst().getId()); + if (smsOtpAuthn !=null + && smsOtpAuthn.validate(validateUserInfo, captcha)){ + UserInfo temp = userInfoService.findByEmailMobile(userInfo.getEmail()); + + if(temp != null) { + return new Message(Message.FAIL); + } + + temp = userInfoService.findByUsername(userInfo.getUsername()); + if(temp != null) { + return new Message(Message.FAIL); + } + + //default InstId + if(StringUtils.isEmpty(userInfo.getInstId())) { + userInfo.setInstId("1"); + } + String password = userInfo.getPassword(); + userInfo.setDecipherable(PasswordReciprocal.getInstance().encode(password)); + password = passwordEncoder.encode(password ); + userInfo.setPassword(password); + userInfo.setStatus(ConstsStatus.INACTIVE); + + if(userInfoService.insert(userInfo)) { + return new Message(); + } + } + return new Message(Message.FAIL); + } } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/SafeController.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/SafeController.java index 980107a18..954d55114 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/SafeController.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/SafeController.java @@ -39,47 +39,47 @@ import jakarta.servlet.http.HttpServletResponse; @Controller @RequestMapping(value={"/safe"}) public class SafeController { - static final Logger logger = LoggerFactory.getLogger(SafeController.class); - - @Autowired - UserInfoService userInfoService; - - @RequestMapping(value="/forward/setting") - public ModelAndView fowardSetting(@CurrentUser UserInfo currentUser) { - ModelAndView modelAndView=new ModelAndView("safe/setting"); - modelAndView.addObject("model", currentUser); - return modelAndView; - } - - @ResponseBody - @RequestMapping(value="/setting") - public Message setting( - HttpServletRequest request, + static final Logger logger = LoggerFactory.getLogger(SafeController.class); + + @Autowired + UserInfoService userInfoService; + + @RequestMapping(value="/forward/setting") + public ModelAndView fowardSetting(@CurrentUser UserInfo currentUser) { + ModelAndView modelAndView=new ModelAndView("safe/setting"); + modelAndView.addObject("model", currentUser); + return modelAndView; + } + + @ResponseBody + @RequestMapping(value="/setting") + public Message setting( + HttpServletRequest request, HttpServletResponse response, - @RequestParam("authnType") String authnType, - @RequestParam("mobile") String mobile, - @RequestParam("mobileVerify") String mobileVerify, - @RequestParam("email") String email, - @RequestParam("emailVerify") String emailVerify, - @RequestParam("theme") String theme, - @CurrentUser UserInfo currentUser) { - currentUser.setAuthnType(Integer.parseInt(authnType)); - userInfoService.updateAuthnType(currentUser); - - currentUser.setMobile(mobile); - userInfoService.updateMobile(currentUser); - - currentUser.setEmail(email); + @RequestParam("authnType") String authnType, + @RequestParam("mobile") String mobile, + @RequestParam("mobileVerify") String mobileVerify, + @RequestParam("email") String email, + @RequestParam("emailVerify") String emailVerify, + @RequestParam("theme") String theme, + @CurrentUser UserInfo currentUser) { + currentUser.setAuthnType(Integer.parseInt(authnType)); + userInfoService.updateAuthnType(currentUser); + + currentUser.setMobile(mobile); + userInfoService.updateMobile(currentUser); + + currentUser.setEmail(email); - currentUser.setTheme(theme); + currentUser.setTheme(theme); WebContext.setCookie(response,null, WebConstants.THEME_COOKIE_NAME, theme, ConstsTimeInterval.ONE_WEEK); - userInfoService.updateEmail(currentUser); - - - return new Message(Message.SUCCESS); - - } - - + userInfoService.updateEmail(currentUser); + + + return new Message(Message.SUCCESS); + + } + + } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/SocialSignOnListController.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/SocialSignOnListController.java index c35d5c3b3..995ec32a1 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/SocialSignOnListController.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/contorller/SocialSignOnListController.java @@ -38,30 +38,30 @@ import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(value={"/config/socialsignon"}) public class SocialSignOnListController { - static final Logger logger = LoggerFactory.getLogger(SocialSignOnListController.class); - - @Autowired - SocialsAssociatesService socialsAssociatesService; - - @RequestMapping(value={"/fetch"}) - @ResponseBody - public Message fetch(@CurrentUser UserInfo currentUser){ - - List listSocialsAssociate= - socialsAssociatesService.queryByUser(currentUser); - - return new Message>(listSocialsAssociate); - } - - @ResponseBody - @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {} " , ids); - if (socialsAssociatesService.deleteBatch(ids)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - + static final Logger logger = LoggerFactory.getLogger(SocialSignOnListController.class); + + @Autowired + SocialsAssociatesService socialsAssociatesService; + + @RequestMapping(value={"/fetch"}) + @ResponseBody + public Message fetch(@CurrentUser UserInfo currentUser){ + + List listSocialsAssociate= + socialsAssociatesService.queryByUser(currentUser); + + return new Message>(listSocialsAssociate); + } + + @ResponseBody + @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {} " , ids); + if (socialsAssociatesService.deleteBatch(ids)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + } diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/historys/contorller/LoginAppsHistoryController.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/historys/contorller/LoginAppsHistoryController.java index 23030f761..29d787bd3 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/historys/contorller/LoginAppsHistoryController.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/historys/contorller/LoginAppsHistoryController.java @@ -47,30 +47,30 @@ import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(value={"/historys"}) public class LoginAppsHistoryController { - static final Logger logger = LoggerFactory.getLogger(LoginAppsHistoryController.class); - - @Autowired - HistoryLoginAppsService historyLoginAppsService; - - /** - * @param loginAppsHistory - * @return - */ - @RequestMapping(value={"/loginAppsHistory/fetch"}) - @ResponseBody - public Message fetch( - @ModelAttribute("historyLoginApp") HistoryLoginApps historyLoginApp, - @CurrentUser UserInfo currentUser){ - logger.debug("historys/loginAppsHistory/fetch/ {}",historyLoginApp); - historyLoginApp.setId(null); - historyLoginApp.setUserId(currentUser.getId()); - historyLoginApp.setInstId(currentUser.getInstId()); - return new Message>( - historyLoginAppsService.fetchPageResults(historyLoginApp) - ); - } + static final Logger logger = LoggerFactory.getLogger(LoginAppsHistoryController.class); + + @Autowired + HistoryLoginAppsService historyLoginAppsService; + + /** + * @param loginAppsHistory + * @return + */ + @RequestMapping(value={"/loginAppsHistory/fetch"}) + @ResponseBody + public Message fetch( + @ModelAttribute("historyLoginApp") HistoryLoginApps historyLoginApp, + @CurrentUser UserInfo currentUser){ + logger.debug("historys/loginAppsHistory/fetch/ {}",historyLoginApp); + historyLoginApp.setId(null); + historyLoginApp.setUserId(currentUser.getId()); + historyLoginApp.setInstId(currentUser.getInstId()); + return new Message>( + historyLoginAppsService.fetchPageResults(historyLoginApp) + ); + } - @InitBinder + @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtils.FORMAT_DATE_HH_MM_SS); dateFormat.setLenient(false); diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/historys/contorller/LoginHistoryController.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/historys/contorller/LoginHistoryController.java index 4225a6a54..a12ec18a0 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/historys/contorller/LoginHistoryController.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/historys/contorller/LoginHistoryController.java @@ -47,30 +47,30 @@ import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(value={"/historys"}) public class LoginHistoryController { - static final Logger logger = LoggerFactory.getLogger(LoginHistoryController.class); - - @Autowired - HistoryLoginService loginHistoryService; - - /** - * @param HistoryLogin - * @return - */ - @RequestMapping(value={"/loginHistory/fetch"}) - @ResponseBody - public Message fetch( - @ModelAttribute("historyLogin") HistoryLogin historyLogin, - @CurrentUser UserInfo currentUser - ){ - logger.debug("historys/loginHistory/fetch/ {}",historyLogin); - historyLogin.setInstId(currentUser.getInstId()); - historyLogin.setUserId(currentUser.getId()); - return new Message>( - loginHistoryService.fetchPageResults(historyLogin) - ); - } - - @InitBinder + static final Logger logger = LoggerFactory.getLogger(LoginHistoryController.class); + + @Autowired + HistoryLoginService loginHistoryService; + + /** + * @param HistoryLogin + * @return + */ + @RequestMapping(value={"/loginHistory/fetch"}) + @ResponseBody + public Message fetch( + @ModelAttribute("historyLogin") HistoryLogin historyLogin, + @CurrentUser UserInfo currentUser + ){ + logger.debug("historys/loginHistory/fetch/ {}",historyLogin); + historyLogin.setInstId(currentUser.getInstId()); + historyLogin.setUserId(currentUser.getId()); + return new Message>( + loginHistoryService.fetchPageResults(historyLogin) + ); + } + + @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtils.FORMAT_DATE_HH_MM_SS); dateFormat.setLenient(false); diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/interceptor/HistorySingleSignOnInterceptor.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/interceptor/HistorySingleSignOnInterceptor.java index 5673fde06..30292e6db 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/interceptor/HistorySingleSignOnInterceptor.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/interceptor/HistorySingleSignOnInterceptor.java @@ -64,9 +64,9 @@ public class HistorySingleSignOnInterceptor implements AsyncHandlerInterceptor SignPrincipal principal = AuthorizationUtils.getPrincipal(); if(principal != null && app !=null) { - final UserInfo userInfo = principal.getUserInfo(); - String sessionId = principal.getSessionId(); - logger.debug("sessionId : {} , appId {}" , sessionId , app.getId()); + final UserInfo userInfo = principal.getUserInfo(); + String sessionId = principal.getSessionId(); + logger.debug("sessionId : {} , appId {}" , sessionId , app.getId()); HistoryLoginApps historyLoginApps = new HistoryLoginApps(); historyLoginApps.setAppId(app.getId()); historyLoginApps.setSessionId(sessionId); diff --git a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/interceptor/SingleSignOnInterceptor.java b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/interceptor/SingleSignOnInterceptor.java index 5a4ee18cf..74e21cc03 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/interceptor/SingleSignOnInterceptor.java +++ b/maxkey-webs/maxkey-web-maxkey/src/main/java/org/dromara/maxkey/web/interceptor/SingleSignOnInterceptor.java @@ -49,10 +49,10 @@ public class SingleSignOnInterceptor implements AsyncHandlerInterceptor { ApplicationConfig applicationConfig; @Autowired - SessionManager sessionManager; + SessionManager sessionManager; @Autowired - AuthTokenService authTokenService ; + AuthTokenService authTokenService ; @Autowired AppsService appsService; @@ -64,63 +64,63 @@ public class SingleSignOnInterceptor implements AsyncHandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - logger.trace("Single Sign On Interceptor"); + logger.trace("Single Sign On Interceptor"); - AuthorizationUtils.authenticateWithCookie(request,authTokenService,sessionManager); + AuthorizationUtils.authenticateWithCookie(request,authTokenService,sessionManager); if(AuthorizationUtils.isNotAuthenticated()) { - String loginUrl = applicationConfig.getFrontendUri() + "/#/passport/login?redirect_uri=%s"; - String redirect_uri = UrlUtils.buildFullRequestUrl(request); - String base64RequestUrl = Base64Utils.base64UrlEncode(redirect_uri.getBytes()); - logger.debug("No Authentication ... Redirect to /passport/login , redirect_uri {} , base64 {}", - redirect_uri ,base64RequestUrl); - response.sendRedirect(String.format(loginUrl,base64RequestUrl)); - return false; + String loginUrl = applicationConfig.getFrontendUri() + "/#/passport/login?redirect_uri=%s"; + String redirect_uri = UrlUtils.buildFullRequestUrl(request); + String base64RequestUrl = Base64Utils.base64UrlEncode(redirect_uri.getBytes()); + logger.debug("No Authentication ... Redirect to /passport/login , redirect_uri {} , base64 {}", + redirect_uri ,base64RequestUrl); + response.sendRedirect(String.format(loginUrl,base64RequestUrl)); + return false; } //判断应用访问权限 if(AuthorizationUtils.isAuthenticated()){ - logger.debug("preHandle {}",request.getRequestURI()); - Apps app = (Apps)WebContext.getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP); - if(app == null) { - - String requestURI = request.getRequestURI(); - if(requestURI.contains("/authz/cas/login")) {//for CAS service - app = casDetailsService.getAppDetails( - request.getParameter(CasConstants.PARAMETER.SERVICE), true); - }else if(requestURI.contains("/authz/jwt/") - ||requestURI.contains("/authz/api/") - ||requestURI.contains("/authz/formbased/") - ||requestURI.contains("/authz/tokenbased/") - ||requestURI.contains("/authz/saml20/consumer/") - ||requestURI.contains("/authz/saml20/idpinit/") - ||requestURI.contains("/authz/cas/") - ) {//for id end of URL - String [] requestURIs = requestURI.split("/"); - String appId = requestURIs[requestURIs.length -1]; - logger.debug("appId {}",appId); - app = appsService.get(appId,true); - }else if(requestURI.contains("/authz/oauth/v20/authorize")) {//oauth - app = appsService.get(request.getParameter(OAuth2Constants.PARAMETER.CLIENT_ID),true); - } - } - - if(app == null) { - logger.debug("preHandle app is not exist . "); - return true; - } - - SignPrincipal principal = AuthorizationUtils.getPrincipal(); - if(principal != null && app !=null) { - if(principal.getGrantedAuthorityApps().contains(new SimpleGrantedAuthority(app.getId()))) { - logger.trace("preHandle have authority access {}" , app); - return true; - } - } - logger.debug("preHandle not have authority access {}" , app); - response.sendRedirect(request.getContextPath()+"/authz/refused"); - return false; - } + logger.debug("preHandle {}",request.getRequestURI()); + Apps app = (Apps)WebContext.getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP); + if(app == null) { + + String requestURI = request.getRequestURI(); + if(requestURI.contains("/authz/cas/login")) {//for CAS service + app = casDetailsService.getAppDetails( + request.getParameter(CasConstants.PARAMETER.SERVICE), true); + }else if(requestURI.contains("/authz/jwt/") + ||requestURI.contains("/authz/api/") + ||requestURI.contains("/authz/formbased/") + ||requestURI.contains("/authz/tokenbased/") + ||requestURI.contains("/authz/saml20/consumer/") + ||requestURI.contains("/authz/saml20/idpinit/") + ||requestURI.contains("/authz/cas/") + ) {//for id end of URL + String [] requestURIs = requestURI.split("/"); + String appId = requestURIs[requestURIs.length -1]; + logger.debug("appId {}",appId); + app = appsService.get(appId,true); + }else if(requestURI.contains("/authz/oauth/v20/authorize")) {//oauth + app = appsService.get(request.getParameter(OAuth2Constants.PARAMETER.CLIENT_ID),true); + } + } + + if(app == null) { + logger.debug("preHandle app is not exist . "); + return true; + } + + SignPrincipal principal = AuthorizationUtils.getPrincipal(); + if(principal != null && app !=null) { + if(principal.getGrantedAuthorityApps().contains(new SimpleGrantedAuthority(app.getId()))) { + logger.trace("preHandle have authority access {}" , app); + return true; + } + } + logger.debug("preHandle not have authority access {}" , app); + response.sendRedirect(request.getContextPath()+"/authz/refused"); + return false; + } return true; } diff --git a/maxkey-webs/maxkey-web-maxkey/src/test/java/org/maxkey/web/authentication/kerberos/KerberosPrincipal.java b/maxkey-webs/maxkey-web-maxkey/src/test/java/org/maxkey/web/authentication/kerberos/KerberosPrincipal.java index 4d2994858..5911648d3 100644 --- a/maxkey-webs/maxkey-web-maxkey/src/test/java/org/maxkey/web/authentication/kerberos/KerberosPrincipal.java +++ b/maxkey-webs/maxkey-web-maxkey/src/test/java/org/maxkey/web/authentication/kerberos/KerberosPrincipal.java @@ -35,40 +35,40 @@ import org.joda.time.chrono.ISOChronology; */ public class KerberosPrincipal { - /** - * - */ - public KerberosPrincipal() { - } + /** + * + */ + public KerberosPrincipal() { + } - /** - * @param args - */ - public static void main(String[] args) { - String kerberosPrincipal="Administrator@CONNSEC.COM"; - kerberosPrincipal=kerberosPrincipal.substring(0, kerberosPrincipal.indexOf("@")); - System.out.println(kerberosPrincipal); + /** + * @param args + */ + public static void main(String[] args) { + String kerberosPrincipal="Administrator@CONNSEC.COM"; + kerberosPrincipal=kerberosPrincipal.substring(0, kerberosPrincipal.indexOf("@")); + System.out.println(kerberosPrincipal); - if (Pattern.matches("[0-9]+", "TWO_WEEK")){ - System.out.println("true"); - }else{ - System.out.println("false"); - } - - DateTime datetime=new DateTime(new Date(), ISOChronology.getInstanceUTC()); - System.out.println(DateUtils.toUtc(datetime)); - - datetime=datetime.plus(10*1000); - - System.out.println(DateUtils.toUtc(datetime)); - String json="{\"fullPrincipal\":\"Administrator@CONNSEC.COM\",\"principal\":\"Administrator\",\"userDomain\":\"CONNSEC\",\"notOnOrAfter\":\"2014-01-18T07:10:16.624Z\"}"; - KerberosToken kerberosToken=new KerberosToken(); - kerberosToken=(KerberosToken)JsonUtils.stringToObject(json, kerberosToken); - - System.out.println(kerberosToken); - - System.out.println(DateUtils.toUtcDate(kerberosToken.getNotOnOrAfter())); - - } + if (Pattern.matches("[0-9]+", "TWO_WEEK")){ + System.out.println("true"); + }else{ + System.out.println("false"); + } + + DateTime datetime=new DateTime(new Date(), ISOChronology.getInstanceUTC()); + System.out.println(DateUtils.toUtc(datetime)); + + datetime=datetime.plus(10*1000); + + System.out.println(DateUtils.toUtc(datetime)); + String json="{\"fullPrincipal\":\"Administrator@CONNSEC.COM\",\"principal\":\"Administrator\",\"userDomain\":\"CONNSEC\",\"notOnOrAfter\":\"2014-01-18T07:10:16.624Z\"}"; + KerberosToken kerberosToken=new KerberosToken(); + kerberosToken=(KerberosToken)JsonUtils.stringToObject(json, kerberosToken); + + System.out.println(kerberosToken); + + System.out.println(DateUtils.toUtcDate(kerberosToken.getNotOnOrAfter())); + + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/MaxKeyMgtApplication.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/MaxKeyMgtApplication.java index 27875a3c0..f42f023f8 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/MaxKeyMgtApplication.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/MaxKeyMgtApplication.java @@ -35,24 +35,24 @@ import org.springframework.context.ConfigurableApplicationContext; @EnableDiscoveryClient @MapperScan("org.dromara.maxkey.persistence.mapper,") public class MaxKeyMgtApplication extends SpringBootServletInitializer { - static final Logger _logger = LoggerFactory.getLogger(MaxKeyMgtApplication.class); + static final Logger _logger = LoggerFactory.getLogger(MaxKeyMgtApplication.class); - public static void main(String[] args) { - _logger.info("Start MaxKeyMgt Application ..."); - ProductEnvironment.listEnvVars(); - - ConfigurableApplicationContext applicationContext = SpringApplication.run(MaxKeyMgtApplication.class, args); - new InitializeContext(applicationContext).init(); - - _logger.info("MaxKeyMgt at {}" , new DateTime()); - _logger.info("MaxKeyMgt Server Port {}" , WebContext.getServerPort()); - _logger.info("MaxKeyMgt started."); - - } + public static void main(String[] args) { + _logger.info("Start MaxKeyMgt Application ..."); + ProductEnvironment.listEnvVars(); + + ConfigurableApplicationContext applicationContext = SpringApplication.run(MaxKeyMgtApplication.class, args); + new InitializeContext(applicationContext).init(); + + _logger.info("MaxKeyMgt at {}" , new DateTime()); + _logger.info("MaxKeyMgt Server Port {}" , WebContext.getServerPort()); + _logger.info("MaxKeyMgt started."); + + } - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { - return application.sources(MaxKeyMgtApplication.class); - } + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(MaxKeyMgtApplication.class); + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyMgtConfig.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyMgtConfig.java index 8fffc4b35..278d55f67 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyMgtConfig.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyMgtConfig.java @@ -48,15 +48,15 @@ public class MaxKeyMgtConfig { UserInfoService userInfoService, IpLocationParser ipLocationParser, JdbcTemplate jdbcTemplate) { - + JdbcAuthenticationRealm authenticationRealm = new JdbcAuthenticationRealm( - passwordEncoder, - passwordPolicyValidatorService, - loginService, - historyLoginService, - userInfoService, - ipLocationParser, - jdbcTemplate); + passwordEncoder, + passwordPolicyValidatorService, + loginService, + historyLoginService, + userInfoService, + ipLocationParser, + jdbcTemplate); logger.debug("JdbcAuthenticationRealm inited."); return authenticationRealm; @@ -64,17 +64,17 @@ public class MaxKeyMgtConfig { @Bean AbstractOtpAuthn timeBasedOtpAuthn() { - AbstractOtpAuthn tfaOtpAuthn = new TimeBasedOtpAuthn(); - logger.debug("TimeBasedOtpAuthn inited."); + AbstractOtpAuthn tfaOtpAuthn = new TimeBasedOtpAuthn(); + logger.debug("TimeBasedOtpAuthn inited."); return tfaOtpAuthn; } - /*@Bean - public ISynchronizerService ldapSynchronizerService() { - LdapSynchronizerService ldapSynchronizerService = new LdapSynchronizerService(); - ldapSynchronizerService.setId("LDAP_11122"); - ldapSynchronizerService.syncOrg(); - return ldapSynchronizerService; - }*/ + /*@Bean + public ISynchronizerService ldapSynchronizerService() { + LdapSynchronizerService ldapSynchronizerService = new LdapSynchronizerService(); + ldapSynchronizerService.setId("LDAP_11122"); + ldapSynchronizerService.syncOrg(); + return ldapSynchronizerService; + }*/ } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyMgtListenerConfig.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyMgtListenerConfig.java index 89032ac9e..cf6d5193b 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyMgtListenerConfig.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyMgtListenerConfig.java @@ -48,29 +48,29 @@ public class MaxKeyMgtListenerConfig { String sessionListenerAdapter( Scheduler scheduler, SessionManager sessionManager) throws SchedulerException { - new ScheduleAdapterBuilder() - .setScheduler(scheduler) - .setCron("0 0/10 * * * ?") - .setJobClass(SessionListenerAdapter.class) - .setJobData("sessionManager",sessionManager) - .setJobData("category", SessionCategory.MGMT) - .build(); + new ScheduleAdapterBuilder() + .setScheduler(scheduler) + .setCron("0 0/10 * * * ?") + .setJobClass(SessionListenerAdapter.class) + .setJobData("sessionManager",sessionManager) + .setJobData("category", SessionCategory.MGMT) + .build(); logger.debug("Session ListenerAdapter inited ."); - return "sessionListenerAdapter"; + return "sessionListenerAdapter"; } @Bean String reorgDeptListenerAdapter( Scheduler scheduler, OrganizationsService organizationsService) throws SchedulerException { - new ScheduleAdapterBuilder() - .setScheduler(scheduler) - .setCron("0 0/30 * * * ?") - .setJobClass(ReorgDeptListenerAdapter.class) - .setJobData("organizationsService",organizationsService) - .build(); + new ScheduleAdapterBuilder() + .setScheduler(scheduler) + .setCron("0 0/30 * * * ?") + .setJobClass(ReorgDeptListenerAdapter.class) + .setJobData("organizationsService",organizationsService) + .build(); logger.debug("ReorgDept ListenerAdapter inited ."); - return "reorgDeptListenerAdapter"; + return "reorgDeptListenerAdapter"; } @Bean @@ -79,12 +79,12 @@ public class MaxKeyMgtListenerConfig { GroupsService groupsService, @Value("${maxkey.job.cron.schedule}") String cronSchedule ) throws SchedulerException { - new ScheduleAdapterBuilder() - .setScheduler(scheduler) - .setCron(cronSchedule) - .setJobClass(DynamicGroupsListenerAdapter.class) - .setJobData("groupsService",groupsService) - .build(); + new ScheduleAdapterBuilder() + .setScheduler(scheduler) + .setCron(cronSchedule) + .setJobClass(DynamicGroupsListenerAdapter.class) + .setJobData("groupsService",groupsService) + .build(); logger.debug("DynamicGroups ListenerAdapter inited ."); return "dynamicGroupsListenerAdapter"; @@ -96,12 +96,12 @@ public class MaxKeyMgtListenerConfig { RolesService rolesService, @Value("${maxkey.job.cron.schedule}") String cronSchedule ) throws SchedulerException { - new ScheduleAdapterBuilder() - .setScheduler(scheduler) - .setCron(cronSchedule) - .setJobClass(DynamicRolesListenerAdapter.class) - .setJobData("rolesService",rolesService) - .build(); + new ScheduleAdapterBuilder() + .setScheduler(scheduler) + .setCron(cronSchedule) + .setJobClass(DynamicRolesListenerAdapter.class) + .setJobData("rolesService",rolesService) + .build(); logger.debug("Dynamic Roles ListenerAdapter inited ."); return "dynamicRolesListenerAdapter"; @@ -114,12 +114,12 @@ public class MaxKeyMgtListenerConfig { ApplicationConfig applicationConfig ) { if(applicationConfig.isProvisionSupport()) { - ProvisioningRunner runner = new ProvisioningRunner(connectorsService,jdbcTemplate); - ProvisioningRunnerThread runnerThread = new ProvisioningRunnerThread(runner); - runnerThread.start(); - logger.debug("provisioning Runner Thread ."); + ProvisioningRunner runner = new ProvisioningRunner(connectorsService,jdbcTemplate); + ProvisioningRunnerThread runnerThread = new ProvisioningRunnerThread(runner); + runnerThread.start(); + logger.debug("provisioning Runner Thread ."); }else { - logger.debug("not need init provisioning Runner Thread ."); + logger.debug("not need init provisioning Runner Thread ."); } return "provisioningRunnerThread"; } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyMgtMvcConfig.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyMgtMvcConfig.java index cd8a101d7..73f24da74 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyMgtMvcConfig.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyMgtMvcConfig.java @@ -34,7 +34,7 @@ public class MaxKeyMgtMvcConfig implements WebMvcConfigurer { private static final Logger logger = LoggerFactory.getLogger(MaxKeyMgtMvcConfig.class); @Autowired - ApplicationConfig applicationConfig; + ApplicationConfig applicationConfig; @Autowired AbstractAuthenticationProvider authenticationProvider ; diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/listener/DynamicGroupsListenerAdapter.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/listener/DynamicGroupsListenerAdapter.java index addc4d333..712f10278 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/listener/DynamicGroupsListenerAdapter.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/listener/DynamicGroupsListenerAdapter.java @@ -27,7 +27,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DynamicGroupsListenerAdapter extends ScheduleAdapter implements Job , Serializable { - static final Logger logger = LoggerFactory.getLogger(DynamicGroupsListenerAdapter.class); + static final Logger logger = LoggerFactory.getLogger(DynamicGroupsListenerAdapter.class); private static final long serialVersionUID = 8831626240807856084L; @@ -43,8 +43,8 @@ public class DynamicGroupsListenerAdapter extends ScheduleAdapter implements Jo jobStatus = JOBSTATUS.RUNNING; try { if(groupsService != null) { - groupsService.refreshAllDynamicGroups(); - Thread.sleep(10 * 1000);//10 minutes + groupsService.refreshAllDynamicGroups(); + Thread.sleep(10 * 1000);//10 minutes } logger.debug("finished " ); jobStatus = JOBSTATUS.FINISHED; @@ -55,10 +55,10 @@ public class DynamicGroupsListenerAdapter extends ScheduleAdapter implements Jo } @Override - protected void init(JobExecutionContext context){ - super.init(context); - if(groupsService == null) { - groupsService = getParameter("groupsService",GroupsService.class); + protected void init(JobExecutionContext context){ + super.init(context); + if(groupsService == null) { + groupsService = getParameter("groupsService",GroupsService.class); } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/listener/DynamicRolesListenerAdapter.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/listener/DynamicRolesListenerAdapter.java index 4159dfb5e..c2ffe41e4 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/listener/DynamicRolesListenerAdapter.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/listener/DynamicRolesListenerAdapter.java @@ -27,12 +27,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DynamicRolesListenerAdapter extends ScheduleAdapter implements Job , Serializable { - /** - * - */ - private static final long serialVersionUID = 7000735366821127880L; + /** + * + */ + private static final long serialVersionUID = 7000735366821127880L; - static final Logger logger = LoggerFactory.getLogger(DynamicRolesListenerAdapter.class); + static final Logger logger = LoggerFactory.getLogger(DynamicRolesListenerAdapter.class); transient RolesService rolesService; @@ -46,8 +46,8 @@ public class DynamicRolesListenerAdapter extends ScheduleAdapter implements Job jobStatus = JOBSTATUS.RUNNING; try { if(rolesService != null) { - rolesService.refreshAllDynamicRoles(); - Thread.sleep(10 * 1000);//10 minutes + rolesService.refreshAllDynamicRoles(); + Thread.sleep(10 * 1000);//10 minutes } logger.debug("finished " ); jobStatus = JOBSTATUS.FINISHED; @@ -58,10 +58,10 @@ public class DynamicRolesListenerAdapter extends ScheduleAdapter implements Job } @Override - protected void init(JobExecutionContext context){ - super.init(context); - if(rolesService == null) { - rolesService = getParameter("rolesService",RolesService.class); + protected void init(JobExecutionContext context){ + super.init(context); + if(rolesService == null) { + rolesService = getParameter("rolesService",RolesService.class); } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/listener/ReorgDeptListenerAdapter.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/listener/ReorgDeptListenerAdapter.java index 6bab37e58..b811daff7 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/listener/ReorgDeptListenerAdapter.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/listener/ReorgDeptListenerAdapter.java @@ -26,35 +26,35 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ReorgDeptListenerAdapter extends ScheduleAdapter implements Job , Serializable { - static final Logger _logger = LoggerFactory.getLogger(ReorgDeptListenerAdapter.class); - - private static final long serialVersionUID = 4782358765969474833L; - - transient OrganizationsService organizationsService; + static final Logger _logger = LoggerFactory.getLogger(ReorgDeptListenerAdapter.class); + + private static final long serialVersionUID = 4782358765969474833L; + + transient OrganizationsService organizationsService; - @Override - public void execute(JobExecutionContext context) throws JobExecutionException { - if(jobStatus == JOBSTATUS.RUNNING) {return;} - init(context); - - _logger.debug("running ... " ); + @Override + public void execute(JobExecutionContext context) throws JobExecutionException { + if(jobStatus == JOBSTATUS.RUNNING) {return;} + init(context); + + _logger.debug("running ... " ); jobStatus = JOBSTATUS.RUNNING; try { - organizationsService.reorgNamePath(null); + organizationsService.reorgNamePath(null); _logger.debug("finished " ); jobStatus = JOBSTATUS.FINISHED; }catch(Exception e) { jobStatus = JOBSTATUS.ERROR; _logger.error("Exception " ,e); } - - } + + } - @Override - protected void init(JobExecutionContext context){ - super.init(context); - if(organizationsService == null) { - organizationsService = getParameter("organizationsService",OrganizationsService.class); + @Override + protected void init(JobExecutionContext context){ + super.init(context); + if(organizationsService == null) { + organizationsService = getParameter("organizationsService",OrganizationsService.class); } } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/access/contorller/AccessController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/access/contorller/AccessController.java index 76201aabd..032f8842e 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/access/contorller/AccessController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/access/contorller/AccessController.java @@ -44,82 +44,82 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value={"/access/access"}) public class AccessController { - static final Logger logger = LoggerFactory.getLogger(AccessController.class); - - @Autowired - AccessService accessService; + static final Logger logger = LoggerFactory.getLogger(AccessController.class); + + @Autowired + AccessService accessService; - @Autowired - HistorySystemLogsService systemLog; - - @GetMapping(value = { "/appsInGroup" }) - public Message> appsInRole( - @ModelAttribute Access groupPermission, - @CurrentUser UserInfo currentUser) { - JpaPageResults groupPermissions; - groupPermission.setInstId(currentUser.getInstId()); - groupPermissions= accessService.fetchPageResults("appsInGroup",groupPermission); + @Autowired + HistorySystemLogsService systemLog; + + @GetMapping(value = { "/appsInGroup" }) + public Message> appsInRole( + @ModelAttribute Access groupPermission, + @CurrentUser UserInfo currentUser) { + JpaPageResults groupPermissions; + groupPermission.setInstId(currentUser.getInstId()); + groupPermissions= accessService.fetchPageResults("appsInGroup",groupPermission); - if(groupPermissions!=null&&groupPermissions.getRows()!=null){ - for (Apps app : groupPermissions.getRows()){ - app.transIconBase64(); - } - } - return new Message<>(Message.FAIL,groupPermissions); - } - - @GetMapping(value = { "/appsNotInGroup" }) - public Message> appsNotInRole( - @ModelAttribute Access groupPermission, - @CurrentUser UserInfo currentUser) { - JpaPageResults groupPermissions; - groupPermission.setInstId(currentUser.getInstId()); - groupPermissions= accessService.fetchPageResults("appsNotInGroup",groupPermission); + if(groupPermissions!=null&&groupPermissions.getRows()!=null){ + for (Apps app : groupPermissions.getRows()){ + app.transIconBase64(); + } + } + return new Message<>(Message.FAIL,groupPermissions); + } + + @GetMapping(value = { "/appsNotInGroup" }) + public Message> appsNotInRole( + @ModelAttribute Access groupPermission, + @CurrentUser UserInfo currentUser) { + JpaPageResults groupPermissions; + groupPermission.setInstId(currentUser.getInstId()); + groupPermissions= accessService.fetchPageResults("appsNotInGroup",groupPermission); - if(groupPermissions!=null&&groupPermissions.getRows()!=null){ - for (Apps app : groupPermissions.getRows()){ - app.transIconBase64(); - } - } - return new Message<>(Message.FAIL,groupPermissions); - } + if(groupPermissions!=null&&groupPermissions.getRows()!=null){ + for (Apps app : groupPermissions.getRows()){ + app.transIconBase64(); + } + } + return new Message<>(Message.FAIL,groupPermissions); + } - @PostMapping(value = {"/add"}) - public Message insertPermission( - @RequestBody Access groupPermission, - @CurrentUser UserInfo currentUser) { - if (groupPermission == null || groupPermission.getGroupId() == null) { - return new Message<>(Message.FAIL); - } - String roleId = groupPermission.getGroupId(); - - boolean result = true; - String appIds = groupPermission.getAppId(); - if (appIds != null) { - String[] arrAppIds = appIds.split(","); - for (int i = 0; i < arrAppIds.length; i++) { - if(StringUtils.isNotBlank(arrAppIds[i])) { - Access newgroupPermissions = - new Access(roleId, arrAppIds[i],currentUser.getInstId()); - newgroupPermissions.setId(WebContext.genId()); - result = accessService.insert(newgroupPermissions); - } - } - if(result) { - return new Message<>(Message.SUCCESS); - } - } - return new Message<>(Message.FAIL); - } - - @DeleteMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {}" , ids); - if (accessService.deleteBatch(ids)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } + @PostMapping(value = {"/add"}) + public Message insertPermission( + @RequestBody Access groupPermission, + @CurrentUser UserInfo currentUser) { + if (groupPermission == null || groupPermission.getGroupId() == null) { + return new Message<>(Message.FAIL); + } + String roleId = groupPermission.getGroupId(); + + boolean result = true; + String appIds = groupPermission.getAppId(); + if (appIds != null) { + String[] arrAppIds = appIds.split(","); + for (int i = 0; i < arrAppIds.length; i++) { + if(StringUtils.isNotBlank(arrAppIds[i])) { + Access newgroupPermissions = + new Access(roleId, arrAppIds[i],currentUser.getInstId()); + newgroupPermissions.setId(WebContext.genId()); + result = accessService.insert(newgroupPermissions); + } + } + if(result) { + return new Message<>(Message.SUCCESS); + } + } + return new Message<>(Message.FAIL); + } + + @DeleteMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {}" , ids); + if (accessService.deleteBatch(ids)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/access/contorller/SessionController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/access/contorller/SessionController.java index 98697784f..05789f4d7 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/access/contorller/SessionController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/access/contorller/SessionController.java @@ -60,7 +60,7 @@ public class SessionController { SessionManager sessionManager; @Autowired - HistorySystemLogsService systemLog; + HistorySystemLogsService systemLog; /** * 查询登录日志. @@ -71,13 +71,13 @@ public class SessionController { @RequestMapping(value = { "/fetch" }) @ResponseBody public Message fetch( - @ModelAttribute("historyLogin") HistoryLogin historyLogin, - @CurrentUser UserInfo currentUser) { + @ModelAttribute("historyLogin") HistoryLogin historyLogin, + @CurrentUser UserInfo currentUser) { logger.debug("history/session/fetch {}" , historyLogin); historyLogin.setInstId(currentUser.getInstId()); return new Message>( - historyLoginService.queryOnlineSession(historyLogin) - ); + historyLoginService.queryOnlineSession(historyLogin) + ); } @@ -101,9 +101,9 @@ public class SessionController { } if(isTerminated) { - return new Message(Message.SUCCESS); + return new Message(Message.SUCCESS); } else { - return new Message(Message.ERROR); + return new Message(Message.ERROR); } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/ApplicationsController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/ApplicationsController.java index da867ea30..0259225df 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/ApplicationsController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/ApplicationsController.java @@ -47,151 +47,151 @@ import com.nimbusds.jose.jwk.gen.RSAKeyGenerator; @RestController @RequestMapping(value={"/apps"}) public class ApplicationsController extends BaseAppContorller { - static final Logger logger = LoggerFactory.getLogger(ApplicationsController.class); - - @GetMapping(value = { "/init" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message init() { - Apps app=new Apps(); - app.setId(app.generateId()); - app.setProtocol(ConstsProtocols.BASIC); - app.setSecret(StringGenerator.generateKey("")); - return new Message<>(app); - } - - - @GetMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message> fetch(@ModelAttribute Apps apps,@CurrentUser UserInfo currentUser) { - apps.setInstId(currentUser.getInstId()); - JpaPageResults appsList =appsService.fetchPageResults(apps); - for (Apps app : appsList.getRows()){ - app.transIconBase64(); - app.setSecret(null); - app.setSharedPassword(null); - } - logger.debug("List {}" , appsList); - return new Message<>(appsList); - } + static final Logger logger = LoggerFactory.getLogger(ApplicationsController.class); + + @GetMapping(value = { "/init" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message init() { + Apps app=new Apps(); + app.setId(app.generateId()); + app.setProtocol(ConstsProtocols.BASIC); + app.setSecret(StringGenerator.generateKey("")); + return new Message<>(app); + } + + + @GetMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message> fetch(@ModelAttribute Apps apps,@CurrentUser UserInfo currentUser) { + apps.setInstId(currentUser.getInstId()); + JpaPageResults appsList =appsService.fetchPageResults(apps); + for (Apps app : appsList.getRows()){ + app.transIconBase64(); + app.setSecret(null); + app.setSharedPassword(null); + } + logger.debug("List {}" , appsList); + return new Message<>(appsList); + } - @GetMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message query(@ModelAttribute Apps apps,@CurrentUser UserInfo currentUser) { - logger.debug("-query : {}" , apps); - if (CollectionUtils.isNotEmpty(appsService.query(apps))) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @GetMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@PathVariable("id") String id) { - Apps apps = appsService.get(id); - decoderSecret(apps); - apps.transIconBase64(); - return new Message<>(apps); - } - - @PostMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message insert(@RequestBody Apps apps,@CurrentUser UserInfo currentUser) { - logger.debug("-Add : {}" , apps); - transform(apps); - apps.setInstId(currentUser.getInstId()); - if (appsService.insert(apps)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update(@RequestBody Apps apps,@CurrentUser UserInfo currentUser) { - logger.debug("-update : {}" , apps); - transform(apps); - apps.setInstId(currentUser.getInstId()); - if (appsService.update(apps)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @DeleteMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {} " , ids); - if (appsService.deleteBatch(ids)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @PostMapping({ "/updateExtendAttr" }) - public Message updateExtendAttr(@RequestBody Apps app) { - logger.debug("-updateExtendAttr id : {} , ExtendAttr : {}" , app.getId(),app.getExtendAttr()); - if (appsService.updateExtendAttr(app)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @GetMapping({ "/generate/secret/{type}" }) - public Message generateSecret(@PathVariable("type") String type,@RequestParam(name="id",required=false) String id) throws JOSEException { - String secret=""; - type=type.toLowerCase(); - if(type.equals("des")){ - secret=StringGenerator.generateKey(ReciprocalUtils.Algorithm.DES); - }else if(type.equals("desede")){ - secret=StringGenerator.generateKey(ReciprocalUtils.Algorithm.DESede); - }else if(type.equals("aes")){ - secret=StringGenerator.generateKey(ReciprocalUtils.Algorithm.AES); - }else if(type.equals("blowfish")){ - secret=StringGenerator.generateKey(ReciprocalUtils.Algorithm.Blowfish); - }else if(type.equalsIgnoreCase("RS256") - ||type.equalsIgnoreCase("RS384") - ||type.equalsIgnoreCase("RS512")) { - RSAKey rsaJWK = new RSAKeyGenerator(2048) - .keyID(id + "_sig") - .keyUse(KeyUse.SIGNATURE) - .algorithm(new JWSAlgorithm(type.toUpperCase(), Requirement.OPTIONAL)) - .generate(); - secret = rsaJWK.toJSONString(); - }else if(type.equalsIgnoreCase("HS256") - ||type.equalsIgnoreCase("HS384") - ||type.equalsIgnoreCase("HS512")) { - OctetSequenceKey octKey= new OctetSequenceKeyGenerator(2048) - .keyID(id + "_sig") - .keyUse(KeyUse.SIGNATURE) - .algorithm(new JWSAlgorithm(type.toUpperCase(), Requirement.OPTIONAL)) - .generate(); - secret = octKey.toJSONString(); - }else if(type.equalsIgnoreCase("RSA1_5") - ||type.equalsIgnoreCase("RSA_OAEP") - ||type.equalsIgnoreCase("RSA-OAEP-256")) { - RSAKey rsaJWK = new RSAKeyGenerator(2048) - .keyID(id + "_enc") - .keyUse(KeyUse.ENCRYPTION) - .algorithm(new JWEAlgorithm(type.toUpperCase(), Requirement.OPTIONAL)) - .generate(); - secret = rsaJWK.toJSONString(); - }else if(type.equalsIgnoreCase("A128KW") - ||type.equalsIgnoreCase("A192KW") - ||type.equalsIgnoreCase("A256KW") - ||type.equalsIgnoreCase("A128GCMKW") - ||type.equalsIgnoreCase("A192GCMKW") - ||type.equalsIgnoreCase("A256GCMKW")) { - int keyLength = Integer.parseInt(type.substring(1, 4)); - OctetSequenceKey octKey= new OctetSequenceKeyGenerator(keyLength) - .keyID(id + "_enc") - .keyUse(KeyUse.ENCRYPTION) - .algorithm(new JWEAlgorithm(type.toUpperCase(), Requirement.OPTIONAL)) - .generate(); - secret = octKey.toJSONString(); - }else{ - secret=StringGenerator.generateKey(""); - } - - return new Message<>(Message.SUCCESS,secret); - } - - + @GetMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message query(@ModelAttribute Apps apps,@CurrentUser UserInfo currentUser) { + logger.debug("-query : {}" , apps); + if (CollectionUtils.isNotEmpty(appsService.query(apps))) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @GetMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@PathVariable("id") String id) { + Apps apps = appsService.get(id); + decoderSecret(apps); + apps.transIconBase64(); + return new Message<>(apps); + } + + @PostMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message insert(@RequestBody Apps apps,@CurrentUser UserInfo currentUser) { + logger.debug("-Add : {}" , apps); + transform(apps); + apps.setInstId(currentUser.getInstId()); + if (appsService.insert(apps)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update(@RequestBody Apps apps,@CurrentUser UserInfo currentUser) { + logger.debug("-update : {}" , apps); + transform(apps); + apps.setInstId(currentUser.getInstId()); + if (appsService.update(apps)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @DeleteMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {} " , ids); + if (appsService.deleteBatch(ids)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @PostMapping({ "/updateExtendAttr" }) + public Message updateExtendAttr(@RequestBody Apps app) { + logger.debug("-updateExtendAttr id : {} , ExtendAttr : {}" , app.getId(),app.getExtendAttr()); + if (appsService.updateExtendAttr(app)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @GetMapping({ "/generate/secret/{type}" }) + public Message generateSecret(@PathVariable("type") String type,@RequestParam(name="id",required=false) String id) throws JOSEException { + String secret=""; + type=type.toLowerCase(); + if(type.equals("des")){ + secret=StringGenerator.generateKey(ReciprocalUtils.Algorithm.DES); + }else if(type.equals("desede")){ + secret=StringGenerator.generateKey(ReciprocalUtils.Algorithm.DESede); + }else if(type.equals("aes")){ + secret=StringGenerator.generateKey(ReciprocalUtils.Algorithm.AES); + }else if(type.equals("blowfish")){ + secret=StringGenerator.generateKey(ReciprocalUtils.Algorithm.Blowfish); + }else if(type.equalsIgnoreCase("RS256") + ||type.equalsIgnoreCase("RS384") + ||type.equalsIgnoreCase("RS512")) { + RSAKey rsaJWK = new RSAKeyGenerator(2048) + .keyID(id + "_sig") + .keyUse(KeyUse.SIGNATURE) + .algorithm(new JWSAlgorithm(type.toUpperCase(), Requirement.OPTIONAL)) + .generate(); + secret = rsaJWK.toJSONString(); + }else if(type.equalsIgnoreCase("HS256") + ||type.equalsIgnoreCase("HS384") + ||type.equalsIgnoreCase("HS512")) { + OctetSequenceKey octKey= new OctetSequenceKeyGenerator(2048) + .keyID(id + "_sig") + .keyUse(KeyUse.SIGNATURE) + .algorithm(new JWSAlgorithm(type.toUpperCase(), Requirement.OPTIONAL)) + .generate(); + secret = octKey.toJSONString(); + }else if(type.equalsIgnoreCase("RSA1_5") + ||type.equalsIgnoreCase("RSA_OAEP") + ||type.equalsIgnoreCase("RSA-OAEP-256")) { + RSAKey rsaJWK = new RSAKeyGenerator(2048) + .keyID(id + "_enc") + .keyUse(KeyUse.ENCRYPTION) + .algorithm(new JWEAlgorithm(type.toUpperCase(), Requirement.OPTIONAL)) + .generate(); + secret = rsaJWK.toJSONString(); + }else if(type.equalsIgnoreCase("A128KW") + ||type.equalsIgnoreCase("A192KW") + ||type.equalsIgnoreCase("A256KW") + ||type.equalsIgnoreCase("A128GCMKW") + ||type.equalsIgnoreCase("A192GCMKW") + ||type.equalsIgnoreCase("A256GCMKW")) { + int keyLength = Integer.parseInt(type.substring(1, 4)); + OctetSequenceKey octKey= new OctetSequenceKeyGenerator(keyLength) + .keyID(id + "_enc") + .keyUse(KeyUse.ENCRYPTION) + .algorithm(new JWEAlgorithm(type.toUpperCase(), Requirement.OPTIONAL)) + .generate(); + secret = octKey.toJSONString(); + }else{ + secret=StringGenerator.generateKey(""); + } + + return new Message<>(Message.SUCCESS,secret); + } + + } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/BaseAppContorller.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/BaseAppContorller.java index 31a449ab0..c35cbca5d 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/BaseAppContorller.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/BaseAppContorller.java @@ -35,70 +35,70 @@ import org.springframework.beans.factory.annotation.Autowired; * */ public class BaseAppContorller { - static final Logger logger = LoggerFactory.getLogger(BaseAppContorller.class); - - @Autowired - protected AppsService appsService; + static final Logger logger = LoggerFactory.getLogger(BaseAppContorller.class); + + @Autowired + protected AppsService appsService; - @Autowired - protected PasswordReciprocal passwordReciprocal; - - @Autowired - protected FileUploadService fileUploadService; - - @Autowired - HistorySystemLogsService systemLog; - - public void setAppsService(AppsService appsService) { - this.appsService = appsService; - } + @Autowired + protected PasswordReciprocal passwordReciprocal; + + @Autowired + protected FileUploadService fileUploadService; + + @Autowired + HistorySystemLogsService systemLog; + + public void setAppsService(AppsService appsService) { + this.appsService = appsService; + } - protected void transform(Apps application) { - encodeSharedPassword(application); - encodeSecret(application); - /* - * string field encoding - */ - encoding(application); - /* - * upload icon Bytes - */ - if(StringUtils.isNotBlank(application.getIconId())){ - application.setIcon(fileUploadService.get(application.getIconId()).getUploaded()); - fileUploadService.delete(application.getIconId()); - } - - } - - protected void encodeSharedPassword(Apps application){ - if(StringUtils.isNotBlank(application.getSharedPassword())){ - application.setSharedPassword( - PasswordReciprocal.getInstance().encode(application.getSharedPassword())); - } - } - - protected void decoderSharedPassword(Apps application){ - if(StringUtils.isNotBlank(application.getSharedPassword())){ - application.setSharedPassword( - PasswordReciprocal.getInstance().decoder(application.getSharedPassword())); - } - } - - protected void encoding(Apps application){ - - } - - protected void encodeSecret(Apps application){ - if(StringUtils.isNotBlank(application.getSecret())){ - String encodeSecret=passwordReciprocal.encode(application.getSecret()); - application.setSecret(encodeSecret); - } - } - - protected void decoderSecret(Apps application){ - if(StringUtils.isNotBlank(application.getSecret())){ - String decodeSecret=passwordReciprocal.decoder(application.getSecret()); - application.setSecret(decodeSecret); - } - } + protected void transform(Apps application) { + encodeSharedPassword(application); + encodeSecret(application); + /* + * string field encoding + */ + encoding(application); + /* + * upload icon Bytes + */ + if(StringUtils.isNotBlank(application.getIconId())){ + application.setIcon(fileUploadService.get(application.getIconId()).getUploaded()); + fileUploadService.delete(application.getIconId()); + } + + } + + protected void encodeSharedPassword(Apps application){ + if(StringUtils.isNotBlank(application.getSharedPassword())){ + application.setSharedPassword( + PasswordReciprocal.getInstance().encode(application.getSharedPassword())); + } + } + + protected void decoderSharedPassword(Apps application){ + if(StringUtils.isNotBlank(application.getSharedPassword())){ + application.setSharedPassword( + PasswordReciprocal.getInstance().decoder(application.getSharedPassword())); + } + } + + protected void encoding(Apps application){ + + } + + protected void encodeSecret(Apps application){ + if(StringUtils.isNotBlank(application.getSecret())){ + String encodeSecret=passwordReciprocal.encode(application.getSecret()); + application.setSecret(encodeSecret); + } + } + + protected void decoderSecret(Apps application){ + if(StringUtils.isNotBlank(application.getSecret())){ + String decodeSecret=passwordReciprocal.decoder(application.getSecret()); + application.setSecret(decodeSecret); + } + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/CasDetailsController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/CasDetailsController.java index f2b451a5e..ebae3d214 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/CasDetailsController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/CasDetailsController.java @@ -36,60 +36,60 @@ import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value={"/apps/cas"}) public class CasDetailsController extends BaseAppContorller { - static final Logger logger = LoggerFactory.getLogger(CasDetailsController.class); - - @Autowired - AppsCasDetailsService casDetailsService; - - @GetMapping(value = { "/init" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message init() { - AppsCasDetails casDetails =new AppsCasDetails(); - casDetails.setId(casDetails.generateId()); - casDetails.setProtocol(ConstsProtocols.CAS); - casDetails.setSecret(StringGenerator.generateKey("")); - return new Message<>(casDetails); - } - - @GetMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@PathVariable("id") String id) { - AppsCasDetails casDetails=casDetailsService.getAppDetails(id , false); - super.decoderSecret(casDetails); - casDetails.transIconBase64(); - return new Message<>(casDetails); - } - - @PostMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message insert(@RequestBody AppsCasDetails casDetails,@CurrentUser UserInfo currentUser) { - logger.debug("-Add : {}" , casDetails); - transform(casDetails); - casDetails.setInstId(currentUser.getInstId()); - if (casDetailsService.insert(casDetails)&&appsService.insertApp(casDetails)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update(@RequestBody AppsCasDetails casDetails,@CurrentUser UserInfo currentUser) { - logger.debug("-update : {}" , casDetails); - transform(casDetails); - casDetails.setInstId(currentUser.getInstId()); - if (casDetailsService.update(casDetails)&&appsService.updateApp(casDetails)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @DeleteMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {} " , ids); - if (casDetailsService.deleteBatch(ids)&&appsService.deleteBatch(ids)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - + static final Logger logger = LoggerFactory.getLogger(CasDetailsController.class); + + @Autowired + AppsCasDetailsService casDetailsService; + + @GetMapping(value = { "/init" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message init() { + AppsCasDetails casDetails =new AppsCasDetails(); + casDetails.setId(casDetails.generateId()); + casDetails.setProtocol(ConstsProtocols.CAS); + casDetails.setSecret(StringGenerator.generateKey("")); + return new Message<>(casDetails); + } + + @GetMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@PathVariable("id") String id) { + AppsCasDetails casDetails=casDetailsService.getAppDetails(id , false); + super.decoderSecret(casDetails); + casDetails.transIconBase64(); + return new Message<>(casDetails); + } + + @PostMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message insert(@RequestBody AppsCasDetails casDetails,@CurrentUser UserInfo currentUser) { + logger.debug("-Add : {}" , casDetails); + transform(casDetails); + casDetails.setInstId(currentUser.getInstId()); + if (casDetailsService.insert(casDetails)&&appsService.insertApp(casDetails)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update(@RequestBody AppsCasDetails casDetails,@CurrentUser UserInfo currentUser) { + logger.debug("-update : {}" , casDetails); + transform(casDetails); + casDetails.setInstId(currentUser.getInstId()); + if (casDetailsService.update(casDetails)&&appsService.updateApp(casDetails)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @DeleteMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {} " , ids); + if (casDetailsService.deleteBatch(ids)&&appsService.deleteBatch(ids)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/ExtendApiDetailsController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/ExtendApiDetailsController.java index e2050337d..14280e635 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/ExtendApiDetailsController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/ExtendApiDetailsController.java @@ -36,64 +36,64 @@ import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value={"/apps/extendapi"}) public class ExtendApiDetailsController extends BaseAppContorller { - static final Logger logger = LoggerFactory.getLogger(ExtendApiDetailsController.class); + static final Logger logger = LoggerFactory.getLogger(ExtendApiDetailsController.class); - @GetMapping(value = { "/init" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message init() { - AppsExtendApiDetails extendApiDetails=new AppsExtendApiDetails(); - extendApiDetails.setId(extendApiDetails.generateId()); - extendApiDetails.setProtocol(ConstsProtocols.EXTEND_API); - extendApiDetails.setSecret(StringGenerator.generateKey("")); - return new Message<>(extendApiDetails); - } - - @GetMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@PathVariable("id") String id) { - Apps application= appsService.get(id); - super.decoderSecret(application); - AppsExtendApiDetails extendApiDetails=new AppsExtendApiDetails(); - BeanUtils.copyProperties(application, extendApiDetails); - extendApiDetails.transIconBase64(); - return new Message<>(extendApiDetails); - } - - @PostMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message add( - @RequestBody AppsExtendApiDetails extendApiDetails, - @CurrentUser UserInfo currentUser) { - logger.debug("-Add : {}" , extendApiDetails); - - transform(extendApiDetails); - extendApiDetails.setInstId(currentUser.getInstId()); - if (appsService.insertApp(extendApiDetails)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update( - @RequestBody AppsExtendApiDetails extendApiDetails, - @CurrentUser UserInfo currentUser) { - logger.debug("-update : {}" , extendApiDetails); - transform(extendApiDetails); - extendApiDetails.setInstId(currentUser.getInstId()); - if (appsService.updateApp(extendApiDetails)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @DeleteMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {} " , ids); - if (appsService.deleteBatch(ids)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } + @GetMapping(value = { "/init" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message init() { + AppsExtendApiDetails extendApiDetails=new AppsExtendApiDetails(); + extendApiDetails.setId(extendApiDetails.generateId()); + extendApiDetails.setProtocol(ConstsProtocols.EXTEND_API); + extendApiDetails.setSecret(StringGenerator.generateKey("")); + return new Message<>(extendApiDetails); + } + + @GetMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@PathVariable("id") String id) { + Apps application= appsService.get(id); + super.decoderSecret(application); + AppsExtendApiDetails extendApiDetails=new AppsExtendApiDetails(); + BeanUtils.copyProperties(application, extendApiDetails); + extendApiDetails.transIconBase64(); + return new Message<>(extendApiDetails); + } + + @PostMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message add( + @RequestBody AppsExtendApiDetails extendApiDetails, + @CurrentUser UserInfo currentUser) { + logger.debug("-Add : {}" , extendApiDetails); + + transform(extendApiDetails); + extendApiDetails.setInstId(currentUser.getInstId()); + if (appsService.insertApp(extendApiDetails)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update( + @RequestBody AppsExtendApiDetails extendApiDetails, + @CurrentUser UserInfo currentUser) { + logger.debug("-update : {}" , extendApiDetails); + transform(extendApiDetails); + extendApiDetails.setInstId(currentUser.getInstId()); + if (appsService.updateApp(extendApiDetails)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @DeleteMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {} " , ids); + if (appsService.deleteBatch(ids)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/FormBasedDetailsController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/FormBasedDetailsController.java index 3f50642e1..2de26e775 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/FormBasedDetailsController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/FormBasedDetailsController.java @@ -41,74 +41,74 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value={"/apps/formbased"}) public class FormBasedDetailsController extends BaseAppContorller { - static final Logger logger = LoggerFactory.getLogger(FormBasedDetailsController.class); - - @Autowired - AppsFormBasedDetailsService formBasedDetailsService; - - @RequestMapping(value = { "/init" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message init() { - AppsFormBasedDetails formBasedDetails=new AppsFormBasedDetails(); - formBasedDetails.setId(formBasedDetails.generateId()); - formBasedDetails.setProtocol(ConstsProtocols.FORMBASED); - formBasedDetails.setSecret(StringGenerator.generateKey("")); - return new Message(formBasedDetails); - } - - @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@PathVariable("id") String id) { - AppsFormBasedDetails formBasedDetails=formBasedDetailsService.getAppDetails(id , false); - decoderSecret(formBasedDetails); - decoderSharedPassword(formBasedDetails); - formBasedDetails.transIconBase64(); - return new Message(formBasedDetails); - } - - @ResponseBody - @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message add( - @RequestBody AppsFormBasedDetails formBasedDetails, - @CurrentUser UserInfo currentUser) { - logger.debug("-Add : {}" , formBasedDetails); - - transform(formBasedDetails); - formBasedDetails.setInstId(currentUser.getInstId()); - if (formBasedDetailsService.insert(formBasedDetails) - &&appsService.insertApp(formBasedDetails)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @ResponseBody - @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update( - @RequestBody AppsFormBasedDetails formBasedDetails, - @CurrentUser UserInfo currentUser) { - logger.debug("-update : {}" , formBasedDetails); - transform(formBasedDetails); - formBasedDetails.setInstId(currentUser.getInstId()); - if (formBasedDetailsService.update(formBasedDetails) - &&appsService.updateApp(formBasedDetails)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @ResponseBody - @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete( - @RequestParam("ids") List ids, - @CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {} " , ids); - if (formBasedDetailsService.deleteBatch(ids) - && appsService.deleteBatch(ids)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - + static final Logger logger = LoggerFactory.getLogger(FormBasedDetailsController.class); + + @Autowired + AppsFormBasedDetailsService formBasedDetailsService; + + @RequestMapping(value = { "/init" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message init() { + AppsFormBasedDetails formBasedDetails=new AppsFormBasedDetails(); + formBasedDetails.setId(formBasedDetails.generateId()); + formBasedDetails.setProtocol(ConstsProtocols.FORMBASED); + formBasedDetails.setSecret(StringGenerator.generateKey("")); + return new Message(formBasedDetails); + } + + @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@PathVariable("id") String id) { + AppsFormBasedDetails formBasedDetails=formBasedDetailsService.getAppDetails(id , false); + decoderSecret(formBasedDetails); + decoderSharedPassword(formBasedDetails); + formBasedDetails.transIconBase64(); + return new Message(formBasedDetails); + } + + @ResponseBody + @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message add( + @RequestBody AppsFormBasedDetails formBasedDetails, + @CurrentUser UserInfo currentUser) { + logger.debug("-Add : {}" , formBasedDetails); + + transform(formBasedDetails); + formBasedDetails.setInstId(currentUser.getInstId()); + if (formBasedDetailsService.insert(formBasedDetails) + &&appsService.insertApp(formBasedDetails)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @ResponseBody + @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update( + @RequestBody AppsFormBasedDetails formBasedDetails, + @CurrentUser UserInfo currentUser) { + logger.debug("-update : {}" , formBasedDetails); + transform(formBasedDetails); + formBasedDetails.setInstId(currentUser.getInstId()); + if (formBasedDetailsService.update(formBasedDetails) + &&appsService.updateApp(formBasedDetails)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @ResponseBody + @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete( + @RequestParam("ids") List ids, + @CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {} " , ids); + if (formBasedDetailsService.deleteBatch(ids) + && appsService.deleteBatch(ids)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/JwtDetailsController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/JwtDetailsController.java index 315f54fa0..61f0014db 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/JwtDetailsController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/JwtDetailsController.java @@ -41,66 +41,66 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value={"/apps/jwt"}) public class JwtDetailsController extends BaseAppContorller { - static final Logger logger = LoggerFactory.getLogger(JwtDetailsController.class); - - @Autowired - AppsJwtDetailsService jwtDetailsService; - - @RequestMapping(value = { "/init" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message init() { - AppsJwtDetails jwtDetails =new AppsJwtDetails(); - jwtDetails.setId(jwtDetails.generateId()); - jwtDetails.setProtocol(ConstsProtocols.JWT); - jwtDetails.setSecret(StringGenerator.generateKey("")); - jwtDetails.setUserPropertys("userPropertys"); - return new Message(jwtDetails); - } - - @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@PathVariable("id") String id) { - AppsJwtDetails jwtDetails=jwtDetailsService.getAppDetails(id , false); - decoderSecret(jwtDetails); - jwtDetails.transIconBase64(); - return new Message(jwtDetails); - } - - @ResponseBody - @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message insert(@RequestBody AppsJwtDetails jwtDetails,@CurrentUser UserInfo currentUser) { - logger.debug("-Add : {}" , jwtDetails); - - transform(jwtDetails); - - jwtDetails.setInstId(currentUser.getInstId()); - if (jwtDetailsService.insert(jwtDetails)&&appsService.insertApp(jwtDetails)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @ResponseBody - @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update(@RequestBody AppsJwtDetails jwtDetails,@CurrentUser UserInfo currentUser) { - logger.debug("-update : {}" , jwtDetails); - transform(jwtDetails); - jwtDetails.setInstId(currentUser.getInstId()); - if (jwtDetailsService.update(jwtDetails)&&appsService.updateApp(jwtDetails)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @ResponseBody - @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {} " , ids); - if (jwtDetailsService.deleteBatch(ids)&&appsService.deleteBatch(ids)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - + static final Logger logger = LoggerFactory.getLogger(JwtDetailsController.class); + + @Autowired + AppsJwtDetailsService jwtDetailsService; + + @RequestMapping(value = { "/init" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message init() { + AppsJwtDetails jwtDetails =new AppsJwtDetails(); + jwtDetails.setId(jwtDetails.generateId()); + jwtDetails.setProtocol(ConstsProtocols.JWT); + jwtDetails.setSecret(StringGenerator.generateKey("")); + jwtDetails.setUserPropertys("userPropertys"); + return new Message(jwtDetails); + } + + @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@PathVariable("id") String id) { + AppsJwtDetails jwtDetails=jwtDetailsService.getAppDetails(id , false); + decoderSecret(jwtDetails); + jwtDetails.transIconBase64(); + return new Message(jwtDetails); + } + + @ResponseBody + @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message insert(@RequestBody AppsJwtDetails jwtDetails,@CurrentUser UserInfo currentUser) { + logger.debug("-Add : {}" , jwtDetails); + + transform(jwtDetails); + + jwtDetails.setInstId(currentUser.getInstId()); + if (jwtDetailsService.insert(jwtDetails)&&appsService.insertApp(jwtDetails)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @ResponseBody + @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update(@RequestBody AppsJwtDetails jwtDetails,@CurrentUser UserInfo currentUser) { + logger.debug("-update : {}" , jwtDetails); + transform(jwtDetails); + jwtDetails.setInstId(currentUser.getInstId()); + if (jwtDetailsService.update(jwtDetails)&&appsService.updateApp(jwtDetails)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @ResponseBody + @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {} " , ids); + if (jwtDetailsService.deleteBatch(ids)&&appsService.deleteBatch(ids)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/OAuth20DetailsController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/OAuth20DetailsController.java index 89102380f..4308518e9 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/OAuth20DetailsController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/OAuth20DetailsController.java @@ -44,97 +44,97 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value={"/apps/oauth20"}) public class OAuth20DetailsController extends BaseAppContorller { - static final Logger logger = LoggerFactory.getLogger(OAuth20DetailsController.class); - - @Autowired - JdbcClientDetailsService oauth20JdbcClientDetailsService; + static final Logger logger = LoggerFactory.getLogger(OAuth20DetailsController.class); + + @Autowired + JdbcClientDetailsService oauth20JdbcClientDetailsService; - @RequestMapping(value = { "/init" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message init() { - AppsOAuth20Details oauth20Details=new AppsOAuth20Details(); - oauth20Details.setId(oauth20Details.generateId()); - oauth20Details.setSecret(StringGenerator.generateKey("")); - oauth20Details.setClientId(oauth20Details.getId()); - oauth20Details.setClientSecret(oauth20Details.getSecret()); - oauth20Details.setProtocol(ConstsProtocols.OAUTH20); - return new Message(oauth20Details); - } - - @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@PathVariable("id") String id) { - BaseClientDetails baseClientDetails=(BaseClientDetails)oauth20JdbcClientDetailsService.loadClientByClientId(id,false); - Apps application=appsService.get(id);// - decoderSecret(application); - AppsOAuth20Details oauth20Details=new AppsOAuth20Details(application,baseClientDetails); - oauth20Details.setSecret(application.getSecret()); - oauth20Details.setClientSecret(application.getSecret()); - logger.debug("forwardUpdate {}" , oauth20Details); - oauth20Details.transIconBase64(); - return new Message(oauth20Details); - } - - @ResponseBody - @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message add( - @RequestBody AppsOAuth20Details oauth20Details, - @CurrentUser UserInfo currentUser) { - logger.debug("-Add : {}", oauth20Details); - - if(oauth20Details.getProtocol().equalsIgnoreCase(ConstsProtocols.OAUTH21)) { - oauth20Details.setPkce(OAuth2Constants.PKCE_TYPE.PKCE_TYPE_YES); - } - transform(oauth20Details); - - oauth20Details.setClientSecret(oauth20Details.getSecret()); - oauth20Details.setInstId(currentUser.getInstId()); - - oauth20JdbcClientDetailsService.addClientDetails(oauth20Details.clientDetailsRowMapper()); - if (appsService.insertApp(oauth20Details)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @ResponseBody - @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update( - @RequestBody AppsOAuth20Details oauth20Details, - @CurrentUser UserInfo currentUser) { - logger.debug("-update : {}" , oauth20Details); - logger.debug("-update application {}" , oauth20Details); - logger.debug("-update oauth20Details use oauth20JdbcClientDetails" ); - if(oauth20Details.getProtocol().equalsIgnoreCase(ConstsProtocols.OAUTH21)) { + @RequestMapping(value = { "/init" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message init() { + AppsOAuth20Details oauth20Details=new AppsOAuth20Details(); + oauth20Details.setId(oauth20Details.generateId()); + oauth20Details.setSecret(StringGenerator.generateKey("")); + oauth20Details.setClientId(oauth20Details.getId()); + oauth20Details.setClientSecret(oauth20Details.getSecret()); + oauth20Details.setProtocol(ConstsProtocols.OAUTH20); + return new Message(oauth20Details); + } + + @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@PathVariable("id") String id) { + BaseClientDetails baseClientDetails=(BaseClientDetails)oauth20JdbcClientDetailsService.loadClientByClientId(id,false); + Apps application=appsService.get(id);// + decoderSecret(application); + AppsOAuth20Details oauth20Details=new AppsOAuth20Details(application,baseClientDetails); + oauth20Details.setSecret(application.getSecret()); + oauth20Details.setClientSecret(application.getSecret()); + logger.debug("forwardUpdate {}" , oauth20Details); + oauth20Details.transIconBase64(); + return new Message(oauth20Details); + } + + @ResponseBody + @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message add( + @RequestBody AppsOAuth20Details oauth20Details, + @CurrentUser UserInfo currentUser) { + logger.debug("-Add : {}", oauth20Details); + + if(oauth20Details.getProtocol().equalsIgnoreCase(ConstsProtocols.OAUTH21)) { oauth20Details.setPkce(OAuth2Constants.PKCE_TYPE.PKCE_TYPE_YES); } - - transform(oauth20Details); - oauth20Details.setClientSecret(oauth20Details.getSecret()); - oauth20Details.setInstId(currentUser.getInstId()); + transform(oauth20Details); + + oauth20Details.setClientSecret(oauth20Details.getSecret()); + oauth20Details.setInstId(currentUser.getInstId()); + + oauth20JdbcClientDetailsService.addClientDetails(oauth20Details.clientDetailsRowMapper()); + if (appsService.insertApp(oauth20Details)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @ResponseBody + @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update( + @RequestBody AppsOAuth20Details oauth20Details, + @CurrentUser UserInfo currentUser) { + logger.debug("-update : {}" , oauth20Details); + logger.debug("-update application {}" , oauth20Details); + logger.debug("-update oauth20Details use oauth20JdbcClientDetails" ); + if(oauth20Details.getProtocol().equalsIgnoreCase(ConstsProtocols.OAUTH21)) { + oauth20Details.setPkce(OAuth2Constants.PKCE_TYPE.PKCE_TYPE_YES); + } + + transform(oauth20Details); + oauth20Details.setClientSecret(oauth20Details.getSecret()); + oauth20Details.setInstId(currentUser.getInstId()); oauth20JdbcClientDetailsService.updateClientDetails(oauth20Details.clientDetailsRowMapper()); oauth20JdbcClientDetailsService.updateClientSecret(oauth20Details.getClientId(), oauth20Details.getClientSecret()); - if (appsService.updateApp(oauth20Details)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @ResponseBody - @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete( - @RequestParam("ids") List ids, - @CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {} " , ids); - for (String id : ids){ - oauth20JdbcClientDetailsService.removeClientDetails(id); - } - if (appsService.deleteBatch(ids)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - + if (appsService.updateApp(oauth20Details)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @ResponseBody + @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete( + @RequestParam("ids") List ids, + @CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {} " , ids); + for (String id : ids){ + oauth20JdbcClientDetailsService.removeClientDetails(id); + } + if (appsService.deleteBatch(ids)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/SAML20DetailsController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/SAML20DetailsController.java index f153c5e8a..ac20bc4ca 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/SAML20DetailsController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/SAML20DetailsController.java @@ -59,149 +59,149 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value={"/apps/saml20"}) public class SAML20DetailsController extends BaseAppContorller { - static final Logger logger = LoggerFactory.getLogger(SAML20DetailsController.class); - - @Autowired - KeyStoreLoader keyStoreLoader; - - @Autowired - AppsSaml20DetailsService saml20DetailsService; - - @Autowired - ApplicationConfig applicationConfig; - - @RequestMapping(value = { "/init" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message init() { - AppsSAML20Details saml20Details=new AppsSAML20Details(); - saml20Details.setSecret(StringGenerator.generateKey("")); - saml20Details.setProtocol(ConstsProtocols.SAML20); - saml20Details.setId(saml20Details.generateId()); - return new Message(saml20Details); - } - - @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@PathVariable("id") String id) { - AppsSAML20Details saml20Details=saml20DetailsService.getAppDetails(id , false); - decoderSecret(saml20Details); - saml20Details.transIconBase64(); - //modelAndView.addObject("authzURI",applicationConfig.getAuthzUri()); - return new Message(saml20Details); - } - - @ResponseBody - @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message add( - @RequestBody AppsSAML20Details saml20Details, - @CurrentUser UserInfo currentUser) { - logger.debug("-Add : {}" , saml20Details); - - try { - transform(saml20Details); - } catch (Exception e) { - e.printStackTrace(); - } - saml20Details.setInstId(currentUser.getInstId()); - saml20DetailsService.insert(saml20Details); - if (appsService.insertApp(saml20Details)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @ResponseBody - @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update( - @RequestBody AppsSAML20Details saml20Details, - @CurrentUser UserInfo currentUser) { - logger.debug("-update : {}" , saml20Details); - try { - transform(saml20Details); - } catch (Exception e) { - e.printStackTrace(); - } - saml20Details.setInstId(currentUser.getInstId()); - saml20DetailsService.update(saml20Details); - if (appsService.updateApp(saml20Details)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @ResponseBody - @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete( - @RequestParam("ids") List ids, - @CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {} " , ids); - if (saml20DetailsService.deleteBatch(ids)&&appsService.deleteBatch(ids)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - protected AppsSAML20Details transform(AppsSAML20Details samlDetails) throws Exception{ - super.transform(samlDetails); - ByteArrayInputStream bArrayInputStream = null; - if(StringUtils.isNotBlank(samlDetails.getMetaFileId())) { - bArrayInputStream = new ByteArrayInputStream( - fileUploadService.get(samlDetails.getMetaFileId()).getUploaded()); - fileUploadService.delete(samlDetails.getMetaFileId()); - } - - if(StringUtils.isNotBlank(samlDetails.getFileType())){ - if(samlDetails.getFileType().equals("certificate")){//certificate file - try { - if(bArrayInputStream != null) { - samlDetails.setTrustCert( - X509CertUtils.loadCertFromInputStream(bArrayInputStream)); - } - } catch (IOException e) { - logger.error("read certificate file error .", e); - } - }else if(samlDetails.getFileType().equals("metadata_file")){//metadata file - if(bArrayInputStream != null) { - samlDetails = resolveMetaData(samlDetails,bArrayInputStream); - } - }else if(samlDetails.getFileType().equals("metadata_url") - &&StringUtils.isNotBlank(samlDetails.getMetaUrl())){//metadata url - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpPost post = new HttpPost(samlDetails.getMetaUrl()); - CloseableHttpResponse response = httpClient.execute(post); - samlDetails = resolveMetaData(samlDetails,response.getEntity().getContent());; - response.close(); - httpClient.close(); - } - } - - if(samlDetails.getTrustCert()!=null) { - samlDetails.setCertSubject(samlDetails.getTrustCert().getSubjectDN().getName()); - samlDetails.setCertExpiration(samlDetails.getTrustCert().getNotAfter().toString()); - - samlDetails.setCertIssuer(X509CertUtils.getCommonName(samlDetails.getTrustCert().getIssuerX500Principal())); - - KeyStore keyStore = KeyStoreUtil.clone(keyStoreLoader.getKeyStore(),keyStoreLoader.getKeystorePassword()); - - KeyStore trustKeyStore = null; - if (!samlDetails.getEntityId().equals("")) { - trustKeyStore = KeyStoreUtil.importTrustCertificate(keyStore,samlDetails.getTrustCert(), samlDetails.getEntityId()); - } else { - trustKeyStore = KeyStoreUtil.importTrustCertificate(keyStore,samlDetails.getTrustCert()); - } - - byte[] keyStoreByte = KeyStoreUtil.keyStore2Bytes(trustKeyStore,keyStoreLoader.getKeystorePassword()); - - // store KeyStore content - samlDetails.setKeyStore(keyStoreByte); - } - return samlDetails; - } - - public AppsSAML20Details resolveMetaData(AppsSAML20Details samlDetails,InputStream inputStream) throws Exception { - X509Certificate trustCert = null; - EntityDescriptor entityDescriptor; + static final Logger logger = LoggerFactory.getLogger(SAML20DetailsController.class); + + @Autowired + KeyStoreLoader keyStoreLoader; + + @Autowired + AppsSaml20DetailsService saml20DetailsService; + + @Autowired + ApplicationConfig applicationConfig; + + @RequestMapping(value = { "/init" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message init() { + AppsSAML20Details saml20Details=new AppsSAML20Details(); + saml20Details.setSecret(StringGenerator.generateKey("")); + saml20Details.setProtocol(ConstsProtocols.SAML20); + saml20Details.setId(saml20Details.generateId()); + return new Message(saml20Details); + } + + @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@PathVariable("id") String id) { + AppsSAML20Details saml20Details=saml20DetailsService.getAppDetails(id , false); + decoderSecret(saml20Details); + saml20Details.transIconBase64(); + //modelAndView.addObject("authzURI",applicationConfig.getAuthzUri()); + return new Message(saml20Details); + } + + @ResponseBody + @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message add( + @RequestBody AppsSAML20Details saml20Details, + @CurrentUser UserInfo currentUser) { + logger.debug("-Add : {}" , saml20Details); + + try { + transform(saml20Details); + } catch (Exception e) { + e.printStackTrace(); + } + saml20Details.setInstId(currentUser.getInstId()); + saml20DetailsService.insert(saml20Details); + if (appsService.insertApp(saml20Details)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @ResponseBody + @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update( + @RequestBody AppsSAML20Details saml20Details, + @CurrentUser UserInfo currentUser) { + logger.debug("-update : {}" , saml20Details); + try { + transform(saml20Details); + } catch (Exception e) { + e.printStackTrace(); + } + saml20Details.setInstId(currentUser.getInstId()); + saml20DetailsService.update(saml20Details); + if (appsService.updateApp(saml20Details)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @ResponseBody + @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete( + @RequestParam("ids") List ids, + @CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {} " , ids); + if (saml20DetailsService.deleteBatch(ids)&&appsService.deleteBatch(ids)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + protected AppsSAML20Details transform(AppsSAML20Details samlDetails) throws Exception{ + super.transform(samlDetails); + ByteArrayInputStream bArrayInputStream = null; + if(StringUtils.isNotBlank(samlDetails.getMetaFileId())) { + bArrayInputStream = new ByteArrayInputStream( + fileUploadService.get(samlDetails.getMetaFileId()).getUploaded()); + fileUploadService.delete(samlDetails.getMetaFileId()); + } + + if(StringUtils.isNotBlank(samlDetails.getFileType())){ + if(samlDetails.getFileType().equals("certificate")){//certificate file + try { + if(bArrayInputStream != null) { + samlDetails.setTrustCert( + X509CertUtils.loadCertFromInputStream(bArrayInputStream)); + } + } catch (IOException e) { + logger.error("read certificate file error .", e); + } + }else if(samlDetails.getFileType().equals("metadata_file")){//metadata file + if(bArrayInputStream != null) { + samlDetails = resolveMetaData(samlDetails,bArrayInputStream); + } + }else if(samlDetails.getFileType().equals("metadata_url") + &&StringUtils.isNotBlank(samlDetails.getMetaUrl())){//metadata url + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpPost post = new HttpPost(samlDetails.getMetaUrl()); + CloseableHttpResponse response = httpClient.execute(post); + samlDetails = resolveMetaData(samlDetails,response.getEntity().getContent());; + response.close(); + httpClient.close(); + } + } + + if(samlDetails.getTrustCert()!=null) { + samlDetails.setCertSubject(samlDetails.getTrustCert().getSubjectDN().getName()); + samlDetails.setCertExpiration(samlDetails.getTrustCert().getNotAfter().toString()); + + samlDetails.setCertIssuer(X509CertUtils.getCommonName(samlDetails.getTrustCert().getIssuerX500Principal())); + + KeyStore keyStore = KeyStoreUtil.clone(keyStoreLoader.getKeyStore(),keyStoreLoader.getKeystorePassword()); + + KeyStore trustKeyStore = null; + if (!samlDetails.getEntityId().equals("")) { + trustKeyStore = KeyStoreUtil.importTrustCertificate(keyStore,samlDetails.getTrustCert(), samlDetails.getEntityId()); + } else { + trustKeyStore = KeyStoreUtil.importTrustCertificate(keyStore,samlDetails.getTrustCert()); + } + + byte[] keyStoreByte = KeyStoreUtil.keyStore2Bytes(trustKeyStore,keyStoreLoader.getKeystorePassword()); + + // store KeyStore content + samlDetails.setKeyStore(keyStoreByte); + } + return samlDetails; + } + + public AppsSAML20Details resolveMetaData(AppsSAML20Details samlDetails,InputStream inputStream) throws Exception { + X509Certificate trustCert = null; + EntityDescriptor entityDescriptor; try { entityDescriptor = MetadataDescriptorUtil.getInstance().getEntityDescriptor(inputStream); } catch (IOException e) { @@ -227,6 +227,6 @@ public class SAML20DetailsController extends BaseAppContorller { logger.info("SPSSODescriptor EntityID {}", entityDescriptor.getEntityID()); return samlDetails; - } - + } + } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/TokenBasedDetailsController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/TokenBasedDetailsController.java index 53e172fef..421f30580 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/TokenBasedDetailsController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/apps/contorller/TokenBasedDetailsController.java @@ -43,79 +43,79 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value={"/apps/tokenbased"}) public class TokenBasedDetailsController extends BaseAppContorller { - static final Logger logger = LoggerFactory.getLogger(TokenBasedDetailsController.class); - - @Autowired - AppsTokenBasedDetailsService tokenBasedDetailsService; - - @RequestMapping(value = { "/init" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message init() { - AppsTokenBasedDetails tokenBasedDetails =new AppsTokenBasedDetails(); - tokenBasedDetails.setId(tokenBasedDetails.generateId()); - tokenBasedDetails.setProtocol(ConstsProtocols.TOKENBASED); - tokenBasedDetails.setSecret(StringGenerator.generateKey(ReciprocalUtils.Algorithm.AES)); - tokenBasedDetails.setAlgorithmKey(tokenBasedDetails.getSecret()); - tokenBasedDetails.setUserPropertys("userPropertys"); - return new Message(tokenBasedDetails); - } - - @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@PathVariable("id") String id) { - AppsTokenBasedDetails tokenBasedDetails=tokenBasedDetailsService.getAppDetails(id , false); - decoderSecret(tokenBasedDetails); - String algorithmKey=passwordReciprocal.decoder(tokenBasedDetails.getAlgorithmKey()); - tokenBasedDetails.setAlgorithmKey(algorithmKey); - tokenBasedDetails.transIconBase64(); - return new Message(tokenBasedDetails); - } - - @ResponseBody - @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message add( - @RequestBody AppsTokenBasedDetails tokenBasedDetails, - @CurrentUser UserInfo currentUser) { - logger.debug("-Add : {}" , tokenBasedDetails); - - transform(tokenBasedDetails); - - tokenBasedDetails.setAlgorithmKey(tokenBasedDetails.getSecret()); - tokenBasedDetails.setInstId(currentUser.getInstId()); - if (tokenBasedDetailsService.insert(tokenBasedDetails) - &&appsService.insertApp(tokenBasedDetails)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @ResponseBody - @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update( - @RequestBody AppsTokenBasedDetails tokenBasedDetails, - @CurrentUser UserInfo currentUser) { - logger.debug("-update : {}" , tokenBasedDetails); - transform(tokenBasedDetails); - tokenBasedDetails.setAlgorithmKey(tokenBasedDetails.getSecret()); - tokenBasedDetails.setInstId(currentUser.getInstId()); - if (tokenBasedDetailsService.update(tokenBasedDetails) - &&appsService.updateApp(tokenBasedDetails)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @ResponseBody - @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete( - @RequestParam("ids") List ids, - @CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {} " , ids); - if (tokenBasedDetailsService.deleteBatch(ids)&&appsService.deleteBatch(ids)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - + static final Logger logger = LoggerFactory.getLogger(TokenBasedDetailsController.class); + + @Autowired + AppsTokenBasedDetailsService tokenBasedDetailsService; + + @RequestMapping(value = { "/init" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message init() { + AppsTokenBasedDetails tokenBasedDetails =new AppsTokenBasedDetails(); + tokenBasedDetails.setId(tokenBasedDetails.generateId()); + tokenBasedDetails.setProtocol(ConstsProtocols.TOKENBASED); + tokenBasedDetails.setSecret(StringGenerator.generateKey(ReciprocalUtils.Algorithm.AES)); + tokenBasedDetails.setAlgorithmKey(tokenBasedDetails.getSecret()); + tokenBasedDetails.setUserPropertys("userPropertys"); + return new Message(tokenBasedDetails); + } + + @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@PathVariable("id") String id) { + AppsTokenBasedDetails tokenBasedDetails=tokenBasedDetailsService.getAppDetails(id , false); + decoderSecret(tokenBasedDetails); + String algorithmKey=passwordReciprocal.decoder(tokenBasedDetails.getAlgorithmKey()); + tokenBasedDetails.setAlgorithmKey(algorithmKey); + tokenBasedDetails.transIconBase64(); + return new Message(tokenBasedDetails); + } + + @ResponseBody + @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message add( + @RequestBody AppsTokenBasedDetails tokenBasedDetails, + @CurrentUser UserInfo currentUser) { + logger.debug("-Add : {}" , tokenBasedDetails); + + transform(tokenBasedDetails); + + tokenBasedDetails.setAlgorithmKey(tokenBasedDetails.getSecret()); + tokenBasedDetails.setInstId(currentUser.getInstId()); + if (tokenBasedDetailsService.insert(tokenBasedDetails) + &&appsService.insertApp(tokenBasedDetails)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @ResponseBody + @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update( + @RequestBody AppsTokenBasedDetails tokenBasedDetails, + @CurrentUser UserInfo currentUser) { + logger.debug("-update : {}" , tokenBasedDetails); + transform(tokenBasedDetails); + tokenBasedDetails.setAlgorithmKey(tokenBasedDetails.getSecret()); + tokenBasedDetails.setInstId(currentUser.getInstId()); + if (tokenBasedDetailsService.update(tokenBasedDetails) + &&appsService.updateApp(tokenBasedDetails)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @ResponseBody + @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete( + @RequestParam("ids") List ids, + @CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {} " , ids); + if (tokenBasedDetailsService.deleteBatch(ids)&&appsService.deleteBatch(ids)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/AccountsStrategyController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/AccountsStrategyController.java index 3daa3ef56..a10541894 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/AccountsStrategyController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/AccountsStrategyController.java @@ -36,71 +36,71 @@ import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value={"/config/accountsstrategy"}) public class AccountsStrategyController { - static final Logger logger = LoggerFactory.getLogger(AccountsStrategyController.class); - - @Autowired - AccountsStrategyService accountsStrategyService; - - @Autowired - AccountsService accountsService; - - @GetMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message> fetch(@ModelAttribute AccountsStrategy accountsStrategy,@CurrentUser UserInfo currentUser) { - accountsStrategy.setInstId(currentUser.getInstId()); - JpaPageResults accountsStrategyList =accountsStrategyService.fetchPageResults(accountsStrategy); - for (AccountsStrategy strategy : accountsStrategyList.getRows()){ - strategy.transIconBase64(); - } - logger.debug("Accounts Strategy {}" , accountsStrategyList); - return new Message<>(accountsStrategyList); - } + static final Logger logger = LoggerFactory.getLogger(AccountsStrategyController.class); + + @Autowired + AccountsStrategyService accountsStrategyService; + + @Autowired + AccountsService accountsService; + + @GetMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message> fetch(@ModelAttribute AccountsStrategy accountsStrategy,@CurrentUser UserInfo currentUser) { + accountsStrategy.setInstId(currentUser.getInstId()); + JpaPageResults accountsStrategyList =accountsStrategyService.fetchPageResults(accountsStrategy); + for (AccountsStrategy strategy : accountsStrategyList.getRows()){ + strategy.transIconBase64(); + } + logger.debug("Accounts Strategy {}" , accountsStrategyList); + return new Message<>(accountsStrategyList); + } - @GetMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message query(@ModelAttribute AccountsStrategy accountsStrategy,@CurrentUser UserInfo currentUser) { - logger.debug("-query : {}" , accountsStrategy); - if (CollectionUtils.isNotEmpty(accountsStrategyService.query(accountsStrategy))) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @GetMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@PathVariable("id") String id) { - AccountsStrategy accountsStrategy = accountsStrategyService.get(id); - return new Message<>(accountsStrategy); - } - - @PostMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message insert(@RequestBody AccountsStrategy accountsStrategy,@CurrentUser UserInfo currentUser) { - logger.debug("-Add : {}" , accountsStrategy); - - if (accountsStrategyService.insert(accountsStrategy)) { - accountsService.refreshByStrategy(accountsStrategy); - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update(@RequestBody AccountsStrategy accountsStrategy,@CurrentUser UserInfo currentUser) { - logger.debug("-update : {}" , accountsStrategy); - if (accountsStrategyService.update(accountsStrategy)) { - accountsService.refreshByStrategy(accountsStrategy); - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @DeleteMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {} " , ids); - if (accountsStrategyService.deleteBatch(ids)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } + @GetMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message query(@ModelAttribute AccountsStrategy accountsStrategy,@CurrentUser UserInfo currentUser) { + logger.debug("-query : {}" , accountsStrategy); + if (CollectionUtils.isNotEmpty(accountsStrategyService.query(accountsStrategy))) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @GetMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@PathVariable("id") String id) { + AccountsStrategy accountsStrategy = accountsStrategyService.get(id); + return new Message<>(accountsStrategy); + } + + @PostMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message insert(@RequestBody AccountsStrategy accountsStrategy,@CurrentUser UserInfo currentUser) { + logger.debug("-Add : {}" , accountsStrategy); + + if (accountsStrategyService.insert(accountsStrategy)) { + accountsService.refreshByStrategy(accountsStrategy); + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update(@RequestBody AccountsStrategy accountsStrategy,@CurrentUser UserInfo currentUser) { + logger.debug("-update : {}" , accountsStrategy); + if (accountsStrategyService.update(accountsStrategy)) { + accountsService.refreshByStrategy(accountsStrategy); + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @DeleteMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {} " , ids); + if (accountsStrategyService.deleteBatch(ids)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/AdaptersController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/AdaptersController.java index 8ddd04b3c..be9ee2e66 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/AdaptersController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/AdaptersController.java @@ -36,62 +36,62 @@ import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value={"/config/adapters"}) public class AdaptersController { - static final Logger logger = LoggerFactory.getLogger(AdaptersController.class); - - @Autowired - AppsAdaptersService appsAdaptersService; - - @GetMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message> fetch(@ModelAttribute AppsAdapters appsAdapter) { - logger.debug("fetch {}",appsAdapter); - return new Message<>( - appsAdaptersService.fetchPageResults(appsAdapter)); - } + static final Logger logger = LoggerFactory.getLogger(AdaptersController.class); + + @Autowired + AppsAdaptersService appsAdaptersService; + + @GetMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message> fetch(@ModelAttribute AppsAdapters appsAdapter) { + logger.debug("fetch {}",appsAdapter); + return new Message<>( + appsAdaptersService.fetchPageResults(appsAdapter)); + } - @GetMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message query(@ModelAttribute AppsAdapters appsAdapter,@CurrentUser UserInfo currentUser) { - logger.debug("-query : {}" , appsAdapter); - if (CollectionUtils.isNotEmpty(appsAdaptersService.query(appsAdapter))) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @GetMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@PathVariable("id") String id) { - AppsAdapters appsAdapter=appsAdaptersService.get(id); - return new Message<>(appsAdapter); - } - - @PostMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message insert(@RequestBody AppsAdapters appsAdapter,@CurrentUser UserInfo currentUser) { - logger.debug("-Add : {}" , appsAdapter); - - if (appsAdaptersService.insert(appsAdapter)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update(@RequestBody AppsAdapters appsAdapter,@CurrentUser UserInfo currentUser) { - logger.debug("-update : {}" , appsAdapter); - if (appsAdaptersService.update(appsAdapter)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @DeleteMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {} " , ids); - if (appsAdaptersService.deleteBatch(ids)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } + @GetMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message query(@ModelAttribute AppsAdapters appsAdapter,@CurrentUser UserInfo currentUser) { + logger.debug("-query : {}" , appsAdapter); + if (CollectionUtils.isNotEmpty(appsAdaptersService.query(appsAdapter))) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @GetMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@PathVariable("id") String id) { + AppsAdapters appsAdapter=appsAdaptersService.get(id); + return new Message<>(appsAdapter); + } + + @PostMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message insert(@RequestBody AppsAdapters appsAdapter,@CurrentUser UserInfo currentUser) { + logger.debug("-Add : {}" , appsAdapter); + + if (appsAdaptersService.insert(appsAdapter)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update(@RequestBody AppsAdapters appsAdapter,@CurrentUser UserInfo currentUser) { + logger.debug("-update : {}" , appsAdapter); + if (appsAdaptersService.update(appsAdapter)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @DeleteMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {} " , ids); + if (appsAdaptersService.deleteBatch(ids)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/CnfEmailSendersController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/CnfEmailSendersController.java index a8f5edf08..b460f6666 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/CnfEmailSendersController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/CnfEmailSendersController.java @@ -33,43 +33,43 @@ import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value={"/config/emailsenders"}) public class CnfEmailSendersController { - static final Logger logger = LoggerFactory.getLogger(CnfEmailSendersController.class); - - @Autowired - CnfEmailSendersService emailSendersService; + static final Logger logger = LoggerFactory.getLogger(CnfEmailSendersController.class); + + @Autowired + CnfEmailSendersService emailSendersService; - @GetMapping({"/get"}) - public Message get(@CurrentUser UserInfo currentUser){ - CnfEmailSenders emailSenders = emailSendersService.get(currentUser.getInstId()); - if(emailSenders != null && StringUtils.isNotBlank(emailSenders.getCredentials())) { - emailSenders.setCredentials(PasswordReciprocal.getInstance().decoder(emailSenders.getCredentials())); - }else { - emailSenders =new CnfEmailSenders(); - emailSenders.setProtocol("smtp"); - emailSenders.setEncoding("utf-8"); - } - return new Message<>(emailSenders); - } + @GetMapping({"/get"}) + public Message get(@CurrentUser UserInfo currentUser){ + CnfEmailSenders emailSenders = emailSendersService.get(currentUser.getInstId()); + if(emailSenders != null && StringUtils.isNotBlank(emailSenders.getCredentials())) { + emailSenders.setCredentials(PasswordReciprocal.getInstance().decoder(emailSenders.getCredentials())); + }else { + emailSenders =new CnfEmailSenders(); + emailSenders.setProtocol("smtp"); + emailSenders.setEncoding("utf-8"); + } + return new Message<>(emailSenders); + } - @PutMapping({"/update"}) - public Message update( @RequestBody CnfEmailSenders emailSenders,@CurrentUser UserInfo currentUser,BindingResult result) { - logger.debug("update emailSenders : {}" , emailSenders); - emailSenders.setInstId(currentUser.getInstId()); - emailSenders.setCredentials(PasswordReciprocal.getInstance().encode(emailSenders.getCredentials())); - if(StringUtils.isBlank(emailSenders.getId())) { - emailSenders.setId(emailSenders.getInstId()); - if(emailSendersService.insert(emailSenders)) { - return new Message<>(Message.SUCCESS); - }else { - return new Message<>(Message.ERROR); - } - }else { - if(emailSendersService.update(emailSenders)) { - return new Message<>(Message.SUCCESS); - }else { - return new Message<>(Message.ERROR); - } - } - - } + @PutMapping({"/update"}) + public Message update( @RequestBody CnfEmailSenders emailSenders,@CurrentUser UserInfo currentUser,BindingResult result) { + logger.debug("update emailSenders : {}" , emailSenders); + emailSenders.setInstId(currentUser.getInstId()); + emailSenders.setCredentials(PasswordReciprocal.getInstance().encode(emailSenders.getCredentials())); + if(StringUtils.isBlank(emailSenders.getId())) { + emailSenders.setId(emailSenders.getInstId()); + if(emailSendersService.insert(emailSenders)) { + return new Message<>(Message.SUCCESS); + }else { + return new Message<>(Message.ERROR); + } + }else { + if(emailSendersService.update(emailSenders)) { + return new Message<>(Message.SUCCESS); + }else { + return new Message<>(Message.ERROR); + } + } + + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/CnfLdapContextController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/CnfLdapContextController.java index 3244709bf..f50c53bc2 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/CnfLdapContextController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/CnfLdapContextController.java @@ -36,76 +36,76 @@ import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value={"/config/ldapcontext"}) public class CnfLdapContextController { - static final Logger logger = LoggerFactory.getLogger(CnfLdapContextController.class); - - @Autowired - CnfLdapContextService ldapContextService; + static final Logger logger = LoggerFactory.getLogger(CnfLdapContextController.class); + + @Autowired + CnfLdapContextService ldapContextService; - @GetMapping(value={"/get"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@CurrentUser UserInfo currentUser){ - CnfLdapContext ldapContext = ldapContextService.get(currentUser.getInstId()); - if(ldapContext != null && StringUtils.isNoneBlank(ldapContext.getCredentials())) { - ldapContext.setCredentials(PasswordReciprocal.getInstance().decoder(ldapContext.getCredentials())); - } - return new Message<>(ldapContext); - } + @GetMapping(value={"/get"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@CurrentUser UserInfo currentUser){ + CnfLdapContext ldapContext = ldapContextService.get(currentUser.getInstId()); + if(ldapContext != null && StringUtils.isNoneBlank(ldapContext.getCredentials())) { + ldapContext.setCredentials(PasswordReciprocal.getInstance().decoder(ldapContext.getCredentials())); + } + return new Message<>(ldapContext); + } - @PutMapping({"/update"}) - public Message update( @RequestBody CnfLdapContext ldapContext,@CurrentUser UserInfo currentUser,BindingResult result) { - logger.debug("update ldapContext : {}" ,ldapContext); - ldapContext.setCredentials(PasswordReciprocal.getInstance().encode(ldapContext.getCredentials())); - ldapContext.setInstId(currentUser.getInstId()); - boolean updateResult = false; - if(StringUtils.isBlank(ldapContext.getId())) { - ldapContext.setId(ldapContext.getInstId()); - updateResult = ldapContextService.insert(ldapContext); - }else { - updateResult = ldapContextService.update(ldapContext); - } - if(updateResult) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - - @GetMapping(value={"/test"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message test(@CurrentUser UserInfo currentUser){ - CnfLdapContext ldapContext = ldapContextService.get(currentUser.getInstId()); - if(ldapContext != null && StringUtils.isNoneBlank(ldapContext.getCredentials())) { - ldapContext.setCredentials(PasswordReciprocal.getInstance().decoder(ldapContext.getCredentials())); - } - - LdapUtils ldapUtils = null; - if(ldapContext != null) { - if(ldapContext.getProduct().equalsIgnoreCase(LdapUtils.Product.ActiveDirectory)) { - ldapUtils = new ActiveDirectoryUtils( - ldapContext.getProviderUrl(), - ldapContext.getPrincipal(), - ldapContext.getCredentials(), - ldapContext.getBasedn(), - ldapContext.getMsadDomain()); - }else if(ldapContext.getProduct().equalsIgnoreCase(LdapUtils.Product.OpenLDAP)) { - ldapUtils = new LdapUtils( - ldapContext.getProviderUrl(), - ldapContext.getPrincipal(), - ldapContext.getCredentials(), - ldapContext.getBasedn()); - }else if(ldapContext.getProduct().equalsIgnoreCase(LdapUtils.Product.StandardLDAP)) { - ldapUtils = new LdapUtils( - ldapContext.getProviderUrl(), - ldapContext.getPrincipal(), - ldapContext.getCredentials(), - ldapContext.getBasedn()); - } - - if(ldapUtils != null && ldapUtils.openConnection() != null) { - ldapUtils.close(); - return new Message<>(Message.SUCCESS); - } - } - - return new Message<>(Message.FAIL); - } + @PutMapping({"/update"}) + public Message update( @RequestBody CnfLdapContext ldapContext,@CurrentUser UserInfo currentUser,BindingResult result) { + logger.debug("update ldapContext : {}" ,ldapContext); + ldapContext.setCredentials(PasswordReciprocal.getInstance().encode(ldapContext.getCredentials())); + ldapContext.setInstId(currentUser.getInstId()); + boolean updateResult = false; + if(StringUtils.isBlank(ldapContext.getId())) { + ldapContext.setId(ldapContext.getInstId()); + updateResult = ldapContextService.insert(ldapContext); + }else { + updateResult = ldapContextService.update(ldapContext); + } + if(updateResult) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + + @GetMapping(value={"/test"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message test(@CurrentUser UserInfo currentUser){ + CnfLdapContext ldapContext = ldapContextService.get(currentUser.getInstId()); + if(ldapContext != null && StringUtils.isNoneBlank(ldapContext.getCredentials())) { + ldapContext.setCredentials(PasswordReciprocal.getInstance().decoder(ldapContext.getCredentials())); + } + + LdapUtils ldapUtils = null; + if(ldapContext != null) { + if(ldapContext.getProduct().equalsIgnoreCase(LdapUtils.Product.ActiveDirectory)) { + ldapUtils = new ActiveDirectoryUtils( + ldapContext.getProviderUrl(), + ldapContext.getPrincipal(), + ldapContext.getCredentials(), + ldapContext.getBasedn(), + ldapContext.getMsadDomain()); + }else if(ldapContext.getProduct().equalsIgnoreCase(LdapUtils.Product.OpenLDAP)) { + ldapUtils = new LdapUtils( + ldapContext.getProviderUrl(), + ldapContext.getPrincipal(), + ldapContext.getCredentials(), + ldapContext.getBasedn()); + }else if(ldapContext.getProduct().equalsIgnoreCase(LdapUtils.Product.StandardLDAP)) { + ldapUtils = new LdapUtils( + ldapContext.getProviderUrl(), + ldapContext.getPrincipal(), + ldapContext.getCredentials(), + ldapContext.getBasedn()); + } + + if(ldapUtils != null && ldapUtils.openConnection() != null) { + ldapUtils.close(); + return new Message<>(Message.SUCCESS); + } + } + + return new Message<>(Message.FAIL); + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/CnfPasswordPolicyController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/CnfPasswordPolicyController.java index 1fe516482..f47f537b2 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/CnfPasswordPolicyController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/CnfPasswordPolicyController.java @@ -35,67 +35,67 @@ import jakarta.validation.Valid; @RestController @RequestMapping(value={"/config/passwordpolicy"}) public class CnfPasswordPolicyController { - static final Logger logger = LoggerFactory.getLogger(CnfPasswordPolicyController.class); - - @Autowired - CnfPasswordPolicyService passwordPolicyService; - - @GetMapping(value={"/get"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@CurrentUser UserInfo currentUser){ - CnfPasswordPolicy passwordPolicy = passwordPolicyService.get(currentUser.getInstId()); - return new Message<>(passwordPolicy); - } + static final Logger logger = LoggerFactory.getLogger(CnfPasswordPolicyController.class); + + @Autowired + CnfPasswordPolicyService passwordPolicyService; + + @GetMapping(value={"/get"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@CurrentUser UserInfo currentUser){ + CnfPasswordPolicy passwordPolicy = passwordPolicyService.get(currentUser.getInstId()); + return new Message<>(passwordPolicy); + } - @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update(@Valid @RequestBody CnfPasswordPolicy passwordPolicy,@CurrentUser UserInfo currentUser,BindingResult result) { - logger.debug("updateRole passwordPolicy : {}" ,passwordPolicy); - //Message message = this.validate(result, passwordPolicy); - - if(passwordPolicyService.update(passwordPolicy)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.ERROR); - } - } - - public Message validate(BindingResult result,CnfPasswordPolicy passwordPolicy) { - if (result.hasErrors()) { - return new Message(result); - } - if(passwordPolicy.getMinLength() < 3) { - FieldError fe = new FieldError("passwordPolicy", "minLength", - passwordPolicy.getMinLength(), true, - new String[]{"ui.passwordpolicy.xe00000001"},//密码最小长度不能小于3位字符 - null, null); - result.addError(fe); - return new Message(result); - } - if(passwordPolicy.getMinLength() > passwordPolicy.getMaxLength()) { - FieldError fe = new FieldError("passwordPolicy", "maxLength", - passwordPolicy.getMinLength(), true, - new String[]{"ui.passwordpolicy.xe00000002"},//密码最大长度不能小于最小长度 - null, null); - result.addError(fe); - return new Message(result); - } - - if(passwordPolicy.getDigits() + passwordPolicy.getLowerCase() + passwordPolicy.getUpperCase() + passwordPolicy.getSpecialChar() < 2) { - FieldError fe = new FieldError("passwordPolicy", "specialChar", - 2, true, - new String[]{"ui.passwordpolicy.xe00000003"},//密码包含小写字母、大写字母、数字、特殊字符的个数不能小于2 - null, null); - result.addError(fe); - return new Message(result); - } - - if(passwordPolicy.getDigits() + passwordPolicy.getLowerCase() + passwordPolicy.getUpperCase() + passwordPolicy.getSpecialChar() > passwordPolicy.getMaxLength()) { - FieldError fe = new FieldError("passwordPolicy", "specialChar", - passwordPolicy.getMinLength(), true, - new String[]{"ui.passwordpolicy.xe00000004"},//密码包含小写字母、大写字母、数字、特殊字符的个数不能大于密码的最大长度 - null, null); - result.addError(fe); - return new Message(result); - } - return null; - } + @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update(@Valid @RequestBody CnfPasswordPolicy passwordPolicy,@CurrentUser UserInfo currentUser,BindingResult result) { + logger.debug("updateRole passwordPolicy : {}" ,passwordPolicy); + //Message message = this.validate(result, passwordPolicy); + + if(passwordPolicyService.update(passwordPolicy)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.ERROR); + } + } + + public Message validate(BindingResult result,CnfPasswordPolicy passwordPolicy) { + if (result.hasErrors()) { + return new Message(result); + } + if(passwordPolicy.getMinLength() < 3) { + FieldError fe = new FieldError("passwordPolicy", "minLength", + passwordPolicy.getMinLength(), true, + new String[]{"ui.passwordpolicy.xe00000001"},//密码最小长度不能小于3位字符 + null, null); + result.addError(fe); + return new Message(result); + } + if(passwordPolicy.getMinLength() > passwordPolicy.getMaxLength()) { + FieldError fe = new FieldError("passwordPolicy", "maxLength", + passwordPolicy.getMinLength(), true, + new String[]{"ui.passwordpolicy.xe00000002"},//密码最大长度不能小于最小长度 + null, null); + result.addError(fe); + return new Message(result); + } + + if(passwordPolicy.getDigits() + passwordPolicy.getLowerCase() + passwordPolicy.getUpperCase() + passwordPolicy.getSpecialChar() < 2) { + FieldError fe = new FieldError("passwordPolicy", "specialChar", + 2, true, + new String[]{"ui.passwordpolicy.xe00000003"},//密码包含小写字母、大写字母、数字、特殊字符的个数不能小于2 + null, null); + result.addError(fe); + return new Message(result); + } + + if(passwordPolicy.getDigits() + passwordPolicy.getLowerCase() + passwordPolicy.getUpperCase() + passwordPolicy.getSpecialChar() > passwordPolicy.getMaxLength()) { + FieldError fe = new FieldError("passwordPolicy", "specialChar", + passwordPolicy.getMinLength(), true, + new String[]{"ui.passwordpolicy.xe00000004"},//密码包含小写字母、大写字母、数字、特殊字符的个数不能大于密码的最大长度 + null, null); + result.addError(fe); + return new Message(result); + } + return null; + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/CnfSmsProviderController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/CnfSmsProviderController.java index 40d913a93..093996453 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/CnfSmsProviderController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/CnfSmsProviderController.java @@ -34,36 +34,36 @@ import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value={"/config/smsprovider"}) public class CnfSmsProviderController { - static final Logger logger = LoggerFactory.getLogger(CnfSmsProviderController.class); - - @Autowired - CnfSmsProviderService smsProviderService; + static final Logger logger = LoggerFactory.getLogger(CnfSmsProviderController.class); + + @Autowired + CnfSmsProviderService smsProviderService; - @GetMapping(value={"/get"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@CurrentUser UserInfo currentUser){ - CnfSmsProvider smsProvider = smsProviderService.get(currentUser.getInstId()); - if(smsProvider != null && StringUtils.isNoneBlank(smsProvider.getId())) { - smsProvider.setAppSecret(PasswordReciprocal.getInstance().decoder(smsProvider.getAppSecret())); - } - return new Message<>(smsProvider); - } + @GetMapping(value={"/get"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@CurrentUser UserInfo currentUser){ + CnfSmsProvider smsProvider = smsProviderService.get(currentUser.getInstId()); + if(smsProvider != null && StringUtils.isNoneBlank(smsProvider.getId())) { + smsProvider.setAppSecret(PasswordReciprocal.getInstance().decoder(smsProvider.getAppSecret())); + } + return new Message<>(smsProvider); + } - @PutMapping({"/update"}) - public Message update( @RequestBody CnfSmsProvider smsProvider,@CurrentUser UserInfo currentUser,BindingResult result) { - logger.debug("update smsProvider : {}" ,smsProvider); - smsProvider.setAppSecret(PasswordReciprocal.getInstance().encode(smsProvider.getAppSecret())); - smsProvider.setInstId(currentUser.getInstId()); - boolean updateResult = false; - if(StringUtils.isBlank(smsProvider.getId())) { - smsProvider.setId(smsProvider.getInstId()); - updateResult = smsProviderService.insert(smsProvider); - }else { - updateResult = smsProviderService.update(smsProvider); - } - if(updateResult) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } + @PutMapping({"/update"}) + public Message update( @RequestBody CnfSmsProvider smsProvider,@CurrentUser UserInfo currentUser,BindingResult result) { + logger.debug("update smsProvider : {}" ,smsProvider); + smsProvider.setAppSecret(PasswordReciprocal.getInstance().encode(smsProvider.getAppSecret())); + smsProvider.setInstId(currentUser.getInstId()); + boolean updateResult = false; + if(StringUtils.isBlank(smsProvider.getId())) { + smsProvider.setId(smsProvider.getInstId()); + updateResult = smsProviderService.insert(smsProvider); + }else { + updateResult = smsProviderService.update(smsProvider); + } + if(updateResult) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/ConnectorsController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/ConnectorsController.java index 17b9528cf..7cbbdd6fa 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/ConnectorsController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/ConnectorsController.java @@ -36,61 +36,61 @@ import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value={"/config/connectors"}) public class ConnectorsController { - static final Logger logger = LoggerFactory.getLogger(ConnectorsController.class); - - @Autowired - ConnectorsService connectorsService; - - @GetMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message> fetch(Connectors connector,@CurrentUser UserInfo currentUser) { - logger.debug("fetch {}" , connector); - connector.setInstId(currentUser.getInstId()); - return new Message<>(connectorsService.fetchPageResults(connector)); - } - - @GetMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@PathVariable("id") String id) { - Connectors connector = connectorsService.get(id); - if(StringUtils.isNotBlank(connector.getCredentials())) { - connector.setCredentials(PasswordReciprocal.getInstance().decoder(connector.getCredentials())); - } - return new Message<>(connector); - } - - @PostMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message insert(@RequestBody Connectors connector,@CurrentUser UserInfo currentUser) { - logger.debug("-Add : {}" , connector); - connector.setInstId(currentUser.getInstId()); - if(StringUtils.isNotBlank(connector.getCredentials())) { - connector.setCredentials(PasswordReciprocal.getInstance().encode(connector.getCredentials())); - } - if (connectorsService.insert(connector)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update(@RequestBody Connectors connector,@CurrentUser UserInfo currentUser) { - logger.debug("-update : {}" , connector); - connector.setInstId(currentUser.getInstId()); - connector.setCredentials(PasswordReciprocal.getInstance().encode(connector.getCredentials())); - if (connectorsService.update(connector)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @DeleteMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {} " , ids); - if (connectorsService.deleteBatch(ids)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } + static final Logger logger = LoggerFactory.getLogger(ConnectorsController.class); + + @Autowired + ConnectorsService connectorsService; + + @GetMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message> fetch(Connectors connector,@CurrentUser UserInfo currentUser) { + logger.debug("fetch {}" , connector); + connector.setInstId(currentUser.getInstId()); + return new Message<>(connectorsService.fetchPageResults(connector)); + } + + @GetMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@PathVariable("id") String id) { + Connectors connector = connectorsService.get(id); + if(StringUtils.isNotBlank(connector.getCredentials())) { + connector.setCredentials(PasswordReciprocal.getInstance().decoder(connector.getCredentials())); + } + return new Message<>(connector); + } + + @PostMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message insert(@RequestBody Connectors connector,@CurrentUser UserInfo currentUser) { + logger.debug("-Add : {}" , connector); + connector.setInstId(currentUser.getInstId()); + if(StringUtils.isNotBlank(connector.getCredentials())) { + connector.setCredentials(PasswordReciprocal.getInstance().encode(connector.getCredentials())); + } + if (connectorsService.insert(connector)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update(@RequestBody Connectors connector,@CurrentUser UserInfo currentUser) { + logger.debug("-update : {}" , connector); + connector.setInstId(currentUser.getInstId()); + connector.setCredentials(PasswordReciprocal.getInstance().encode(connector.getCredentials())); + if (connectorsService.update(connector)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @DeleteMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {} " , ids); + if (connectorsService.deleteBatch(ids)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/InstitutionsController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/InstitutionsController.java index c0847697c..3971d8337 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/InstitutionsController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/InstitutionsController.java @@ -34,27 +34,27 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value={"/config/institutions"}) public class InstitutionsController { - static final Logger logger = LoggerFactory.getLogger(InstitutionsController.class); - - @Autowired - InstitutionsService institutionsService; - - @RequestMapping(value={"/get"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@CurrentUser UserInfo currentUser){ - Institutions institutions = institutionsService.get(currentUser.getInstId()); - return new Message(Message.SUCCESS,institutions); - } - - @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update( - @RequestBody Institutions institutions, - @CurrentUser UserInfo currentUser, - BindingResult result) { - logger.debug("updateRole institutions : {}" , institutions); - if(institutionsService.update(institutions)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } + static final Logger logger = LoggerFactory.getLogger(InstitutionsController.class); + + @Autowired + InstitutionsService institutionsService; + + @RequestMapping(value={"/get"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@CurrentUser UserInfo currentUser){ + Institutions institutions = institutionsService.get(currentUser.getInstId()); + return new Message(Message.SUCCESS,institutions); + } + + @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update( + @RequestBody Institutions institutions, + @CurrentUser UserInfo currentUser, + BindingResult result) { + logger.debug("updateRole institutions : {}" , institutions); + if(institutionsService.update(institutions)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/SocialsProviderController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/SocialsProviderController.java index f398c9e6b..64852314f 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/SocialsProviderController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/config/contorller/SocialsProviderController.java @@ -42,75 +42,75 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value={"/config/socialsprovider"}) public class SocialsProviderController { - static final Logger logger = LoggerFactory.getLogger(SocialsProviderController.class); - - @Autowired - SocialsProviderService socialsProviderService; - - @RequestMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - @ResponseBody - public Message fetch(@ModelAttribute SocialsProvider socialsProvider,@CurrentUser UserInfo currentUser) { - logger.debug("fetch {}" ,socialsProvider); - socialsProvider.setInstId(currentUser.getInstId()); - return new Message>( - socialsProviderService.fetchPageResults(socialsProvider)); - } + static final Logger logger = LoggerFactory.getLogger(SocialsProviderController.class); + + @Autowired + SocialsProviderService socialsProviderService; + + @RequestMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + @ResponseBody + public Message fetch(@ModelAttribute SocialsProvider socialsProvider,@CurrentUser UserInfo currentUser) { + logger.debug("fetch {}" ,socialsProvider); + socialsProvider.setInstId(currentUser.getInstId()); + return new Message>( + socialsProviderService.fetchPageResults(socialsProvider)); + } - @ResponseBody - @RequestMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message query(@ModelAttribute SocialsProvider socialsProvider,@CurrentUser UserInfo currentUser) { - logger.debug("-query : {}" , socialsProvider); - socialsProvider.setInstId(currentUser.getInstId()); - if (socialsProviderService.query(socialsProvider)!=null) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.SUCCESS); - } - } - - @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@PathVariable("id") String id) { - SocialsProvider socialsProvider=socialsProviderService.get(id); - socialsProvider.setClientSecret(PasswordReciprocal.getInstance().decoder(socialsProvider.getClientSecret())); - return new Message(socialsProvider); - } - - @ResponseBody - @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message insert(@RequestBody SocialsProvider socialsProvider,@CurrentUser UserInfo currentUser) { - logger.debug("-Add : {}" , socialsProvider); - socialsProvider.setInstId(currentUser.getInstId()); - socialsProvider.setClientSecret(PasswordReciprocal.getInstance().encode(socialsProvider.getClientSecret())); - if (socialsProviderService.insert(socialsProvider)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @ResponseBody - @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update(@RequestBody SocialsProvider socialsProvider,@CurrentUser UserInfo currentUser) { - logger.debug("-update : {}" , socialsProvider); - socialsProvider.setInstId(currentUser.getInstId()); - socialsProvider.setClientSecret(PasswordReciprocal.getInstance().encode(socialsProvider.getClientSecret())); - if (socialsProviderService.update(socialsProvider)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - - @ResponseBody - @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {} " , ids); - if (socialsProviderService.deleteBatch(ids)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } + @ResponseBody + @RequestMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message query(@ModelAttribute SocialsProvider socialsProvider,@CurrentUser UserInfo currentUser) { + logger.debug("-query : {}" , socialsProvider); + socialsProvider.setInstId(currentUser.getInstId()); + if (socialsProviderService.query(socialsProvider)!=null) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.SUCCESS); + } + } + + @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@PathVariable("id") String id) { + SocialsProvider socialsProvider=socialsProviderService.get(id); + socialsProvider.setClientSecret(PasswordReciprocal.getInstance().decoder(socialsProvider.getClientSecret())); + return new Message(socialsProvider); + } + + @ResponseBody + @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message insert(@RequestBody SocialsProvider socialsProvider,@CurrentUser UserInfo currentUser) { + logger.debug("-Add : {}" , socialsProvider); + socialsProvider.setInstId(currentUser.getInstId()); + socialsProvider.setClientSecret(PasswordReciprocal.getInstance().encode(socialsProvider.getClientSecret())); + if (socialsProviderService.insert(socialsProvider)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @ResponseBody + @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update(@RequestBody SocialsProvider socialsProvider,@CurrentUser UserInfo currentUser) { + logger.debug("-update : {}" , socialsProvider); + socialsProvider.setInstId(currentUser.getInstId()); + socialsProvider.setClientSecret(PasswordReciprocal.getInstance().encode(socialsProvider.getClientSecret())); + if (socialsProviderService.update(socialsProvider)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + + @ResponseBody + @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {} " , ids); + if (socialsProviderService.deleteBatch(ids)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/contorller/AccountsController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/contorller/AccountsController.java index 7bc912a9b..2f1742052 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/contorller/AccountsController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/contorller/AccountsController.java @@ -54,135 +54,135 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value={"/accounts"}) public class AccountsController { - static final Logger _logger = LoggerFactory.getLogger(AccountsController.class); + static final Logger _logger = LoggerFactory.getLogger(AccountsController.class); - @Autowired - AccountsService accountsService; - - @Autowired - AccountsStrategyService accountsStrategyService; - - @Autowired - AppsService appsService; - - @Autowired - UserInfoService userInfoService; - - @Autowired - HistorySystemLogsService systemLog; - - @GetMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message> fetch(@ModelAttribute Accounts accounts,@CurrentUser UserInfo currentUser) { - _logger.debug("fetch {}" , accounts); - accounts.setInstId(currentUser.getInstId()); - return new Message<>( - accountsService.fetchPageResults(accounts)); - } + @Autowired + AccountsService accountsService; + + @Autowired + AccountsStrategyService accountsStrategyService; + + @Autowired + AppsService appsService; + + @Autowired + UserInfoService userInfoService; + + @Autowired + HistorySystemLogsService systemLog; + + @GetMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message> fetch(@ModelAttribute Accounts accounts,@CurrentUser UserInfo currentUser) { + _logger.debug("fetch {}" , accounts); + accounts.setInstId(currentUser.getInstId()); + return new Message<>( + accountsService.fetchPageResults(accounts)); + } - @GetMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message query(@ModelAttribute Accounts account,@CurrentUser UserInfo currentUser) { - _logger.debug("-query : {}" , account); - account.setInstId(currentUser.getInstId()); - if (CollectionUtils.isNotEmpty(accountsService.query(account))) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } + @GetMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message query(@ModelAttribute Accounts account,@CurrentUser UserInfo currentUser) { + _logger.debug("-query : {}" , account); + account.setInstId(currentUser.getInstId()); + if (CollectionUtils.isNotEmpty(accountsService.query(account))) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } - @GetMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@PathVariable("id") String id) { - Accounts account=accountsService.get(id); - account.setRelatedPassword(PasswordReciprocal.getInstance().decoder(account.getRelatedPassword())); - return new Message<>(account); - } + @GetMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@PathVariable("id") String id) { + Accounts account=accountsService.get(id); + account.setRelatedPassword(PasswordReciprocal.getInstance().decoder(account.getRelatedPassword())); + return new Message<>(account); + } - @PostMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message insert(@RequestBody Accounts account,@CurrentUser UserInfo currentUser) { - _logger.debug("-Add : {}" , account); - account.setInstId(currentUser.getInstId()); - account.setRelatedPassword(PasswordReciprocal.getInstance().encode(account.getRelatedPassword())); - if (accountsService.insert(account)) { - systemLog.insert( - ConstsEntryType.ACCOUNT, - account, - ConstsAct.CREATE, - ConstsActResult.SUCCESS, - currentUser); - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update(@RequestBody Accounts account,@CurrentUser UserInfo currentUser) { - _logger.debug("-update : {}" , account); - account.setInstId(currentUser.getInstId()); - account.setRelatedPassword(PasswordReciprocal.getInstance().encode(account.getRelatedPassword())); - if (accountsService.update(account)) { - systemLog.insert( - ConstsEntryType.ACCOUNT, - account, - ConstsAct.UPDATE, - ConstsActResult.SUCCESS, - currentUser); - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - - @GetMapping(value = { "/updateStatus" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message updateStatus(@ModelAttribute Accounts accounts,@CurrentUser UserInfo currentUser) { - _logger.debug("accounts : {}" , accounts); - Accounts loadAccount = accountsService.get(accounts.getId()); - accounts.setInstId(currentUser.getInstId()); - accounts.setAppId(loadAccount.getAppId()); - accounts.setAppName(loadAccount.getAppName()); - accounts.setUserId(loadAccount.getUserId()); - accounts.setUsername(loadAccount.getUsername()); - accounts.setDisplayName(loadAccount.getDisplayName()); - accounts.setRelatedUsername(loadAccount.getRelatedUsername()); - if (accountsService.updateStatus(accounts)) { - systemLog.insert( - ConstsEntryType.ACCOUNT, - accounts, - ConstsAct.statusActon.get(accounts.getStatus()), - ConstsActResult.SUCCESS, - currentUser); - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } - - @DeleteMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { - _logger.debug("-delete ids : {} " , ids); - - if (accountsService.deleteBatch(ids)) { - systemLog.insert( - ConstsEntryType.ACCOUNT, - ids, - ConstsAct.DELETE, - ConstsActResult.SUCCESS, - currentUser); - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - - } - + @PostMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message insert(@RequestBody Accounts account,@CurrentUser UserInfo currentUser) { + _logger.debug("-Add : {}" , account); + account.setInstId(currentUser.getInstId()); + account.setRelatedPassword(PasswordReciprocal.getInstance().encode(account.getRelatedPassword())); + if (accountsService.insert(account)) { + systemLog.insert( + ConstsEntryType.ACCOUNT, + account, + ConstsAct.CREATE, + ConstsActResult.SUCCESS, + currentUser); + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update(@RequestBody Accounts account,@CurrentUser UserInfo currentUser) { + _logger.debug("-update : {}" , account); + account.setInstId(currentUser.getInstId()); + account.setRelatedPassword(PasswordReciprocal.getInstance().encode(account.getRelatedPassword())); + if (accountsService.update(account)) { + systemLog.insert( + ConstsEntryType.ACCOUNT, + account, + ConstsAct.UPDATE, + ConstsActResult.SUCCESS, + currentUser); + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + + @GetMapping(value = { "/updateStatus" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message updateStatus(@ModelAttribute Accounts accounts,@CurrentUser UserInfo currentUser) { + _logger.debug("accounts : {}" , accounts); + Accounts loadAccount = accountsService.get(accounts.getId()); + accounts.setInstId(currentUser.getInstId()); + accounts.setAppId(loadAccount.getAppId()); + accounts.setAppName(loadAccount.getAppName()); + accounts.setUserId(loadAccount.getUserId()); + accounts.setUsername(loadAccount.getUsername()); + accounts.setDisplayName(loadAccount.getDisplayName()); + accounts.setRelatedUsername(loadAccount.getRelatedUsername()); + if (accountsService.updateStatus(accounts)) { + systemLog.insert( + ConstsEntryType.ACCOUNT, + accounts, + ConstsAct.statusActon.get(accounts.getStatus()), + ConstsActResult.SUCCESS, + currentUser); + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } + + @DeleteMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { + _logger.debug("-delete ids : {} " , ids); + + if (accountsService.deleteBatch(ids)) { + systemLog.insert( + ConstsEntryType.ACCOUNT, + ids, + ConstsAct.DELETE, + ConstsActResult.SUCCESS, + currentUser); + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + + } + @GetMapping(value = "/generate") public Message generate(@ModelAttribute Accounts account) { - AccountsStrategy accountsStrategy = accountsStrategyService.get(account.getStrategyId()); - UserInfo userInfo = userInfoService.get(account.getUserId()); + AccountsStrategy accountsStrategy = accountsStrategyService.get(account.getStrategyId()); + UserInfo userInfo = userInfoService.get(account.getUserId()); return new Message<>( - Message.SUCCESS,accountsService.generateAccount(userInfo,accountsStrategy) - ); + Message.SUCCESS,accountsService.generateAccount(userInfo,accountsStrategy) + ); } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/contorller/DashboardController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/contorller/DashboardController.java index b8873e524..c99e2a6a6 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/contorller/DashboardController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/contorller/DashboardController.java @@ -36,38 +36,38 @@ import org.springframework.web.bind.annotation.RestController; */ @RestController public class DashboardController { - private static Logger logger = LoggerFactory.getLogger(DashboardController.class); - - @Autowired - ReportService reportService; + private static Logger logger = LoggerFactory.getLogger(DashboardController.class); + + @Autowired + ReportService reportService; - @GetMapping(value={"/dashboard"}) - public Message dashboard(@CurrentUser UserInfo currentUser) { - logger.debug("dashboard . "); - HashMap reportParameter = new HashMap<>(); - reportParameter.put("instId", currentUser.getInstId()); - - reportParameter.put("dayCount", reportService.analysisDay(reportParameter)); - reportParameter.put("newUsers", reportService.analysisNewUsers(reportParameter)); - - reportParameter.put("onlineUsers", reportService.analysisOnlineUsers(reportParameter)); - reportParameter.put("activeUsers", reportService.analysisActiveUsers(reportParameter)); - - reportParameter.put("totalUsers", reportService.totalUsers(reportParameter)); - reportParameter.put("totalDepts", reportService.totalDepts(reportParameter)); - reportParameter.put("totalApps", reportService.totalApps(reportParameter)); - - reportParameter.put("reportMonth", reportService.analysisMonth(reportParameter)); - reportParameter.put("reportDayHour", reportService.analysisDayHour(reportParameter)); - - reportParameter.put("reportProvince", reportService.analysisProvince(reportParameter)); - - reportParameter.put("reportCountry", reportService.analysisCountry(reportParameter)); - - reportParameter.put("reportBrowser", reportService.analysisBrowser(reportParameter)); - - reportParameter.put("reportApp", reportService.analysisApp(reportParameter)); - return new Message<>(reportParameter); - } + @GetMapping(value={"/dashboard"}) + public Message dashboard(@CurrentUser UserInfo currentUser) { + logger.debug("dashboard . "); + HashMap reportParameter = new HashMap<>(); + reportParameter.put("instId", currentUser.getInstId()); + + reportParameter.put("dayCount", reportService.analysisDay(reportParameter)); + reportParameter.put("newUsers", reportService.analysisNewUsers(reportParameter)); + + reportParameter.put("onlineUsers", reportService.analysisOnlineUsers(reportParameter)); + reportParameter.put("activeUsers", reportService.analysisActiveUsers(reportParameter)); + + reportParameter.put("totalUsers", reportService.totalUsers(reportParameter)); + reportParameter.put("totalDepts", reportService.totalDepts(reportParameter)); + reportParameter.put("totalApps", reportService.totalApps(reportParameter)); + + reportParameter.put("reportMonth", reportService.analysisMonth(reportParameter)); + reportParameter.put("reportDayHour", reportService.analysisDayHour(reportParameter)); + + reportParameter.put("reportProvince", reportService.analysisProvince(reportParameter)); + + reportParameter.put("reportCountry", reportService.analysisCountry(reportParameter)); + + reportParameter.put("reportBrowser", reportService.analysisBrowser(reportParameter)); + + reportParameter.put("reportApp", reportService.analysisApp(reportParameter)); + return new Message<>(reportParameter); + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/contorller/LoginEntryPoint.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/contorller/LoginEntryPoint.java index b123c8449..0723eb02d 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/contorller/LoginEntryPoint.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/contorller/LoginEntryPoint.java @@ -45,53 +45,53 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value = "/login") public class LoginEntryPoint { - private static Logger logger = LoggerFactory.getLogger(LoginEntryPoint.class); - - @Autowired - AuthTokenService authTokenService; - - @Autowired - ApplicationConfig applicationConfig; - - @Autowired - AbstractAuthenticationProvider authenticationProvider ; - - /** - * init login - * @return - */ - @GetMapping("/get") - public Message get() { - logger.debug("/login."); - - HashMap model = new HashMap(); - Institutions inst = (Institutions)WebContext.getAttribute(WebConstants.CURRENT_INST); - model.put("inst", inst); - if(applicationConfig.getLoginConfig().isCaptcha()) { - model.put("captcha", applicationConfig.getLoginConfig().getCaptchaType()); - }else { - model.put("captcha", "NONE"); - } - model.put("state", authTokenService.genRandomJwt()); - return new Message>(model); - } - - @PostMapping("/signin") - public Message signin( @RequestBody LoginCredential loginCredential) { - Message authJwtMessage = new Message(Message.FAIL); - if(authTokenService.validateJwtToken(loginCredential.getState())){ - Authentication authentication = authenticationProvider.authenticate(loginCredential); - if(authentication != null) { - AuthJwt authJwt = authTokenService.genAuthJwt(authentication); - authJwtMessage = new Message(authJwt); - }else {//fail - String errorMsg = WebContext.getAttribute(WebConstants.LOGIN_ERROR_SESSION_MESSAGE) == null ? - "" : WebContext.getAttribute(WebConstants.LOGIN_ERROR_SESSION_MESSAGE).toString(); - authJwtMessage.setMessage(Message.FAIL,errorMsg); - logger.debug("login fail , message {}",errorMsg); - } - } - return authJwtMessage; - } - + private static Logger logger = LoggerFactory.getLogger(LoginEntryPoint.class); + + @Autowired + AuthTokenService authTokenService; + + @Autowired + ApplicationConfig applicationConfig; + + @Autowired + AbstractAuthenticationProvider authenticationProvider ; + + /** + * init login + * @return + */ + @GetMapping("/get") + public Message get() { + logger.debug("/login."); + + HashMap model = new HashMap(); + Institutions inst = (Institutions)WebContext.getAttribute(WebConstants.CURRENT_INST); + model.put("inst", inst); + if(applicationConfig.getLoginConfig().isCaptcha()) { + model.put("captcha", applicationConfig.getLoginConfig().getCaptchaType()); + }else { + model.put("captcha", "NONE"); + } + model.put("state", authTokenService.genRandomJwt()); + return new Message>(model); + } + + @PostMapping("/signin") + public Message signin( @RequestBody LoginCredential loginCredential) { + Message authJwtMessage = new Message(Message.FAIL); + if(authTokenService.validateJwtToken(loginCredential.getState())){ + Authentication authentication = authenticationProvider.authenticate(loginCredential); + if(authentication != null) { + AuthJwt authJwt = authTokenService.genAuthJwt(authentication); + authJwtMessage = new Message(authJwt); + }else {//fail + String errorMsg = WebContext.getAttribute(WebConstants.LOGIN_ERROR_SESSION_MESSAGE) == null ? + "" : WebContext.getAttribute(WebConstants.LOGIN_ERROR_SESSION_MESSAGE).toString(); + authJwtMessage.setMessage(Message.FAIL,errorMsg); + logger.debug("login fail , message {}",errorMsg); + } + } + return authJwtMessage; + } + } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/contorller/LogoutEndpoint.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/contorller/LogoutEndpoint.java index 4a7f8b0d1..5a6c73cda 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/contorller/LogoutEndpoint.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/contorller/LogoutEndpoint.java @@ -32,22 +32,22 @@ import jakarta.servlet.http.HttpServletRequest; @Controller public class LogoutEndpoint { - private static Logger logger = LoggerFactory.getLogger(LogoutEndpoint.class); - - @Autowired + private static Logger logger = LoggerFactory.getLogger(LogoutEndpoint.class); + + @Autowired SessionManager sessionManager; - - @GetMapping(value={"/logout"}) - @ResponseBody - public Message logout(HttpServletRequest request,@CurrentUser UserInfo currentUser){ - sessionManager.terminate( - currentUser.getSessionId(), - currentUser.getId(), - currentUser.getUsername()); - //invalidate http session - logger.debug("/logout invalidate http Session id {}",request.getSession().getId()); - request.getSession().invalidate(); - return new Message(); - } - + + @GetMapping(value={"/logout"}) + @ResponseBody + public Message logout(HttpServletRequest request,@CurrentUser UserInfo currentUser){ + sessionManager.terminate( + currentUser.getSessionId(), + currentUser.getId(), + currentUser.getUsername()); + //invalidate http session + logger.debug("/logout invalidate http Session id {}",request.getSession().getId()); + request.getSession().invalidate(); + return new Message(); + } + } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/ConnectorHistoryController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/ConnectorHistoryController.java index 01aa6ebb0..33d3b5a73 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/ConnectorHistoryController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/ConnectorHistoryController.java @@ -43,28 +43,28 @@ import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value={"/historys"}) public class ConnectorHistoryController { - static final Logger logger = LoggerFactory.getLogger(ConnectorHistoryController.class); + static final Logger logger = LoggerFactory.getLogger(ConnectorHistoryController.class); - @Autowired - HistoryConnectorService historyConnectorService; - - /** + @Autowired + HistoryConnectorService historyConnectorService; + + /** * @param historySynchronizer * @return */ @GetMapping({"/connectorHistory/fetch"}) @ResponseBody public Message fetch( - @ModelAttribute("historyConnector") HistoryConnector historyConnector, - @CurrentUser UserInfo currentUser){ - logger.debug("historys/historyConnector/fetch/ {}",historyConnector); + @ModelAttribute("historyConnector") HistoryConnector historyConnector, + @CurrentUser UserInfo currentUser){ + logger.debug("historys/historyConnector/fetch/ {}",historyConnector); historyConnector.setInstId(currentUser.getInstId()); return new Message>( - historyConnectorService.fetchPageResults(historyConnector) - ); + historyConnectorService.fetchPageResults(historyConnector) + ); } - @InitBinder + @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtils.FORMAT_DATE_HH_MM_SS); dateFormat.setLenient(false); diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/LoginAppsHistoryController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/LoginAppsHistoryController.java index e08186b09..e1ad76093 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/LoginAppsHistoryController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/LoginAppsHistoryController.java @@ -43,29 +43,29 @@ import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value={"/historys"}) public class LoginAppsHistoryController { - static final Logger logger = LoggerFactory.getLogger(LoginAppsHistoryController.class); - - @Autowired - HistoryLoginAppsService historyLoginAppsService; - - /** - * @param loginAppsHistory - * @return - */ - @GetMapping({"/loginAppsHistory/fetch"}) - @ResponseBody - public Message fetch( - @ModelAttribute("historyLoginApp") HistoryLoginApps historyLoginApp, - @CurrentUser UserInfo currentUser){ - logger.debug("historys/loginAppsHistory/fetch/ {}",historyLoginApp); - historyLoginApp.setId(null); - historyLoginApp.setInstId(currentUser.getInstId()); - return new Message>( - historyLoginAppsService.fetchPageResults(historyLoginApp) - ); - } + static final Logger logger = LoggerFactory.getLogger(LoginAppsHistoryController.class); + + @Autowired + HistoryLoginAppsService historyLoginAppsService; + + /** + * @param loginAppsHistory + * @return + */ + @GetMapping({"/loginAppsHistory/fetch"}) + @ResponseBody + public Message fetch( + @ModelAttribute("historyLoginApp") HistoryLoginApps historyLoginApp, + @CurrentUser UserInfo currentUser){ + logger.debug("historys/loginAppsHistory/fetch/ {}",historyLoginApp); + historyLoginApp.setId(null); + historyLoginApp.setInstId(currentUser.getInstId()); + return new Message>( + historyLoginAppsService.fetchPageResults(historyLoginApp) + ); + } - @InitBinder + @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtils.FORMAT_DATE_HH_MM_SS); dateFormat.setLenient(false); diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/LoginHistoryController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/LoginHistoryController.java index 4890ddd00..117128f17 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/LoginHistoryController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/LoginHistoryController.java @@ -43,29 +43,29 @@ import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value={"/historys"}) public class LoginHistoryController { - static final Logger logger = LoggerFactory.getLogger(LoginHistoryController.class); - - @Autowired - HistoryLoginService loginHistoryService; - - /** - * @param HistoryLogin - * @return - */ - @GetMapping({"/loginHistory/fetch"}) - @ResponseBody - public Message fetch( - @ModelAttribute("historyLogin") HistoryLogin historyLogin, - @CurrentUser UserInfo currentUser - ){ - logger.debug("historys/loginHistory/fetch/ {}",historyLogin); - historyLogin.setInstId(currentUser.getInstId()); - return new Message>( - loginHistoryService.fetchPageResults(historyLogin) - ); - } - - @InitBinder + static final Logger logger = LoggerFactory.getLogger(LoginHistoryController.class); + + @Autowired + HistoryLoginService loginHistoryService; + + /** + * @param HistoryLogin + * @return + */ + @GetMapping({"/loginHistory/fetch"}) + @ResponseBody + public Message fetch( + @ModelAttribute("historyLogin") HistoryLogin historyLogin, + @CurrentUser UserInfo currentUser + ){ + logger.debug("historys/loginHistory/fetch/ {}",historyLogin); + historyLogin.setInstId(currentUser.getInstId()); + return new Message>( + loginHistoryService.fetchPageResults(historyLogin) + ); + } + + @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtils.FORMAT_DATE_HH_MM_SS); dateFormat.setLenient(false); diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/SynchronizerHistoryController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/SynchronizerHistoryController.java index 604d290cb..6106c8657 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/SynchronizerHistoryController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/SynchronizerHistoryController.java @@ -43,28 +43,28 @@ import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value={"/historys"}) public class SynchronizerHistoryController { - static final Logger logger = LoggerFactory.getLogger(SynchronizerHistoryController.class); + static final Logger logger = LoggerFactory.getLogger(SynchronizerHistoryController.class); - @Autowired - HistorySynchronizerService historySynchronizerService; - - /** + @Autowired + HistorySynchronizerService historySynchronizerService; + + /** * @param historySynchronizer * @return */ @GetMapping({"/synchronizerHistory/fetch"}) @ResponseBody public Message fetch( - @ModelAttribute("historySynchronizer") HistorySynchronizer historySynchronizer, - @CurrentUser UserInfo currentUser){ - logger.debug("historys/synchronizerHistory/fetch/ {}",historySynchronizer); + @ModelAttribute("historySynchronizer") HistorySynchronizer historySynchronizer, + @CurrentUser UserInfo currentUser){ + logger.debug("historys/synchronizerHistory/fetch/ {}",historySynchronizer); historySynchronizer.setInstId(currentUser.getInstId()); return new Message>( - historySynchronizerService.fetchPageResults(historySynchronizer) - ); + historySynchronizerService.fetchPageResults(historySynchronizer) + ); } - @InitBinder + @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtils.FORMAT_DATE_HH_MM_SS); dateFormat.setLenient(false); diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/SystemLogsController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/SystemLogsController.java index 908c69b74..2925716d3 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/SystemLogsController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/historys/contorller/SystemLogsController.java @@ -43,28 +43,28 @@ import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value={"/historys"}) public class SystemLogsController { - static final Logger logger = LoggerFactory.getLogger(SystemLogsController.class); + static final Logger logger = LoggerFactory.getLogger(SystemLogsController.class); - @Autowired - HistorySystemLogsService historySystemLogsService; - - /** - * 查询操作日志 - * @param logs - * @return - */ - @GetMapping({"/systemLogs/fetch"}) - @ResponseBody - public Message fetch(@ModelAttribute("historyLog") HistorySystemLogs historyLog, - @CurrentUser UserInfo currentUser){ - logger.debug("historys/historyLog/fetch {} ",historyLog); - historyLog.setInstId(currentUser.getInstId()); - return new Message>( - historySystemLogsService.fetchPageResults(historyLog) - ); - } - - @InitBinder + @Autowired + HistorySystemLogsService historySystemLogsService; + + /** + * 查询操作日志 + * @param logs + * @return + */ + @GetMapping({"/systemLogs/fetch"}) + @ResponseBody + public Message fetch(@ModelAttribute("historyLog") HistorySystemLogs historyLog, + @CurrentUser UserInfo currentUser){ + logger.debug("historys/historyLog/fetch {} ",historyLog); + historyLog.setInstId(currentUser.getInstId()); + return new Message>( + historySystemLogsService.fetchPageResults(historyLog) + ); + } + + @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtils.FORMAT_DATE_HH_MM_SS); dateFormat.setLenient(false); diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/idm/contorller/GroupMemberController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/idm/contorller/GroupMemberController.java index 286d27e75..c10a27c6c 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/idm/contorller/GroupMemberController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/idm/contorller/GroupMemberController.java @@ -46,155 +46,155 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value={"/access/groupmembers"}) public class GroupMemberController { - static final Logger logger = LoggerFactory.getLogger(GroupMemberController.class); - - @Autowired - GroupMemberService service; + static final Logger logger = LoggerFactory.getLogger(GroupMemberController.class); + + @Autowired + GroupMemberService service; - @Autowired - GroupsService rolesService; - - @Autowired - UserInfoService userInfoService; - - @Autowired - HistorySystemLogsService systemLog; - - @RequestMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - @ResponseBody - public Message fetch( - @ModelAttribute GroupMember groupMember, - @CurrentUser UserInfo currentUser) { - logger.debug("fetch {}" , groupMember); - groupMember.setInstId(currentUser.getInstId()); - return new Message>( - service.fetchPageResults(groupMember)); - } + @Autowired + GroupsService rolesService; + + @Autowired + UserInfoService userInfoService; + + @Autowired + HistorySystemLogsService systemLog; + + @RequestMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + @ResponseBody + public Message fetch( + @ModelAttribute GroupMember groupMember, + @CurrentUser UserInfo currentUser) { + logger.debug("fetch {}" , groupMember); + groupMember.setInstId(currentUser.getInstId()); + return new Message>( + service.fetchPageResults(groupMember)); + } - @RequestMapping(value = { "/memberIn" }) - @ResponseBody - public Message memberInRole(@ModelAttribute GroupMember groupMember,@CurrentUser UserInfo currentUser) { - logger.debug("groupMember : {}" , groupMember); - groupMember.setInstId(currentUser.getInstId()); - return new Message>( - service.fetchPageResults("memberIn",groupMember)); + @RequestMapping(value = { "/memberIn" }) + @ResponseBody + public Message memberInRole(@ModelAttribute GroupMember groupMember,@CurrentUser UserInfo currentUser) { + logger.debug("groupMember : {}" , groupMember); + groupMember.setInstId(currentUser.getInstId()); + return new Message>( + service.fetchPageResults("memberIn",groupMember)); - } + } - - @RequestMapping(value = { "/memberNotIn" }) - @ResponseBody - public Message memberNotIn(@ModelAttribute GroupMember groupMember,@CurrentUser UserInfo currentUser) { - groupMember.setInstId(currentUser.getInstId()); - return new Message>( - service.fetchPageResults("memberNotIn",groupMember)); - } + + @RequestMapping(value = { "/memberNotIn" }) + @ResponseBody + public Message memberNotIn(@ModelAttribute GroupMember groupMember,@CurrentUser UserInfo currentUser) { + groupMember.setInstId(currentUser.getInstId()); + return new Message>( + service.fetchPageResults("memberNotIn",groupMember)); + } - @RequestMapping(value = { "/noMember" }) - @ResponseBody - public Message noMember(@ModelAttribute GroupMember groupMember,@CurrentUser UserInfo currentUser) { - groupMember.setInstId(currentUser.getInstId()); - return new Message>( - service.noMember(groupMember)); - } - - /** - * Members add to the Role - * @param groupMember - * @param currentUser - * @return - */ - @RequestMapping(value = {"/add"}) - @ResponseBody - public Message addGroupMember(@RequestBody GroupMember groupMember,@CurrentUser UserInfo currentUser) { - if (groupMember == null || groupMember.getGroupId() == null) { - return new Message(Message.FAIL); - } - String groupId = groupMember.getGroupId(); - - - boolean result = true; - String memberIds = groupMember.getMemberId(); - String memberNames = groupMember.getMemberName(); - if (memberIds != null) { - String[] arrMemberIds = memberIds.split(","); - String[] arrMemberNames = memberNames.split(","); - //set default as USER - if(StringUtils.isBlank(groupMember.getType())) { - groupMember.setType("USER"); - } - for (int i = 0; i < arrMemberIds.length; i++) { - if(StringUtils.isNotBlank(arrMemberIds[i])) { - GroupMember newGroupMember = - new GroupMember( - groupId, - groupMember.getGroupName(), - arrMemberIds[i], - arrMemberNames[i], - groupMember.getType(), - currentUser.getInstId()); - newGroupMember.setId(WebContext.genId()); - result = service.insert(newGroupMember); - } - } - if(result) { - return new Message(Message.SUCCESS); - } - } - return new Message(Message.FAIL); - } - - - /** - * Member add to Roles - * @param groupMember - * @param currentUser - * @return - */ - @RequestMapping(value = {"/addMember2Groups"}) - @ResponseBody - public Message addMember2Groups(@RequestBody GroupMember groupMember,@CurrentUser UserInfo currentUser) { - if (groupMember == null || StringUtils.isBlank(groupMember.getUsername())) { - return new Message(Message.FAIL); - } - UserInfo userInfo = userInfoService.findByUsername(groupMember.getUsername()); - - boolean result = true; - String groupIds = groupMember.getGroupId(); - String groupNames = groupMember.getGroupName(); - if (groupIds != null && userInfo != null) { - String[] arrGroupIds = groupIds.split(","); - String[] arrGroupNames = groupNames.split(","); - - for (int i = 0; i < arrGroupIds.length; i++) { - if(StringUtils.isNotBlank(arrGroupIds[i])) { - GroupMember newGroupMember = - new GroupMember( - arrGroupIds[i], - arrGroupNames[i], - userInfo.getId(), - userInfo.getDisplayName(), - "USER", - currentUser.getInstId()); - newGroupMember.setId(WebContext.genId()); - result = service.insert(newGroupMember); - } - } - if(result) { - return new Message(Message.SUCCESS); - } - } - return new Message(Message.FAIL); - } - - @ResponseBody - @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {}" , ids); - if (service.deleteBatch(ids)) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } + @RequestMapping(value = { "/noMember" }) + @ResponseBody + public Message noMember(@ModelAttribute GroupMember groupMember,@CurrentUser UserInfo currentUser) { + groupMember.setInstId(currentUser.getInstId()); + return new Message>( + service.noMember(groupMember)); + } + + /** + * Members add to the Role + * @param groupMember + * @param currentUser + * @return + */ + @RequestMapping(value = {"/add"}) + @ResponseBody + public Message addGroupMember(@RequestBody GroupMember groupMember,@CurrentUser UserInfo currentUser) { + if (groupMember == null || groupMember.getGroupId() == null) { + return new Message(Message.FAIL); + } + String groupId = groupMember.getGroupId(); + + + boolean result = true; + String memberIds = groupMember.getMemberId(); + String memberNames = groupMember.getMemberName(); + if (memberIds != null) { + String[] arrMemberIds = memberIds.split(","); + String[] arrMemberNames = memberNames.split(","); + //set default as USER + if(StringUtils.isBlank(groupMember.getType())) { + groupMember.setType("USER"); + } + for (int i = 0; i < arrMemberIds.length; i++) { + if(StringUtils.isNotBlank(arrMemberIds[i])) { + GroupMember newGroupMember = + new GroupMember( + groupId, + groupMember.getGroupName(), + arrMemberIds[i], + arrMemberNames[i], + groupMember.getType(), + currentUser.getInstId()); + newGroupMember.setId(WebContext.genId()); + result = service.insert(newGroupMember); + } + } + if(result) { + return new Message(Message.SUCCESS); + } + } + return new Message(Message.FAIL); + } + + + /** + * Member add to Roles + * @param groupMember + * @param currentUser + * @return + */ + @RequestMapping(value = {"/addMember2Groups"}) + @ResponseBody + public Message addMember2Groups(@RequestBody GroupMember groupMember,@CurrentUser UserInfo currentUser) { + if (groupMember == null || StringUtils.isBlank(groupMember.getUsername())) { + return new Message(Message.FAIL); + } + UserInfo userInfo = userInfoService.findByUsername(groupMember.getUsername()); + + boolean result = true; + String groupIds = groupMember.getGroupId(); + String groupNames = groupMember.getGroupName(); + if (groupIds != null && userInfo != null) { + String[] arrGroupIds = groupIds.split(","); + String[] arrGroupNames = groupNames.split(","); + + for (int i = 0; i < arrGroupIds.length; i++) { + if(StringUtils.isNotBlank(arrGroupIds[i])) { + GroupMember newGroupMember = + new GroupMember( + arrGroupIds[i], + arrGroupNames[i], + userInfo.getId(), + userInfo.getDisplayName(), + "USER", + currentUser.getInstId()); + newGroupMember.setId(WebContext.genId()); + result = service.insert(newGroupMember); + } + } + if(result) { + return new Message(Message.SUCCESS); + } + } + return new Message(Message.FAIL); + } + + @ResponseBody + @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {}" , ids); + if (service.deleteBatch(ids)) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/idm/contorller/GroupsController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/idm/contorller/GroupsController.java index ca751682d..ccb19ef37 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/idm/contorller/GroupsController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/idm/contorller/GroupsController.java @@ -48,104 +48,104 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value={"/access/groups"}) public class GroupsController { - static final Logger logger = LoggerFactory.getLogger(GroupsController.class); - - @Autowired - GroupsService service; - - @Autowired - HistorySystemLogsService systemLog; - - @RequestMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - @ResponseBody - public Message fetch( - @ModelAttribute Groups group, - @CurrentUser UserInfo currentUser) { - logger.debug("group {}" , group); - group.setInstId(currentUser.getInstId()); - return new Message>( - service.fetchPageResults(group)); - } + static final Logger logger = LoggerFactory.getLogger(GroupsController.class); + + @Autowired + GroupsService service; + + @Autowired + HistorySystemLogsService systemLog; + + @RequestMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + @ResponseBody + public Message fetch( + @ModelAttribute Groups group, + @CurrentUser UserInfo currentUser) { + logger.debug("group {}" , group); + group.setInstId(currentUser.getInstId()); + return new Message>( + service.fetchPageResults(group)); + } - @ResponseBody - @RequestMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message query(@ModelAttribute Groups group,@CurrentUser UserInfo currentUser) { - logger.debug("-query : {}" , group); - group.setInstId(currentUser.getInstId()); - if (service.query(group)!=null) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - - } - - @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@PathVariable("id") String id,@CurrentUser UserInfo currentUser) { - Groups group =service.get(id); - return new Message(group); - } - - @ResponseBody - @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message insert(@RequestBody Groups group,@CurrentUser UserInfo currentUser) { - logger.debug("-Add : {}" , group); - group.setInstId(currentUser.getInstId()); - group.setId(group.generateId()); - if(StringUtils.isBlank(group.getGroupCode())) { - group.setGroupCode(group.getId()); - } - if (service.insert(group)) { - service.refreshDynamicGroups(group); - systemLog.insert( - ConstsEntryType.ROLE, - group, - ConstsAct.CREATE, - ConstsActResult.SUCCESS, - currentUser); - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @ResponseBody - @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update(@RequestBody Groups group,@CurrentUser UserInfo currentUser) { - logger.debug("-update group : {}" , group); - if(group.getId().equalsIgnoreCase("ROLE_ALL_USER")) { - group.setDefaultAllUser(); - } - group.setInstId(currentUser.getInstId()); - if (service.update(group)) { - service.refreshDynamicGroups(group); - systemLog.insert( - ConstsEntryType.ROLE, - group, - ConstsAct.UPDATE, - ConstsActResult.SUCCESS, - currentUser); - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } + @ResponseBody + @RequestMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message query(@ModelAttribute Groups group,@CurrentUser UserInfo currentUser) { + logger.debug("-query : {}" , group); + group.setInstId(currentUser.getInstId()); + if (service.query(group)!=null) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + + } + + @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@PathVariable("id") String id,@CurrentUser UserInfo currentUser) { + Groups group =service.get(id); + return new Message(group); + } + + @ResponseBody + @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message insert(@RequestBody Groups group,@CurrentUser UserInfo currentUser) { + logger.debug("-Add : {}" , group); + group.setInstId(currentUser.getInstId()); + group.setId(group.generateId()); + if(StringUtils.isBlank(group.getGroupCode())) { + group.setGroupCode(group.getId()); + } + if (service.insert(group)) { + service.refreshDynamicGroups(group); + systemLog.insert( + ConstsEntryType.ROLE, + group, + ConstsAct.CREATE, + ConstsActResult.SUCCESS, + currentUser); + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @ResponseBody + @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update(@RequestBody Groups group,@CurrentUser UserInfo currentUser) { + logger.debug("-update group : {}" , group); + if(group.getId().equalsIgnoreCase("ROLE_ALL_USER")) { + group.setDefaultAllUser(); + } + group.setInstId(currentUser.getInstId()); + if (service.update(group)) { + service.refreshDynamicGroups(group); + systemLog.insert( + ConstsEntryType.ROLE, + group, + ConstsAct.UPDATE, + ConstsActResult.SUCCESS, + currentUser); + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } - @ResponseBody - @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {}" , ids); - ids.removeAll(Arrays.asList("ROLE_ALL_USER","ROLE_ADMINISTRATORS","-1")); - if (service.deleteBatch(ids)) { - systemLog.insert( - ConstsEntryType.ROLE, - ids, - ConstsAct.DELETE, - ConstsActResult.SUCCESS, - currentUser); - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } + @ResponseBody + @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {}" , ids); + ids.removeAll(Arrays.asList("ROLE_ALL_USER","ROLE_ADMINISTRATORS","-1")); + if (service.deleteBatch(ids)) { + systemLog.insert( + ConstsEntryType.ROLE, + ids, + ConstsAct.DELETE, + ConstsActResult.SUCCESS, + currentUser); + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/idm/contorller/OrganizationsController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/idm/contorller/OrganizationsController.java index 8ea91d769..f359ff711 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/idm/contorller/OrganizationsController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/idm/contorller/OrganizationsController.java @@ -63,138 +63,138 @@ import com.google.common.collect.Lists; public class OrganizationsController { static final Logger logger = LoggerFactory.getLogger(OrganizationsController.class); - @Autowired - OrganizationsService organizationsService; - - @Autowired - HistorySystemLogsService systemLog; + @Autowired + OrganizationsService organizationsService; + + @Autowired + HistorySystemLogsService systemLog; - @RequestMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - @ResponseBody - public Message fetch(@ModelAttribute Organizations org,@CurrentUser UserInfo currentUser) { - logger.debug("fetch {}" , org); - org.setInstId(currentUser.getInstId()); - return new Message>( - organizationsService.fetchPageResults(org)); - } + @RequestMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + @ResponseBody + public Message fetch(@ModelAttribute Organizations org,@CurrentUser UserInfo currentUser) { + logger.debug("fetch {}" , org); + org.setInstId(currentUser.getInstId()); + return new Message>( + organizationsService.fetchPageResults(org)); + } - @ResponseBody - @RequestMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message query(@ModelAttribute Organizations org,@CurrentUser UserInfo currentUser) { - logger.debug("-query {}" , org); - org.setInstId(currentUser.getInstId()); - List orgList = organizationsService.query(org); - if (orgList != null) { - return new Message>(Message.SUCCESS,orgList); - } else { - return new Message>(Message.FAIL); - } - } - - @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@PathVariable("id") String id) { - Organizations org=organizationsService.get(id); - return new Message(org); - } - - @ResponseBody - @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message insert(@RequestBody Organizations org,@CurrentUser UserInfo currentUser) { - logger.debug("-Add : {}" , org); - org.setInstId(currentUser.getInstId()); - if (organizationsService.insert(org)) { - systemLog.insert( - ConstsEntryType.ORGANIZATION, - org, - ConstsAct.CREATE, - ConstsActResult.SUCCESS, - currentUser); - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @ResponseBody - @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update(@RequestBody Organizations org,@CurrentUser UserInfo currentUser) { - logger.debug("-update :{}" , org); - org.setInstId(currentUser.getInstId()); - if (organizationsService.update(org)) { - systemLog.insert( - ConstsEntryType.ORGANIZATION, - org, - ConstsAct.UPDATE, - ConstsActResult.SUCCESS, - currentUser); - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @ResponseBody - @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {} " , ids); - if (organizationsService.deleteBatch(ids)) { - systemLog.insert( - ConstsEntryType.ORGANIZATION, - ids, - ConstsAct.DELETE, - ConstsActResult.SUCCESS, - currentUser); - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } + @ResponseBody + @RequestMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message query(@ModelAttribute Organizations org,@CurrentUser UserInfo currentUser) { + logger.debug("-query {}" , org); + org.setInstId(currentUser.getInstId()); + List orgList = organizationsService.query(org); + if (orgList != null) { + return new Message>(Message.SUCCESS,orgList); + } else { + return new Message>(Message.FAIL); + } + } + + @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@PathVariable("id") String id) { + Organizations org=organizationsService.get(id); + return new Message(org); + } + + @ResponseBody + @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message insert(@RequestBody Organizations org,@CurrentUser UserInfo currentUser) { + logger.debug("-Add : {}" , org); + org.setInstId(currentUser.getInstId()); + if (organizationsService.insert(org)) { + systemLog.insert( + ConstsEntryType.ORGANIZATION, + org, + ConstsAct.CREATE, + ConstsActResult.SUCCESS, + currentUser); + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @ResponseBody + @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update(@RequestBody Organizations org,@CurrentUser UserInfo currentUser) { + logger.debug("-update :{}" , org); + org.setInstId(currentUser.getInstId()); + if (organizationsService.update(org)) { + systemLog.insert( + ConstsEntryType.ORGANIZATION, + org, + ConstsAct.UPDATE, + ConstsActResult.SUCCESS, + currentUser); + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @ResponseBody + @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {} " , ids); + if (organizationsService.deleteBatch(ids)) { + systemLog.insert( + ConstsEntryType.ORGANIZATION, + ids, + ConstsAct.DELETE, + ConstsActResult.SUCCESS, + currentUser); + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } - @ResponseBody - @RequestMapping(value={"/tree"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message tree(@ModelAttribute Organizations organization,@CurrentUser UserInfo currentUser) { - logger.debug("-tree {}" , organization); - List orgList = organizationsService.query( - Query.builder().eq("instid", currentUser.getInstId())); - if (orgList != null) { - TreeAttributes treeAttributes = new TreeAttributes(); - int nodeCount = 0; - for (Organizations org : orgList) { - TreeNode treeNode = new TreeNode(org.getId(),org.getOrgName()); - treeNode.setCode(org.getOrgCode()); - treeNode.setCodePath(org.getCodePath()); - treeNode.setNamePath(org.getNamePath()); - treeNode.setParentKey(org.getParentId()); - treeNode.setParentTitle(org.getParentName()); - treeNode.setParentCode(org.getParentCode()); - treeNode.setAttrs(org); - treeNode.setLeaf(true); - treeAttributes.addNode(treeNode); - nodeCount ++; - //root organization node,parentId is null or parentId = -1 or parentId = 0 or id = instId or id = parentId - if(org.getParentId() == null - ||org.getParentId().equalsIgnoreCase("0") - ||org.getParentId().equalsIgnoreCase("-1") - ||org.getId().equalsIgnoreCase(currentUser.getInstId()) - ||org.getId().equalsIgnoreCase(org.getParentId()) - ) { - treeNode.setExpanded(true); - treeNode.setLeaf(false); - treeAttributes.setRootNode(treeNode); - } - } - treeAttributes.setNodeCount(nodeCount); - return new Message(Message.SUCCESS,treeAttributes); - } else { - return new Message(Message.FAIL); - } - } + @ResponseBody + @RequestMapping(value={"/tree"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message tree(@ModelAttribute Organizations organization,@CurrentUser UserInfo currentUser) { + logger.debug("-tree {}" , organization); + List orgList = organizationsService.query( + Query.builder().eq("instid", currentUser.getInstId())); + if (orgList != null) { + TreeAttributes treeAttributes = new TreeAttributes(); + int nodeCount = 0; + for (Organizations org : orgList) { + TreeNode treeNode = new TreeNode(org.getId(),org.getOrgName()); + treeNode.setCode(org.getOrgCode()); + treeNode.setCodePath(org.getCodePath()); + treeNode.setNamePath(org.getNamePath()); + treeNode.setParentKey(org.getParentId()); + treeNode.setParentTitle(org.getParentName()); + treeNode.setParentCode(org.getParentCode()); + treeNode.setAttrs(org); + treeNode.setLeaf(true); + treeAttributes.addNode(treeNode); + nodeCount ++; + //root organization node,parentId is null or parentId = -1 or parentId = 0 or id = instId or id = parentId + if(org.getParentId() == null + ||org.getParentId().equalsIgnoreCase("0") + ||org.getParentId().equalsIgnoreCase("-1") + ||org.getId().equalsIgnoreCase(currentUser.getInstId()) + ||org.getId().equalsIgnoreCase(org.getParentId()) + ) { + treeNode.setExpanded(true); + treeNode.setLeaf(false); + treeAttributes.setRootNode(treeNode); + } + } + treeAttributes.setNodeCount(nodeCount); + return new Message(Message.SUCCESS,treeAttributes); + } else { + return new Message(Message.FAIL); + } + } @RequestMapping(value = "/import") public Message importingOrganizations( - @ModelAttribute("excelImportFile")ExcelImport excelImportFile, - @CurrentUser UserInfo currentUser) { + @ModelAttribute("excelImportFile")ExcelImport excelImportFile, + @CurrentUser UserInfo currentUser) { if (excelImportFile.isExcelNotEmpty() ) { try { List orgsList = Lists.newArrayList(); @@ -205,7 +205,7 @@ public class OrganizationsController { Sheet sheet = workbook.getSheetAt(i); int rowSize = sheet.getLastRowNum() + 1; for (int j = 1; j < rowSize; j++) {//遍历行 - Row row = sheet.getRow(j); + Row row = sheet.getRow(j); if (row == null || j <3 ) {//略过空行和前3行 continue; } else {//其他行是数据行 @@ -217,71 +217,71 @@ public class OrganizationsController { if(!CollectionUtils.isEmpty(orgsList)){ orgsList = orgsList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getId()))), ArrayList::new)); if(organizationsService.insertBatch(orgsList)) { - return new Message(Message.SUCCESS); - }else { - return new Message(Message.FAIL); - } + return new Message(Message.SUCCESS); + }else { + return new Message(Message.FAIL); + } } } catch (IOException e) { e.printStackTrace(); }finally { - excelImportFile.closeWorkbook(); + excelImportFile.closeWorkbook(); } - } + } - return new Message(Message.FAIL); + return new Message(Message.FAIL); } public Organizations buildOrganizationsFromSheetRow(Row row,UserInfo currentUser) { - Organizations organization = new Organizations(); - // 上级编码 - organization.setParentId(ExcelUtils.getValue(row, 0)); - // 上级名称 - organization.setParentName(ExcelUtils.getValue(row, 1)); - // 组织编码 - organization.setId(ExcelUtils.getValue(row, 2)); - // 组织名称 - organization.setOrgName(ExcelUtils.getValue(row, 3)); - // 组织全称 - organization.setFullName(ExcelUtils.getValue(row, 4)); - // 编码路径 - organization.setCodePath(ExcelUtils.getValue(row, 5)); - // 名称路径 - organization.setNamePath(ExcelUtils.getValue(row, 6)); - // 组织类型 - organization.setType(ExcelUtils.getValue(row, 7)); - // 所属分支机构 - organization.setDivision(ExcelUtils.getValue(row, 8)); - // 级别 - String level = ExcelUtils.getValue(row, 9); - organization.setLevel(level.equals("") ? 1 : Integer.parseInt(level)); - // 排序 - String sortIndex = ExcelUtils.getValue(row, 10); - organization.setSortIndex(sortIndex.equals("") ? 1 : Integer.parseInt(sortIndex)); - // 联系人 - organization.setContact(ExcelUtils.getValue(row, 11)); - // 联系电话 - organization.setPhone(ExcelUtils.getValue(row, 12)); - // 邮箱 - organization.setEmail(ExcelUtils.getValue(row, 13)); - // 传真 - organization.setFax(ExcelUtils.getValue(row, 14)); - // 工作-国家 - organization.setCountry(ExcelUtils.getValue(row, 15)); - // 工作-省 - organization.setRegion(ExcelUtils.getValue(row, 16)); - // 工作-城市 - organization.setLocality(ExcelUtils.getValue(row, 17)); - // 工作-地址 - organization.setLocality(ExcelUtils.getValue(row, 18)); - // 邮编 - organization.setPostalCode(ExcelUtils.getValue(row, 19)); - // 详细描述 - organization.setDescription(ExcelUtils.getValue(row, 20)); - organization.setStatus(1); - - organization.setInstId(currentUser.getInstId()); + Organizations organization = new Organizations(); + // 上级编码 + organization.setParentId(ExcelUtils.getValue(row, 0)); + // 上级名称 + organization.setParentName(ExcelUtils.getValue(row, 1)); + // 组织编码 + organization.setId(ExcelUtils.getValue(row, 2)); + // 组织名称 + organization.setOrgName(ExcelUtils.getValue(row, 3)); + // 组织全称 + organization.setFullName(ExcelUtils.getValue(row, 4)); + // 编码路径 + organization.setCodePath(ExcelUtils.getValue(row, 5)); + // 名称路径 + organization.setNamePath(ExcelUtils.getValue(row, 6)); + // 组织类型 + organization.setType(ExcelUtils.getValue(row, 7)); + // 所属分支机构 + organization.setDivision(ExcelUtils.getValue(row, 8)); + // 级别 + String level = ExcelUtils.getValue(row, 9); + organization.setLevel(level.equals("") ? 1 : Integer.parseInt(level)); + // 排序 + String sortIndex = ExcelUtils.getValue(row, 10); + organization.setSortIndex(sortIndex.equals("") ? 1 : Integer.parseInt(sortIndex)); + // 联系人 + organization.setContact(ExcelUtils.getValue(row, 11)); + // 联系电话 + organization.setPhone(ExcelUtils.getValue(row, 12)); + // 邮箱 + organization.setEmail(ExcelUtils.getValue(row, 13)); + // 传真 + organization.setFax(ExcelUtils.getValue(row, 14)); + // 工作-国家 + organization.setCountry(ExcelUtils.getValue(row, 15)); + // 工作-省 + organization.setRegion(ExcelUtils.getValue(row, 16)); + // 工作-城市 + organization.setLocality(ExcelUtils.getValue(row, 17)); + // 工作-地址 + organization.setLocality(ExcelUtils.getValue(row, 18)); + // 邮编 + organization.setPostalCode(ExcelUtils.getValue(row, 19)); + // 详细描述 + organization.setDescription(ExcelUtils.getValue(row, 20)); + organization.setStatus(1); + + organization.setInstId(currentUser.getInstId()); return organization; } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/idm/contorller/UserInfoController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/idm/contorller/UserInfoController.java index 4eca264aa..ebe1205ae 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/idm/contorller/UserInfoController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/idm/contorller/UserInfoController.java @@ -75,206 +75,206 @@ import com.google.common.collect.Lists; @RestController @RequestMapping(value = { "/users" }) public class UserInfoController { - static final Logger logger = LoggerFactory.getLogger(UserInfoController.class); - - @Autowired - UserInfoService userInfoService; - - @Autowired - FileUploadService fileUploadService; + static final Logger logger = LoggerFactory.getLogger(UserInfoController.class); + + @Autowired + UserInfoService userInfoService; + + @Autowired + FileUploadService fileUploadService; - @Autowired - HistorySystemLogsService systemLog; - - @RequestMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - @ResponseBody - public Message fetch(@ModelAttribute UserInfo userInfo,@CurrentUser UserInfo currentUser) { - logger.debug(""+userInfo); - userInfo.setInstId(currentUser.getInstId()); - return new Message>( - userInfoService.fetchPageResults(userInfo)); - } + @Autowired + HistorySystemLogsService systemLog; + + @RequestMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + @ResponseBody + public Message fetch(@ModelAttribute UserInfo userInfo,@CurrentUser UserInfo currentUser) { + logger.debug(""+userInfo); + userInfo.setInstId(currentUser.getInstId()); + return new Message>( + userInfoService.fetchPageResults(userInfo)); + } - @ResponseBody - @RequestMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message query(@ModelAttribute UserInfo userInfo,@CurrentUser UserInfo currentUser) { - logger.debug("-query :" + userInfo); - if (userInfoService.query(userInfo)!=null) { - return new Message(Message.SUCCESS); - } else { - return new Message(Message.SUCCESS); - } - } - - @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@PathVariable("id") String id) { - UserInfo userInfo=userInfoService.get(id); - userInfo.trans(); - return new Message(userInfo); - } - - @RequestMapping(value = { "/getByUsername/{username}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message getByUsername(@PathVariable("username") String username) { - UserInfo userInfo=userInfoService.findByUsername(username); - userInfo.trans(); - return new Message(userInfo); - } - - @ResponseBody - @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message insert(@RequestBody UserInfo userInfo,@CurrentUser UserInfo currentUser) { - logger.debug("-Add :" + userInfo); - userInfo.setId(WebContext.genId()); - userInfo.setInstId(currentUser.getInstId()); - if(StringUtils.isNotBlank(userInfo.getPictureId())) { - userInfo.setPicture(fileUploadService.get(userInfo.getPictureId()).getUploaded()); - fileUploadService.delete(userInfo.getPictureId()); - } - if (userInfoService.insert(userInfo)) { - systemLog.insert( - ConstsEntryType.USERINFO, - userInfo, - ConstsAct.CREATE, - ConstsActResult.SUCCESS, - currentUser); - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @ResponseBody - @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update(@RequestBody UserInfo userInfo,@CurrentUser UserInfo currentUser) { - logger.debug("-update :" + userInfo); - logger.info(userInfo.getExtraAttributeName()); - logger.info(userInfo.getExtraAttributeValue()); - //userInfo.setNameZHShortSpell(StringUtils.hanYu2Pinyin(userInfo.getDisplayName(), true)); - //userInfo.setNameZHSpell(StringUtils.hanYu2Pinyin(userInfo.getDisplayName(), false)); - convertExtraAttribute(userInfo) ; - logger.info(userInfo.getExtraAttribute()); - userInfo.setInstId(currentUser.getInstId()); - if(StringUtils.isNotBlank(userInfo.getPictureId())) { - userInfo.setPicture(fileUploadService.get(userInfo.getPictureId()).getUploaded()); - fileUploadService.delete(userInfo.getPictureId()); - } - if (userInfoService.update(userInfo)) { - systemLog.insert( - ConstsEntryType.USERINFO, - userInfo, - ConstsAct.UPDATE, - ConstsActResult.SUCCESS, - currentUser); - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @ResponseBody - @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {} " , ids); - - if (userInfoService.deleteBatch(ids)) { - systemLog.insert( - ConstsEntryType.USERINFO, - ids, - ConstsAct.DELETE, - ConstsActResult.SUCCESS, - currentUser); - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } + @ResponseBody + @RequestMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message query(@ModelAttribute UserInfo userInfo,@CurrentUser UserInfo currentUser) { + logger.debug("-query :" + userInfo); + if (userInfoService.query(userInfo)!=null) { + return new Message(Message.SUCCESS); + } else { + return new Message(Message.SUCCESS); + } + } + + @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@PathVariable("id") String id) { + UserInfo userInfo=userInfoService.get(id); + userInfo.trans(); + return new Message(userInfo); + } + + @RequestMapping(value = { "/getByUsername/{username}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message getByUsername(@PathVariable("username") String username) { + UserInfo userInfo=userInfoService.findByUsername(username); + userInfo.trans(); + return new Message(userInfo); + } + + @ResponseBody + @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message insert(@RequestBody UserInfo userInfo,@CurrentUser UserInfo currentUser) { + logger.debug("-Add :" + userInfo); + userInfo.setId(WebContext.genId()); + userInfo.setInstId(currentUser.getInstId()); + if(StringUtils.isNotBlank(userInfo.getPictureId())) { + userInfo.setPicture(fileUploadService.get(userInfo.getPictureId()).getUploaded()); + fileUploadService.delete(userInfo.getPictureId()); + } + if (userInfoService.insert(userInfo)) { + systemLog.insert( + ConstsEntryType.USERINFO, + userInfo, + ConstsAct.CREATE, + ConstsActResult.SUCCESS, + currentUser); + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @ResponseBody + @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update(@RequestBody UserInfo userInfo,@CurrentUser UserInfo currentUser) { + logger.debug("-update :" + userInfo); + logger.info(userInfo.getExtraAttributeName()); + logger.info(userInfo.getExtraAttributeValue()); + //userInfo.setNameZHShortSpell(StringUtils.hanYu2Pinyin(userInfo.getDisplayName(), true)); + //userInfo.setNameZHSpell(StringUtils.hanYu2Pinyin(userInfo.getDisplayName(), false)); + convertExtraAttribute(userInfo) ; + logger.info(userInfo.getExtraAttribute()); + userInfo.setInstId(currentUser.getInstId()); + if(StringUtils.isNotBlank(userInfo.getPictureId())) { + userInfo.setPicture(fileUploadService.get(userInfo.getPictureId()).getUploaded()); + fileUploadService.delete(userInfo.getPictureId()); + } + if (userInfoService.update(userInfo)) { + systemLog.insert( + ConstsEntryType.USERINFO, + userInfo, + ConstsAct.UPDATE, + ConstsActResult.SUCCESS, + currentUser); + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @ResponseBody + @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {} " , ids); + + if (userInfoService.deleteBatch(ids)) { + systemLog.insert( + ConstsEntryType.USERINFO, + ids, + ConstsAct.DELETE, + ConstsActResult.SUCCESS, + currentUser); + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } - + @ResponseBody @RequestMapping(value = "/randomPassword", produces = {MediaType.APPLICATION_JSON_VALUE}) public Message randomPassword() { return new Message( - Message.SUCCESS, - (Object)userInfoService.randomPassword() - ); + Message.SUCCESS, + (Object)userInfoService.randomPassword() + ); } - - - protected void convertExtraAttribute(UserInfo userInfo) { - if(userInfo.getExtraAttributeValue()!=null){ - String []extraAttributeLabel=userInfo.getExtraAttributeName().split(","); - String []extraAttributeValue=userInfo.getExtraAttributeValue().split(","); - Map extraAttributeMap=new HashMap (); - for(int i=0;i changePassword( - @RequestBody ChangePassword changePassword, - @CurrentUser UserInfo currentUser) { - logger.debug("UserId {}",changePassword.getUserId()); - changePassword.setPasswordSetType(ConstsPasswordSetType.PASSWORD_NORMAL); - if(userInfoService.changePassword(changePassword,true)) { - systemLog.insert( - ConstsEntryType.USERINFO, - changePassword, - ConstsAct.CHANGE_PASSWORD, - ConstsActResult.SUCCESS, - currentUser); - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @RequestMapping(value = { "/updateStatus" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - @ResponseBody - public Message updateStatus(@ModelAttribute UserInfo userInfo,@CurrentUser UserInfo currentUser) { - logger.debug(""+userInfo); - UserInfo loadUserInfo = userInfoService.get(userInfo.getId()); - userInfo.setInstId(currentUser.getInstId()); - userInfo.setUsername(loadUserInfo.getUsername()); - userInfo.setDisplayName(loadUserInfo.getDisplayName()); - if(userInfoService.updateStatus(userInfo)) { - systemLog.insert( - ConstsEntryType.USERINFO, - userInfo, - ConstsAct.statusActon.get(userInfo.getStatus()), - ConstsActResult.SUCCESS, - currentUser); - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - /** + + + protected void convertExtraAttribute(UserInfo userInfo) { + if(userInfo.getExtraAttributeValue()!=null){ + String []extraAttributeLabel=userInfo.getExtraAttributeName().split(","); + String []extraAttributeValue=userInfo.getExtraAttributeValue().split(","); + Map extraAttributeMap=new HashMap (); + for(int i=0;i changePassword( + @RequestBody ChangePassword changePassword, + @CurrentUser UserInfo currentUser) { + logger.debug("UserId {}",changePassword.getUserId()); + changePassword.setPasswordSetType(ConstsPasswordSetType.PASSWORD_NORMAL); + if(userInfoService.changePassword(changePassword,true)) { + systemLog.insert( + ConstsEntryType.USERINFO, + changePassword, + ConstsAct.CHANGE_PASSWORD, + ConstsActResult.SUCCESS, + currentUser); + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @RequestMapping(value = { "/updateStatus" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + @ResponseBody + public Message updateStatus(@ModelAttribute UserInfo userInfo,@CurrentUser UserInfo currentUser) { + logger.debug(""+userInfo); + UserInfo loadUserInfo = userInfoService.get(userInfo.getId()); + userInfo.setInstId(currentUser.getInstId()); + userInfo.setUsername(loadUserInfo.getUsername()); + userInfo.setDisplayName(loadUserInfo.getDisplayName()); + if(userInfoService.updateStatus(userInfo)) { + systemLog.insert( + ConstsEntryType.USERINFO, + userInfo, + ConstsAct.statusActon.get(userInfo.getStatus()), + ConstsActResult.SUCCESS, + currentUser); + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + /** * AuthnType. * * @param userInfo * @param result * @return */ - @PutMapping("/updateAuthnType") - public Message updateAuthnType(@RequestBody UserInfo userInfo) { + @PutMapping("/updateAuthnType") + public Message updateAuthnType(@RequestBody UserInfo userInfo) { logger.debug("updateAuthnType {}",userInfo); if (userInfoService.updateAuthnType(userInfo)) { - return new Message<>(Message.SUCCESS); + return new Message<>(Message.SUCCESS); } return new Message<>(Message.FAIL); } - + @RequestMapping(value = "/import") public Message importingUsers( - @ModelAttribute("excelImportFile")ExcelImport excelImportFile, - @CurrentUser UserInfo currentUser) { + @ModelAttribute("excelImportFile")ExcelImport excelImportFile, + @CurrentUser UserInfo currentUser) { if (excelImportFile.isExcelNotEmpty() ) { try { List userInfoList = Lists.newArrayList(); @@ -289,7 +289,7 @@ public class UserInfoController { if (row == null || j <3 ) {//略过空行和前3行 continue; } else {//其他行是数据行 - UserInfo userInfo = buildUserFromSheetRow(row,currentUser); + UserInfo userInfo = buildUserFromSheetRow(row,currentUser); userInfoList.add(userInfo); recordCount ++; logger.debug("record {} user {} account {}",recordCount,userInfo.getDisplayName(),userInfo.getUsername()); @@ -300,141 +300,141 @@ public class UserInfoController { if(!CollectionUtils.isEmpty(userInfoList)){ userInfoList = userInfoList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getUsername()))), ArrayList::new)); if( userInfoService.insertBatch(userInfoList)) { - return new Message(Message.SUCCESS); + return new Message(Message.SUCCESS); } } } catch (IOException e) { e.printStackTrace(); }finally { - excelImportFile.closeWorkbook(); + excelImportFile.closeWorkbook(); } } return new Message(Message.FAIL); } - @InitBinder - public void binder(WebDataBinder binder) { - binder.registerCustomEditor(String.class, new PropertyEditorSupport() { - @Override - public void setAsText(String value) { - if(StringUtils.isEmpty(value)){ - setValue(null); - }else{ - setValue(value); - } - } + @InitBinder + public void binder(WebDataBinder binder) { + binder.registerCustomEditor(String.class, new PropertyEditorSupport() { + @Override + public void setAsText(String value) { + if(StringUtils.isEmpty(value)){ + setValue(null); + }else{ + setValue(value); + } + } - - }); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - dateFormat.setLenient(false); - binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); - } - - - public UserInfo buildUserFromSheetRow(Row row,UserInfo currentUser) { - UserInfo userInfo = new UserInfo(); + + }); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + dateFormat.setLenient(false); + binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); + } + + + public UserInfo buildUserFromSheetRow(Row row,UserInfo currentUser) { + UserInfo userInfo = new UserInfo(); userInfo.setCreatedDate(new Date()); - // 登录账号 - userInfo.setUsername(ExcelUtils.getValue(row, 0)); - // 密码 - userInfo.setPassword(ExcelUtils.getValue(row, 1)); - // 用户显示 - userInfo.setDisplayName(ExcelUtils.getValue(row, 2)); - // 姓 - userInfo.setFamilyName(ExcelUtils.getValue(row, 3)); - // 名 - userInfo.setGivenName(ExcelUtils.getValue(row, 4)); - // 中间名 - userInfo.setMiddleName(ExcelUtils.getValue(row, 5)); - // 昵称 - userInfo.setNickName(ExcelUtils.getValue(row, 6)); - // 性别 - String gender = ExcelUtils.getValue(row, 7); - userInfo.setGender(gender.equals("") ? 1 : Integer.valueOf(gender)); - // 语言偏好 - userInfo.setPreferredLanguage(ExcelUtils.getValue(row, 8)); - // 时区 - userInfo.setTimeZone(ExcelUtils.getValue(row, 9)); - // 用户类型 - userInfo.setUserType(ExcelUtils.getValue(row, 10)); - // 员工编码 - userInfo.setEmployeeNumber(ExcelUtils.getValue(row, 11)); - // AD域账号 - userInfo.setWindowsAccount(ExcelUtils.getValue(row, 12)); - // 所属机构 - userInfo.setOrganization(ExcelUtils.getValue(row, 13)); - // 分支机构 - userInfo.setDivision(ExcelUtils.getValue(row, 14)); - // 部门编号 - userInfo.setDepartmentId(ExcelUtils.getValue(row, 15)); - // 部门名称 - userInfo.setDepartment(ExcelUtils.getValue(row, 16)); - // 成本中心 - userInfo.setCostCenter(ExcelUtils.getValue(row, 17)); - // 职位 - userInfo.setJobTitle(ExcelUtils.getValue(row, 18)); - // 级别 - userInfo.setJobLevel(ExcelUtils.getValue(row, 19)); - // 上级经理 - userInfo.setManager(ExcelUtils.getValue(row, 20)); - // 助理 - userInfo.setAssistant(ExcelUtils.getValue(row, 21)); - // 入职时间 - userInfo.setEntryDate(ExcelUtils.getValue(row, 22)); - // 离职时间 - userInfo.setQuitDate(ExcelUtils.getValue(row, 23)); - // 工作-国家 - userInfo.setWorkCountry(ExcelUtils.getValue(row, 24)); - // 工作-省 - userInfo.setWorkRegion(ExcelUtils.getValue(row, 25)); - // 工作-城市 - userInfo.setTimeZone(ExcelUtils.getValue(row, 26)); - // 工作-地址 - userInfo.setWorkLocality(ExcelUtils.getValue(row, 27)); - // 邮编 - userInfo.setWorkPostalCode(ExcelUtils.getValue(row, 28)); - // 传真 - userInfo.setWorkFax(ExcelUtils.getValue(row, 29)); - // 工作电话 - userInfo.setWorkPhoneNumber(ExcelUtils.getValue(row, 30)); - // 工作邮件 - userInfo.setWorkEmail(ExcelUtils.getValue(row, 31)); - // 证件类型 todo 现在数据库中存储的是tinyint + // 登录账号 + userInfo.setUsername(ExcelUtils.getValue(row, 0)); + // 密码 + userInfo.setPassword(ExcelUtils.getValue(row, 1)); + // 用户显示 + userInfo.setDisplayName(ExcelUtils.getValue(row, 2)); + // 姓 + userInfo.setFamilyName(ExcelUtils.getValue(row, 3)); + // 名 + userInfo.setGivenName(ExcelUtils.getValue(row, 4)); + // 中间名 + userInfo.setMiddleName(ExcelUtils.getValue(row, 5)); + // 昵称 + userInfo.setNickName(ExcelUtils.getValue(row, 6)); + // 性别 + String gender = ExcelUtils.getValue(row, 7); + userInfo.setGender(gender.equals("") ? 1 : Integer.valueOf(gender)); + // 语言偏好 + userInfo.setPreferredLanguage(ExcelUtils.getValue(row, 8)); + // 时区 + userInfo.setTimeZone(ExcelUtils.getValue(row, 9)); + // 用户类型 + userInfo.setUserType(ExcelUtils.getValue(row, 10)); + // 员工编码 + userInfo.setEmployeeNumber(ExcelUtils.getValue(row, 11)); + // AD域账号 + userInfo.setWindowsAccount(ExcelUtils.getValue(row, 12)); + // 所属机构 + userInfo.setOrganization(ExcelUtils.getValue(row, 13)); + // 分支机构 + userInfo.setDivision(ExcelUtils.getValue(row, 14)); + // 部门编号 + userInfo.setDepartmentId(ExcelUtils.getValue(row, 15)); + // 部门名称 + userInfo.setDepartment(ExcelUtils.getValue(row, 16)); + // 成本中心 + userInfo.setCostCenter(ExcelUtils.getValue(row, 17)); + // 职位 + userInfo.setJobTitle(ExcelUtils.getValue(row, 18)); + // 级别 + userInfo.setJobLevel(ExcelUtils.getValue(row, 19)); + // 上级经理 + userInfo.setManager(ExcelUtils.getValue(row, 20)); + // 助理 + userInfo.setAssistant(ExcelUtils.getValue(row, 21)); + // 入职时间 + userInfo.setEntryDate(ExcelUtils.getValue(row, 22)); + // 离职时间 + userInfo.setQuitDate(ExcelUtils.getValue(row, 23)); + // 工作-国家 + userInfo.setWorkCountry(ExcelUtils.getValue(row, 24)); + // 工作-省 + userInfo.setWorkRegion(ExcelUtils.getValue(row, 25)); + // 工作-城市 + userInfo.setTimeZone(ExcelUtils.getValue(row, 26)); + // 工作-地址 + userInfo.setWorkLocality(ExcelUtils.getValue(row, 27)); + // 邮编 + userInfo.setWorkPostalCode(ExcelUtils.getValue(row, 28)); + // 传真 + userInfo.setWorkFax(ExcelUtils.getValue(row, 29)); + // 工作电话 + userInfo.setWorkPhoneNumber(ExcelUtils.getValue(row, 30)); + // 工作邮件 + userInfo.setWorkEmail(ExcelUtils.getValue(row, 31)); + // 证件类型 todo 现在数据库中存储的是tinyint // userInfo.setIdType(ExcelUtils.getValue(row, 32)); - // 证件号码 - userInfo.setIdCardNo(ExcelUtils.getValue(row, 33)); - // 出生日期 - userInfo.setBirthDate(ExcelUtils.getValue(row, 34)); - // 婚姻状态 todo 现在数据字段类型是 tinyint + // 证件号码 + userInfo.setIdCardNo(ExcelUtils.getValue(row, 33)); + // 出生日期 + userInfo.setBirthDate(ExcelUtils.getValue(row, 34)); + // 婚姻状态 todo 现在数据字段类型是 tinyint // userInfo.setMarried(ExcelUtils.getValue(row, 35)); - // 开始工作时间 - userInfo.setStartWorkDate(ExcelUtils.getValue(row, 36)); - // 个人主页 - userInfo.setWebSite(ExcelUtils.getValue(row, 37)); - // 即时通讯 - userInfo.setDefineIm(ExcelUtils.getValue(row, 38)); - // 国家 - userInfo.setHomeCountry(ExcelUtils.getValue(row, 39)); - // 省 - userInfo.setHomeRegion(ExcelUtils.getValue(row, 40)); - // 城市 - userInfo.setHomeLocality(ExcelUtils.getValue(row, 41)); - // 家庭地址 - userInfo.setHomeStreetAddress(ExcelUtils.getValue(row, 42)); - // 家庭邮编 - userInfo.setHomePostalCode(ExcelUtils.getValue(row, 43)); - // 家庭传真 - userInfo.setHomeFax(ExcelUtils.getValue(row, 44)); - // 家庭电话 - userInfo.setHomePhoneNumber(ExcelUtils.getValue(row, 45)); - // 家庭邮箱 - userInfo.setHomeEmail(ExcelUtils.getValue(row, 46)); - userInfoService.passwordEncoder(userInfo); + // 开始工作时间 + userInfo.setStartWorkDate(ExcelUtils.getValue(row, 36)); + // 个人主页 + userInfo.setWebSite(ExcelUtils.getValue(row, 37)); + // 即时通讯 + userInfo.setDefineIm(ExcelUtils.getValue(row, 38)); + // 国家 + userInfo.setHomeCountry(ExcelUtils.getValue(row, 39)); + // 省 + userInfo.setHomeRegion(ExcelUtils.getValue(row, 40)); + // 城市 + userInfo.setHomeLocality(ExcelUtils.getValue(row, 41)); + // 家庭地址 + userInfo.setHomeStreetAddress(ExcelUtils.getValue(row, 42)); + // 家庭邮编 + userInfo.setHomePostalCode(ExcelUtils.getValue(row, 43)); + // 家庭传真 + userInfo.setHomeFax(ExcelUtils.getValue(row, 44)); + // 家庭电话 + userInfo.setHomePhoneNumber(ExcelUtils.getValue(row, 45)); + // 家庭邮箱 + userInfo.setHomeEmail(ExcelUtils.getValue(row, 46)); + userInfoService.passwordEncoder(userInfo); userInfo.setStatus(1); userInfo.setInstId(currentUser.getInstId()); return userInfo; - } + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/PermissionController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/PermissionController.java index 47cf31ac5..42c60c5c9 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/PermissionController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/PermissionController.java @@ -41,92 +41,92 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value={"/permissions/permission"}) public class PermissionController { - static final Logger logger = LoggerFactory.getLogger(PermissionController.class); - - @Autowired - PermissionService permissionService; - - @Autowired - HistorySystemLogsService systemLog; - - @ResponseBody - @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update( - @RequestBody Permission groupPrivileges, - @CurrentUser UserInfo currentUser) { - logger.debug("-update : {}" , groupPrivileges); - //have - Permission queryGroupPrivileges = - new Permission( - groupPrivileges.getAppId(), - groupPrivileges.getGroupId(), - currentUser.getInstId()); - List groupPrivilegesList = permissionService.queryGroupPrivileges(queryGroupPrivileges); - - HashMapprivilegeMap =new HashMap(); - for(Permission rolePrivilege : groupPrivilegesList) { - privilegeMap.put(rolePrivilege.getUniqueId(),rolePrivilege.getId()); - } - //Maybe insert - ArrayList newGroupPrivilegesList =new ArrayList(); - ListresourceIds = StrUtils.string2List(groupPrivileges.getResourceId(), ","); - HashMapnewPrivilegesMap =new HashMap(); - for(String resourceId : resourceIds) { - Permission newGroupPrivilege=new Permission( - WebContext.genId(), - groupPrivileges.getAppId(), - groupPrivileges.getGroupId(), + static final Logger logger = LoggerFactory.getLogger(PermissionController.class); + + @Autowired + PermissionService permissionService; + + @Autowired + HistorySystemLogsService systemLog; + + @ResponseBody + @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update( + @RequestBody Permission groupPrivileges, + @CurrentUser UserInfo currentUser) { + logger.debug("-update : {}" , groupPrivileges); + //have + Permission queryGroupPrivileges = + new Permission( + groupPrivileges.getAppId(), + groupPrivileges.getGroupId(), + currentUser.getInstId()); + List groupPrivilegesList = permissionService.queryGroupPrivileges(queryGroupPrivileges); + + HashMapprivilegeMap =new HashMap(); + for(Permission rolePrivilege : groupPrivilegesList) { + privilegeMap.put(rolePrivilege.getUniqueId(),rolePrivilege.getId()); + } + //Maybe insert + ArrayList newGroupPrivilegesList =new ArrayList(); + ListresourceIds = StrUtils.string2List(groupPrivileges.getResourceId(), ","); + HashMapnewPrivilegesMap =new HashMap(); + for(String resourceId : resourceIds) { + Permission newGroupPrivilege=new Permission( + WebContext.genId(), + groupPrivileges.getAppId(), + groupPrivileges.getGroupId(), resourceId, currentUser.getInstId()); - newGroupPrivilege.setId(newGroupPrivilege.generateId()); - newPrivilegesMap.put(newGroupPrivilege.getUniqueId(), groupPrivileges.getAppId()); - - if(!groupPrivileges.getAppId().equalsIgnoreCase(resourceId) && - !privilegeMap.containsKey(newGroupPrivilege.getUniqueId())) { - newGroupPrivilegesList.add(newGroupPrivilege); - } - } - - //delete - ArrayList deleteGroupPrivilegesList =new ArrayList(); - for(Permission rolePrivilege : groupPrivilegesList) { + newGroupPrivilege.setId(newGroupPrivilege.generateId()); + newPrivilegesMap.put(newGroupPrivilege.getUniqueId(), groupPrivileges.getAppId()); + + if(!groupPrivileges.getAppId().equalsIgnoreCase(resourceId) && + !privilegeMap.containsKey(newGroupPrivilege.getUniqueId())) { + newGroupPrivilegesList.add(newGroupPrivilege); + } + } + + //delete + ArrayList deleteGroupPrivilegesList =new ArrayList(); + for(Permission rolePrivilege : groupPrivilegesList) { if(!newPrivilegesMap.containsKey(rolePrivilege.getUniqueId())) { - rolePrivilege.setInstId(currentUser.getInstId()); - deleteGroupPrivilegesList.add(rolePrivilege); + rolePrivilege.setInstId(currentUser.getInstId()); + deleteGroupPrivilegesList.add(rolePrivilege); } } - if (!deleteGroupPrivilegesList.isEmpty()) { - logger.debug("-remove : {}" , deleteGroupPrivilegesList); - permissionService.deleteGroupPrivileges(deleteGroupPrivilegesList); - } - - if (!newGroupPrivilegesList.isEmpty() && permissionService.insertGroupPrivileges(newGroupPrivilegesList)) { - logger.debug("-insert : {}" , newGroupPrivilegesList); - return new Message(Message.SUCCESS); - - } else { - return new Message(Message.SUCCESS); - } - - } - - @ResponseBody + if (!deleteGroupPrivilegesList.isEmpty()) { + logger.debug("-remove : {}" , deleteGroupPrivilegesList); + permissionService.deleteGroupPrivileges(deleteGroupPrivilegesList); + } + + if (!newGroupPrivilegesList.isEmpty() && permissionService.insertGroupPrivileges(newGroupPrivilegesList)) { + logger.debug("-insert : {}" , newGroupPrivilegesList); + return new Message(Message.SUCCESS); + + } else { + return new Message(Message.SUCCESS); + } + + } + + @ResponseBody @RequestMapping(value={"/get"}, produces = {MediaType.APPLICATION_JSON_VALUE}) public Message get( - @ModelAttribute Permission groupPrivileges, - @CurrentUser UserInfo currentUser) { + @ModelAttribute Permission groupPrivileges, + @CurrentUser UserInfo currentUser) { logger.debug("-get : {}" , groupPrivileges); //have Permission queryGroupPrivilege = - new Permission( - groupPrivileges.getAppId(), - groupPrivileges.getGroupId(), - currentUser.getInstId()); + new Permission( + groupPrivileges.getAppId(), + groupPrivileges.getGroupId(), + currentUser.getInstId()); List rolePrivilegeList = permissionService.queryGroupPrivileges(queryGroupPrivilege); return new Message>( - rolePrivilegeList); - } + rolePrivilegeList); + } - + } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/PermissionRoleController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/PermissionRoleController.java index 14730580d..f17b9ebac 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/PermissionRoleController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/PermissionRoleController.java @@ -46,90 +46,90 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value={"/permissions/permissionRole"}) public class PermissionRoleController { - static final Logger _logger = LoggerFactory.getLogger(PermissionRoleController.class); - - @Autowired - PermissionRoleService permissionRoleService; - - @Autowired - HistorySystemLogsService systemLog; - - @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update( - @RequestBody PermissionRole permissionRole, - @CurrentUser UserInfo currentUser) { - _logger.debug("-update : {}" , permissionRole); - //have - PermissionRole queryPermissionRole = - new PermissionRole( - permissionRole.getAppId(), - permissionRole.getRoleId(), - currentUser.getInstId()); - List permissionRolesList = permissionRoleService.queryPermissionRoles(queryPermissionRole); - - HashMappermissionRolesMap =new HashMap<>(); - for(PermissionRole tempPermissionRole : permissionRolesList) { - permissionRolesMap.put(tempPermissionRole.getUniqueId(),tempPermissionRole.getId()); - } - //Maybe insert - ArrayList newPermissionRolesList =new ArrayList<>(); - ListresourceIds = StrUtils.string2List(permissionRole.getResourceId(), ","); - HashMapnewPermissionRolesMap =new HashMap<>(); - for(String resourceId : resourceIds) { - PermissionRole newPermissionRole =new PermissionRole( - WebContext.genId(), - permissionRole.getAppId(), - permissionRole.getRoleId(), + static final Logger _logger = LoggerFactory.getLogger(PermissionRoleController.class); + + @Autowired + PermissionRoleService permissionRoleService; + + @Autowired + HistorySystemLogsService systemLog; + + @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update( + @RequestBody PermissionRole permissionRole, + @CurrentUser UserInfo currentUser) { + _logger.debug("-update : {}" , permissionRole); + //have + PermissionRole queryPermissionRole = + new PermissionRole( + permissionRole.getAppId(), + permissionRole.getRoleId(), + currentUser.getInstId()); + List permissionRolesList = permissionRoleService.queryPermissionRoles(queryPermissionRole); + + HashMappermissionRolesMap =new HashMap<>(); + for(PermissionRole tempPermissionRole : permissionRolesList) { + permissionRolesMap.put(tempPermissionRole.getUniqueId(),tempPermissionRole.getId()); + } + //Maybe insert + ArrayList newPermissionRolesList =new ArrayList<>(); + ListresourceIds = StrUtils.string2List(permissionRole.getResourceId(), ","); + HashMapnewPermissionRolesMap =new HashMap<>(); + for(String resourceId : resourceIds) { + PermissionRole newPermissionRole =new PermissionRole( + WebContext.genId(), + permissionRole.getAppId(), + permissionRole.getRoleId(), resourceId, currentUser.getId(), currentUser.getInstId()); - newPermissionRole.setId(newPermissionRole.generateId()); - newPermissionRolesMap.put(newPermissionRole.getUniqueId(), permissionRole.getAppId()); - - if(!permissionRole.getAppId().equalsIgnoreCase(resourceId) && - !permissionRolesMap.containsKey(newPermissionRole.getUniqueId())) { - newPermissionRolesList.add(newPermissionRole); - } - } - - //delete - ArrayList deletePermissionRolesList =new ArrayList<>(); - for(PermissionRole tempPermissionRole : permissionRolesList) { + newPermissionRole.setId(newPermissionRole.generateId()); + newPermissionRolesMap.put(newPermissionRole.getUniqueId(), permissionRole.getAppId()); + + if(!permissionRole.getAppId().equalsIgnoreCase(resourceId) && + !permissionRolesMap.containsKey(newPermissionRole.getUniqueId())) { + newPermissionRolesList.add(newPermissionRole); + } + } + + //delete + ArrayList deletePermissionRolesList =new ArrayList<>(); + for(PermissionRole tempPermissionRole : permissionRolesList) { if(!newPermissionRolesMap.containsKey(tempPermissionRole.getUniqueId())) { - tempPermissionRole.setInstId(currentUser.getInstId()); - deletePermissionRolesList.add(tempPermissionRole); + tempPermissionRole.setInstId(currentUser.getInstId()); + deletePermissionRolesList.add(tempPermissionRole); } } - if (!deletePermissionRolesList.isEmpty()) { - _logger.debug("-remove : {}" , deletePermissionRolesList); - permissionRoleService.deletePermissionRoles(deletePermissionRolesList); - } - - if (!newPermissionRolesList.isEmpty() && permissionRoleService.insertPermissionRoles(newPermissionRolesList)) { - _logger.debug("-insert : {}" ,newPermissionRolesList); - return new Message<>(Message.SUCCESS); - - } else { - return new Message<>(Message.SUCCESS); - } - - } - + if (!deletePermissionRolesList.isEmpty()) { + _logger.debug("-remove : {}" , deletePermissionRolesList); + permissionRoleService.deletePermissionRoles(deletePermissionRolesList); + } + + if (!newPermissionRolesList.isEmpty() && permissionRoleService.insertPermissionRoles(newPermissionRolesList)) { + _logger.debug("-insert : {}" ,newPermissionRolesList); + return new Message<>(Message.SUCCESS); + + } else { + return new Message<>(Message.SUCCESS); + } + + } + @GetMapping(value={"/get"}, produces = {MediaType.APPLICATION_JSON_VALUE}) public Message> get( - @ModelAttribute PermissionRole permissionRole, - @CurrentUser UserInfo currentUser) { + @ModelAttribute PermissionRole permissionRole, + @CurrentUser UserInfo currentUser) { _logger.debug("-get : {}" , permissionRole); //have PermissionRole queryPermissionRole = - new PermissionRole( - permissionRole.getAppId(), - permissionRole.getRoleId(), - currentUser.getInstId()); + new PermissionRole( + permissionRole.getAppId(), + permissionRole.getRoleId(), + currentUser.getInstId()); ListpermissionRoleList = permissionRoleService.queryPermissionRoles(queryPermissionRole); return new Message<>(permissionRoleList); - } + } - + } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/ResourcesController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/ResourcesController.java index ba5aedf5d..c09ecb9cd 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/ResourcesController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/ResourcesController.java @@ -48,131 +48,131 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value={"/permissions/resources"}) public class ResourcesController { - static final Logger logger = LoggerFactory.getLogger(ResourcesController.class); - - @Autowired - ResourcesService resourcesService; - - @Autowired - HistorySystemLogsService systemLog; + static final Logger logger = LoggerFactory.getLogger(ResourcesController.class); + + @Autowired + ResourcesService resourcesService; + + @Autowired + HistorySystemLogsService systemLog; - @RequestMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - @ResponseBody - public Message fetch(@ModelAttribute Resources resource,@CurrentUser UserInfo currentUser) { - logger.debug("fetch {}" , resource); - resource.setInstId(currentUser.getInstId()); - return new Message>( - resourcesService.fetchPageResults(resource)); - } + @RequestMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + @ResponseBody + public Message fetch(@ModelAttribute Resources resource,@CurrentUser UserInfo currentUser) { + logger.debug("fetch {}" , resource); + resource.setInstId(currentUser.getInstId()); + return new Message>( + resourcesService.fetchPageResults(resource)); + } - @ResponseBody - @RequestMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message query(@ModelAttribute Resources resource,@CurrentUser UserInfo currentUser) { - logger.debug("-query {}" , resource); - resource.setInstId(currentUser.getInstId()); - List resourceList = resourcesService.query(resource); - if (resourceList != null) { - return new Message>(Message.SUCCESS,resourceList); - } else { - return new Message>(Message.FAIL); - } - } - - @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@PathVariable("id") String id) { - Resources resource=resourcesService.get(id); - return new Message(resource); - } - - @ResponseBody - @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message insert(@RequestBody Resources resource,@CurrentUser UserInfo currentUser) { - logger.debug("-Add :" + resource); - resource.setInstId(currentUser.getInstId()); - if (resourcesService.insert(resource)) { - systemLog.insert( - ConstsEntryType.RESOURCE, - resource, - ConstsAct.CREATE, - ConstsActResult.SUCCESS, - currentUser); - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @ResponseBody - @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update(@RequestBody Resources resource,@CurrentUser UserInfo currentUser) { - logger.debug("-update :" + resource); - resource.setInstId(currentUser.getInstId()); - if (resourcesService.update(resource)) { - systemLog.insert( - ConstsEntryType.RESOURCE, - resource, - ConstsAct.UPDATE, - ConstsActResult.SUCCESS, - currentUser); - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } - - @ResponseBody - @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { - logger.debug("-delete ids : {} " , ids); - if (resourcesService.deleteBatch(ids)) { - systemLog.insert( - ConstsEntryType.RESOURCE, - ids, - ConstsAct.DELETE, - ConstsActResult.SUCCESS, - currentUser); - return new Message(Message.SUCCESS); - } else { - return new Message(Message.FAIL); - } - } + @ResponseBody + @RequestMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message query(@ModelAttribute Resources resource,@CurrentUser UserInfo currentUser) { + logger.debug("-query {}" , resource); + resource.setInstId(currentUser.getInstId()); + List resourceList = resourcesService.query(resource); + if (resourceList != null) { + return new Message>(Message.SUCCESS,resourceList); + } else { + return new Message>(Message.FAIL); + } + } + + @RequestMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@PathVariable("id") String id) { + Resources resource=resourcesService.get(id); + return new Message(resource); + } + + @ResponseBody + @RequestMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message insert(@RequestBody Resources resource,@CurrentUser UserInfo currentUser) { + logger.debug("-Add :" + resource); + resource.setInstId(currentUser.getInstId()); + if (resourcesService.insert(resource)) { + systemLog.insert( + ConstsEntryType.RESOURCE, + resource, + ConstsAct.CREATE, + ConstsActResult.SUCCESS, + currentUser); + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @ResponseBody + @RequestMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update(@RequestBody Resources resource,@CurrentUser UserInfo currentUser) { + logger.debug("-update :" + resource); + resource.setInstId(currentUser.getInstId()); + if (resourcesService.update(resource)) { + systemLog.insert( + ConstsEntryType.RESOURCE, + resource, + ConstsAct.UPDATE, + ConstsActResult.SUCCESS, + currentUser); + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } + + @ResponseBody + @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { + logger.debug("-delete ids : {} " , ids); + if (resourcesService.deleteBatch(ids)) { + systemLog.insert( + ConstsEntryType.RESOURCE, + ids, + ConstsAct.DELETE, + ConstsActResult.SUCCESS, + currentUser); + return new Message(Message.SUCCESS); + } else { + return new Message(Message.FAIL); + } + } - @ResponseBody - @RequestMapping(value={"/tree"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message tree(@ModelAttribute Resources resource,@CurrentUser UserInfo currentUser) { - logger.debug("-tree {}" , resource); - List resourceList = resourcesService.query(Query.builder().eq("instid", currentUser.getInstId())); - if (resourceList != null) { - TreeAttributes treeAttributes = new TreeAttributes(); - int nodeCount = 0; - for (Resources r : resourceList) { - TreeNode treeNode = new TreeNode(r.getId(),r.getResourceName()); - treeNode.setParentKey(r.getParentId()); - treeNode.setParentTitle(r.getParentName()); - treeNode.setAttrs(r); - treeNode.setLeaf(true); - treeAttributes.addNode(treeNode); - nodeCount ++; - if(r.getId().equalsIgnoreCase(currentUser.getInstId())) { - treeNode.setExpanded(true); - treeNode.setLeaf(false); - treeAttributes.setRootNode(treeNode); - } - } - - TreeNode rootNode = new TreeNode(resource.getAppId(),resource.getAppName()); - rootNode.setParentKey(resource.getAppId()); - rootNode.setExpanded(true); - rootNode.setLeaf(false); - treeAttributes.setRootNode(rootNode); - - treeAttributes.setNodeCount(nodeCount); - return new Message(Message.SUCCESS,treeAttributes); - } else { - return new Message(Message.FAIL); - } - } - + @ResponseBody + @RequestMapping(value={"/tree"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message tree(@ModelAttribute Resources resource,@CurrentUser UserInfo currentUser) { + logger.debug("-tree {}" , resource); + List resourceList = resourcesService.query(Query.builder().eq("instid", currentUser.getInstId())); + if (resourceList != null) { + TreeAttributes treeAttributes = new TreeAttributes(); + int nodeCount = 0; + for (Resources r : resourceList) { + TreeNode treeNode = new TreeNode(r.getId(),r.getResourceName()); + treeNode.setParentKey(r.getParentId()); + treeNode.setParentTitle(r.getParentName()); + treeNode.setAttrs(r); + treeNode.setLeaf(true); + treeAttributes.addNode(treeNode); + nodeCount ++; + if(r.getId().equalsIgnoreCase(currentUser.getInstId())) { + treeNode.setExpanded(true); + treeNode.setLeaf(false); + treeAttributes.setRootNode(treeNode); + } + } + + TreeNode rootNode = new TreeNode(resource.getAppId(),resource.getAppName()); + rootNode.setParentKey(resource.getAppId()); + rootNode.setExpanded(true); + rootNode.setLeaf(false); + treeAttributes.setRootNode(rootNode); + + treeAttributes.setNodeCount(nodeCount); + return new Message(Message.SUCCESS,treeAttributes); + } else { + return new Message(Message.FAIL); + } + } + } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/RoleMemberController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/RoleMemberController.java index 2ba2ade21..ceb7a9340 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/RoleMemberController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/RoleMemberController.java @@ -50,147 +50,147 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value={"/permissions/rolemembers"}) public class RoleMemberController { - static final Logger _logger = LoggerFactory.getLogger(RoleMemberController.class); - - @Autowired - RoleMemberService roleMemberService; + static final Logger _logger = LoggerFactory.getLogger(RoleMemberController.class); + + @Autowired + RoleMemberService roleMemberService; - @Autowired - RolesService rolesService; - - @Autowired - UserInfoService userInfoService; - - @Autowired - HistorySystemLogsService systemLog; - - @GetMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message> fetch( - @ModelAttribute RoleMember roleMember, - @CurrentUser UserInfo currentUser) { - _logger.debug("fetch {}",roleMember); - roleMember.setInstId(currentUser.getInstId()); - return new Message<>(roleMemberService.fetchPageResults(roleMember)); - } + @Autowired + RolesService rolesService; + + @Autowired + UserInfoService userInfoService; + + @Autowired + HistorySystemLogsService systemLog; + + @GetMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message> fetch( + @ModelAttribute RoleMember roleMember, + @CurrentUser UserInfo currentUser) { + _logger.debug("fetch {}",roleMember); + roleMember.setInstId(currentUser.getInstId()); + return new Message<>(roleMemberService.fetchPageResults(roleMember)); + } - @RequestMapping(value = { "/memberInRole" }) - public Message> memberInRole(@ModelAttribute RoleMember roleMember,@CurrentUser UserInfo currentUser) { - _logger.debug("roleMember : {}",roleMember); - roleMember.setInstId(currentUser.getInstId()); + @RequestMapping(value = { "/memberInRole" }) + public Message> memberInRole(@ModelAttribute RoleMember roleMember,@CurrentUser UserInfo currentUser) { + _logger.debug("roleMember : {}",roleMember); + roleMember.setInstId(currentUser.getInstId()); - return new Message<>(roleMemberService.fetchPageResults("memberInRole",roleMember)); - } + return new Message<>(roleMemberService.fetchPageResults("memberInRole",roleMember)); + } - - @RequestMapping(value = { "/memberNotInRole" }) - public Message> memberNotInRole(@ModelAttribute RoleMember roleMember,@CurrentUser UserInfo currentUser) { - roleMember.setInstId(currentUser.getInstId()); - return new Message<>(roleMemberService.fetchPageResults("memberNotInRole",roleMember)); - } - - @RequestMapping(value = { "/memberPostNotInRole" }) - public Message> memberPostNotInRole(@ModelAttribute RoleMember roleMember,@CurrentUser UserInfo currentUser) { - roleMember.setInstId(currentUser.getInstId()); - return new Message<>(roleMemberService.fetchPageResults("memberPostNotInRole",roleMember)); - } - - @RequestMapping(value = { "/rolesNoMember" }) - public Message> rolesNoMember(@ModelAttribute RoleMember roleMember,@CurrentUser UserInfo currentUser) { - roleMember.setInstId(currentUser.getInstId()); - return new Message<>(roleMemberService.rolesNoMember(roleMember)); - } - - /** - * Members add to the Role - * @param roleMember - * @param currentUser - * @return - */ - @PostMapping(value = {"/add"}) - @ResponseBody - public Message addRoleMember(@RequestBody RoleMember roleMember,@CurrentUser UserInfo currentUser) { - if (roleMember == null || roleMember.getRoleId() == null) { - return new Message<>(Message.FAIL); - } - String roleId = roleMember.getRoleId(); - - - boolean result = true; - String memberIds = roleMember.getMemberId(); - String memberNames = roleMember.getMemberName(); - if (memberIds != null) { - String[] arrMemberIds = memberIds.split(","); - String[] arrMemberNames = memberNames.split(","); - - for (int i = 0; i < arrMemberIds.length; i++) { - RoleMember newRoleMember = - new RoleMember( - roleId, - roleMember.getRoleName(), - arrMemberIds[i], - arrMemberNames[i], - roleMember.getType(), - currentUser.getId(), - currentUser.getInstId()); - newRoleMember.setId(WebContext.genId()); - result = roleMemberService.insert(newRoleMember); - } - if(result) { - return new Message<>(Message.SUCCESS); - } - } - return new Message<>(Message.FAIL); - } - - - /** - * Member add to Roles - * @param roleMember - * @param currentUser - * @return - */ - @RequestMapping(value = {"/addMember2Roles"}) - public Message addMember2Roles(@RequestBody RoleMember roleMember,@CurrentUser UserInfo currentUser) { - if (roleMember == null || StringUtils.isBlank(roleMember.getUsername())) { - return new Message<>(Message.FAIL); - } - UserInfo userInfo = userInfoService.findByUsername(roleMember.getUsername()); - - boolean result = true; - String roleIds = roleMember.getRoleId(); - String roleNames = roleMember.getRoleName(); - if (roleIds != null && userInfo != null) { - String[] arrRoleIds = roleIds.split(","); - String[] arrRoleNames = roleNames.split(","); - - for (int i = 0; i < arrRoleIds.length; i++) { - RoleMember newRoleMember = - new RoleMember( - arrRoleIds[i], - arrRoleNames[i], - userInfo.getId(), - userInfo.getDisplayName(), - "USER", - currentUser.getId(), - currentUser.getInstId()); - newRoleMember.setId(WebContext.genId()); - result = roleMemberService.insert(newRoleMember); - } - if(result) { - return new Message<>(Message.SUCCESS); - } - } - return new Message<>(Message.FAIL); - } - - @ResponseBody - @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { - _logger.debug("-delete ids : {}" , ids); - if (roleMemberService.deleteBatch(ids)) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } + + @RequestMapping(value = { "/memberNotInRole" }) + public Message> memberNotInRole(@ModelAttribute RoleMember roleMember,@CurrentUser UserInfo currentUser) { + roleMember.setInstId(currentUser.getInstId()); + return new Message<>(roleMemberService.fetchPageResults("memberNotInRole",roleMember)); + } + + @RequestMapping(value = { "/memberPostNotInRole" }) + public Message> memberPostNotInRole(@ModelAttribute RoleMember roleMember,@CurrentUser UserInfo currentUser) { + roleMember.setInstId(currentUser.getInstId()); + return new Message<>(roleMemberService.fetchPageResults("memberPostNotInRole",roleMember)); + } + + @RequestMapping(value = { "/rolesNoMember" }) + public Message> rolesNoMember(@ModelAttribute RoleMember roleMember,@CurrentUser UserInfo currentUser) { + roleMember.setInstId(currentUser.getInstId()); + return new Message<>(roleMemberService.rolesNoMember(roleMember)); + } + + /** + * Members add to the Role + * @param roleMember + * @param currentUser + * @return + */ + @PostMapping(value = {"/add"}) + @ResponseBody + public Message addRoleMember(@RequestBody RoleMember roleMember,@CurrentUser UserInfo currentUser) { + if (roleMember == null || roleMember.getRoleId() == null) { + return new Message<>(Message.FAIL); + } + String roleId = roleMember.getRoleId(); + + + boolean result = true; + String memberIds = roleMember.getMemberId(); + String memberNames = roleMember.getMemberName(); + if (memberIds != null) { + String[] arrMemberIds = memberIds.split(","); + String[] arrMemberNames = memberNames.split(","); + + for (int i = 0; i < arrMemberIds.length; i++) { + RoleMember newRoleMember = + new RoleMember( + roleId, + roleMember.getRoleName(), + arrMemberIds[i], + arrMemberNames[i], + roleMember.getType(), + currentUser.getId(), + currentUser.getInstId()); + newRoleMember.setId(WebContext.genId()); + result = roleMemberService.insert(newRoleMember); + } + if(result) { + return new Message<>(Message.SUCCESS); + } + } + return new Message<>(Message.FAIL); + } + + + /** + * Member add to Roles + * @param roleMember + * @param currentUser + * @return + */ + @RequestMapping(value = {"/addMember2Roles"}) + public Message addMember2Roles(@RequestBody RoleMember roleMember,@CurrentUser UserInfo currentUser) { + if (roleMember == null || StringUtils.isBlank(roleMember.getUsername())) { + return new Message<>(Message.FAIL); + } + UserInfo userInfo = userInfoService.findByUsername(roleMember.getUsername()); + + boolean result = true; + String roleIds = roleMember.getRoleId(); + String roleNames = roleMember.getRoleName(); + if (roleIds != null && userInfo != null) { + String[] arrRoleIds = roleIds.split(","); + String[] arrRoleNames = roleNames.split(","); + + for (int i = 0; i < arrRoleIds.length; i++) { + RoleMember newRoleMember = + new RoleMember( + arrRoleIds[i], + arrRoleNames[i], + userInfo.getId(), + userInfo.getDisplayName(), + "USER", + currentUser.getId(), + currentUser.getInstId()); + newRoleMember.setId(WebContext.genId()); + result = roleMemberService.insert(newRoleMember); + } + if(result) { + return new Message<>(Message.SUCCESS); + } + } + return new Message<>(Message.FAIL); + } + + @ResponseBody + @RequestMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { + _logger.debug("-delete ids : {}" , ids); + if (roleMemberService.deleteBatch(ids)) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } } diff --git a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/RolesController.java b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/RolesController.java index 9ea4e9596..208890d3f 100644 --- a/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/RolesController.java +++ b/maxkey-webs/maxkey-web-mgt/src/main/java/org/dromara/maxkey/web/permissions/contorller/RolesController.java @@ -52,100 +52,100 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value={"/permissions/roles"}) public class RolesController { - static final Logger _logger = LoggerFactory.getLogger(RolesController.class); - - @Autowired - RolesService rolesService; - - @Autowired - HistorySystemLogsService systemLog; - - @GetMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message> fetch( - @ModelAttribute Roles role, - @CurrentUser UserInfo currentUser) { - _logger.debug("fetch {}",role); - role.setInstId(currentUser.getInstId()); - return new Message<>(rolesService.fetchPageResults(role)); - } + static final Logger _logger = LoggerFactory.getLogger(RolesController.class); + + @Autowired + RolesService rolesService; + + @Autowired + HistorySystemLogsService systemLog; + + @GetMapping(value = { "/fetch" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message> fetch( + @ModelAttribute Roles role, + @CurrentUser UserInfo currentUser) { + _logger.debug("fetch {}",role); + role.setInstId(currentUser.getInstId()); + return new Message<>(rolesService.fetchPageResults(role)); + } - @GetMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message query(@ModelAttribute Roles role,@CurrentUser UserInfo currentUser) { - _logger.debug("-query : {}" , role); - role.setInstId(currentUser.getInstId()); - if (!rolesService.query(role).isEmpty()) { - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - - } - - @GetMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message get(@PathVariable("id") String id,@CurrentUser UserInfo currentUser) { - Roles role=rolesService.get(id); - return new Message<>(role); - } - - @PostMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message insert(@RequestBody Roles role,@CurrentUser UserInfo currentUser) { - _logger.debug("-Add : {}" , role); - role.setCreatedBy(currentUser.getId()); - role.setInstId(currentUser.getInstId()); - role.setId(role.generateId()); - if(StringUtils.isBlank(role.getRoleCode())) { - role.setRoleCode(role.getId()); - } - if (rolesService.insert(role)) { - rolesService.refreshDynamicRoles(role); - systemLog.insert( - ConstsEntryType.ROLE, - role, - ConstsAct.CREATE, - ConstsActResult.SUCCESS, - currentUser); - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } + @GetMapping(value={"/query"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message query(@ModelAttribute Roles role,@CurrentUser UserInfo currentUser) { + _logger.debug("-query : {}" , role); + role.setInstId(currentUser.getInstId()); + if (!rolesService.query(role).isEmpty()) { + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + + } + + @GetMapping(value = { "/get/{id}" }, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message get(@PathVariable("id") String id,@CurrentUser UserInfo currentUser) { + Roles role=rolesService.get(id); + return new Message<>(role); + } + + @PostMapping(value={"/add"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message insert(@RequestBody Roles role,@CurrentUser UserInfo currentUser) { + _logger.debug("-Add : {}" , role); + role.setCreatedBy(currentUser.getId()); + role.setInstId(currentUser.getInstId()); + role.setId(role.generateId()); + if(StringUtils.isBlank(role.getRoleCode())) { + role.setRoleCode(role.getId()); + } + if (rolesService.insert(role)) { + rolesService.refreshDynamicRoles(role); + systemLog.insert( + ConstsEntryType.ROLE, + role, + ConstsAct.CREATE, + ConstsActResult.SUCCESS, + currentUser); + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } - @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message update(@RequestBody Roles role,@CurrentUser UserInfo currentUser) { - _logger.debug("-update group : {}" , role); - if(role.getId().equalsIgnoreCase("ROLE_ALL_USER")) { - role.setDefaultAllUser(); - } - role.setModifiedBy(currentUser.getId()); - role.setInstId(currentUser.getInstId()); - if (rolesService.update(role)) { - rolesService.refreshDynamicRoles(role); - systemLog.insert( - ConstsEntryType.ROLE, - role, - ConstsAct.UPDATE, - ConstsActResult.SUCCESS, - currentUser); - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } + @PutMapping(value={"/update"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message update(@RequestBody Roles role,@CurrentUser UserInfo currentUser) { + _logger.debug("-update group : {}" , role); + if(role.getId().equalsIgnoreCase("ROLE_ALL_USER")) { + role.setDefaultAllUser(); + } + role.setModifiedBy(currentUser.getId()); + role.setInstId(currentUser.getInstId()); + if (rolesService.update(role)) { + rolesService.refreshDynamicRoles(role); + systemLog.insert( + ConstsEntryType.ROLE, + role, + ConstsAct.UPDATE, + ConstsActResult.SUCCESS, + currentUser); + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } - @DeleteMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) - public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { - _logger.debug("-delete ids : {}" , ids); - ids.removeAll(Arrays.asList("ROLE_ALL_USER","ROLE_ADMINISTRATORS","-1")); - if (rolesService.deleteBatch(ids)) { - systemLog.insert( - ConstsEntryType.ROLE, - ids, - ConstsAct.DELETE, - ConstsActResult.SUCCESS, - currentUser); - return new Message<>(Message.SUCCESS); - } else { - return new Message<>(Message.FAIL); - } - } + @DeleteMapping(value={"/delete"}, produces = {MediaType.APPLICATION_JSON_VALUE}) + public Message delete(@RequestParam("ids") List ids,@CurrentUser UserInfo currentUser) { + _logger.debug("-delete ids : {}" , ids); + ids.removeAll(Arrays.asList("ROLE_ALL_USER","ROLE_ADMINISTRATORS","-1")); + if (rolesService.deleteBatch(ids)) { + systemLog.insert( + ConstsEntryType.ROLE, + ids, + ConstsAct.DELETE, + ConstsActResult.SUCCESS, + currentUser); + return new Message<>(Message.SUCCESS); + } else { + return new Message<>(Message.FAIL); + } + } } diff --git a/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/MaxKeyApiApplication.java b/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/MaxKeyApiApplication.java index b1255115c..ac04f7097 100644 --- a/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/MaxKeyApiApplication.java +++ b/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/MaxKeyApiApplication.java @@ -36,24 +36,24 @@ import org.springframework.context.ConfigurableApplicationContext; @EnableDiscoveryClient @MapperScan("org.dromara.maxkey.persistence.mapper,") public class MaxKeyApiApplication extends SpringBootServletInitializer { - static final Logger _logger = LoggerFactory.getLogger(MaxKeyApiApplication.class); + static final Logger _logger = LoggerFactory.getLogger(MaxKeyApiApplication.class); - public static void main(String[] args) { - _logger.info("Start MaxKey Api Application ..."); - ProductEnvironment.listEnvVars(); - - ConfigurableApplicationContext applicationContext = SpringApplication.run(MaxKeyApiApplication.class, args); - new InitializeContext(applicationContext).init(); - - _logger.info("MaxKey Api at {}" , new DateTime()); - _logger.info("MaxKey Api Server Port {}" , WebContext.getServerPort()); - _logger.info("MaxKey Api started."); - - } + public static void main(String[] args) { + _logger.info("Start MaxKey Api Application ..."); + ProductEnvironment.listEnvVars(); + + ConfigurableApplicationContext applicationContext = SpringApplication.run(MaxKeyApiApplication.class, args); + new InitializeContext(applicationContext).init(); + + _logger.info("MaxKey Api at {}" , new DateTime()); + _logger.info("MaxKey Api Server Port {}" , WebContext.getServerPort()); + _logger.info("MaxKey Api started."); + + } - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { - return application.sources(MaxKeyApiApplication.class); - } + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(MaxKeyApiApplication.class); + } } diff --git a/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyOpenApiConfig.java b/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyOpenApiConfig.java index 2c71d340b..76064d762 100644 --- a/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyOpenApiConfig.java +++ b/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyOpenApiConfig.java @@ -48,15 +48,15 @@ public class MaxKeyOpenApiConfig{ UserInfoService userInfoService, IpLocationParser ipLocationParser, JdbcTemplate jdbcTemplate) { - + JdbcAuthenticationRealm authenticationRealm = new JdbcAuthenticationRealm( - passwordEncoder, - passwordPolicyValidatorService, - loginService, - historyLoginService, - userInfoService, - ipLocationParser, - jdbcTemplate); + passwordEncoder, + passwordPolicyValidatorService, + loginService, + historyLoginService, + userInfoService, + ipLocationParser, + jdbcTemplate); logger.debug("JdbcAuthenticationRealm inited."); return authenticationRealm; @@ -64,8 +64,8 @@ public class MaxKeyOpenApiConfig{ @Bean AbstractOtpAuthn timeBasedOtpAuthn() { - AbstractOtpAuthn tfaOtpAuthn = new TimeBasedOtpAuthn(); - logger.debug("TimeBasedOtpAuthn inited."); + AbstractOtpAuthn tfaOtpAuthn = new TimeBasedOtpAuthn(); + logger.debug("TimeBasedOtpAuthn inited."); return tfaOtpAuthn; } } diff --git a/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyOpenApiMvcConfig.java b/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyOpenApiMvcConfig.java index ddaa42c87..dc0b80c45 100644 --- a/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyOpenApiMvcConfig.java +++ b/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/autoconfigure/MaxKeyOpenApiMvcConfig.java @@ -35,7 +35,7 @@ public class MaxKeyOpenApiMvcConfig implements WebMvcConfigurer { private static final Logger logger = LoggerFactory.getLogger(MaxKeyOpenApiMvcConfig.class); @Autowired - ApplicationConfig applicationConfig; + ApplicationConfig applicationConfig; @Autowired AbstractAuthenticationProvider authenticationProvider ; @@ -96,7 +96,7 @@ public class MaxKeyOpenApiMvcConfig implements WebMvcConfigurer { .addPathPatterns("/api/idm/**") .addPathPatterns("/api/idm/scim/**") ; - + logger.debug("add Rest Api Permission Adapter"); } diff --git a/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/web/api/endpoint/RestTimeBasedOtpController.java b/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/web/api/endpoint/RestTimeBasedOtpController.java index 2ee2927de..a17eadb9d 100644 --- a/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/web/api/endpoint/RestTimeBasedOtpController.java +++ b/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/web/api/endpoint/RestTimeBasedOtpController.java @@ -34,7 +34,7 @@ import io.swagger.v3.oas.annotations.tags.Tag; @RequestMapping(value={"/api/otp"}) public class RestTimeBasedOtpController { - @Autowired + @Autowired AbstractOtpAuthn timeBasedOtpAuthn; @Autowired @@ -44,15 +44,15 @@ public class RestTimeBasedOtpController { @ResponseBody @RequestMapping(value = "/timebased/validate", method = RequestMethod.GET) public boolean getUser(@RequestParam String username, - @RequestParam String token) { - - UserInfo validUserInfo = userInfoService.findByUsername(username); - if(validUserInfo != null) { - if(timeBasedOtpAuthn.validate(validUserInfo, token)) { - return true; - } - } - + @RequestParam String token) { + + UserInfo validUserInfo = userInfoService.findByUsername(username); + if(validUserInfo != null) { + if(timeBasedOtpAuthn.validate(validUserInfo, token)) { + return true; + } + } + return false; } diff --git a/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/web/interceptor/RestApiPermissionAdapter.java b/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/web/interceptor/RestApiPermissionAdapter.java index 5691a58db..922d906e1 100644 --- a/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/web/interceptor/RestApiPermissionAdapter.java +++ b/maxkey-webs/maxkey-web-openapi/src/main/java/org/dromara/maxkey/web/interceptor/RestApiPermissionAdapter.java @@ -48,79 +48,79 @@ import jakarta.servlet.http.HttpServletResponse; */ @Component public class RestApiPermissionAdapter implements AsyncHandlerInterceptor { - private static final Logger logger = LoggerFactory.getLogger(RestApiPermissionAdapter.class); + private static final Logger logger = LoggerFactory.getLogger(RestApiPermissionAdapter.class); - static final String PASSWORD = "password"; - - @Autowired - DefaultTokenServices oauth20TokenServices; + static final String PASSWORD = "password"; + + @Autowired + DefaultTokenServices oauth20TokenServices; - @Autowired - AppsService appsService; - - /* - * 请求前处理 - * (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("Rest API Permission Adapter pre handle"); - AuthorizationHeader headerCredential = AuthorizationHeaderUtils.resolve(request); - - //判断应用的AppId和Secret - if(headerCredential != null){ - UsernamePasswordAuthenticationToken authenticationToken = null; - if(headerCredential.isBasic()) { - if(StringUtils.isNotBlank(headerCredential.getUsername())&& - StringUtils.isNotBlank(headerCredential.getCredential()) - ) { - String appId = headerCredential.getUsername(); - String credential = headerCredential.getCredential(); - Apps app = appsService.get(appId, true); - if(app != null ) { - if( PasswordReciprocal.getInstance().matches(credential, app.getSecret())) { - ArrayList grantedAuthoritys = new ArrayList<>(); - grantedAuthoritys.add(new SimpleGrantedAuthority("ROLE_USER")); - User user = new User(appId, PASSWORD, grantedAuthoritys); - authenticationToken= new UsernamePasswordAuthenticationToken(user, PASSWORD, grantedAuthoritys); - }else { - logger.trace("app {} secret not matches . ",appId); - } - }else { - logger.trace("app {} not exists . ",appId); - } - } - }else if(StringUtils.isNotBlank(headerCredential.getCredential())){ - logger.trace("Authentication bearer {}" , headerCredential.getCredential()); - OAuth2Authentication oauth2Authentication = - oauth20TokenServices.loadAuthentication(headerCredential.getCredential()); - - if(oauth2Authentication != null) { - logger.trace("Authentication token {}" , oauth2Authentication.getPrincipal().toString()); - authenticationToken= new UsernamePasswordAuthenticationToken( - new User( - oauth2Authentication.getPrincipal().toString(), - "CLIENT_SECRET", - oauth2Authentication.getAuthorities()), - "PASSWORD", - oauth2Authentication.getAuthorities() - ); - }else { - logger.trace("Authentication token is null "); - } - } - - if(authenticationToken !=null && authenticationToken.isAuthenticated()) { - AuthorizationUtils.setAuthentication(authenticationToken); - return true; - } - } - - logger.trace("No Authentication ... forward to /login"); + @Autowired + AppsService appsService; + + /* + * 请求前处理 + * (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("Rest API Permission Adapter pre handle"); + AuthorizationHeader headerCredential = AuthorizationHeaderUtils.resolve(request); + + //判断应用的AppId和Secret + if(headerCredential != null){ + UsernamePasswordAuthenticationToken authenticationToken = null; + if(headerCredential.isBasic()) { + if(StringUtils.isNotBlank(headerCredential.getUsername())&& + StringUtils.isNotBlank(headerCredential.getCredential()) + ) { + String appId = headerCredential.getUsername(); + String credential = headerCredential.getCredential(); + Apps app = appsService.get(appId, true); + if(app != null ) { + if( PasswordReciprocal.getInstance().matches(credential, app.getSecret())) { + ArrayList grantedAuthoritys = new ArrayList<>(); + grantedAuthoritys.add(new SimpleGrantedAuthority("ROLE_USER")); + User user = new User(appId, PASSWORD, grantedAuthoritys); + authenticationToken= new UsernamePasswordAuthenticationToken(user, PASSWORD, grantedAuthoritys); + }else { + logger.trace("app {} secret not matches . ",appId); + } + }else { + logger.trace("app {} not exists . ",appId); + } + } + }else if(StringUtils.isNotBlank(headerCredential.getCredential())){ + logger.trace("Authentication bearer {}" , headerCredential.getCredential()); + OAuth2Authentication oauth2Authentication = + oauth20TokenServices.loadAuthentication(headerCredential.getCredential()); + + if(oauth2Authentication != null) { + logger.trace("Authentication token {}" , oauth2Authentication.getPrincipal().toString()); + authenticationToken= new UsernamePasswordAuthenticationToken( + new User( + oauth2Authentication.getPrincipal().toString(), + "CLIENT_SECRET", + oauth2Authentication.getAuthorities()), + "PASSWORD", + oauth2Authentication.getAuthorities() + ); + }else { + logger.trace("Authentication token is null "); + } + } + + if(authenticationToken !=null && authenticationToken.isAuthenticated()) { + AuthorizationUtils.setAuthentication(authenticationToken); + return true; + } + } + + logger.trace("No Authentication ... forward to /login"); RequestDispatcher dispatcher = request.getRequestDispatcher("/login"); dispatcher.forward(request, response); - return false; - } + return false; + } } diff --git a/summer-ospp/2023/pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/endpoint/PigTokenEndpoint.java b/summer-ospp/2023/pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/endpoint/PigTokenEndpoint.java index 6ff908ea6..4d204e51b 100644 --- a/summer-ospp/2023/pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/endpoint/PigTokenEndpoint.java +++ b/summer-ospp/2023/pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/endpoint/PigTokenEndpoint.java @@ -84,209 +84,209 @@ import java.util.stream.Collectors; @RequestMapping("/token") public class PigTokenEndpoint { - private final HttpMessageConverter accessTokenHttpResponseConverter = new OAuth2AccessTokenResponseHttpMessageConverter(); + private final HttpMessageConverter accessTokenHttpResponseConverter = new OAuth2AccessTokenResponseHttpMessageConverter(); - private final AuthenticationFailureHandler authenticationFailureHandler = new PigAuthenticationFailureEventHandler(); + private final AuthenticationFailureHandler authenticationFailureHandler = new PigAuthenticationFailureEventHandler(); - private final OAuth2AuthorizationService authorizationService; + private final OAuth2AuthorizationService authorizationService; - private final RemoteClientDetailsService clientDetailsService; + private final RemoteClientDetailsService clientDetailsService; - private final RedisTemplate redisTemplate; + private final RedisTemplate redisTemplate; - private final CacheManager cacheManager; + private final CacheManager cacheManager; - @Resource - private RedisUtils redisUtils; + @Resource + private RedisUtils redisUtils; - @Resource - private TokenManager tokenManager; + @Resource + private TokenManager tokenManager; - private final static String SPRING_SESSION_PREFIX = "spring:session:sessions:%s"; - private final static String PIG_TOKEN_PREFIX = "pig:token:%s:%s"; - private final static String ASSCEE_TOKEN = "access_token"; - private final static String REFRESH_TOKEN = "refresh_token"; + private final static String SPRING_SESSION_PREFIX = "spring:session:sessions:%s"; + private final static String PIG_TOKEN_PREFIX = "pig:token:%s:%s"; + private final static String ASSCEE_TOKEN = "access_token"; + private final static String REFRESH_TOKEN = "refresh_token"; - private long tokenExpiration = 24 * 60 * 60 * 1000; + private long tokenExpiration = 24 * 60 * 60 * 1000; - /** - * 认证页面 - * - * @param modelAndView - * @param error 表单登录失败处理回调的错误信息 - * @return ModelAndView - */ - @GetMapping("/login") - public ModelAndView require(ModelAndView modelAndView, @RequestParam(required = false) String error) { - modelAndView.setViewName("ftl/login"); - modelAndView.addObject("error", error); - return modelAndView; - } + /** + * 认证页面 + * + * @param modelAndView + * @param error 表单登录失败处理回调的错误信息 + * @return ModelAndView + */ + @GetMapping("/login") + public ModelAndView require(ModelAndView modelAndView, @RequestParam(required = false) String error) { + modelAndView.setViewName("ftl/login"); + modelAndView.addObject("error", error); + return modelAndView; + } - @GetMapping("/confirm_access") - public ModelAndView confirm(Principal principal, ModelAndView modelAndView, - @RequestParam(OAuth2ParameterNames.CLIENT_ID) String clientId, - @RequestParam(OAuth2ParameterNames.SCOPE) String scope, - @RequestParam(OAuth2ParameterNames.STATE) String state) { - SysOauthClientDetails clientDetails = RetOps.of(clientDetailsService.getClientDetailsById(clientId)) - .getData() - .orElseThrow(() -> new OAuthClientException("clientId 不合法")); + @GetMapping("/confirm_access") + public ModelAndView confirm(Principal principal, ModelAndView modelAndView, + @RequestParam(OAuth2ParameterNames.CLIENT_ID) String clientId, + @RequestParam(OAuth2ParameterNames.SCOPE) String scope, + @RequestParam(OAuth2ParameterNames.STATE) String state) { + SysOauthClientDetails clientDetails = RetOps.of(clientDetailsService.getClientDetailsById(clientId)) + .getData() + .orElseThrow(() -> new OAuthClientException("clientId 不合法")); - Set authorizedScopes = StringUtils.commaDelimitedListToSet(clientDetails.getScope()); - modelAndView.addObject("clientId", clientId); - modelAndView.addObject("state", state); - modelAndView.addObject("scopeList", authorizedScopes); - modelAndView.addObject("principalName", principal.getName()); - modelAndView.setViewName("ftl/confirm"); - return modelAndView; - } + Set authorizedScopes = StringUtils.commaDelimitedListToSet(clientDetails.getScope()); + modelAndView.addObject("clientId", clientId); + modelAndView.addObject("state", state); + modelAndView.addObject("scopeList", authorizedScopes); + modelAndView.addObject("principalName", principal.getName()); + modelAndView.setViewName("ftl/confirm"); + return modelAndView; + } - /** - * 退出并删除token - * - * @param authHeader Authorization - */ - @DeleteMapping("/logout") - public R logout(HttpServletRequest request, @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) { - if (StrUtil.isBlank(authHeader)) { - return R.ok(); - } - String sessonId = request.getSession().getId(); - if (StrUtil.isBlank(sessonId)) { - return R.ok(); - } - boolean isSuccess = redisUtils.deleteKey(generateSessionId(sessonId)); - if (isSuccess) { - return R.ok(); - } else { - return R.failed(); - } + /** + * 退出并删除token + * + * @param authHeader Authorization + */ + @DeleteMapping("/logout") + public R logout(HttpServletRequest request, @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) { + if (StrUtil.isBlank(authHeader)) { + return R.ok(); + } + String sessonId = request.getSession().getId(); + if (StrUtil.isBlank(sessonId)) { + return R.ok(); + } + boolean isSuccess = redisUtils.deleteKey(generateSessionId(sessonId)); + if (isSuccess) { + return R.ok(); + } else { + return R.failed(); + } - } + } - /** - * 校验token - * - * @param token 令牌 - */ - @SneakyThrows - @GetMapping("/check_token") - public void checkToken(String token, HttpServletResponse response, HttpServletRequest request) { + /** + * 校验token + * + * @param token 令牌 + */ + @SneakyThrows + @GetMapping("/check_token") + public void checkToken(String token, HttpServletResponse response, HttpServletRequest request) { - ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); + ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); - if (StrUtil.isBlank(token)) { - httpResponse.setStatusCode(HttpStatus.UNAUTHORIZED); - this.authenticationFailureHandler.onAuthenticationFailure(request, response, - new InvalidBearerTokenException(OAuth2ErrorCodesExpand.TOKEN_MISSING)); - return; - } - OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); + if (StrUtil.isBlank(token)) { + httpResponse.setStatusCode(HttpStatus.UNAUTHORIZED); + this.authenticationFailureHandler.onAuthenticationFailure(request, response, + new InvalidBearerTokenException(OAuth2ErrorCodesExpand.TOKEN_MISSING)); + return; + } + OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); - // 如果令牌不存在 返回401 - if (authorization == null || authorization.getAccessToken() == null) { - this.authenticationFailureHandler.onAuthenticationFailure(request, response, - new InvalidBearerTokenException(OAuth2ErrorCodesExpand.INVALID_BEARER_TOKEN)); - return; - } + // 如果令牌不存在 返回401 + if (authorization == null || authorization.getAccessToken() == null) { + this.authenticationFailureHandler.onAuthenticationFailure(request, response, + new InvalidBearerTokenException(OAuth2ErrorCodesExpand.INVALID_BEARER_TOKEN)); + return; + } - Map claims = authorization.getAccessToken().getClaims(); - OAuth2AccessTokenResponse sendAccessTokenResponse = OAuth2EndpointUtils.sendAccessTokenResponse(authorization, - claims); - this.accessTokenHttpResponseConverter.write(sendAccessTokenResponse, MediaType.APPLICATION_JSON, httpResponse); - } + Map claims = authorization.getAccessToken().getClaims(); + OAuth2AccessTokenResponse sendAccessTokenResponse = OAuth2EndpointUtils.sendAccessTokenResponse(authorization, + claims); + this.accessTokenHttpResponseConverter.write(sendAccessTokenResponse, MediaType.APPLICATION_JSON, httpResponse); + } - /** - * 令牌管理调用 - * - * @param token token - */ - @Inner - @DeleteMapping("/{token}") - public R removeToken(@PathVariable("token") String token) { - OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); - if (authorization == null) { - return R.ok(); - } + /** + * 令牌管理调用 + * + * @param token token + */ + @Inner + @DeleteMapping("/{token}") + public R removeToken(@PathVariable("token") String token) { + OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); + if (authorization == null) { + return R.ok(); + } - OAuth2Authorization.Token accessToken = authorization.getAccessToken(); - if (accessToken == null || StrUtil.isBlank(accessToken.getToken().getTokenValue())) { - return R.ok(); - } - // 清空用户信息 - cacheManager.getCache(CacheConstants.USER_DETAILS).evict(authorization.getPrincipalName()); - // 清空access token - authorizationService.remove(authorization); - // 处理自定义退出事件,保存相关日志 - SpringContextHolder.publishEvent(new LogoutSuccessEvent(new PreAuthenticatedAuthenticationToken( - authorization.getPrincipalName(), authorization.getRegisteredClientId()))); - return R.ok(); - } + OAuth2Authorization.Token accessToken = authorization.getAccessToken(); + if (accessToken == null || StrUtil.isBlank(accessToken.getToken().getTokenValue())) { + return R.ok(); + } + // 清空用户信息 + cacheManager.getCache(CacheConstants.USER_DETAILS).evict(authorization.getPrincipalName()); + // 清空access token + authorizationService.remove(authorization); + // 处理自定义退出事件,保存相关日志 + SpringContextHolder.publishEvent(new LogoutSuccessEvent(new PreAuthenticatedAuthenticationToken( + authorization.getPrincipalName(), authorization.getRegisteredClientId()))); + return R.ok(); + } - /** - * 查询token - * - * @param params 分页参数 - * @return - */ - @Inner - @PostMapping("/page") - public R tokenList(@RequestBody Map params) { - // 根据分页参数获取对应数据 - String key = String.format("%s::*", CacheConstants.PROJECT_OAUTH_ACCESS); - int current = MapUtil.getInt(params, CommonConstants.CURRENT); - int size = MapUtil.getInt(params, CommonConstants.SIZE); - Set keys = redisTemplate.keys(key); - List pages = keys.stream().skip((current - 1) * size).limit(size).collect(Collectors.toList()); - Page result = new Page(current, size); + /** + * 查询token + * + * @param params 分页参数 + * @return + */ + @Inner + @PostMapping("/page") + public R tokenList(@RequestBody Map params) { + // 根据分页参数获取对应数据 + String key = String.format("%s::*", CacheConstants.PROJECT_OAUTH_ACCESS); + int current = MapUtil.getInt(params, CommonConstants.CURRENT); + int size = MapUtil.getInt(params, CommonConstants.SIZE); + Set keys = redisTemplate.keys(key); + List pages = keys.stream().skip((current - 1) * size).limit(size).collect(Collectors.toList()); + Page result = new Page(current, size); - List tokenVoList = redisTemplate.opsForValue().multiGet(pages).stream().map(obj -> { - OAuth2Authorization authorization = (OAuth2Authorization) obj; - TokenVo tokenVo = new TokenVo(); - tokenVo.setClientId(authorization.getRegisteredClientId()); - tokenVo.setId(authorization.getId()); - tokenVo.setUsername(authorization.getPrincipalName()); - OAuth2Authorization.Token accessToken = authorization.getAccessToken(); - tokenVo.setAccessToken(accessToken.getToken().getTokenValue()); + List tokenVoList = redisTemplate.opsForValue().multiGet(pages).stream().map(obj -> { + OAuth2Authorization authorization = (OAuth2Authorization) obj; + TokenVo tokenVo = new TokenVo(); + tokenVo.setClientId(authorization.getRegisteredClientId()); + tokenVo.setId(authorization.getId()); + tokenVo.setUsername(authorization.getPrincipalName()); + OAuth2Authorization.Token accessToken = authorization.getAccessToken(); + tokenVo.setAccessToken(accessToken.getToken().getTokenValue()); - String expiresAt = TemporalAccessorUtil.format(accessToken.getToken().getExpiresAt(), - DatePattern.NORM_DATETIME_PATTERN); - tokenVo.setExpiresAt(expiresAt); + String expiresAt = TemporalAccessorUtil.format(accessToken.getToken().getExpiresAt(), + DatePattern.NORM_DATETIME_PATTERN); + tokenVo.setExpiresAt(expiresAt); - String issuedAt = TemporalAccessorUtil.format(accessToken.getToken().getIssuedAt(), - DatePattern.NORM_DATETIME_PATTERN); - tokenVo.setIssuedAt(issuedAt); - return tokenVo; - }).collect(Collectors.toList()); - result.setRecords(tokenVoList); - result.setTotal(keys.size()); - return R.ok(result); - } + String issuedAt = TemporalAccessorUtil.format(accessToken.getToken().getIssuedAt(), + DatePattern.NORM_DATETIME_PATTERN); + tokenVo.setIssuedAt(issuedAt); + return tokenVo; + }).collect(Collectors.toList()); + result.setRecords(tokenVoList); + result.setTotal(keys.size()); + return R.ok(result); + } - @GetMapping("sso_login_get_token") - public R> getToken(String ticket, String service) { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - PigUser pigUser = (PigUser) authentication.getPrincipal(); - Map ans = new HashMap<>(); - String access_token = tokenManager.createToken(ASSCEE_TOKEN, pigUser.getName(), pigUser.getId().toString()); - String refresh_token = tokenManager.createToken(REFRESH_TOKEN, pigUser.getName(), pigUser.getId().toString()); - redisUtils.setValue(generateTokenKey(ASSCEE_TOKEN, pigUser.getId().toString()), access_token, tokenExpiration); - redisUtils.setValue(generateTokenKey(REFRESH_TOKEN, pigUser.getId().toString()), refresh_token, tokenExpiration); - ans.put("access_token", access_token); - ans.put("refresh_token", refresh_token); - return R.ok(ans); - } + @GetMapping("sso_login_get_token") + public R> getToken(String ticket, String service) { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + PigUser pigUser = (PigUser) authentication.getPrincipal(); + Map ans = new HashMap<>(); + String access_token = tokenManager.createToken(ASSCEE_TOKEN, pigUser.getName(), pigUser.getId().toString()); + String refresh_token = tokenManager.createToken(REFRESH_TOKEN, pigUser.getName(), pigUser.getId().toString()); + redisUtils.setValue(generateTokenKey(ASSCEE_TOKEN, pigUser.getId().toString()), access_token, tokenExpiration); + redisUtils.setValue(generateTokenKey(REFRESH_TOKEN, pigUser.getId().toString()), refresh_token, tokenExpiration); + ans.put("access_token", access_token); + ans.put("refresh_token", refresh_token); + return R.ok(ans); + } - private String generateSessionId(String sessionId) { - return String.format(SPRING_SESSION_PREFIX, sessionId); - } + private String generateSessionId(String sessionId) { + return String.format(SPRING_SESSION_PREFIX, sessionId); + } - private String generateTokenKey(String type, String userId) { - return String.format(PIG_TOKEN_PREFIX, type, userId); - } + private String generateTokenKey(String type, String userId) { + return String.format(PIG_TOKEN_PREFIX, type, userId); + } } diff --git a/summer-ospp/2023/pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/utils/RedisUtils.java b/summer-ospp/2023/pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/utils/RedisUtils.java index ad86cc6e4..8b32dc5c7 100644 --- a/summer-ospp/2023/pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/utils/RedisUtils.java +++ b/summer-ospp/2023/pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/utils/RedisUtils.java @@ -8,16 +8,16 @@ import javax.annotation.Resource; @Component public class RedisUtils { - @Resource - private RedisTemplate redisTemplate; + @Resource + private RedisTemplate redisTemplate; - public boolean deleteKey(String key) { - return redisTemplate.delete(key); - } + public boolean deleteKey(String key) { + return redisTemplate.delete(key); + } - public void setValue(String key, Object object, Long expire) { - redisTemplate.opsForValue().set(key, object, expire); - } + public void setValue(String key, Object object, Long expire) { + redisTemplate.opsForValue().set(key, object, expire); + } } diff --git a/summer-ospp/2023/pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/utils/TokenManager.java b/summer-ospp/2023/pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/utils/TokenManager.java index 6a2c1ada1..ce0ceb14c 100644 --- a/summer-ospp/2023/pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/utils/TokenManager.java +++ b/summer-ospp/2023/pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/utils/TokenManager.java @@ -9,28 +9,28 @@ import java.util.Date; @Component public class TokenManager { - private long tokenExpiration = 24 * 60 * 60 * 1000; - private final static String TOKEN_SIGN_KEY = "MAKKEY_PIG"; + private long tokenExpiration = 24 * 60 * 60 * 1000; + private final static String TOKEN_SIGN_KEY = "MAKKEY_PIG"; - public String createToken(String subject, String username, String id) { - String token = Jwts.builder() - .setSubject(subject) - .claim("nickname", username) - .claim("id", id) - .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)) - .signWith(SignatureAlgorithm.HS512, TOKEN_SIGN_KEY) - .compressWith(CompressionCodecs.GZIP).compact(); - return token; - } + public String createToken(String subject, String username, String id) { + String token = Jwts.builder() + .setSubject(subject) + .claim("nickname", username) + .claim("id", id) + .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)) + .signWith(SignatureAlgorithm.HS512, TOKEN_SIGN_KEY) + .compressWith(CompressionCodecs.GZIP).compact(); + return token; + } - public String getUserFromToken(String token) { - String user = Jwts.parser().setSigningKey(TOKEN_SIGN_KEY).parseClaimsJws(token).getBody().getSubject(); - return user; - } + public String getUserFromToken(String token) { + String user = Jwts.parser().setSigningKey(TOKEN_SIGN_KEY).parseClaimsJws(token).getBody().getSubject(); + return user; + } - public void removeToken(String token) { - //jwttoken无需删除,客户端扔掉即可。 - } + public void removeToken(String token) { + //jwttoken无需删除,客户端扔掉即可。 + } } diff --git a/summer-ospp/2023/pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/config/CasProperties.java b/summer-ospp/2023/pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/config/CasProperties.java index 1eda0a6f0..a2c5fcb27 100644 --- a/summer-ospp/2023/pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/config/CasProperties.java +++ b/summer-ospp/2023/pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/config/CasProperties.java @@ -8,52 +8,52 @@ import org.springframework.stereotype.Component; @Component public class CasProperties { - /** - * 秘钥 - */ - @Value("${cas.key}") - private String casKey; + /** + * 秘钥 + */ + @Value("${cas.key}") + private String casKey; - /** - * cas服务端地址 - */ - @Value("${cas.server.host.url}") - private String casServerUrl; + /** + * cas服务端地址 + */ + @Value("${cas.server.host.url}") + private String casServerUrl; - /** - * cas服务端地址 - */ - @Value("${cas.server.host.grant_url}") - private String casGrantingUrl; + /** + * cas服务端地址 + */ + @Value("${cas.server.host.grant_url}") + private String casGrantingUrl; - /** - * cas服务端登录地址 - */ - @Value("${cas.server.host.login_url}") - private String casServerLoginUrl; + /** + * cas服务端登录地址 + */ + @Value("${cas.server.host.login_url}") + private String casServerLoginUrl; - /** - * cas服务端登出地址 并回跳到制定页面 - */ - @Value("${cas.server.host.logout_url}") - private String casServerLogoutUrl; + /** + * cas服务端登出地址 并回跳到制定页面 + */ + @Value("${cas.server.host.logout_url}") + private String casServerLogoutUrl; - /** - * cas客户端地址 - */ - @Value("${cas.service.host.url}") - private String casServiceUrl; + /** + * cas客户端地址 + */ + @Value("${cas.service.host.url}") + private String casServiceUrl; - /** - * cas客户端地址登录地址 - */ - @Value("${cas.service.host.login_url}") - private String casServiceLoginUrl; + /** + * cas客户端地址登录地址 + */ + @Value("${cas.service.host.login_url}") + private String casServiceLoginUrl; - /** - * cas客户端地址登出地址 - */ - @Value("${cas.service.host.logout_url}") - private String casServiceLogoutUrl; + /** + * cas客户端地址登出地址 + */ + @Value("${cas.service.host.logout_url}") + private String casServiceLogoutUrl; } diff --git a/summer-ospp/2023/pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/config/SecurityConfig.java b/summer-ospp/2023/pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/config/SecurityConfig.java index 8ed246682..b610cdc9a 100644 --- a/summer-ospp/2023/pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/config/SecurityConfig.java +++ b/summer-ospp/2023/pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/config/SecurityConfig.java @@ -32,125 +32,125 @@ import org.springframework.security.web.authentication.logout.SecurityContextLog @RequiredArgsConstructor public class SecurityConfig extends WebSecurityConfigurerAdapter { - @Autowired - private CasProperties casProperties; + @Autowired + private CasProperties casProperties; - @Autowired - private AuthenticationUserDetailsService casUserDetailService; + @Autowired + private AuthenticationUserDetailsService casUserDetailService; - private final PermitAllUrlProperties permitAllUrl; + private final PermitAllUrlProperties permitAllUrl; - /** - * 定义认证用户信息获取来源,密码校验规则等 - */ - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - super.configure(auth); - auth.authenticationProvider(casAuthenticationProvider()); - } + /** + * 定义认证用户信息获取来源,密码校验规则等 + */ + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + super.configure(auth); + auth.authenticationProvider(casAuthenticationProvider()); + } - /** - * 定义安全策略 - */ - @Override - protected void configure(HttpSecurity http) throws Exception { + /** + * 定义安全策略 + */ + @Override + protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests()// 配置安全策略 - .antMatchers(ArrayUtil.toArray(permitAllUrl.getUrls(), String.class)).permitAll() - .anyRequest().authenticated()// 其余的所有请求都需要验证 - .and().logout().permitAll()// 定义logout不需要验证 - .and().formLogin();// 使用form表单登录 + http.authorizeRequests()// 配置安全策略 + .antMatchers(ArrayUtil.toArray(permitAllUrl.getUrls(), String.class)).permitAll() + .anyRequest().authenticated()// 其余的所有请求都需要验证 + .and().logout().permitAll()// 定义logout不需要验证 + .and().formLogin();// 使用form表单登录 - http.exceptionHandling() - .authenticationEntryPoint(casAuthenticationEntryPoint()) - .and() - .addFilter(casAuthenticationFilter()) - .addFilterBefore(casLogoutFilter(), LogoutFilter.class) - .addFilterBefore(singleSignOutFilter(), CasAuthenticationFilter.class); - // 取消跨站请求伪造防护 - http.csrf().disable(); + http.exceptionHandling() + .authenticationEntryPoint(casAuthenticationEntryPoint()) + .and() + .addFilter(casAuthenticationFilter()) + .addFilterBefore(casLogoutFilter(), LogoutFilter.class) + .addFilterBefore(singleSignOutFilter(), CasAuthenticationFilter.class); + // 取消跨站请求伪造防护 + http.csrf().disable(); // // 防止iframe 造成跨域 - http.headers().frameOptions().disable(); - // http.csrf().disable(); //禁用CSRF - } + http.headers().frameOptions().disable(); + // http.csrf().disable(); //禁用CSRF + } - /** - * 认证的入口 - */ - @Bean - public CasAuthenticationEntryPoint casAuthenticationEntryPoint() { - CasAuthenticationEntryPoint casAuthenticationEntryPoint = new CasAuthenticationEntryPoint(); - casAuthenticationEntryPoint.setLoginUrl(casProperties.getCasServerLoginUrl()); - casAuthenticationEntryPoint.setServiceProperties(serviceProperties()); - return casAuthenticationEntryPoint; - } + /** + * 认证的入口 + */ + @Bean + public CasAuthenticationEntryPoint casAuthenticationEntryPoint() { + CasAuthenticationEntryPoint casAuthenticationEntryPoint = new CasAuthenticationEntryPoint(); + casAuthenticationEntryPoint.setLoginUrl(casProperties.getCasServerLoginUrl()); + casAuthenticationEntryPoint.setServiceProperties(serviceProperties()); + return casAuthenticationEntryPoint; + } - /** - * 指定service相关信息 - */ - @Bean - public ServiceProperties serviceProperties() { - ServiceProperties serviceProperties = new ServiceProperties(); - //设置cas客户端登录完整的url - serviceProperties.setService(casProperties.getCasServiceUrl() + casProperties.getCasServiceLoginUrl()); - serviceProperties.setSendRenew(false); - serviceProperties.setAuthenticateAllArtifacts(true); - return serviceProperties; - } + /** + * 指定service相关信息 + */ + @Bean + public ServiceProperties serviceProperties() { + ServiceProperties serviceProperties = new ServiceProperties(); + //设置cas客户端登录完整的url + serviceProperties.setService(casProperties.getCasServiceUrl() + casProperties.getCasServiceLoginUrl()); + serviceProperties.setSendRenew(false); + serviceProperties.setAuthenticateAllArtifacts(true); + return serviceProperties; + } - /** - * CAS认证过滤器 - */ - @Bean - public CasAuthenticationFilter casAuthenticationFilter() throws Exception { - CasAuthenticationFilter casAuthenticationFilter = new CasAuthenticationFilter(); - casAuthenticationFilter.setAuthenticationManager(authenticationManager()); - casAuthenticationFilter.setFilterProcessesUrl(casProperties.getCasServiceUrl() + casProperties.getCasServiceLoginUrl()); - casAuthenticationFilter.setServiceProperties(serviceProperties()); - return casAuthenticationFilter; - } + /** + * CAS认证过滤器 + */ + @Bean + public CasAuthenticationFilter casAuthenticationFilter() throws Exception { + CasAuthenticationFilter casAuthenticationFilter = new CasAuthenticationFilter(); + casAuthenticationFilter.setAuthenticationManager(authenticationManager()); + casAuthenticationFilter.setFilterProcessesUrl(casProperties.getCasServiceUrl() + casProperties.getCasServiceLoginUrl()); + casAuthenticationFilter.setServiceProperties(serviceProperties()); + return casAuthenticationFilter; + } - /** - * cas 认证 Provider - */ - @Bean - public CasAuthenticationProvider casAuthenticationProvider() { - CasAuthenticationProvider casAuthenticationProvider = new CasAuthenticationProvider(); - casAuthenticationProvider.setAuthenticationUserDetailsService(casUserDetailService); - // //这里只是接口类型,实现的接口不一样,都可以的。 - casAuthenticationProvider.setServiceProperties(serviceProperties()); - casAuthenticationProvider.setTicketValidator(cas20ServiceTicketValidator()); - casAuthenticationProvider.setKey("casAuthenticationProviderKey"); - return casAuthenticationProvider; - } + /** + * cas 认证 Provider + */ + @Bean + public CasAuthenticationProvider casAuthenticationProvider() { + CasAuthenticationProvider casAuthenticationProvider = new CasAuthenticationProvider(); + casAuthenticationProvider.setAuthenticationUserDetailsService(casUserDetailService); + // //这里只是接口类型,实现的接口不一样,都可以的。 + casAuthenticationProvider.setServiceProperties(serviceProperties()); + casAuthenticationProvider.setTicketValidator(cas20ServiceTicketValidator()); + casAuthenticationProvider.setKey("casAuthenticationProviderKey"); + return casAuthenticationProvider; + } - @Bean - public Cas20ServiceTicketValidator cas20ServiceTicketValidator() { - return new Cas20ServiceTicketValidator(casProperties.getCasGrantingUrl()); - } + @Bean + public Cas20ServiceTicketValidator cas20ServiceTicketValidator() { + return new Cas20ServiceTicketValidator(casProperties.getCasGrantingUrl()); + } - /** - * 单点登出过滤器 - */ - @Bean - public SingleSignOutFilter singleSignOutFilter() { - SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); - singleSignOutFilter.setLogoutCallbackPath(casProperties.getCasServerUrl()); - singleSignOutFilter.setIgnoreInitConfiguration(true); - return singleSignOutFilter; - } + /** + * 单点登出过滤器 + */ + @Bean + public SingleSignOutFilter singleSignOutFilter() { + SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); + singleSignOutFilter.setLogoutCallbackPath(casProperties.getCasServerUrl()); + singleSignOutFilter.setIgnoreInitConfiguration(true); + return singleSignOutFilter; + } - /** - * 请求单点退出过滤器 - */ - @Bean - public LogoutFilter casLogoutFilter() { - LogoutFilter logoutFilter = new LogoutFilter(casProperties.getCasServerLogoutUrl(), new SecurityContextLogoutHandler()); - logoutFilter.setFilterProcessesUrl(casProperties.getCasServiceLogoutUrl()); - return logoutFilter; - } + /** + * 请求单点退出过滤器 + */ + @Bean + public LogoutFilter casLogoutFilter() { + LogoutFilter logoutFilter = new LogoutFilter(casProperties.getCasServerLogoutUrl(), new SecurityContextLogoutHandler()); + logoutFilter.setFilterProcessesUrl(casProperties.getCasServiceLogoutUrl()); + return logoutFilter; + } } diff --git a/summer-ospp/2023/pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/service/PigUserDetailsServiceImpl.java b/summer-ospp/2023/pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/service/PigUserDetailsServiceImpl.java index 35f8b1b40..929776b7c 100644 --- a/summer-ospp/2023/pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/service/PigUserDetailsServiceImpl.java +++ b/summer-ospp/2023/pig/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/service/PigUserDetailsServiceImpl.java @@ -43,51 +43,51 @@ import java.util.*; @RequiredArgsConstructor public class PigUserDetailsServiceImpl implements PigUserDetailsService, AuthenticationUserDetailsService { - private final RemoteUserService remoteUserService; + private final RemoteUserService remoteUserService; - private final CacheManager cacheManager; + private final CacheManager cacheManager; - /** - * 用户名密码登录 - * - * @param username 用户名 - * @return - */ - @Override - @SneakyThrows - public UserDetails loadUserByUsername(String username) { - Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS); - if (cache != null && cache.get(username) != null) { - return (PigUser) cache.get(username).get(); - } - return getUserDetails(remoteUserService.info(username), username); - } + /** + * 用户名密码登录 + * + * @param username 用户名 + * @return + */ + @Override + @SneakyThrows + public UserDetails loadUserByUsername(String username) { + Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS); + if (cache != null && cache.get(username) != null) { + return (PigUser) cache.get(username).get(); + } + return getUserDetails(remoteUserService.info(username), username); + } - @Override - public int getOrder() { - return Integer.MIN_VALUE; - } + @Override + public int getOrder() { + return Integer.MIN_VALUE; + } - @Override - public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException { - log.info("getCredentials:{}", token.getCredentials()); - String username = token.getName(); - Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS); - if (cache != null && cache.get(username) != null) { - return (PigUser) cache.get(username).get(); - } - R result = remoteUserService.saveIfNotExist(token.getAssertion().getPrincipal().getAttributes()); - return getUserDetails(result, username); - } + @Override + public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException { + log.info("getCredentials:{}", token.getCredentials()); + String username = token.getName(); + Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS); + if (cache != null && cache.get(username) != null) { + return (PigUser) cache.get(username).get(); + } + R result = remoteUserService.saveIfNotExist(token.getAssertion().getPrincipal().getAttributes()); + return getUserDetails(result, username); + } - private UserDetails getUserDetails(R result, String username) { - Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS); - UserDetails userDetails = getUserDetails(result); - if (cache != null) { - cache.put(username, userDetails); - } - return userDetails; - } + private UserDetails getUserDetails(R result, String username) { + Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS); + UserDetails userDetails = getUserDetails(result); + if (cache != null) { + cache.put(username, userDetails); + } + return userDetails; + } } diff --git a/summer-ospp/2023/pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/SysUserController.java b/summer-ospp/2023/pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/SysUserController.java index 670f47896..0c3401f54 100644 --- a/summer-ospp/2023/pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/SysUserController.java +++ b/summer-ospp/2023/pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/SysUserController.java @@ -67,203 +67,203 @@ import java.util.Set; @SecurityRequirement(name = HttpHeaders.AUTHORIZATION) public class SysUserController { - private final SysUserService userService; + private final SysUserService userService; - /** - * 获取当前用户全部信息 - * - * @return 用户信息 - */ - @GetMapping(value = {"/info"}) - public R info() { - String username = SecurityUtils.getUser().getUsername(); - SysUser user = userService.getOne(Wrappers.query().lambda().eq(SysUser::getUsername, username)); - if (user == null) { - return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_QUERY_ERROR)); - } - UserInfo userInfo = userService.getUserInfo(user); - UserInfoVO vo = new UserInfoVO(); - vo.setSysUser(userInfo.getSysUser()); - vo.setRoles(userInfo.getRoles()); - vo.setPermissions(userInfo.getPermissions()); - return R.ok(vo); - } + /** + * 获取当前用户全部信息 + * + * @return 用户信息 + */ + @GetMapping(value = {"/info"}) + public R info() { + String username = SecurityUtils.getUser().getUsername(); + SysUser user = userService.getOne(Wrappers.query().lambda().eq(SysUser::getUsername, username)); + if (user == null) { + return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_QUERY_ERROR)); + } + UserInfo userInfo = userService.getUserInfo(user); + UserInfoVO vo = new UserInfoVO(); + vo.setSysUser(userInfo.getSysUser()); + vo.setRoles(userInfo.getRoles()); + vo.setPermissions(userInfo.getPermissions()); + return R.ok(vo); + } - /** - * 获取指定用户全部信息 - * - * @return 用户信息 - */ - @Inner - @GetMapping("/info/{username}") - public R info(@PathVariable String username) { - SysUser user = userService.getOne(Wrappers.query().lambda().eq(SysUser::getUsername, username)); - if (user == null) { - return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_USERINFO_EMPTY, username)); - } - return R.ok(userService.getUserInfo(user)); - } + /** + * 获取指定用户全部信息 + * + * @return 用户信息 + */ + @Inner + @GetMapping("/info/{username}") + public R info(@PathVariable String username) { + SysUser user = userService.getOne(Wrappers.query().lambda().eq(SysUser::getUsername, username)); + if (user == null) { + return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_USERINFO_EMPTY, username)); + } + return R.ok(userService.getUserInfo(user)); + } - @Inner - @PostMapping("/sso_save") - public R save_sso(@RequestBody Map attributes) { - String username = (String) attributes.getOrDefault("username", "pig"); - // 判断用户名是否存在 - SysUser sysUser = userService.getOne(Wrappers.lambdaQuery().eq(SysUser::getUsername, username)); - if (sysUser == null) { - SysUser sysUserByMap = BeanCreator.createSysUserByMap(attributes); - UserDTO userDTO = new UserDTO(); - BeanUtils.copyProperties(sysUserByMap,userDTO); + @Inner + @PostMapping("/sso_save") + public R save_sso(@RequestBody Map attributes) { + String username = (String) attributes.getOrDefault("username", "pig"); + // 判断用户名是否存在 + SysUser sysUser = userService.getOne(Wrappers.lambdaQuery().eq(SysUser::getUsername, username)); + if (sysUser == null) { + SysUser sysUserByMap = BeanCreator.createSysUserByMap(attributes); + UserDTO userDTO = new UserDTO(); + BeanUtils.copyProperties(sysUserByMap,userDTO); - userDTO.setPost(Lists.newArrayList(1l)); - userDTO.setDeptId(6l); - userDTO.setRole(Lists.newArrayList(2l)); - // 添加用户 - userService.saveUser(userDTO); - } - return info(username); - } + userDTO.setPost(Lists.newArrayList(1l)); + userDTO.setDeptId(6l); + userDTO.setRole(Lists.newArrayList(2l)); + // 添加用户 + userService.saveUser(userDTO); + } + return info(username); + } - /** - * 根据部门id,查询对应的用户 id 集合 - * - * @param deptIds 部门id 集合 - * @return 用户 id 集合 - */ - @Inner - @GetMapping("/ids") - public R> listUserIdByDeptIds(@RequestParam("deptIds") Set deptIds) { - return R.ok(userService.listUserIdByDeptIds(deptIds)); - } + /** + * 根据部门id,查询对应的用户 id 集合 + * + * @param deptIds 部门id 集合 + * @return 用户 id 集合 + */ + @Inner + @GetMapping("/ids") + public R> listUserIdByDeptIds(@RequestParam("deptIds") Set deptIds) { + return R.ok(userService.listUserIdByDeptIds(deptIds)); + } - /** - * 通过ID查询用户信息 - * - * @param id ID - * @return 用户信息 - */ - @GetMapping("/{id:\\d+}") - public R user(@PathVariable Long id) { - return R.ok(userService.getUserVoById(id)); - } + /** + * 通过ID查询用户信息 + * + * @param id ID + * @return 用户信息 + */ + @GetMapping("/{id:\\d+}") + public R user(@PathVariable Long id) { + return R.ok(userService.getUserVoById(id)); + } - /** - * 判断用户是否存在 - * - * @param userDTO 查询条件 - * @return - */ - @Inner(false) - @GetMapping("/check/exist") - public R isExist(UserDTO userDTO) { - List sysUserList = userService.list(new QueryWrapper<>(userDTO)); - if (CollUtil.isNotEmpty(sysUserList)) { - return R.ok(Boolean.TRUE, MsgUtils.getMessage(ErrorCodes.SYS_USER_EXISTING)); - } - return R.ok(Boolean.FALSE); - } + /** + * 判断用户是否存在 + * + * @param userDTO 查询条件 + * @return + */ + @Inner(false) + @GetMapping("/check/exist") + public R isExist(UserDTO userDTO) { + List sysUserList = userService.list(new QueryWrapper<>(userDTO)); + if (CollUtil.isNotEmpty(sysUserList)) { + return R.ok(Boolean.TRUE, MsgUtils.getMessage(ErrorCodes.SYS_USER_EXISTING)); + } + return R.ok(Boolean.FALSE); + } - /** - * 删除用户信息 - * - * @param id ID - * @return R - */ - @SysLog("删除用户信息") - @DeleteMapping("/{id:\\d+}") - @PreAuthorize("@pms.hasPermission('sys_user_del')") - public R userDel(@PathVariable Long id) { - SysUser sysUser = userService.getById(id); - return R.ok(userService.removeUserById(sysUser)); - } + /** + * 删除用户信息 + * + * @param id ID + * @return R + */ + @SysLog("删除用户信息") + @DeleteMapping("/{id:\\d+}") + @PreAuthorize("@pms.hasPermission('sys_user_del')") + public R userDel(@PathVariable Long id) { + SysUser sysUser = userService.getById(id); + return R.ok(userService.removeUserById(sysUser)); + } - /** - * 添加用户 - * - * @param userDto 用户信息 - * @return success/false - */ - @SysLog("添加用户") - @PostMapping - @XssCleanIgnore({"password"}) - @PreAuthorize("@pms.hasPermission('sys_user_add')") - public R user(@RequestBody UserDTO userDto) { - return R.ok(userService.saveUser(userDto)); - } + /** + * 添加用户 + * + * @param userDto 用户信息 + * @return success/false + */ + @SysLog("添加用户") + @PostMapping + @XssCleanIgnore({"password"}) + @PreAuthorize("@pms.hasPermission('sys_user_add')") + public R user(@RequestBody UserDTO userDto) { + return R.ok(userService.saveUser(userDto)); + } - /** - * 管理员更新用户信息 - * - * @param userDto 用户信息 - * @return R - */ - @SysLog("更新用户信息") - @PutMapping - @XssCleanIgnore({"password"}) - @PreAuthorize("@pms.hasPermission('sys_user_edit')") - public R updateUser(@Valid @RequestBody UserDTO userDto) { - return userService.updateUser(userDto); - } + /** + * 管理员更新用户信息 + * + * @param userDto 用户信息 + * @return R + */ + @SysLog("更新用户信息") + @PutMapping + @XssCleanIgnore({"password"}) + @PreAuthorize("@pms.hasPermission('sys_user_edit')") + public R updateUser(@Valid @RequestBody UserDTO userDto) { + return userService.updateUser(userDto); + } - /** - * 分页查询用户 - * - * @param page 参数集 - * @param userDTO 查询参数列表 - * @return 用户集合 - */ - @GetMapping("/page") - public R> getUserPage(Page page, UserDTO userDTO) { - return R.ok(userService.getUserWithRolePage(page, userDTO)); - } + /** + * 分页查询用户 + * + * @param page 参数集 + * @param userDTO 查询参数列表 + * @return 用户集合 + */ + @GetMapping("/page") + public R> getUserPage(Page page, UserDTO userDTO) { + return R.ok(userService.getUserWithRolePage(page, userDTO)); + } - /** - * 个人修改个人信息 - * - * @param userDto userDto - * @return success/false - */ - @SysLog("修改个人信息") - @PutMapping("/edit") - @XssCleanIgnore({"password", "newpassword1"}) - public R updateUserInfo(@Valid @RequestBody UserDTO userDto) { - userDto.setUsername(SecurityUtils.getUser().getUsername()); - return userService.updateUserInfo(userDto); - } + /** + * 个人修改个人信息 + * + * @param userDto userDto + * @return success/false + */ + @SysLog("修改个人信息") + @PutMapping("/edit") + @XssCleanIgnore({"password", "newpassword1"}) + public R updateUserInfo(@Valid @RequestBody UserDTO userDto) { + userDto.setUsername(SecurityUtils.getUser().getUsername()); + return userService.updateUserInfo(userDto); + } - /** - * @param username 用户名称 - * @return 上级部门用户列表 - */ - @GetMapping("/ancestor/{username}") - public R> listAncestorUsers(@PathVariable String username) { - return R.ok(userService.listAncestorUsersByUsername(username)); - } + /** + * @param username 用户名称 + * @return 上级部门用户列表 + */ + @GetMapping("/ancestor/{username}") + public R> listAncestorUsers(@PathVariable String username) { + return R.ok(userService.listAncestorUsersByUsername(username)); + } - /** - * 导出excel 表格 - * - * @param userDTO 查询条件 - * @return - */ - @ResponseExcel - @GetMapping("/export") - @PreAuthorize("@pms.hasPermission('sys_user_import_export')") - public List export(UserDTO userDTO) { - return userService.listUser(userDTO); - } + /** + * 导出excel 表格 + * + * @param userDTO 查询条件 + * @return + */ + @ResponseExcel + @GetMapping("/export") + @PreAuthorize("@pms.hasPermission('sys_user_import_export')") + public List export(UserDTO userDTO) { + return userService.listUser(userDTO); + } - /** - * 导入用户 - * - * @param excelVOList 用户列表 - * @param bindingResult 错误信息列表 - * @return R - */ - @PostMapping("/import") - @PreAuthorize("@pms.hasPermission('sys_user_import_export')") - public R importUser(@RequestExcel List excelVOList, BindingResult bindingResult) { - return userService.importUser(excelVOList, bindingResult); - } + /** + * 导入用户 + * + * @param excelVOList 用户列表 + * @param bindingResult 错误信息列表 + * @return R + */ + @PostMapping("/import") + @PreAuthorize("@pms.hasPermission('sys_user_import_export')") + public R importUser(@RequestExcel List excelVOList, BindingResult bindingResult) { + return userService.importUser(excelVOList, bindingResult); + } } diff --git a/summer-ospp/2023/pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/utils/BeanCreator.java b/summer-ospp/2023/pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/utils/BeanCreator.java index e0ea3dca6..3096e5171 100644 --- a/summer-ospp/2023/pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/utils/BeanCreator.java +++ b/summer-ospp/2023/pig/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/utils/BeanCreator.java @@ -6,18 +6,18 @@ import java.util.Map; public class BeanCreator { - private static final String DEFAULT_PASSWORD = "pigmax123456"; + private static final String DEFAULT_PASSWORD = "pigmax123456"; - public static SysUser createSysUserByMap(Map map) { - SysUser sysUser = new SysUser(); - String username = (String) map.get("username"); - String phone = (String) map.get("mobile"); - String deptId = (String) map.get("departmentId"); - sysUser.setUsername(username); - sysUser.setPhone(phone); - sysUser.setDeptId(Long.parseLong(deptId)); - sysUser.setPassword(DEFAULT_PASSWORD); - return sysUser; - } + public static SysUser createSysUserByMap(Map map) { + SysUser sysUser = new SysUser(); + String username = (String) map.get("username"); + String phone = (String) map.get("mobile"); + String deptId = (String) map.get("departmentId"); + sysUser.setUsername(username); + sysUser.setPhone(phone); + sysUser.setDeptId(Long.parseLong(deptId)); + sysUser.setPassword(DEFAULT_PASSWORD); + return sysUser; + } }