zhou-hao 5 rokov pred
rodič
commit
22a7b9ec30
100 zmenil súbory, kde vykonal 504 pridanie a 3898 odobranie
  1. 2 5
      hsweb-authorization/hsweb-authorization-api/pom.xml
  2. 12 3
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/Authentication.java
  3. 7 9
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthenticationHolder.java
  4. 3 2
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthenticationInitializeService.java
  5. 2 13
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthenticationManager.java
  6. 3 3
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthenticationSupplier.java
  7. 0 1
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/CompositeAuthentication.java
  8. 93 0
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/ReactiveAuthenticationHolder.java
  9. 12 8
      hsweb-starter/hsweb-spring-boot-starter/src/main/java/org/hswebframework/web/starter/resolver/JsonParam.java
  10. 1 1
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/define/AuthorizingContext.java
  11. 1 1
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/events/AbstractAuthorizationEvent.java
  12. 1 1
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/setting/UserSettingPermission.java
  13. 5 5
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/simple/DefaultAuthorizationAutoConfiguration.java
  14. 100 90
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/token/DefaultUserTokenManager.java
  15. 4 4
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/token/UserTokenHolder.java
  16. 17 21
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/token/UserTokenManager.java
  17. 4 4
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/token/UserTokenAuthenticationSupplier.java
  18. 5 12
      hsweb-authorization/hsweb-authorization-api/src/test/java/org/hswebframework/web/authorization/AuthenticationTests.java
  19. 47 22
      hsweb-authorization/hsweb-authorization-api/src/test/java/org/hswebframework/web/authorization/UserTokenManagerTests.java
  20. 15 54
      hsweb-authorization/hsweb-authorization-basic/pom.xml
  21. 6 6
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/aop/AopAuthorizingController.java
  22. 2 2
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/aop/AopMethodAuthorizeDefinitionCustomizerParser.java
  23. 1 1
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/aop/AopMethodAuthorizeDefinitionParser.java
  24. 7 7
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/aop/DefaultAopMethodAuthorizeDefinitionParser.java
  25. 0 7
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/configuration/AuthorizingHandlerAutoConfiguration.java
  26. 5 2
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/configuration/BasicAuthorizationTokenParser.java
  27. 18 23
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/embed/EmbedAuthenticationManager.java
  28. 1 1
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/DefaultAuthorizingHandler.java
  29. 0 1
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/access/DefaultDataAccessController.java
  30. 6 13
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/access/FieldFilterDataAccessHandler.java
  31. 20 22
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/access/FieldScopeDataAccessHandler.java
  32. 6 8
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/access/InvokeResultUtils.java
  33. 0 156
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/access/OwnCreatedDataAccessHandler.java
  34. 44 51
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/AuthorizationController.java
  35. 2 2
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/SessionIdUserTokenGenerator.java
  36. 1 1
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/SessionIdUserTokenParser.java
  37. 43 48
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/UserTokenController.java
  38. 8 7
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/WebUserTokenInterceptor.java
  39. 0 26
      hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/session/UserTokenAutoExpiredListener.java
  40. 0 229
      hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/AuthorizeTests.java
  41. 0 80
      hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/RedisUserTokenManagerTests.java
  42. 0 16
      hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/TestApplication.java
  43. 0 42
      hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/basic/embed/EmbedAuthenticationManagerTest.groovy
  44. 0 24
      hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/basic/handler/TestController.java
  45. 0 61
      hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/basic/handler/UserAllowPermissionHandlerTest.groovy
  46. 0 160
      hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/full/FullFunctionTest.groovy
  47. 0 39
      hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/full/controller/CrudController.java
  48. 0 32
      hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/full/controller/TestCrudController.java
  49. 0 39
      hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/full/controller/TestTwoFactorValidatorProvider.java
  50. 0 21
      hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/full/controller/model/TestModel.java
  51. 0 68
      hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/full/token/TestTokenGeneratorAndParser.java
  52. 0 60
      hsweb-authorization/hsweb-authorization-basic/src/test/resources/application.yml
  53. 0 37
      hsweb-authorization/hsweb-authorization-jwt/README.md
  54. 0 42
      hsweb-authorization/hsweb-authorization-jwt/pom.xml
  55. 0 47
      hsweb-authorization/hsweb-authorization-jwt/src/main/java/org/hswebframework/web/authorization/jwt/JwtAuthorizedToken.java
  56. 0 28
      hsweb-authorization/hsweb-authorization-jwt/src/main/java/org/hswebframework/web/authorization/jwt/JwtAutoConfiguration.java
  57. 0 57
      hsweb-authorization/hsweb-authorization-jwt/src/main/java/org/hswebframework/web/authorization/jwt/JwtConfig.java
  58. 0 95
      hsweb-authorization/hsweb-authorization-jwt/src/main/java/org/hswebframework/web/authorization/jwt/JwtTokenGenerator.java
  59. 0 72
      hsweb-authorization/hsweb-authorization-jwt/src/main/java/org/hswebframework/web/authorization/jwt/JwtTokenParser.java
  60. 0 3
      hsweb-authorization/hsweb-authorization-jwt/src/main/resources/META-INF/spring.factories
  61. 0 7
      hsweb-authorization/hsweb-authorization-oauth2/README.md
  62. 0 76
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/pom.xml
  63. 0 31
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/AuthorizationService.java
  64. 0 74
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/OAuth2AccessToken.java
  65. 0 29
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/OAuth2Authorization.java
  66. 0 32
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/OAuth2ServerAutoConfiguration.java
  67. 0 33
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/TokenRequest.java
  68. 0 51
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/client/MemoryOAuth2ClientConfigRepository.java
  69. 0 58
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/client/OAuth2Client.java
  70. 0 38
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/client/OAuth2ClientConfigRepository.java
  71. 0 31
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/client/SimpleOAuth2Client.java
  72. 0 15
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/event/OAuth2GrantEvent.java
  73. 0 41
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/exception/GrantTokenException.java
  74. 0 91
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/AbstractAuthorizationService.java
  75. 0 115
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/DefaultOAuth2Granter.java
  76. 0 124
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/HttpTokenRequest.java
  77. 0 29
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/OAuth2Granter.java
  78. 0 40
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/client/ClientCredentialGranter.java
  79. 0 31
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/client/ClientCredentialRequest.java
  80. 0 63
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/client/DefaultClientCredentialGranter.java
  81. 0 50
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/client/HttpClientCredentialRequest.java
  82. 0 51
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/AuthorizationCode.java
  83. 0 37
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/AuthorizationCodeGranter.java
  84. 0 55
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/AuthorizationCodeRequest.java
  85. 0 29
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/AuthorizationCodeService.java
  86. 0 55
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/AuthorizationCodeTokenRequest.java
  87. 0 86
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/DefaultAuthorizationCodeGranter.java
  88. 0 63
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/HttpAuthorizationCodeRequest.java
  89. 0 67
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/HttpAuthorizationCodeTokenRequest.java
  90. 0 73
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/implicit/DefaultImplicitGranter.java
  91. 0 53
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/implicit/HttpImplicitRequest.java
  92. 0 31
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/implicit/ImplicitGranter.java
  93. 0 34
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/implicit/ImplicitRequest.java
  94. 0 80
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/password/DefaultPasswordGranter.java
  95. 0 58
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/password/HttpPasswordRequest.java
  96. 0 30
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/password/PasswordGranter.java
  97. 0 34
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/password/PasswordRequest.java
  98. 0 26
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/password/PasswordService.java
  99. 0 82
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/refresh/DefaultRefreshTokenGranter.java
  100. 0 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/refresh/HttpRefreshTokenRequest.java

+ 2 - 5
hsweb-authorization/hsweb-authorization-api/pom.xml

@@ -17,20 +17,17 @@
             <artifactId>hsweb-core</artifactId>
             <version>${project.version}</version>
         </dependency>
+
         <dependency>
             <groupId>com.alibaba</groupId>
             <artifactId>fastjson</artifactId>
         </dependency>
+
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter</artifactId>
             <optional>true</optional>
         </dependency>
-        <dependency>
-            <groupId>org.springframework</groupId>
-            <artifactId>spring-webmvc</artifactId>
-            <optional>true</optional>
-        </dependency>
 
         <dependency>
             <groupId>io.projectreactor</groupId>

+ 12 - 3
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/Authentication.java

@@ -31,7 +31,7 @@ import java.util.*;
  * </ul>
  *
  * @author zhouhao
- * @see AuthenticationHolder
+ * @see ReactiveAuthenticationHolder
  * @see AuthenticationManager
  * @since 3.0
  */
@@ -49,10 +49,19 @@ public interface Authentication extends Serializable {
      * </pre>
      *
      * @return 返回Optional对象进行操作
+     * @see ReactiveAuthenticationHolder
+     */
+    static Mono<Authentication> currentReactive() {
+        return ReactiveAuthenticationHolder.get();
+    }
+
+    /**
+     * 非响应式环境适用
+     *
+     * @return 当前用户权限信息
      * @see Optional
-     * @see AuthenticationHolder
      */
-    static Mono<Authentication> current() {
+    static Optional<Authentication> current() {
         return AuthenticationHolder.get();
     }
 

+ 7 - 9
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthenticationHolder.java

@@ -18,13 +18,12 @@
 
 package org.hswebframework.web.authorization;
 
-import org.hswebframework.web.ThreadLocalUtils;
 import reactor.core.publisher.Flux;
 import reactor.core.publisher.Mono;
 
 import java.util.ArrayList;
 import java.util.List;
-import java.util.Objects;
+import java.util.Optional;
 import java.util.concurrent.locks.ReadWriteLock;
 import java.util.concurrent.locks.ReentrantReadWriteLock;
 import java.util.function.Function;
@@ -50,20 +49,19 @@ public final class AuthenticationHolder {
 
     private static final ReadWriteLock lock = new ReentrantReadWriteLock();
 
-    private static Mono<Authentication> get(Function<AuthenticationSupplier, Mono<Authentication>> function) {
+    private static Optional<Authentication> get(Function<AuthenticationSupplier, Authentication> function) {
 
-        return Flux.concat(suppliers.stream()
-                .map(function)
-                .collect(Collectors.toList()))
+        return Flux.fromStream(suppliers.stream().map(function))
                 .reduceWith(CompositeAuthentication::new, CompositeAuthentication::merge)
                 .filter(CompositeAuthentication::isNotEmpty)
-                .map(Authentication.class::cast);
+                .map(Authentication.class::cast)
+                .blockOptional();
     }
 
     /**
      * @return 当前登录的用户权限信息
      */
-    public static Mono<Authentication> get() {
+    public static Optional<Authentication> get() {
 
         return get(AuthenticationSupplier::get);
     }
@@ -74,7 +72,7 @@ public final class AuthenticationHolder {
      * @param userId 用户ID
      * @return 权限信息
      */
-    public static Mono<Authentication> get(String userId) {
+    public static Optional<Authentication> get(String userId) {
         return get(supplier -> supplier.get(userId));
     }
 

+ 3 - 2
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthenticationInitializeService.java

@@ -19,12 +19,13 @@
 package org.hswebframework.web.authorization;
 
 import org.hswebframework.web.authorization.events.AuthorizationInitializeEvent;
+import reactor.core.publisher.Mono;
 
 /**
  * 授权信息初始化服务接口,使用该接口初始化用的权限信息
  *
  * @author zhouhao
- * @since 3.0
+ * @since 4.0
  */
 public interface AuthenticationInitializeService {
     /**
@@ -34,6 +35,6 @@ public interface AuthenticationInitializeService {
      * @return 权限信息
      * @see AuthorizationInitializeEvent
      */
-    Authentication initUserAuthorization(String userId);
+    Mono<Authentication> initUserAuthorization(String userId);
 
 }

+ 2 - 13
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthenticationManager.java

@@ -30,7 +30,6 @@ import java.util.Map;
  * @see 3.0
  */
 public interface AuthenticationManager {
-    String USER_AUTH_CACHE_NAME = "user-auth-";
 
     /**
      * 进行授权操作
@@ -38,7 +37,7 @@ public interface AuthenticationManager {
      * @param request 授权请求
      * @return 授权成功则返回用户权限信息
      */
-    Mono<Authentication> authenticate(AuthenticationRequest request);
+    Mono<Authentication> authenticate(Mono<AuthenticationRequest> request);
 
     /**
      * 根据用户ID获取权限信息
@@ -48,15 +47,5 @@ public interface AuthenticationManager {
      */
     Mono<Authentication> getByUserId(String userId);
 
-    /**
-     * 同步授权信息,在调用了{@link Authentication#setAttribute(String, Serializable)}或者
-     * {@link Authentication#setAttributes(Map)} 后,需要调用次方法进行同步.
-     * 因为如果权限信息不是存在于内存中,而是redis或者其他方案.
-     * 在调用了上述方法后,实际的存储值并不会发生改变.
-     * 注意: Authentication的实现类应该实现自动同步功能。
-     *
-     * @param authentication 要同步的权限信息
-     * @return 同步后的权限信息
-     */
-    Mono<Authentication> sync(Authentication authentication);
+
 }

+ 3 - 3
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthenticationSupplier.java

@@ -25,8 +25,8 @@ import java.util.function.Supplier;
  * @author zhouhao
  * @see Supplier
  * @see Authentication
- * @see AuthenticationHolder
+ * @see ReactiveAuthenticationHolder
  */
-public interface AuthenticationSupplier extends Supplier<Mono<Authentication>> {
-    Mono<Authentication> get(String userId);
+public interface AuthenticationSupplier extends Supplier<Authentication> {
+    Authentication get(String userId);
 }

+ 0 - 1
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/CompositeAuthentication.java

@@ -23,7 +23,6 @@ public class CompositeAuthentication implements Authentication {
         return !isEmpty();
     }
 
-
     @Override
     public User getUser() {
 

+ 93 - 0
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/ReactiveAuthenticationHolder.java

@@ -0,0 +1,93 @@
+/*
+ *  Copyright 2019 http://www.hswebframework.org
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ *
+ */
+
+package org.hswebframework.web.authorization;
+
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+/**
+ * 权限获取器,用于静态方式获取当前登录用户的权限信息.
+ * 例如:
+ * <pre>
+ *     &#064;RequestMapping("/example")
+ *     public ResponseMessage example(){
+ *         Authorization auth = AuthorizationHolder.get();
+ *         return ResponseMessage.ok();
+ *     }
+ * </pre>
+ *
+ * @author zhouhao
+ * @see ReactiveAuthenticationSupplier
+ * @since 3.0
+ */
+public final class ReactiveAuthenticationHolder {
+    private static final List<ReactiveAuthenticationSupplier> suppliers = new ArrayList<>();
+
+    private static final ReadWriteLock lock = new ReentrantReadWriteLock();
+
+    private static Mono<Authentication> get(Function<ReactiveAuthenticationSupplier, Mono<Authentication>> function) {
+
+        return Flux.concat(suppliers.stream()
+                .map(function)
+                .collect(Collectors.toList()))
+                .reduceWith(CompositeAuthentication::new, CompositeAuthentication::merge)
+                .filter(CompositeAuthentication::isNotEmpty)
+                .map(Authentication.class::cast);
+    }
+
+    /**
+     * @return 当前登录的用户权限信息
+     */
+    public static Mono<Authentication> get() {
+
+        return get(ReactiveAuthenticationSupplier::get);
+    }
+
+    /**
+     * 获取指定用户的权限信息
+     *
+     * @param userId 用户ID
+     * @return 权限信息
+     */
+    public static Mono<Authentication> get(String userId) {
+        return get(supplier -> supplier.get(userId));
+    }
+
+    /**
+     * 初始化 {@link ReactiveAuthenticationSupplier}
+     *
+     * @param supplier
+     */
+    public static void addSupplier(ReactiveAuthenticationSupplier supplier) {
+        lock.writeLock().lock();
+        try {
+            suppliers.add(supplier);
+        } finally {
+            lock.writeLock().unlock();
+        }
+    }
+
+}

+ 12 - 8
hsweb-starter/hsweb-spring-boot-starter/src/main/java/org/hswebframework/web/starter/resolver/JsonParam.java

@@ -15,15 +15,19 @@
  *
  */
 
-package org.hswebframework.web.starter.resolver;
+package org.hswebframework.web.authorization;
 
-import java.lang.annotation.*;
+import reactor.core.publisher.Mono;
 
-@Target(ElementType.PARAMETER)
-@Retention(RetentionPolicy.RUNTIME)
-@Documented
-public @interface JsonParam {
-    String value();
+import java.util.function.Supplier;
 
-    Class<?> type() default Void.class;
+/**
+ * @author zhouhao
+ * @see Supplier
+ * @see Authentication
+ * @see ReactiveAuthenticationHolder
+ * @since 4.0
+ */
+public interface ReactiveAuthenticationSupplier extends Supplier<Mono<Authentication>> {
+    Mono<Authentication> get(String userId);
 }

+ 1 - 1
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/define/AuthorizingContext.java

@@ -4,8 +4,8 @@ import lombok.AllArgsConstructor;
 import lombok.Getter;
 import lombok.NoArgsConstructor;
 import lombok.Setter;
+import org.hswebframework.web.aop.MethodInterceptorContext;
 import org.hswebframework.web.authorization.Authentication;
-import org.hswebframework.web.boost.aop.context.MethodInterceptorContext;
 
 /**
  * 权限控制上下文

+ 1 - 1
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/events/AbstractAuthorizationEvent.java

@@ -40,7 +40,7 @@ public abstract class AbstractAuthorizationEvent extends ApplicationEvent implem
     private transient Function<String, Object> parameterGetter;
 
     /**
-     * 带参构造方法,所有参数不能为null
+     * 所有参数不能为null
      *
      * @param username        用户名
      * @param password        密码

+ 1 - 1
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/setting/UserSettingPermission.java

@@ -11,7 +11,7 @@ import org.hswebframework.web.dict.EnumDict;
  */
 @AllArgsConstructor
 @Getter
-@Dict(id = "user-setting-permission")
+@Dict("user-setting-permission")
 public enum UserSettingPermission implements EnumDict<String> {
     NONE("无"),
     R("读"),

+ 5 - 5
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/simple/DefaultAuthorizationAutoConfiguration.java

@@ -1,7 +1,7 @@
 package org.hswebframework.web.authorization.simple;
 
 import org.hswebframework.web.authorization.Authentication;
-import org.hswebframework.web.authorization.AuthenticationHolder;
+import org.hswebframework.web.authorization.ReactiveAuthenticationHolder;
 import org.hswebframework.web.authorization.AuthenticationManager;
 import org.hswebframework.web.authorization.builder.AuthenticationBuilderFactory;
 import org.hswebframework.web.authorization.builder.DataAccessConfigBuilderFactory;
@@ -9,7 +9,7 @@ import org.hswebframework.web.authorization.simple.builder.DataAccessConfigConve
 import org.hswebframework.web.authorization.simple.builder.SimpleAuthenticationBuilderFactory;
 import org.hswebframework.web.authorization.simple.builder.SimpleDataAccessConfigBuilderFactory;
 import org.hswebframework.web.authorization.token.DefaultUserTokenManager;
-import org.hswebframework.web.authorization.token.UserTokenAuthenticationSupplier;
+import org.hswebframework.web.authorization.token.UserTokenReactiveAuthenticationSupplier;
 import org.hswebframework.web.authorization.token.UserTokenManager;
 import org.hswebframework.web.authorization.twofactor.TwoFactorValidatorManager;
 import org.hswebframework.web.authorization.twofactor.defaults.DefaultTwoFactorValidatorManager;
@@ -41,9 +41,9 @@ public class DefaultAuthorizationAutoConfiguration {
 
     @Bean
     @ConditionalOnBean(AuthenticationManager.class)
-    public UserTokenAuthenticationSupplier userTokenAuthenticationSupplier(AuthenticationManager authenticationManager) {
-        UserTokenAuthenticationSupplier supplier = new UserTokenAuthenticationSupplier(authenticationManager);
-        AuthenticationHolder.addSupplier(supplier);
+    public UserTokenReactiveAuthenticationSupplier userTokenAuthenticationSupplier(AuthenticationManager authenticationManager) {
+        UserTokenReactiveAuthenticationSupplier supplier = new UserTokenReactiveAuthenticationSupplier(authenticationManager);
+        ReactiveAuthenticationHolder.addSupplier(supplier);
         return supplier;
     }
 

+ 100 - 90
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/token/DefaultUserTokenManager.java

@@ -27,7 +27,10 @@ import org.hswebframework.web.authorization.token.event.UserTokenRemovedEvent;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.ApplicationEvent;
 import org.springframework.context.ApplicationEventPublisher;
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
 
+import javax.validation.constraints.NotNull;
 import java.util.*;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
@@ -90,97 +93,90 @@ public class DefaultUserTokenManager implements UserTokenManager {
         return userStorage.computeIfAbsent(userId, key -> new HashSet<>());
     }
 
-    private SimpleUserToken checkTimeout(SimpleUserToken detail) {
+    private Mono<UserToken> checkTimeout(UserToken detail) {
         if (null == detail) {
-            return null;
+            return Mono.empty();
         }
         if (detail.getMaxInactiveInterval() <= 0) {
-            return detail;
+            return Mono.just(detail);
         }
         if (System.currentTimeMillis() - detail.getLastRequestTime() > detail.getMaxInactiveInterval()) {
-            changeTokenState(detail, TokenState.expired);
-            return detail;
+            return changeTokenState(detail, TokenState.expired)
+                    .thenReturn(detail);
         }
-        return detail;
+        return Mono.just(detail);
     }
 
     @Override
-    public SimpleUserToken getByToken(String token) {
+    public Mono<UserToken> getByToken(String token) {
         if (token == null) {
-            return null;
+            return Mono.empty();
         }
         return checkTimeout(tokenStorage.get(token));
     }
 
     @Override
-    public List<UserToken> getByUserId(String userId) {
+    public Flux<UserToken> getByUserId(String userId) {
         if (userId == null) {
-            return new ArrayList<>();
+            return Flux.empty();
         }
         Set<String> tokens = getUserToken(userId);
         if (tokens.isEmpty()) {
             userStorage.remove(userId);
-            return new ArrayList<>();
+            return Flux.empty();
         }
-        return tokens
+        return Flux.fromStream(tokens
                 .stream()
                 .map(tokenStorage::get)
-                .filter(Objects::nonNull)
-                .collect(Collectors.toList());
+                .filter(Objects::nonNull));
     }
 
     @Override
-    public boolean userIsLoggedIn(String userId) {
+    public Mono<Boolean> userIsLoggedIn(String userId) {
         if (userId == null) {
-            return false;
+            return Mono.just(false);
         }
-        for (UserToken userToken : getByUserId(userId)) {
-            if (userToken.isNormal()) {
-                return true;
-            }
-        }
-        return false;
+        return getByUserId(userId)
+                .any(UserToken::isNormal);
     }
 
     @Override
-    public boolean tokenIsLoggedIn(String token) {
+    public Mono<Boolean> tokenIsLoggedIn(String token) {
         if (token == null) {
-            return false;
+            return Mono.just(false);
         }
-        UserToken userToken = getByToken(token);
-
-        return userToken != null && !userToken.isExpired();
-    }
-
-    @Override
-    public long totalUser() {
-        return userStorage.size();
+        return getByToken(token)
+                .map(t -> !t.isExpired())
+                .defaultIfEmpty(false);
     }
 
     @Override
-    public long totalToken() {
-        return tokenStorage.size();
+    public Mono<Integer> totalUser() {
+        return Mono.just(userStorage.size());
     }
 
     @Override
-    public void allLoggedUser(Consumer<UserToken> consumer) {
-        tokenStorage.values().forEach(consumer);
+    public Mono<Integer> totalToken() {
+        return Mono.just(tokenStorage.size());
     }
 
     @Override
-    public List<UserToken> allLoggedUser() {
-        return new ArrayList<>(tokenStorage.values());
+    public Flux<UserToken> allLoggedUser() {
+        return Flux.fromIterable(tokenStorage.values());
     }
 
     @Override
-    public void signOutByUserId(String userId) {
+    public Mono<Void> signOutByUserId(String userId) {
         if (null == userId) {
-            return;
+            return Mono.empty();
         }
-        Set<String> tokens = getUserToken(userId);
-        tokens.forEach(token -> signOutByToken(token, false));
-        tokens.clear();
-        userStorage.remove(userId);
+        return Mono.defer(() -> {
+            Set<String> tokens = getUserToken(userId);
+            tokens.forEach(token -> signOutByToken(token, false));
+            tokens.clear();
+            userStorage.remove(userId);
+            return Mono.empty();
+        });
     }
 
     private void signOutByToken(String token, boolean removeUserToken) {
@@ -204,8 +200,8 @@ public class DefaultUserTokenManager implements UserTokenManager {
     }
 
     @Override
-    public void signOutByToken(String token) {
-        signOutByToken(token, true);
+    public Mono<Void> signOutByToken(String token) {
+        return Mono.fromRunnable(() -> signOutByToken(token, true));
     }
 
     protected void publishEvent(ApplicationEvent event) {
@@ -214,78 +210,92 @@ public class DefaultUserTokenManager implements UserTokenManager {
         }
     }
 
-    public void changeTokenState(SimpleUserToken userToken, TokenState state) {
+    public Mono<Void> changeTokenState(UserToken userToken, TokenState state) {
         if (null != userToken) {
-            SimpleUserToken copy = userToken.copy();
+            SimpleUserToken token = ((SimpleUserToken) userToken);
+            SimpleUserToken copy = token.copy();
 
-            userToken.setState(state);
+            token.setState(state);
             syncToken(userToken);
 
             publishEvent(new UserTokenChangedEvent(copy, userToken));
         }
+        return Mono.empty();
     }
 
     @Override
-    public void changeTokenState(String token, TokenState state) {
-        changeTokenState(getByToken(token), state);
+    public Mono<Void> changeTokenState(String token, TokenState state) {
+        return getByToken(token)
+                .flatMap(t -> changeTokenState(t, state));
     }
 
     @Override
-    public void changeUserState(String user, TokenState state) {
-        getByUserId(user).forEach(token -> changeTokenState(token.getToken(), state));
+    public Mono<Void> changeUserState(String user, TokenState state) {
+        return Mono.from(getByUserId(user)
+                .flatMap(token -> changeTokenState(token.getToken(), state)));
     }
 
     @Override
-    public UserToken signIn(String token, String type, String userId, long maxInactiveInterval) {
-        SimpleUserToken detail = new SimpleUserToken(userId, token);
-        detail.setType(type);
-        detail.setMaxInactiveInterval(maxInactiveInterval);
-        AllopatricLoginMode mode = allopatricLoginModes.getOrDefault(type, allopatricLoginMode);
-        if (mode == AllopatricLoginMode.deny) {
-            boolean hasAnotherToken = getByUserId(userId)
-                    .stream()
-                    .filter(userToken -> type.equals(userToken.getType()))
-                    .map(SimpleUserToken.class::cast)
-                    .peek(this::checkTimeout)
-                    .anyMatch(UserToken::isNormal);
-            if (hasAnotherToken) {
-                throw new AccessDenyException("该用户已在其他地方登陆");
-            }
-        } else if (mode == AllopatricLoginMode.offlineOther) {
-            //将在其他地方登录的用户设置为离线
-            List<UserToken> oldToken = getByUserId(userId);
-            for (UserToken userToken : oldToken) {
-                //相同的tokenType才让其下线
-                if (type.equals(userToken.getType())) {
-                    changeTokenState(userToken.getToken(), TokenState.offline);
-                }
+    public Mono<UserToken> signIn(String token, String type, String userId, long maxInactiveInterval) {
+
+        return Mono.defer(() -> {
+            SimpleUserToken detail = new SimpleUserToken(userId, token);
+            detail.setType(type);
+            detail.setMaxInactiveInterval(maxInactiveInterval);
+            detail.setState(TokenState.normal);
+            Runnable doSign = () -> {
+                tokenStorage.put(token, detail);
+
+                getUserToken(userId).add(token);
+
+                publishEvent(new UserTokenCreatedEvent(detail));
+            };
+            AllopatricLoginMode mode = allopatricLoginModes.getOrDefault(type, allopatricLoginMode);
+            if (mode == AllopatricLoginMode.deny) {
+                return getByUserId(userId)
+                        .filter(userToken -> type.equals(userToken.getType()))
+                        .flatMap(this::checkTimeout)
+                        .filterWhen(t -> {
+                            if (t.isNormal()) {
+                                return Mono.error(new AccessDenyException("该用户已在其他地方登陆"));
+                            }
+                            return Mono.empty();
+                        })
+                        .then(Mono.just(detail))
+                        .doOnNext(__ -> doSign.run());
+            } else if (mode == AllopatricLoginMode.offlineOther) {
+                return getByUserId(userId)
+                        .filter(userToken -> type.equals(userToken.getType()))
+                        .flatMap(userToken -> changeTokenState(userToken, TokenState.offline))
+                        .then(Mono.just(detail))
+                        .doOnNext(__ -> doSign.run());
             }
-        }
-        detail.setState(TokenState.normal);
-        tokenStorage.put(token, detail);
+            doSign.run();
+            return Mono.just(detail);
+        });
 
-        getUserToken(userId).add(token);
-
-        publishEvent(new UserTokenCreatedEvent(detail));
-        return detail;
     }
 
     @Override
-    public void touch(String token) {
+    public Mono<Void> touch(String token) {
         SimpleUserToken userToken = tokenStorage.get(token);
         if (null != userToken) {
             userToken.touch();
             syncToken(userToken);
         }
+        return Mono.empty();
     }
 
     @Override
-    public void checkExpiredToken() {
-        for (SimpleUserToken token : tokenStorage.values()) {
-            if (token != null && checkTimeout(token).isExpired()) {
-                signOutByToken(token.getToken());
-            }
-        }
+    public Mono<Void> checkExpiredToken() {
+
+        return Flux
+                .fromIterable(tokenStorage.values())
+                .doOnNext(this::checkTimeout)
+                .filter(UserToken::isExpired)
+                .map(UserToken::getToken)
+                .flatMap(this::signOutByToken)
+                .then();
     }
 
     /**

+ 4 - 4
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/token/UserTokenHolder.java

@@ -1,7 +1,7 @@
 package org.hswebframework.web.authorization.token;
 
-import org.hswebframework.web.ThreadLocalUtils;
-import org.hswebframework.web.authorization.token.UserToken;
+
+import org.hswebframework.web.context.ContextUtils;
 
 /**
  * @author zhouhao
@@ -12,11 +12,11 @@ public final class UserTokenHolder {
     }
 
     public static UserToken currentToken() {
-        return ThreadLocalUtils.get(UserToken.class.getName());
+        return ContextUtils.currentContext().get(UserToken.class).orElse(null);
     }
 
     public static UserToken setCurrent(UserToken token) {
-        ThreadLocalUtils.put(UserToken.class.getName(), token);
+        ContextUtils.currentContext().put(UserToken.class, token);
         return token;
     }
 

+ 17 - 21
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/token/UserTokenManager.java

@@ -18,6 +18,9 @@
 
 package org.hswebframework.web.authorization.token;
 
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
 import java.util.List;
 import java.util.function.Consumer;
 import java.util.function.Predicate;
@@ -36,7 +39,7 @@ public interface UserTokenManager {
      * @param token token
      * @return 令牌信息, 未授权时返回null
      */
-    UserToken getByToken(String token);
+    Mono<UserToken> getByToken(String token);
 
     /**
      * 根据用户id,获取全部令牌信息,如果没有则返回空集合而不是<code>null</code>
@@ -44,48 +47,41 @@ public interface UserTokenManager {
      * @param userId 用户id
      * @return 授权信息
      */
-    List<UserToken> getByUserId(String userId);
+    Flux<UserToken> getByUserId(String userId);
 
     /**
      * @param userId 用户ID
      * @return 用户是否已经授权
      */
-    boolean userIsLoggedIn(String userId);
+    Mono<Boolean> userIsLoggedIn(String userId);
 
     /**
      * @param token token
      * @return token是否已登记
      */
-    boolean tokenIsLoggedIn(String token);
+    Mono<Boolean> tokenIsLoggedIn(String token);
 
     /**
      * @return 总用户数量,一个用户多个地方登陆数量算1
      */
-    long totalUser();
+    Mono<Integer> totalUser();
 
     /**
      * @return 总token数量
      */
-    long totalToken();
+    Mono<Integer> totalToken();
 
     /**
      * @return 所有token
      */
-    List<UserToken> allLoggedUser();
-
-    /**
-     * 遍历全部token信息
-     *
-     * @param consumer token消费者
-     */
-    void allLoggedUser(Consumer<UserToken> consumer);
+    Flux<UserToken> allLoggedUser();
 
     /**
      * 删除用户授权信息
      *
      * @param userId 用户ID
      */
-    void signOutByUserId(String userId);
+    Mono<Void> signOutByUserId(String userId);
 
     /**
      * 根据token删除
@@ -93,7 +89,7 @@ public interface UserTokenManager {
      * @param token 令牌
      * @see org.hswebframework.web.authorization.token.event.UserTokenRemovedEvent
      */
-    void signOutByToken(String token);
+    Mono<Void> signOutByToken(String token);
 
     /**
      * 修改userId的状态
@@ -103,7 +99,7 @@ public interface UserTokenManager {
      * @see org.hswebframework.web.authorization.token.event.UserTokenChangedEvent
      * @see this#changeTokenState
      */
-    void changeUserState(String userId, TokenState state);
+    Mono<Void> changeUserState(String userId, TokenState state);
 
     /**
      * 修改token的状态
@@ -112,7 +108,7 @@ public interface UserTokenManager {
      * @param state 状态
      * @see org.hswebframework.web.authorization.token.event.UserTokenChangedEvent
      */
-    void changeTokenState(String token, TokenState state);
+    Mono<Void> changeTokenState(String token, TokenState state);
 
     /**
      * 登记一个用户的token
@@ -123,20 +119,20 @@ public interface UserTokenManager {
      * @param maxInactiveInterval 最大不活动时间,超过后令牌状态{@link UserToken#getState()}将变为过期{@link TokenState#expired}
      * @see org.hswebframework.web.authorization.token.event.UserTokenCreatedEvent
      */
-    UserToken signIn(String token, String type, String userId, long maxInactiveInterval);
+    Mono<UserToken> signIn(String token, String type, String userId, long maxInactiveInterval);
 
     /**
      * 更新token,使其不过期
      *
      * @param token token
      */
-    void touch(String token);
+    Mono<Void> touch(String token);
 
     /**
      * 检查已过期的token,并将其remove
      *
      * @see this#signOutByToken(String)
      */
-    void checkExpiredToken();
+    Mono<Void> checkExpiredToken();
 
 }

+ 4 - 4
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/token/UserTokenAuthenticationSupplier.java

@@ -2,7 +2,7 @@ package org.hswebframework.web.authorization.token;
 
 import org.hswebframework.web.authorization.Authentication;
 import org.hswebframework.web.authorization.AuthenticationManager;
-import org.hswebframework.web.authorization.AuthenticationSupplier;
+import org.hswebframework.web.authorization.ReactiveAuthenticationSupplier;
 import org.hswebframework.web.context.ContextKey;
 import org.hswebframework.web.context.ContextUtils;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -15,13 +15,13 @@ import java.util.Map;
 /**
  * @author zhouhao
  */
-public class UserTokenAuthenticationSupplier implements AuthenticationSupplier {
+public class UserTokenReactiveAuthenticationSupplier implements ReactiveAuthenticationSupplier {
 
     private AuthenticationManager defaultAuthenticationManager;
 
     private Map<String, ThirdPartAuthenticationManager> thirdPartAuthenticationManager = new HashMap<>();
 
-    public UserTokenAuthenticationSupplier(AuthenticationManager defaultAuthenticationManager) {
+    public UserTokenReactiveAuthenticationSupplier(AuthenticationManager defaultAuthenticationManager) {
         this.defaultAuthenticationManager = defaultAuthenticationManager;
     }
 
@@ -62,7 +62,7 @@ public class UserTokenAuthenticationSupplier implements AuthenticationSupplier {
 
     @Override
     public Mono<Authentication> get() {
-        return ContextUtils.currentContext()
+        return ContextUtils.reactiveContext()
                 .flatMap(context ->
                         context.get(ContextKey.of(UserToken.class))
                                 .filter(UserToken::validate)

+ 5 - 12
hsweb-authorization/hsweb-authorization-api/src/test/java/org/hswebframework/web/authorization/AuthenticationTests.java

@@ -1,13 +1,10 @@
 package org.hswebframework.web.authorization;
 
 import org.hswebframework.web.authorization.builder.AuthenticationBuilder;
-import org.hswebframework.web.authorization.exception.AccessDenyException;
-import org.hswebframework.web.authorization.exception.UnAuthorizedException;
 import org.hswebframework.web.authorization.simple.builder.SimpleAuthenticationBuilder;
 import org.hswebframework.web.authorization.simple.builder.SimpleDataAccessConfigBuilderFactory;
 import org.hswebframework.web.authorization.token.*;
 import org.hswebframework.web.context.ContextKey;
-import org.hswebframework.web.context.ContextUtils;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
@@ -101,8 +98,8 @@ public class AuthenticationTests {
         //初始化权限管理器,用于获取用户的权限信息
         AuthenticationManager authenticationManager = new AuthenticationManager() {
             @Override
-            public Mono<Authentication> authenticate(AuthenticationRequest request) {
-                return null;
+            public Mono<Authentication> authenticate(Mono<AuthenticationRequest> request) {
+                return Mono.empty();
             }
 
             @Override
@@ -113,20 +110,16 @@ public class AuthenticationTests {
                 return Mono.empty();
             }
 
-            @Override
-            public Mono<Authentication> sync(Authentication authentication) {
-                return Mono.just(authentication);
-            }
         };
-        AuthenticationHolder.addSupplier(new UserTokenAuthenticationSupplier(authenticationManager));
+        ReactiveAuthenticationHolder.addSupplier(new UserTokenReactiveAuthenticationSupplier(authenticationManager));
 
         //绑定用户token
         UserTokenManager userTokenManager = new DefaultUserTokenManager();
-        UserToken token = userTokenManager.signIn("test", "token-test", "admin", -1);
+        UserToken token = userTokenManager.signIn("test", "token-test", "admin", -1).block();
 
         //获取当前登录用户
         Authentication
-                .current()
+                .currentReactive()
                 .map(Authentication::getUser)
                 .map(User::getId)
                 .subscriberContext(acceptContext(ctx->ctx.put(ContextKey.of(UserToken.class),token)))

+ 47 - 22
hsweb-authorization/hsweb-authorization-api/src/test/java/org/hswebframework/web/authorization/UserTokenManagerTests.java

@@ -4,6 +4,7 @@ import org.hswebframework.web.authorization.exception.AccessDenyException;
 import org.hswebframework.web.authorization.token.*;
 import org.junit.Assert;
 import org.junit.Test;
+import reactor.test.StepVerifier;
 
 public class UserTokenManagerTests {
 
@@ -17,34 +18,58 @@ public class UserTokenManagerTests {
         DefaultUserTokenManager userTokenManager = new DefaultUserTokenManager();
         userTokenManager.setAllopatricLoginMode(AllopatricLoginMode.allow); //允许异地登录
 
-        UserToken userToken = userTokenManager.signIn("test", "sessionId", "admin", 1000);
+        UserToken userToken = userTokenManager.signIn("test", "sessionId", "admin", 1000).block();
         Assert.assertNotNull(userToken);
 
         //可重复登录
-        userTokenManager.signIn("test2", "sessionId", "admin", 30000);
-        Assert.assertEquals(userTokenManager.totalToken(), 2); //2个token
-        Assert.assertEquals(userTokenManager.totalUser(), 1);//1个用户
+        userTokenManager.signIn("test2", "sessionId", "admin", 30000).block();
+
+        //2个token
+        userTokenManager.totalToken()
+                .as(StepVerifier::create)
+                .expectNext(2)
+                .verifyComplete();
+
+        //1个用户
+        userTokenManager.totalUser()
+                .as(StepVerifier::create)
+                .expectNext(1)
+                .verifyComplete();
 
         //改变token状态
-        userTokenManager.changeUserState("admin", TokenState.deny);
+        userTokenManager.changeUserState("admin", TokenState.deny).subscribe();
 
-        userToken = userTokenManager.getByToken(userToken.getToken());
+        userToken = userTokenManager.getByToken(userToken.getToken()).block();
 
         Assert.assertEquals(userToken.getState(), TokenState.deny);
 
-        userTokenManager.changeUserState("admin", TokenState.effective);
+        userTokenManager.changeUserState("admin", TokenState.effective).subscribe();
 
         Thread.sleep(1200);
 
-        userToken = userTokenManager.getByToken(userToken.getToken());
-        Assert.assertTrue(userToken.isExpired());
+        userTokenManager.getByToken(userToken.getToken())
+                .map(UserToken::isExpired)
+                .as(StepVerifier::create)
+                .expectNext(true)
+                .verifyComplete();
+
+        userTokenManager.checkExpiredToken().subscribe();
+
+
+        userTokenManager.getByToken(userToken.getToken())
+                .as(StepVerifier::create)
+                .expectNextCount(0)
+                .verifyComplete();
 
-        userTokenManager.checkExpiredToken();
+        userTokenManager.totalToken()
+                .as(StepVerifier::create)
+                .expectNext(1)
+                .verifyComplete();
 
-        userToken = userTokenManager.getByToken(userToken.getToken());
-        Assert.assertTrue(userToken == null);
-        Assert.assertEquals(userTokenManager.totalToken(), 1);
-        Assert.assertEquals(userTokenManager.totalUser(), 1);
+        userTokenManager.totalUser()
+                .as(StepVerifier::create)
+                .expectNext(1)
+                .verifyComplete();
 
     }
 
@@ -57,16 +82,16 @@ public class UserTokenManagerTests {
         DefaultUserTokenManager userTokenManager = new DefaultUserTokenManager();
         userTokenManager.setAllopatricLoginMode(AllopatricLoginMode.deny);//如果在其他地方登录,本地禁止登录
 
-        userTokenManager.signIn("test", "sessionId", "admin", 10000);
+        userTokenManager.signIn("test", "sessionId", "admin", 10000).subscribe();
 
         try {
-            userTokenManager.signIn("test2", "sessionId", "admin", 30000);
+            userTokenManager.signIn("test2", "sessionId", "admin", 30000).block();
             Assert.assertTrue(false);
         } catch (AccessDenyException e) {
 
         }
-        Assert.assertTrue(userTokenManager.getByToken("test").isNormal());
-        Assert.assertTrue(userTokenManager.getByToken("test2")==null);
+        Assert.assertTrue(userTokenManager.getByToken("test").block().isNormal());
+        Assert.assertNull(userTokenManager.getByToken("test2").block());
 
     }
 
@@ -78,13 +103,13 @@ public class UserTokenManagerTests {
         DefaultUserTokenManager userTokenManager = new DefaultUserTokenManager();
         userTokenManager.setAllopatricLoginMode(AllopatricLoginMode.offlineOther); //将其他地方登录的用户踢下线
 
-        userTokenManager.signIn("test", "sessionId", "admin", 1000);
+        userTokenManager.signIn("test", "sessionId", "admin", 1000).subscribe();
 
-        userTokenManager.signIn("test2", "sessionId", "admin", 30000);
+        userTokenManager.signIn("test2", "sessionId", "admin", 30000).subscribe();
 
-        Assert.assertTrue(userTokenManager.getByToken("test2").isNormal());
+        Assert.assertTrue(userTokenManager.getByToken("test2").block().isNormal());
 
-        Assert.assertTrue(userTokenManager.getByToken("test").isOffline());
+        Assert.assertTrue(userTokenManager.getByToken("test").block().isOffline());
 
     }
 

+ 15 - 54
hsweb-authorization/hsweb-authorization-basic/pom.xml

@@ -19,25 +19,39 @@
             <artifactId>hsweb-authorization-api</artifactId>
             <version>${project.version}</version>
         </dependency>
+
         <dependency>
             <groupId>org.hswebframework</groupId>
             <artifactId>hsweb-expands-script</artifactId>
         </dependency>
+
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-aop</artifactId>
         </dependency>
 
+        <dependency>
+            <groupId>org.hswebframework.web</groupId>
+            <artifactId>hsweb-access-logging-api</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-configuration-processor</artifactId>
             <optional>true</optional>
         </dependency>
+
         <dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-webmvc</artifactId>
         </dependency>
 
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-webflux</artifactId>
+        </dependency>
+
         <dependency>
             <groupId>commons-beanutils</groupId>
             <artifactId>commons-beanutils</artifactId>
@@ -47,64 +61,11 @@
             <artifactId>hsweb-easy-orm-rdb</artifactId>
         </dependency>
 
-        <dependency>
-            <groupId>org.hswebframework.web</groupId>
-            <artifactId>hsweb-spring-boot-starter</artifactId>
-            <version>${project.version}</version>
-            <scope>test</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.hswebframework.web</groupId>
-            <artifactId>hsweb-tests</artifactId>
-            <version>${project.version}</version>
-            <scope>test</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>com.alibaba</groupId>
-            <artifactId>druid</artifactId>
-            <version>1.0.26</version>
-            <scope>test</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>com.h2database</groupId>
-            <artifactId>h2</artifactId>
-            <scope>test</scope>
-        </dependency>
-
-        <dependency>
-            <groupId>org.hswebframework.web</groupId>
-            <artifactId>hsweb-commons-controller</artifactId>
-            <version>${project.version}</version>
-        </dependency>
         <dependency>
             <groupId>javax.servlet</groupId>
             <artifactId>javax.servlet-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.hswebframework.web</groupId>
-            <artifactId>hsweb-commons-entity</artifactId>
-            <version>${project.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>junit</groupId>
-            <artifactId>junit</artifactId>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.redisson</groupId>
-            <artifactId>redisson</artifactId>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.mockito</groupId>
-            <artifactId>mockito-all</artifactId>
-            <version>1.10.19</version>
-            <scope>test</scope>
         </dependency>
+
     </dependencies>
 
 </project>

+ 6 - 6
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/aop/AopAuthorizingController.java

@@ -2,7 +2,8 @@ package org.hswebframework.web.authorization.basic.aop;
 
 import lombok.extern.slf4j.Slf4j;
 import org.aopalliance.intercept.MethodInterceptor;
-import org.hswebframework.web.AopUtils;
+import org.hswebframework.web.aop.MethodInterceptorContext;
+import org.hswebframework.web.aop.MethodInterceptorHolder;
 import org.hswebframework.web.authorization.Authentication;
 import org.hswebframework.web.authorization.annotation.Authorize;
 import org.hswebframework.web.authorization.basic.handler.AuthorizingHandler;
@@ -11,8 +12,7 @@ import org.hswebframework.web.authorization.define.AuthorizeDefinitionInitialize
 import org.hswebframework.web.authorization.define.AuthorizingContext;
 import org.hswebframework.web.authorization.define.Phased;
 import org.hswebframework.web.authorization.exception.UnAuthorizedException;
-import org.hswebframework.web.boost.aop.context.MethodInterceptorContext;
-import org.hswebframework.web.boost.aop.context.MethodInterceptorHolder;
+import org.hswebframework.web.utils.AnnotationUtils;
 import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.CommandLineRunner;
@@ -112,9 +112,9 @@ public class AopAuthorizingController extends StaticMethodMatcherPointcutAdvisor
 
     @Override
     public boolean matches(Method method, Class<?> aClass) {
-        boolean support = AopUtils.findAnnotation(aClass, Controller.class) != null
-                || AopUtils.findAnnotation(aClass, RestController.class) != null
-                || AopUtils.findAnnotation(aClass, method, Authorize.class) != null;
+        boolean support = AnnotationUtils.findAnnotation(aClass, Controller.class) != null
+                || AnnotationUtils.findAnnotation(aClass, RestController.class) != null
+                || AnnotationUtils.findAnnotation(aClass, method, Authorize.class) != null;
 
         if (support && autoParse) {
             defaultParser.parse(aClass, method);

+ 2 - 2
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/aop/AopMethodAuthorizeDefinitionCustomizerParser.java

@@ -1,7 +1,7 @@
 package org.hswebframework.web.authorization.basic.aop;
 
+import org.hswebframework.web.aop.MethodInterceptorContext;
 import org.hswebframework.web.authorization.define.AuthorizeDefinition;
-import org.hswebframework.web.boost.aop.context.MethodInterceptorContext;
 
 import java.lang.reflect.Method;
 
@@ -11,5 +11,5 @@ import java.lang.reflect.Method;
  * @author zhouhao
  */
 public interface AopMethodAuthorizeDefinitionCustomizerParser {
-    AuthorizeDefinition parse(Class target, Method method,MethodInterceptorContext context);
+    AuthorizeDefinition parse(Class target, Method method, MethodInterceptorContext context);
 }

+ 1 - 1
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/aop/AopMethodAuthorizeDefinitionParser.java

@@ -1,7 +1,7 @@
 package org.hswebframework.web.authorization.basic.aop;
 
+import org.hswebframework.web.aop.MethodInterceptorContext;
 import org.hswebframework.web.authorization.define.AuthorizeDefinition;
-import org.hswebframework.web.boost.aop.context.MethodInterceptorContext;
 
 import java.lang.reflect.Method;
 import java.util.List;

+ 7 - 7
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/aop/DefaultAopMethodAuthorizeDefinitionParser.java

@@ -1,14 +1,14 @@
 package org.hswebframework.web.authorization.basic.aop;
 
 import lombok.extern.slf4j.Slf4j;
-import org.hswebframework.web.AopUtils;
+import org.hswebframework.web.aop.MethodInterceptorContext;
 import org.hswebframework.web.authorization.annotation.Authorize;
 import org.hswebframework.web.authorization.annotation.RequiresDataAccess;
 import org.hswebframework.web.authorization.annotation.RequiresExpression;
 import org.hswebframework.web.authorization.basic.define.DefaultBasicAuthorizeDefinition;
 import org.hswebframework.web.authorization.basic.define.EmptyAuthorizeDefinition;
 import org.hswebframework.web.authorization.define.AuthorizeDefinition;
-import org.hswebframework.web.boost.aop.context.MethodInterceptorContext;
+import org.hswebframework.web.utils.AnnotationUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.util.ClassUtils;
 import org.springframework.util.CollectionUtils;
@@ -71,14 +71,14 @@ public class DefaultAopMethodAuthorizeDefinitionParser implements AopMethodAutho
                 return definition;
             }
         }
-        Authorize classAuth = AopUtils.findAnnotation(target, Authorize.class);
-        Authorize methodAuth = AopUtils.findMethodAnnotation(target, method, Authorize.class);
+        Authorize classAuth = AnnotationUtils.findAnnotation(target, Authorize.class);
+        Authorize methodAuth = AnnotationUtils.findMethodAnnotation(target, method, Authorize.class);
 
-        RequiresDataAccess classDataAccess = AopUtils.findAnnotation(target, RequiresDataAccess.class);
+        RequiresDataAccess classDataAccess = AnnotationUtils.findAnnotation(target, RequiresDataAccess.class);
 
-        RequiresDataAccess methodDataAccess = AopUtils.findMethodAnnotation(target, method, RequiresDataAccess.class);
+        RequiresDataAccess methodDataAccess = AnnotationUtils.findMethodAnnotation(target, method, RequiresDataAccess.class);
 
-        RequiresExpression expression = AopUtils.findAnnotation(target, RequiresExpression.class);
+        RequiresExpression expression = AnnotationUtils.findAnnotation(target, RequiresExpression.class);
 
         if (classAuth == null && methodAuth == null && classDataAccess == null && methodDataAccess == null && expression == null) {
             cache.put(key, EmptyAuthorizeDefinition.instance);

+ 0 - 7
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/configuration/AuthorizingHandlerAutoConfiguration.java

@@ -10,13 +10,11 @@ import org.hswebframework.web.authorization.basic.handler.UserAllowPermissionHan
 import org.hswebframework.web.authorization.basic.handler.access.DefaultDataAccessController;
 import org.hswebframework.web.authorization.basic.twofactor.TwoFactorHandlerInterceptorAdapter;
 import org.hswebframework.web.authorization.basic.web.*;
-import org.hswebframework.web.authorization.basic.web.session.UserTokenAutoExpiredListener;
 import org.hswebframework.web.authorization.token.UserTokenManager;
 import org.hswebframework.web.authorization.twofactor.TwoFactorValidatorManager;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.config.BeanPostProcessor;
 import org.springframework.boot.autoconfigure.condition.*;
-import org.springframework.boot.context.properties.ConfigurationProperties;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.core.Ordered;
@@ -108,11 +106,6 @@ public class AuthorizingHandlerAutoConfiguration {
         return new UserOnSignOut(userTokenManager);
     }
 
-    @Bean
-    public UserTokenAutoExpiredListener userTokenAutoExpiredListener(UserTokenManager userTokenManager) {
-        return new UserTokenAutoExpiredListener(userTokenManager);
-    }
-
     @Bean
     public AuthorizationController authorizationController() {
         return new AuthorizationController();

+ 5 - 2
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/configuration/BasicAuthorizationTokenParser.java

@@ -9,6 +9,7 @@ import org.hswebframework.web.authorization.basic.web.UserTokenForTypeParser;
 import org.hswebframework.web.authorization.simple.PlainTextUsernamePasswordAuthenticationRequest;
 import org.hswebframework.web.authorization.token.UserToken;
 import org.hswebframework.web.authorization.token.UserTokenManager;
+import reactor.core.publisher.Mono;
 
 import javax.servlet.http.HttpServletRequest;
 
@@ -42,7 +43,7 @@ public class BasicAuthorizationTokenParser implements UserTokenForTypeParser {
         }
         try {
             String usernameAndPassword = new String(Base64.decodeBase64(authorization));
-            UserToken token = userTokenManager.getByToken(usernameAndPassword);
+            UserToken token = userTokenManager.getByToken(usernameAndPassword).blockOptional().orElse(null);
             if (token != null && token.isNormal()) {
                 return new ParsedToken() {
                     @Override
@@ -58,7 +59,9 @@ public class BasicAuthorizationTokenParser implements UserTokenForTypeParser {
             }
             if (usernameAndPassword.contains(":")) {
                 String[] arr = usernameAndPassword.split("[:]");
-                Authentication authentication = authenticationManager.authenticate(new PlainTextUsernamePasswordAuthenticationRequest(arr[0], arr[1]));
+                Authentication authentication = authenticationManager
+                        .authenticate(Mono.just(new PlainTextUsernamePasswordAuthenticationRequest(arr[0], arr[1])))
+                        .blockOptional().orElse(null);
                 if (authentication != null) {
                     return new AuthorizedToken() {
                         @Override

+ 18 - 23
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/embed/EmbedAuthenticationManager.java

@@ -8,14 +8,15 @@ import org.hswebframework.web.authorization.AuthenticationRequest;
 import org.hswebframework.web.authorization.builder.DataAccessConfigBuilderFactory;
 import org.hswebframework.web.authorization.simple.PlainTextUsernamePasswordAuthenticationRequest;
 import org.hswebframework.web.authorization.simple.builder.SimpleDataAccessConfigBuilderFactory;
-import org.hswebframework.web.validate.ValidationException;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.context.properties.ConfigurationProperties;
 import org.springframework.core.Ordered;
 import org.springframework.core.annotation.Order;
 import org.springframework.util.StringUtils;
+import reactor.core.publisher.Mono;
 
 import javax.annotation.PostConstruct;
+import javax.validation.ValidationException;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -46,7 +47,7 @@ public class EmbedAuthenticationManager implements AuthenticationManager {
                 for (Map<String, Object> objectMap : permissionInfo.getDataAccesses()) {
                     for (Map.Entry<String, Object> stringObjectEntry : objectMap.entrySet()) {
                         if (stringObjectEntry.getValue() instanceof Map) {
-                            Map mapVal = ((Map) stringObjectEntry.getValue());
+                            Map<?, ?> mapVal = ((Map) stringObjectEntry.getValue());
                             boolean maybeIsList = mapVal.keySet().stream().allMatch(org.hswebframework.utils.StringUtils::isInt);
                             if (maybeIsList) {
                                 stringObjectEntry.setValue(mapVal.values());
@@ -60,33 +61,27 @@ public class EmbedAuthenticationManager implements AuthenticationManager {
     }
 
     @Override
-    public Authentication authenticate(AuthenticationRequest request) {
-        if (request instanceof PlainTextUsernamePasswordAuthenticationRequest) {
-            return sync(users.values().stream()
-                    .filter(user ->
-                            ((PlainTextUsernamePasswordAuthenticationRequest) request).getUsername().equals(user.getUsername())
-                                    && ((PlainTextUsernamePasswordAuthenticationRequest) request).getPassword().equals(user.getPassword()))
-                    .findFirst()
-                    .map(properties -> authentications.get(properties.getId()))
-                    .orElseThrow(() -> new ValidationException("用户不存在")));
-        }
+    public Mono<Authentication> authenticate(Mono<AuthenticationRequest> request) {
+        return request.filter(r -> r instanceof PlainTextUsernamePasswordAuthenticationRequest)
+                .map(PlainTextUsernamePasswordAuthenticationRequest.class::cast)
+                .map(pwdReq -> users.values()
+                        .stream()
+                        .filter(user ->
+                                pwdReq.getUsername().equals(user.getUsername())
+                                        && pwdReq.getPassword().equals(user.getPassword()))
+                        .findFirst()
+                        .map(EmbedAuthenticationProperties::getId)
+                        .map(authentications::get)
+                        .orElseThrow(() -> new ValidationException("用户不存在")));
 
-        throw new UnsupportedOperationException("不支持的授权类型:" + request);
-
-    }
-
-    @Override
-    public Authentication getByUserId(String userId) {
-        return authentications.get(userId);
     }
 
     @Override
-    public Authentication sync(Authentication authentication) {
-        authentications.put(authentication.getUser().getId(), authentication);
-        return authentication;
+    public Mono<Authentication> getByUserId(String userId) {
+        return Mono.just(authentications.get(userId));
     }
 
     void addAuthentication(Authentication authentication) {
-        sync(authentication);
+        authentications.put(authentication.getUser().getId(), authentication);
     }
 }

+ 1 - 1
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/DefaultAuthorizingHandler.java

@@ -4,6 +4,7 @@ import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.commons.collections.CollectionUtils;
 import org.hswebframework.expands.script.engine.DynamicScriptEngine;
 import org.hswebframework.expands.script.engine.DynamicScriptEngineFactory;
+import org.hswebframework.web.aop.MethodInterceptorContext;
 import org.hswebframework.web.authorization.Authentication;
 import org.hswebframework.web.authorization.Permission;
 import org.hswebframework.web.authorization.Role;
@@ -15,7 +16,6 @@ import org.hswebframework.web.authorization.define.AuthorizingContext;
 import org.hswebframework.web.authorization.define.HandleType;
 import org.hswebframework.web.authorization.exception.AccessDenyException;
 import org.hswebframework.web.authorization.events.AuthorizingHandleBeforeEvent;
-import org.hswebframework.web.boost.aop.context.MethodInterceptorContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;

+ 0 - 1
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/access/DefaultDataAccessController.java

@@ -31,7 +31,6 @@ public final class DefaultDataAccessController implements DataAccessController {
         }
         this.parent = parent;
         addHandler(new CustomDataAccessHandler()).
-                addHandler(new OwnCreatedDataAccessHandler()).
                 addHandler(new ScriptDataAccessHandler()).
                 addHandler(new FieldFilterDataAccessHandler()).
                 addHandler(new FieldScopeDataAccessHandler());

+ 6 - 13
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/access/FieldFilterDataAccessHandler.java

@@ -1,23 +1,16 @@
 package org.hswebframework.web.authorization.basic.handler.access;
 
 import org.apache.commons.beanutils.BeanUtilsBean;
+import org.hswebframework.ezorm.core.param.QueryParam;
 import org.hswebframework.web.authorization.Permission;
 import org.hswebframework.web.authorization.access.DataAccessConfig;
 import org.hswebframework.web.authorization.access.DataAccessHandler;
 import org.hswebframework.web.authorization.access.FieldFilterDataAccessConfig;
 import org.hswebframework.web.authorization.define.AuthorizingContext;
 import org.hswebframework.web.authorization.define.Phased;
-import org.hswebframework.web.commons.entity.Entity;
-import org.hswebframework.web.commons.entity.param.QueryParamEntity;
-import org.hswebframework.web.commons.model.Model;
-import org.hswebframework.web.controller.message.ResponseMessage;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.springframework.http.ResponseEntity;
-
-import java.lang.reflect.InvocationTargetException;
 import java.util.Collection;
-import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
@@ -63,10 +56,10 @@ public class FieldFilterDataAccessHandler implements DataAccessHandler {
     protected boolean doUpdateAccess(FieldFilterDataAccessConfig accesses, AuthorizingContext params) {
         Map<String, Object> paramsMap = params.getParamContext().getParams();
 
-        Object supportParam = paramsMap.size() == 0 ?
+        Object supportParam = paramsMap.size() == 1 ?
                 paramsMap.values().iterator().next() :
                 paramsMap.values().stream()
-                        .filter(param -> (param instanceof Entity) || (param instanceof Model) || (param instanceof Map))
+                       // .filter(param -> (param instanceof Entity) || (param instanceof Model) || (param instanceof Map))
                         .findAny()
                         .orElse(null);
         if (null != supportParam) {
@@ -89,10 +82,10 @@ public class FieldFilterDataAccessHandler implements DataAccessHandler {
     @SuppressWarnings("all")
     protected boolean doQueryAccess(FieldFilterDataAccessConfig access, AuthorizingContext context) {
         if (context.getDefinition().getDataAccessDefinition().getPhased() == Phased.before) {
-            QueryParamEntity entity = context.getParamContext().getParams()
+            QueryParam entity = context.getParamContext().getParams()
                     .values().stream()
-                    .filter(QueryParamEntity.class::isInstance)
-                    .map(QueryParamEntity.class::cast)
+                    .filter(QueryParam.class::isInstance)
+                    .map(QueryParam.class::cast)
                     .findAny().orElse(null);
             if (entity == null) {
                 logger.warn("try validate query access, but query entity is null or not instance of org.hswebframework.web.commons.entity.Entity");

+ 20 - 22
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/access/FieldScopeDataAccessHandler.java

@@ -2,6 +2,7 @@ package org.hswebframework.web.authorization.basic.handler.access;
 
 import org.apache.commons.beanutils.BeanUtilsBean;
 import org.apache.commons.beanutils.PropertyUtilsBean;
+import org.hswebframework.ezorm.core.param.QueryParam;
 import org.hswebframework.ezorm.core.param.Term;
 import org.hswebframework.ezorm.core.param.TermType;
 import org.hswebframework.web.authorization.Permission;
@@ -10,13 +11,10 @@ import org.hswebframework.web.authorization.access.DataAccessHandler;
 import org.hswebframework.web.authorization.access.FieldScopeDataAccessConfig;
 import org.hswebframework.web.authorization.define.AuthorizingContext;
 import org.hswebframework.web.authorization.define.Phased;
-import org.hswebframework.web.commons.entity.param.QueryParamEntity;
-import org.hswebframework.web.controller.QueryController;
-import org.hswebframework.web.service.QueryService;
+
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import java.lang.reflect.InvocationTargetException;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
@@ -63,21 +61,21 @@ public class FieldScopeDataAccessHandler implements DataAccessHandler {
         Object id = context.getParamContext().<String>getParameter(context.getDefinition().getDataAccessDefinition().getIdParameterName()).orElse(null);
         //通过QueryController获取QueryService
         //然后调用selectByPk 查询旧的数据,进行对比
-        if (controller instanceof QueryController) {
-            QueryService queryService = (QueryService) ((QueryController) controller).getService();
-            Object oldData = queryService.selectByPk(id);
-            if (oldData != null) {
-                try {
-                    Object value = propertyUtilsBean.getProperty(oldData, access.getField());
-                    return access.getScope().contains(value);
-                } catch (Exception e) {
-                    logger.error("can't read property {}", access.getField(), e);
-                }
-                return false;
-            }
-        } else {
-            logger.warn("controller is not instanceof QueryController");
-        }
+//        if (controller instanceof QueryController) {
+//            QueryService queryService = (QueryService) ((QueryController) controller).getService();
+//            Object oldData = queryService.selectByPk(id);
+//            if (oldData != null) {
+//                try {
+//                    Object value = propertyUtilsBean.getProperty(oldData, access.getField());
+//                    return access.getScope().contains(value);
+//                } catch (Exception e) {
+//                    logger.error("can't read property {}", access.getField(), e);
+//                }
+//                return false;
+//            }
+//        } else {
+//            logger.warn("controller is not instanceof QueryController");
+//        }
         return true;
     }
 
@@ -85,10 +83,10 @@ public class FieldScopeDataAccessHandler implements DataAccessHandler {
     @SuppressWarnings("all")
     protected boolean doQueryAccess(FieldScopeDataAccessConfig access, AuthorizingContext context) {
         if (context.getDefinition().getDataAccessDefinition().getPhased() == Phased.before) {
-            QueryParamEntity entity = context.getParamContext().getParams()
+            QueryParam entity = context.getParamContext().getParams()
                     .values().stream()
-                    .filter(QueryParamEntity.class::isInstance)
-                    .map(QueryParamEntity.class::cast)
+                    .filter(QueryParam.class::isInstance)
+                    .map(QueryParam.class::cast)
                     .findAny().orElse(null);
             if (entity == null) {
                 logger.warn("try validate query access, but query entity is null or not instance of org.hswebframework.web.commons.entity.Entity");

+ 6 - 8
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/access/InvokeResultUtils.java

@@ -1,7 +1,5 @@
 package org.hswebframework.web.authorization.basic.handler.access;
 
-import org.hswebframework.web.commons.entity.PagerResult;
-import org.hswebframework.web.controller.message.ResponseMessage;
 import org.springframework.http.ResponseEntity;
 
 public class InvokeResultUtils {
@@ -9,12 +7,12 @@ public class InvokeResultUtils {
         if (result instanceof ResponseEntity) {
             result = ((ResponseEntity) result).getBody();
         }
-        if (result instanceof ResponseMessage) {
-            result = ((ResponseMessage) result).getResult();
-        }
-        if (result instanceof PagerResult) {
-            result = ((PagerResult) result).getData();
-        }
+//        if (result instanceof ResponseMessage) {
+//            result = ((ResponseMessage) result).getResult();
+//        }
+//        if (result instanceof PagerResult) {
+//            result = ((PagerResult) result).getData();
+//        }
         return result;
     }
 }

+ 0 - 156
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/handler/access/OwnCreatedDataAccessHandler.java

@@ -1,156 +0,0 @@
-package org.hswebframework.web.authorization.basic.handler.access;
-
-import org.apache.commons.beanutils.PropertyUtils;
-import org.apache.commons.beanutils.PropertyUtilsBean;
-import org.hswebframework.ezorm.core.param.Term;
-import org.hswebframework.utils.ClassUtils;
-import org.hswebframework.web.authorization.Permission;
-import org.hswebframework.web.authorization.access.DataAccessConfig;
-import org.hswebframework.web.authorization.access.DataAccessHandler;
-import org.hswebframework.web.authorization.access.OwnCreatedDataAccessConfig;
-import org.hswebframework.web.authorization.define.AuthorizingContext;
-import org.hswebframework.web.authorization.define.Phased;
-import org.hswebframework.web.commons.entity.Entity;
-import org.hswebframework.web.commons.entity.RecordCreationEntity;
-import org.hswebframework.web.commons.entity.param.QueryParamEntity;
-import org.hswebframework.web.controller.QueryController;
-import org.hswebframework.web.service.QueryService;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.stream.Collectors;
-
-/**
- * @author zhouhao
- */
-public class OwnCreatedDataAccessHandler implements DataAccessHandler {
-    private static final Logger logger = LoggerFactory.getLogger(OwnCreatedDataAccessHandler.class);
-
-    @Override
-    public boolean isSupport(DataAccessConfig access) {
-        return access instanceof OwnCreatedDataAccessConfig;
-    }
-
-    @Override
-    public boolean handle(DataAccessConfig access, AuthorizingContext context) {
-        OwnCreatedDataAccessConfig own = ((OwnCreatedDataAccessConfig) access);
-        Object controller = context.getParamContext().getTarget();
-        if (controller != null) {
-            switch (access.getAction()) {
-                case Permission.ACTION_GET:
-                case Permission.ACTION_QUERY:
-                    return doQueryAccess(own, context);
-
-                case Permission.ACTION_DELETE:
-                case Permission.ACTION_UPDATE:
-                    return doRWAccess(own, context, controller);
-                case Permission.ACTION_ADD:
-                    //put creator_id to result
-                    return putCreatorId(own, context);
-                default:
-                    logger.warn("action: {} not support now!", access.getAction());
-            }
-        } else {
-            logger.warn("target is null!");
-        }
-        return true;
-    }
-
-    public boolean putCreatorId(OwnCreatedDataAccessConfig access, AuthorizingContext context) {
-        RecordCreationEntity entity = context.getParamContext().getParams()
-                .values().stream()
-                .filter(RecordCreationEntity.class::isInstance)
-                .map(RecordCreationEntity.class::cast)
-                .findAny().orElse(null);
-        if (entity != null) {
-            entity.setCreatorId(context.getAuthentication().getUser().getId());
-        } else {
-            logger.warn("try put creatorId property,but not found any RecordCreationEntity!");
-        }
-        return true;
-    }
-
-    @SuppressWarnings("unchecked")
-    protected boolean doRWAccess(OwnCreatedDataAccessConfig access, AuthorizingContext context, Object controller) {
-        //获取注解
-        Object id = context.getParamContext().<String>getParameter(context.getDefinition().getDataAccessDefinition().getIdParameterName()).orElse(null);
-        //通过QueryController获取QueryService
-        //然后调用selectByPk 查询旧的数据,进行对比
-        if (controller instanceof QueryController) {
-            //判断是否满足条件(泛型为 RecordCreationEntity)
-            Class entityType = ClassUtils.getGenericType(controller.getClass(), 0);
-            if (ClassUtils.instanceOf(entityType, RecordCreationEntity.class)) {
-                QueryService<RecordCreationEntity, Object> queryService =
-                        ((QueryController<RecordCreationEntity, Object, Entity>) controller).getService();
-                RecordCreationEntity oldData = queryService.selectByPk(id);
-                if (oldData != null && !context.getAuthentication().getUser().getId().equals(oldData.getCreatorId())) {
-                    return false;
-                }
-            }
-        }
-        return true;
-    }
-
-    protected boolean doQueryAccess(OwnCreatedDataAccessConfig access, AuthorizingContext context) {
-        String userId = context.getAuthentication().getUser().getId();
-
-        if (context.getDefinition().getDataAccessDefinition().getPhased() == Phased.before) {
-            Entity entity = context.getParamContext().getParams()
-                    .values().stream()
-                    .filter(Entity.class::isInstance)
-                    .map(Entity.class::cast)
-                    .findAny().orElse(null);
-            if (entity == null) {
-                logger.warn("try validate query access, but query entity is null or not instance of org.hswebframework.web.commons.entity.Entity");
-                return true;
-            }
-            if (entity instanceof QueryParamEntity) {
-                QueryParamEntity queryParamEntity = ((QueryParamEntity) entity);
-                //重构查询条件
-                //如: 旧的条件为 where name =? or name = ?
-                //重构后为: where creatorId=? and (name = ? or name = ?)
-                List<Term> oldParam = queryParamEntity.getTerms();
-                //清空旧的查询条件
-                queryParamEntity.setTerms(new ArrayList<>());
-                //添加一个查询条件
-                queryParamEntity
-                        .where(RecordCreationEntity.creatorId, userId)
-                        //客户端提交的参数 作为嵌套参数
-                        .nest().setTerms(oldParam);
-            } else if (entity instanceof RecordCreationEntity) {
-                ((RecordCreationEntity) entity).setCreatorId(userId);
-            } else {
-                logger.warn("try validate query access,but entity not support, QueryParamEntity and RecordCreationEntity support now!");
-            }
-        } else {
-            Object result = InvokeResultUtils.convertRealResult(context.getParamContext().getInvokeResult());
-            return matchCreatorId(result, userId);
-        }
-        return true;
-    }
-
-    @SuppressWarnings("all")
-    protected boolean matchCreatorId(Object result, String userId) {
-        if (null == result) {
-            return true;
-        }
-        if (result instanceof RecordCreationEntity) {
-            return userId.equals(((RecordCreationEntity) result).getCreatorId());
-        } else if (result instanceof Collection) {
-            Collection<?> collection = ((Collection) result);
-            //删掉不能访问的对象
-            collection.removeAll(collection.stream().filter((Object o) -> !matchCreatorId(o, userId)).collect(Collectors.toList()));
-        } else {
-            try {
-                return userId.equals(PropertyUtils.getProperty(result, "creatorId"));
-            } catch (Exception ignore) {
-            }
-        }
-        return true;
-    }
-}

+ 44 - 51
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/AuthorizationController.java

@@ -21,26 +21,23 @@ import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import io.swagger.annotations.ApiParam;
 import lombok.SneakyThrows;
-import org.hswebframework.web.WebUtil;
 import org.hswebframework.web.authorization.Authentication;
 import org.hswebframework.web.authorization.AuthenticationManager;
 import org.hswebframework.web.authorization.annotation.Authorize;
 import org.hswebframework.web.authorization.events.*;
 import org.hswebframework.web.authorization.simple.PlainTextUsernamePasswordAuthenticationRequest;
-import org.hswebframework.web.controller.message.ResponseMessage;
 import org.hswebframework.web.logging.AccessLogger;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.ApplicationEventPublisher;
 import org.springframework.http.MediaType;
 import org.springframework.util.Assert;
 import org.springframework.web.bind.annotation.*;
+import reactor.core.publisher.Mono;
 
 import javax.servlet.http.HttpServletRequest;
 import java.util.Map;
 import java.util.function.Function;
 
-import static org.hswebframework.web.controller.message.ResponseMessage.ok;
-
 /**
  * @author zhouhao
  */
@@ -56,71 +53,67 @@ public class AuthorizationController {
     @Autowired
     private ApplicationEventPublisher eventPublisher;
 
-    @GetMapping({"/login-out", "/sign-out", "/exit"})
-    @Authorize
-    @ApiOperation("退出当前登录")
-    public ResponseMessage exit(@ApiParam(hidden = true) Authentication authentication) {
-        eventPublisher.publishEvent(new AuthorizationExitEvent(authentication));
-        return ok();
-    }
-
     @GetMapping("/me")
     @Authorize
     @ApiOperation("当前登录用户权限信息")
-    public ResponseMessage<Authentication> me(@ApiParam(hidden = true) Authentication authentication) {
-        return ok(authentication);
+    public Mono<Authentication> me(@ApiParam(hidden = true) Mono<Authentication> authentication) {
+        return authentication;
     }
 
-
     @PostMapping(value = "/login", consumes = MediaType.APPLICATION_JSON_VALUE)
     @ApiOperation("用户名密码登录,json方式")
-    public ResponseMessage<Map<String, Object>> authorize(@ApiParam(example = "{\"username\":\"admin\",\"password\":\"admin\"}")
-                                                          @RequestBody Map<String, String> parameter) {
-
-
-        return doLogin(parameter.get("username"), parameter.get("password"), parameter);
+    public Mono<Map<String, Object>> authorizeByJson(@ApiParam(example = "{\"username\":\"admin\",\"password\":\"admin\"}")
+                                                     @RequestBody Mono<Map<String, Object>> parameter) {
+        return doLogin(parameter);
     }
 
     @PostMapping(value = "/login", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
     @ApiOperation("用户名密码登录,参数方式")
-    public ResponseMessage<Map<String, Object>> authorize(@RequestParam @ApiParam("用户名") String username,
-                                                          @RequestParam @ApiParam("密码") String password,
-                                                          @ApiParam(hidden = true) HttpServletRequest request) {
+    public Mono<Map<String, Object>> authorizeByUrlEncoded(@ApiParam(hidden = true) @RequestParam Mono<Map<String, Object>> parameter) {
 
-        return doLogin(username, password, WebUtil.getParameters(request));
+        return doLogin(parameter);
     }
 
     /**
      * <img src="https://raw.githubusercontent.com/hs-web/hsweb-framework/3.0.x/hsweb-authorization/hsweb-authorization-basic/img/autz-flow.png">
      */
     @SneakyThrows
-    protected ResponseMessage<Map<String, Object>> doLogin(String username, String password, Map<String, ?> parameter) {
-        Assert.hasLength(username, "用户名不能为空");
-        Assert.hasLength(password, "密码不能为空");
-
-        AuthorizationFailedEvent.Reason reason = AuthorizationFailedEvent.Reason.OTHER;
-        Function<String, Object> parameterGetter = parameter::get;
-        try {
-            AuthorizationDecodeEvent decodeEvent = new AuthorizationDecodeEvent(username, password, parameterGetter);
-            eventPublisher.publishEvent(decodeEvent);
-            username = decodeEvent.getUsername();
-            password = decodeEvent.getPassword();
-            AuthorizationBeforeEvent beforeEvent = new AuthorizationBeforeEvent(username, password, parameterGetter);
-            eventPublisher.publishEvent(beforeEvent);
-            // 验证通过
-            Authentication authentication = authenticationManager.authenticate(new PlainTextUsernamePasswordAuthenticationRequest(username, password));
-
-            //触发授权成功事件
-            AuthorizationSuccessEvent event = new AuthorizationSuccessEvent(authentication, parameterGetter);
-            event.getResult().put("userId", authentication.getUser().getId());
-            eventPublisher.publishEvent(event);
-            return ok(event.getResult());
-        } catch (Exception e) {
-            AuthorizationFailedEvent failedEvent = new AuthorizationFailedEvent(username, password, parameterGetter, reason);
-            failedEvent.setException(e);
-            eventPublisher.publishEvent(failedEvent);
-            throw failedEvent.getException();
-        }
+    protected Mono<Map<String, Object>> doLogin(Mono<Map<String, Object>> parameter) {
+
+        return parameter.flatMap(parameters -> {
+            String username = (String) parameters.get("username");
+            String password = (String) parameters.get("password");
+
+            Assert.hasLength(username, "用户名不能为空");
+            Assert.hasLength(password, "密码不能为空");
+
+            AuthorizationFailedEvent.Reason reason = AuthorizationFailedEvent.Reason.OTHER;
+            Function<String, Object> parameterGetter = parameters::get;
+            try {
+                AuthorizationDecodeEvent decodeEvent = new AuthorizationDecodeEvent(username, password, parameterGetter);
+                eventPublisher.publishEvent(decodeEvent);
+                username = decodeEvent.getUsername();
+                password = decodeEvent.getPassword();
+                AuthorizationBeforeEvent beforeEvent = new AuthorizationBeforeEvent(username, password, parameterGetter);
+                eventPublisher.publishEvent(beforeEvent);
+                // 验证通过
+                return authenticationManager
+                        .authenticate(Mono.just(new PlainTextUsernamePasswordAuthenticationRequest(username, password)))
+                        .map(auth -> {
+                            //触发授权成功事件
+                            AuthorizationSuccessEvent event = new AuthorizationSuccessEvent(auth, parameterGetter);
+                            event.getResult().put("userId", auth.getUser().getId());
+                            eventPublisher.publishEvent(event);
+                            return event.getResult();
+                        });
+            } catch (Exception e) {
+                AuthorizationFailedEvent failedEvent = new AuthorizationFailedEvent(username, password, parameterGetter, reason);
+                failedEvent.setException(e);
+                eventPublisher.publishEvent(failedEvent);
+                return Mono.error(failedEvent.getException());
+            }
+        });
+
     }
 
 }

+ 2 - 2
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/SessionIdUserTokenGenerator.java

@@ -1,7 +1,7 @@
 package org.hswebframework.web.authorization.basic.web;
 
-import org.hswebframework.web.WebUtil;
 import org.hswebframework.web.authorization.Authentication;
+import org.hswebframework.web.utils.WebUtils;
 
 import javax.servlet.http.HttpServletRequest;
 import java.io.Serializable;
@@ -22,7 +22,7 @@ public class SessionIdUserTokenGenerator implements UserTokenGenerator, Serializ
 
     @Override
     public GeneratedToken generate(Authentication authentication) {
-        HttpServletRequest request = WebUtil.getHttpServletRequest();
+        HttpServletRequest request = WebUtils.getHttpServletRequest();
         if (null == request) {
             throw new UnsupportedOperationException();
         }

+ 1 - 1
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/SessionIdUserTokenParser.java

@@ -30,7 +30,7 @@ public class SessionIdUserTokenParser implements UserTokenParser {
 
         if (session != null) {
             String sessionId = session.getId();
-            UserToken token = userTokenManager.getByToken(sessionId);
+            UserToken token = userTokenManager.getByToken(sessionId).block();
             long interval = session.getMaxInactiveInterval();
             //当前已登录token已失效但是session未失效
             if (token != null && token.isExpired()) {

+ 43 - 48
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/UserTokenController.java

@@ -6,18 +6,17 @@ import org.hswebframework.web.authorization.Authentication;
 import org.hswebframework.web.authorization.AuthenticationManager;
 import org.hswebframework.web.authorization.Permission;
 import org.hswebframework.web.authorization.annotation.Authorize;
+import org.hswebframework.web.authorization.exception.UnAuthorizedException;
 import org.hswebframework.web.authorization.token.TokenState;
 import org.hswebframework.web.authorization.token.UserToken;
-import org.hswebframework.web.authorization.token.UserTokenHolder;
 import org.hswebframework.web.authorization.token.UserTokenManager;
-import org.hswebframework.web.controller.message.ResponseMessage;
+import org.hswebframework.web.context.ContextKey;
+import org.hswebframework.web.context.ContextUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Lazy;
 import org.springframework.web.bind.annotation.*;
-
-import java.util.List;
-
-import static org.hswebframework.web.controller.message.ResponseMessage.ok;
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
 
 @RestController
 @RequestMapping
@@ -43,124 +42,120 @@ public class UserTokenController {
     @GetMapping("/user-token/reset")
     @Authorize(merge = false)
     @ApiOperation("重置当前用户的令牌")
-    public ResponseMessage<Boolean> resetToken() {
-        UserToken token = UserTokenHolder.currentToken();
-        if (token != null) {
-            userTokenManager.signOutByToken(token.getToken());
-        }
-        return ok(true);
+    public Mono<Boolean> resetToken() {
+        return ContextUtils.reactiveContext()
+                .map(context -> context.get(ContextKey.of(UserToken.class)).orElseThrow(UnAuthorizedException::new))
+                .flatMap(token -> userTokenManager.signOutByToken(token.getToken()))
+                .thenReturn(true);
     }
 
     @PutMapping("/user-token/check")
     @ApiOperation("检查所有已过期的token并移除")
     @Authorize(action = Permission.ACTION_UPDATE)
-    public ResponseMessage<Boolean> checkExpiredToken() {
-        userTokenManager.checkExpiredToken();
-        return ok(true);
+    public Mono<Boolean> checkExpiredToken() {
+        return userTokenManager
+                .checkExpiredToken()
+                .thenReturn(true);
     }
 
     @GetMapping("/user-token/token/{token}")
     @ApiOperation("根据token获取令牌信息")
     @Authorize(action = Permission.ACTION_GET)
-    public ResponseMessage<UserToken> getByToken(@PathVariable String token) {
-        return ok(userTokenManager.getByToken(token));
+    public Mono<UserToken> getByToken(@PathVariable String token) {
+        return userTokenManager.getByToken(token);
     }
 
     @GetMapping("/user-token/user/{userId}")
     @ApiOperation("根据用户ID获取全部令牌信息")
     @Authorize(action = Permission.ACTION_GET)
-    public ResponseMessage<List<UserToken>> getByUserId(@PathVariable String userId) {
-        return ok(userTokenManager.getByUserId(userId));
+    public Flux<UserToken> getByUserId(@PathVariable String userId) {
+        return userTokenManager.getByUserId(userId);
     }
 
     @GetMapping("/user-token/user/{userId}/logged")
     @ApiOperation("根据用户ID判断用户是否已经登录")
     @Authorize(action = Permission.ACTION_GET)
-    public ResponseMessage<Boolean> userIsLoggedIn(@PathVariable String userId) {
-        return ok(userTokenManager.userIsLoggedIn(userId));
+    public Mono<Boolean> userIsLoggedIn(@PathVariable String userId) {
+        return userTokenManager.userIsLoggedIn(userId);
     }
 
     @GetMapping("/user-token/token/{token}/logged")
     @ApiOperation("根据令牌判断用户是否已经登录")
     @Authorize(action = Permission.ACTION_GET)
-    public ResponseMessage<Boolean> tokenIsLoggedIn(@PathVariable String token) {
-        return ok(userTokenManager.tokenIsLoggedIn(token));
+    public Mono<Boolean> tokenIsLoggedIn(@PathVariable String token) {
+        return userTokenManager.tokenIsLoggedIn(token);
     }
 
     @GetMapping("/user-token/user/total")
     @ApiOperation("获取当前已经登录的用户数量")
     @Authorize
-    public ResponseMessage<Long> totalUser() {
-        return ok(userTokenManager.totalUser());
+    public Mono<Integer> totalUser() {
+        return userTokenManager.totalUser();
     }
 
     @GetMapping("/user-token/token/total")
     @ApiOperation("获取当前已经登录的令牌数量")
     @Authorize
-    public ResponseMessage<Long> totalToken() {
-        return ok(userTokenManager.totalToken());
+    public Mono<Integer> totalToken() {
+        return userTokenManager.totalToken();
     }
 
     @GetMapping("/user-token")
     @ApiOperation("获取全部用户令牌信息")
     @Authorize(action = Permission.ACTION_GET)
-    public ResponseMessage<List<UserToken>> allLoggedUser() {
-        return ok(userTokenManager.allLoggedUser());
+    public Flux<UserToken> allLoggedUser() {
+        return userTokenManager.allLoggedUser();
     }
 
     @DeleteMapping("/user-token/user/{userId}")
     @ApiOperation("根据用户id将用户踢下线")
     @Authorize(action = Permission.ACTION_UPDATE)
-    public ResponseMessage<Void> signOutByUserId(@PathVariable String userId) {
-        userTokenManager.signOutByUserId(userId);
-        return ok();
+    public Mono<Void> signOutByUserId(@PathVariable String userId) {
+        return userTokenManager.signOutByUserId(userId);
     }
 
     @DeleteMapping("/user-token/token/{token}")
     @ApiOperation("根据令牌将用户踢下线")
     @Authorize(action = Permission.ACTION_UPDATE)
-    public ResponseMessage<Void> signOutByToken(@PathVariable String token) {
-        userTokenManager.signOutByToken(token);
-        return ok();
+    public Mono<Void> signOutByToken(@PathVariable String token) {
+        return userTokenManager.signOutByToken(token);
+
     }
 
     @PutMapping("/user-token/user/{userId}/{state}")
     @ApiOperation("根据用户id更新用户令牌状态")
     @Authorize(action = Permission.ACTION_UPDATE)
-    public ResponseMessage<Void> changeUserState(@PathVariable String userId, @PathVariable TokenState state) {
+    public Mono<Void> changeUserState(@PathVariable String userId, @PathVariable TokenState state) {
 
-        userTokenManager.changeUserState(userId, state);
-        return ok();
+        return userTokenManager.changeUserState(userId, state);
     }
 
     @PutMapping("/user-token/token/{token}/{state}")
     @ApiOperation("根据令牌更新用户令牌状态")
     @Authorize(action = Permission.ACTION_UPDATE)
-    public ResponseMessage<Void> changeTokenState(@PathVariable String token, @PathVariable TokenState state) {
-        userTokenManager.changeTokenState(token, state);
-        return ok();
+    public Mono<Void> changeTokenState(@PathVariable String token, @PathVariable TokenState state) {
+        return userTokenManager.changeTokenState(token, state);
     }
 
     @PostMapping("/user-token/{token}/{type}/{userId}/{maxInactiveInterval}")
     @ApiOperation("将用户设置为登录")
     @Authorize(action = Permission.ACTION_ADD)
-    public ResponseMessage<UserToken> signIn(@PathVariable String token, @PathVariable String type, @PathVariable String userId, @PathVariable long maxInactiveInterval) {
-        return ok(userTokenManager.signIn(token, type, userId, maxInactiveInterval));
+    public Mono<UserToken> signIn(@PathVariable String token, @PathVariable String type, @PathVariable String userId, @PathVariable long maxInactiveInterval) {
+        return userTokenManager.signIn(token, type, userId, maxInactiveInterval);
     }
 
     @GetMapping("/user-token/{token}/touch")
     @ApiOperation("更新token有效期")
     @Authorize(action = Permission.ACTION_UPDATE)
-    public ResponseMessage<Void> touch(@PathVariable String token) {
-        userTokenManager.touch(token);
-        return ok();
+    public Mono<Void> touch(@PathVariable String token) {
+        return userTokenManager.touch(token);
     }
 
     @GetMapping("/user-auth/{userId}")
     @ApiOperation("根据用户id获取用户的权限信息")
     @Authorize(action = Permission.ACTION_GET)
-    public ResponseMessage<Authentication> userAuthInfo(@PathVariable String userId) {
-        return ok(authenticationManager.getByUserId(userId));
+    public Mono<Authentication> userAuthInfo(@PathVariable String userId) {
+        return authenticationManager.getByUserId(userId);
     }
 
 }

+ 8 - 7
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/WebUserTokenInterceptor.java

@@ -30,10 +30,10 @@ public class WebUserTokenInterceptor extends HandlerInterceptorAdapter {
 
     private boolean enableBasicAuthorization = false;
 
-    public WebUserTokenInterceptor(UserTokenManager userTokenManager, List<UserTokenParser> userTokenParser,AopMethodAuthorizeDefinitionParser definitionParser) {
+    public WebUserTokenInterceptor(UserTokenManager userTokenManager, List<UserTokenParser> userTokenParser, AopMethodAuthorizeDefinitionParser definitionParser) {
         this.userTokenManager = userTokenManager;
         this.userTokenParser = userTokenParser;
-        this.parser=definitionParser;
+        this.parser = definitionParser;
 
         enableBasicAuthorization = userTokenParser.stream()
                 .filter(UserTokenForTypeParser.class::isInstance)
@@ -60,18 +60,19 @@ public class WebUserTokenInterceptor extends HandlerInterceptorAdapter {
         for (ParsedToken parsedToken : tokens) {
             UserToken userToken = null;
             String token = parsedToken.getToken();
-            if (userTokenManager.tokenIsLoggedIn(token)) {
-                userToken = userTokenManager.getByToken(token);
+            if (userTokenManager.tokenIsLoggedIn(token).blockOptional().orElse(false)) {
+                userToken = userTokenManager.getByToken(token).blockOptional().orElse(null);
             }
             if ((userToken == null || userToken.isExpired()) && parsedToken instanceof AuthorizedToken) {
                 //先踢出旧token
-                userTokenManager.signOutByToken(token);
+                userTokenManager.signOutByToken(token).subscribe();
 
                 userToken = userTokenManager
-                        .signIn(parsedToken.getToken(), parsedToken.getType(), ((AuthorizedToken) parsedToken).getUserId(), ((AuthorizedToken) parsedToken).getMaxInactiveInterval());
+                        .signIn(parsedToken.getToken(), parsedToken.getType(), ((AuthorizedToken) parsedToken).getUserId(), ((AuthorizedToken) parsedToken).getMaxInactiveInterval())
+                        .block();
             }
             if (null != userToken) {
-                userTokenManager.touch(token);
+                userTokenManager.touch(token).subscribe();
                 UserTokenHolder.setCurrent(userToken);
             }
         }

+ 0 - 26
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/web/session/UserTokenAutoExpiredListener.java

@@ -1,26 +0,0 @@
-package org.hswebframework.web.authorization.basic.web.session;
-
-import org.hswebframework.web.authorization.token.UserTokenManager;
-
-import javax.servlet.http.HttpSessionEvent;
-import javax.servlet.http.HttpSessionListener;
-
-public class UserTokenAutoExpiredListener implements HttpSessionListener {
-
-    private UserTokenManager userTokenManager;
-
-    public UserTokenAutoExpiredListener(UserTokenManager userTokenManager) {
-        this.userTokenManager = userTokenManager;
-    }
-
-    @Override
-    public void sessionCreated(HttpSessionEvent se) {
-
-    }
-
-    @Override
-    public void sessionDestroyed(HttpSessionEvent se) {
-        String sessionId = se.getSession().getId();
-        userTokenManager.signOutByToken(sessionId);
-    }
-}

+ 0 - 229
hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/AuthorizeTests.java

@@ -1,229 +0,0 @@
-package org.hswebframework.web.authorization;
-
-import com.alibaba.fastjson.JSON;
-import com.alibaba.fastjson.serializer.SerializerFeature;
-import lombok.*;
-import org.hswebframework.web.authorization.annotation.Authorize;
-import org.hswebframework.web.authorization.annotation.RequiresDataAccess;
-import org.hswebframework.web.authorization.basic.aop.AopMethodAuthorizeDefinitionParser;
-import org.hswebframework.web.authorization.basic.aop.DefaultAopMethodAuthorizeDefinitionParser;
-import org.hswebframework.web.authorization.basic.handler.DefaultAuthorizingHandler;
-import org.hswebframework.web.authorization.basic.handler.access.DefaultDataAccessController;
-import org.hswebframework.web.authorization.define.AuthorizeDefinition;
-import org.hswebframework.web.authorization.define.AuthorizingContext;
-import org.hswebframework.web.authorization.define.Phased;
-import org.hswebframework.web.authorization.simple.*;
-import org.hswebframework.web.boost.aop.context.MethodInterceptorContext;
-import org.hswebframework.web.commons.entity.param.QueryParamEntity;
-import org.hswebframework.web.controller.message.ResponseMessage;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-
-import java.util.*;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-@RunWith(MockitoJUnitRunner.class)
-public class AuthorizeTests {
-
-    @Mock
-    private MethodInterceptorContext queryById;
-    @Mock
-    private MethodInterceptorContext dynamicQuery;
-
-    @Mock
-    private Authentication authentication;
-
-    AopMethodAuthorizeDefinitionParser parser = new DefaultAopMethodAuthorizeDefinitionParser();
-
-    @Before
-    public void init() throws NoSuchMethodException {
-        TestClass testClass = new TestClass();
-
-        QueryParamEntity entity = new QueryParamEntity();
-        entity.where("id", "admin").or("name", "admin");
-
-        User user = User.builder().name("test").id("test")
-                .orgId("400000")
-                .password("admin").salt("1234").build();
-
-        //mock MethodInterceptorContext
-        when(queryById.getMethod()).thenReturn(TestClass.class.getMethod("queryById", String.class));
-        when(queryById.getTarget()).thenReturn(testClass);
-        when(queryById.getParameter("id")).thenReturn(Optional.of("test"));
-        when(queryById.getParams()).thenReturn(Collections.singletonMap("id", "test"));
-        when(queryById.getInvokeResult()).thenReturn(ResponseMessage.ok(user));
-
-
-        //mock MethodInterceptorContext
-        when(dynamicQuery.getMethod()).thenReturn(TestClass.class.getMethod("dynamicQuery", QueryParamEntity.class));
-        when(dynamicQuery.getTarget()).thenReturn(testClass);
-        when(dynamicQuery.getParams()).thenReturn(Collections.singletonMap("paramEntity", entity));
-        when(dynamicQuery.getParameter("paramEntity")).thenReturn(Optional.of(entity));
-
-
-        //过滤字段
-        AbstractDataAccessConfig fieldFilter = new SimpleFieldFilterDataAccessConfig("password", "salt");
-        fieldFilter.setAction(Permission.ACTION_QUERY);
-
-        SimpleFiledScopeDataAccessConfig filedScope = new SimpleFiledScopeDataAccessConfig();
-        filedScope.setAction(Permission.ACTION_QUERY);
-        filedScope.setField("orgId");
-        filedScope.setScopeType("org");
-        filedScope.setScope(Collections.singleton("400000"));
-
-        //mock authentication
-        when(authentication.getUser()).thenReturn(SimpleUser.builder().id("admin").name("admin").build());
-        when(authentication.getPermissions()).thenReturn(Arrays.asList(SimplePermission.builder()
-                .id("test")
-                .dataAccesses(new HashSet<>(Arrays.asList(fieldFilter, filedScope)))
-
-                .actions(new HashSet<>(Arrays.asList(Permission.ACTION_QUERY, Permission.ACTION_UPDATE))).build()));
-
-    }
-
-
-    @Test
-    public void testParseAuthorizeDefinition() {
-        AuthorizeDefinition definition = parser.parse(queryById.getTarget().getClass(), queryById.getMethod());
-
-        Assert.assertNotNull(definition);
-        Assert.assertEquals(definition.getPermissions().size(), 1);
-        Assert.assertEquals(definition.getPermissions().iterator().next(), "test");
-        Assert.assertEquals(definition.getActions().iterator().next(), Permission.ACTION_QUERY);
-    }
-
-    @Test
-    public void testAuthorizingHandler() {
-        DefaultAuthorizingHandler handler = new DefaultAuthorizingHandler();
-
-        AuthorizeDefinition definition = parser.parse(queryById.getTarget().getClass(), queryById.getMethod());
-
-        AuthorizingContext authorizingContext = new AuthorizingContext();
-        authorizingContext.setAuthentication(authentication);
-        authorizingContext.setDefinition(definition);
-        authorizingContext.setParamContext(queryById);
-
-        handler.handRBAC(authorizingContext);
-
-
-    }
-
-    /**
-     * 测试数据权限控制s
-     */
-    @Test
-    public void testDynamicQueryDataAccessHandler() {
-
-        DefaultAuthorizingHandler handler = new DefaultAuthorizingHandler();
-        DefaultDataAccessController controller = new DefaultDataAccessController();
-        handler.setDataAccessController(controller);
-
-
-        AuthorizeDefinition definition = parser.parse(dynamicQuery.getTarget().getClass(), dynamicQuery.getMethod());
-
-        //获取到请求参数
-        QueryParamEntity entity = dynamicQuery.<QueryParamEntity>getParameter("paramEntity").orElseThrow(NullPointerException::new);
-        System.out.println(JSON.toJSONString(entity, SerializerFeature.PrettyFormat));
-
-        AuthorizingContext authorizingContext = new AuthorizingContext();
-        authorizingContext.setAuthentication(authentication);
-        authorizingContext.setDefinition(definition);
-        authorizingContext.setParamContext(dynamicQuery);
-
-        handler.handleDataAccess(authorizingContext);
-
-        System.out.println(JSON.toJSONString(entity, SerializerFeature.PrettyFormat));
-
-        Assert.assertTrue(entity.getExcludes().size() == 2);
-        Assert.assertTrue(entity.getTerms().size() == 2);
-        Assert.assertTrue(entity.getTerms().get(1).getTerms().size() == 2);
-    }
-
-    /**
-     * 测试数据权限控制s
-     */
-    @Test
-    public void testGetDataAccessHandler() {
-
-        DefaultAuthorizingHandler handler = new DefaultAuthorizingHandler();
-        DefaultDataAccessController controller = new DefaultDataAccessController();
-        handler.setDataAccessController(controller);
-
-
-        AuthorizeDefinition definition = parser.parse(queryById.getTarget().getClass(), queryById.getMethod());
-
-        //响应结果
-        Object response = queryById.getInvokeResult();
-
-        System.out.println(JSON.toJSONString(response, SerializerFeature.PrettyFormat));
-
-        AuthorizingContext authorizingContext = new AuthorizingContext();
-        authorizingContext.setAuthentication(authentication);
-        authorizingContext.setDefinition(definition);
-        authorizingContext.setParamContext(queryById);
-
-        handler.handleDataAccess(authorizingContext);
-
-        System.out.println(JSON.toJSONString(response, SerializerFeature.PrettyFormat));
-        Assert.assertTrue(response instanceof ResponseMessage);
-        Assert.assertTrue(((User) ((ResponseMessage) response).getResult()).getPassword() == null);
-        Assert.assertTrue(((User) ((ResponseMessage) response).getResult()).getSalt() == null);
-    }
-
-    @Authorize(permission = "test")
-    public static class TestClass implements TestClassSuper {
-
-        public ResponseMessage<User> queryById(String id) {
-            return ResponseMessage.ok();
-        }
-
-        @Authorize(action = Permission.ACTION_QUERY)
-        @RequiresDataAccess
-        public void dynamicQuery(QueryParamEntity paramEntity) {
-            System.out.println(JSON.toJSON(paramEntity));
-        }
-
-    }
-
-    public interface TestClassSuper {
-
-        @Authorize(action = Permission.ACTION_QUERY,
-                phased = Phased.after,
-                dataAccess = @RequiresDataAccess(phased = Phased.after))
-        default ResponseMessage<User> queryById(String id) {
-            return ResponseMessage.ok();
-        }
-
-        @Authorize(action = Permission.ACTION_QUERY)
-        @RequiresDataAccess
-        default void dynamicQuery(QueryParamEntity paramEntity) {
-            System.out.println(JSON.toJSON(paramEntity));
-        }
-
-    }
-
-    @Getter
-    @Setter
-    @Builder
-    @NoArgsConstructor
-    @AllArgsConstructor
-    public static class User {
-        private String id;
-
-        private String name;
-
-        private String password;
-
-        private String salt;
-
-        private String orgId;
-
-    }
-}

+ 0 - 80
hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/RedisUserTokenManagerTests.java

@@ -1,80 +0,0 @@
-package org.hswebframework.web.authorization;
-
-import org.hswebframework.web.authorization.token.*;
-import org.hswebframework.web.id.IDGenerator;
-import org.junit.Assert;
-import org.redisson.Redisson;
-import org.redisson.api.LocalCachedMapOptions;
-import org.redisson.api.RedissonClient;
-import org.redisson.codec.FstCodec;
-import org.redisson.codec.SerializationCodec;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.ConcurrentMap;
-
-public class RedisUserTokenManagerTests {
-
-    static DefaultUserTokenManager userTokenManager;
-
-    static String token = IDGenerator.MD5.generate();
-
-    private static Logger logger = LoggerFactory.getLogger("hsweb.session");
-
-    public static void main(String[] args) throws InterruptedException {
-        RedissonClient client = Redisson.create();
-
-        try {
-            ConcurrentMap<String, SimpleUserToken> repo = client.getMap("hsweb.user-token", new SerializationCodec());
-            ConcurrentMap<String, Set<String>> userRepo = client.getMap("hsweb.user-token-u", new SerializationCodec());
-
-            userTokenManager = new DefaultUserTokenManager(repo, userRepo) {
-                @Override
-                protected Set<String> getUserToken(String userId) {
-                    userRepo.computeIfAbsent(userId,u->new HashSet<>());
-
-                    return client.getSet("hsweb.user-token-"+userId, new SerializationCodec());
-                }
-
-            };
-
-            userTokenManager.setAllopatricLoginMode(AllopatricLoginMode.deny);
-//            userTokenManager=new DefaultUserTokenManager();
-
-
-//            userRepo.clear();
-//            repo.clear();
-//            for (int i = 0; i < 1000; i++) {
-//                userTokenManager.signIn(IDGenerator.MD5.generate(), "sessionId", "admin", 60*3600*1000);
-//            }
-//            userTokenManager.signIn(IDGenerator.MD5.generate(), "sessionId", "admin2", 60*3600*1000);
-
-            testGet();
-            testGetAll();
-            testSignOut();
-
-            testGetAll();
-        } finally {
-            client.shutdown();
-        }
-    }
-    public static void testSignOut(){
-        userTokenManager.signOutByUserId("admin");
-
-    }
-    public static void testGet() {
-        List<UserToken> userToken = userTokenManager.getByUserId("admin");
-        Assert.assertTrue(!userToken.isEmpty());
-    }
-
-    public static void testGetAll() {
-        logger.warn("total user : " + userTokenManager.totalUser());
-        logger.warn("total token : " + userTokenManager.totalToken());
-
-        userTokenManager.allLoggedUser(token -> System.out.println(token.getToken()));
-    }
-}

+ 0 - 16
hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/TestApplication.java

@@ -1,16 +0,0 @@
-package org.hswebframework.web.authorization;
-
-import org.hswebframework.web.authorization.basic.configuration.EnableAopAuthorize;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-import org.springframework.test.context.web.WebAppConfiguration;
-
-/**
- * @author zhouhao
- * @since 3.0.0-RC
- */
-@SpringBootApplication
-@WebAppConfiguration
-@EnableAopAuthorize
-public class TestApplication {
-
-}

+ 0 - 42
hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/basic/embed/EmbedAuthenticationManagerTest.groovy

@@ -1,42 +0,0 @@
-package org.hswebframework.web.authorization.basic.embed
-
-import org.hswebframework.web.authorization.Authentication
-import org.hswebframework.web.authorization.AuthenticationManager
-import org.hswebframework.web.authorization.TestApplication
-import org.hswebframework.web.authorization.simple.PlainTextUsernamePasswordAuthenticationRequest
-import org.springframework.beans.factory.annotation.Autowired
-import org.springframework.boot.test.context.SpringBootTest
-import org.springframework.test.context.ContextConfiguration
-import org.springframework.test.context.web.WebAppConfiguration
-import spock.lang.Specification
-
-/**
- * @author zhouhao
- * @since 3.0.0-RC
- */
-@WebAppConfiguration
-@ContextConfiguration
-@SpringBootTest(classes = [TestApplication.class], properties = ["classpath:application.yml"])
-class EmbedAuthenticationManagerTest extends Specification {
-
-    @Autowired
-    private AuthenticationManager manager;
-
-
-    def "Test"() {
-        setup:
-        Authentication authentication = manager.authenticate(new PlainTextUsernamePasswordAuthenticationRequest("admin", "admin"));
-        expect:
-        authentication != null
-        authentication.getUser() != null
-        authentication.getUser().getName() == "超级管理员"
-        authentication.hasPermission("user-manager", "query")
-        authentication.hasPermission("test", "query")
-        authentication.getPermission("user-manager") != null
-        authentication.hasRole("user")
-        authentication.getPermission("user-manager")
-                .get().findDenyFields("query") != null
-        authentication.getPermission("user-manager")
-                .get().findDenyFields("query").contains("password")
-    }
-}

+ 0 - 24
hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/basic/handler/TestController.java

@@ -1,24 +0,0 @@
-package org.hswebframework.web.authorization.basic.handler;
-
-import org.hswebframework.web.authorization.annotation.Authorize;
-import org.hswebframework.web.controller.message.ResponseMessage;
-
-/**
- * @author zhouhao
- * @since 3.0.1
- */
-public class TestController {
-
-    public ResponseMessage<String> query() {
-        return ResponseMessage.ok();
-    }
-
-    public ResponseMessage<String> update() {
-        return ResponseMessage.ok();
-    }
-
-    public ResponseMessage<String> delete() {
-        return ResponseMessage.ok();
-    }
-
-}

+ 0 - 61
hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/basic/handler/UserAllowPermissionHandlerTest.groovy

@@ -1,61 +0,0 @@
-package org.hswebframework.web.authorization.basic.handler
-
-import org.hswebframework.web.authorization.Authentication
-import org.hswebframework.web.authorization.AuthenticationManager
-import org.hswebframework.web.authorization.TestApplication
-import org.hswebframework.web.authorization.basic.define.EmptyAuthorizeDefinition
-import org.hswebframework.web.authorization.define.AuthorizeDefinition
-import org.hswebframework.web.authorization.define.AuthorizingContext
-import org.hswebframework.web.authorization.define.HandleType
-import org.hswebframework.web.authorization.events.AuthorizingHandleBeforeEvent
-import org.hswebframework.web.authorization.simple.PlainTextUsernamePasswordAuthenticationRequest
-import org.hswebframework.web.boost.aop.context.MethodInterceptorContext
-import org.hswebframework.web.boost.aop.context.MethodInterceptorHolder
-import org.springframework.beans.factory.annotation.Autowired
-import org.springframework.boot.test.context.SpringBootTest
-import org.springframework.test.context.ContextConfiguration
-import org.springframework.test.context.web.WebAppConfiguration
-import spock.lang.Specification
-
-/**
- * @author zhouhao
- * @since 3.0.1
- */
-@WebAppConfiguration
-@ContextConfiguration
-@SpringBootTest(classes = [TestApplication.class], properties = ["classpath:application.yml"])
-class UserAllowPermissionHandlerTest extends Specification {
-
-    @Autowired
-    UserAllowPermissionHandler handler;
-
-    @Autowired
-    private AuthenticationManager manager;
-
-    def createMethodInterceptorContext(TestController controller, String name) {
-        return new MethodInterceptorHolder(
-                "test"
-                , TestController.class.getMethod(name)
-                , controller
-                , new HashMap<String, Object>())
-                .createParamContext()
-    }
-
-    def "Test"() {
-        setup:
-        def authentication = manager.authenticate(new PlainTextUsernamePasswordAuthenticationRequest("admin", "admin"));
-        def definition = EmptyAuthorizeDefinition.instance;
-        def controller = new TestController();
-        def context = createMethodInterceptorContext(controller, "query");
-        def authorizingContext = new AuthorizingContext(
-                authentication: authentication
-                , definition: definition
-                , paramContext: context);
-        def event = new AuthorizingHandleBeforeEvent(authorizingContext, HandleType.RBAC);
-        handler.handEvent(event);
-        expect:
-        authentication != null
-        event.isAllow()
-
-    }
-}

+ 0 - 160
hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/full/FullFunctionTest.groovy

@@ -1,160 +0,0 @@
-package org.hswebframework.web.authorization.full
-
-import com.alibaba.fastjson.JSON
-import org.hswebframework.web.authorization.AuthenticationManager
-import org.hswebframework.web.authorization.TestApplication
-import org.springframework.beans.factory.annotation.Autowired
-import org.springframework.boot.test.context.SpringBootTest
-import org.springframework.context.ConfigurableApplicationContext
-import org.springframework.http.MediaType
-import org.springframework.test.context.ContextConfiguration
-import org.springframework.test.context.web.WebAppConfiguration
-import org.springframework.test.web.servlet.MockMvc
-import org.springframework.test.web.servlet.setup.MockMvcBuilders
-import spock.lang.Shared
-import spock.lang.Specification
-import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*
-import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
-
-/**
- * 完整功能测试
- * @author zhouhao
- * @since 3.0.2
- */
-@WebAppConfiguration
-@ContextConfiguration
-@SpringBootTest(classes = [TestApplication.class], properties = ["classpath:application.yml"])
-class FullFunctionTest extends Specification {
-
-    @Autowired
-    private ConfigurableApplicationContext context;
-
-    @Shared
-    private MockMvc mockMvc;
-
-    @Autowired
-    private AuthenticationManager authenticationManager;
-
-    void setup() {
-        mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
-    }
-
-    def doLogin(String username, String password) {
-        return JSON.parseObject(mockMvc.perform(post("/authorize/login")
-                .contentType(MediaType.APPLICATION_JSON)
-                .content("""{"token_type":"test-token","username":"${username}","password":"${password}"}"""))
-                .andExpect(status().is(200))
-                .andReturn()
-                .getResponse()
-                .getContentAsString())
-                .getJSONObject("result").getString("token")
-    }
-
-
-    def "测试双重验证"() {
-        given: "登录"
-        def token = doLogin("admin", "admin")
-        when: "登录成功"
-        token != null
-        then: "调用双重验证接口"
-        mockMvc.perform(get("/test/two-factor")
-                .header("token", token))
-                .andExpect(status().is(403))
-                .andReturn()
-                .getResponse()
-                .getContentAsString()
-        def resp = mockMvc.perform(get("/test/two-factor")
-                .header("token", token)
-                .param("verifyCode", "test"))
-                .andExpect(status().is(200))
-                .andReturn()
-                .getResponse()
-                .getContentAsString()
-        expect:
-        resp != null
-    }
-
-    def "测试查询"() {
-        given: "登录"
-        def token = doLogin("admin", "admin")
-        when: "登录成功"
-        token != null
-        then: "进行查询"
-        def resp = mockMvc.perform(get("/test")
-                .header("token", token)//登录返回的token
-                .param("terms[0].column", "name")
-                .param("terms[0].value", "test"))
-                .andExpect(status().is(200))
-                .andReturn()
-                .getResponse()
-                .getContentAsString()
-        def result = JSON.parseObject(resp).getJSONObject("result");
-        expect: "权限控制成功"
-        result.getJSONArray("excludes") != null
-        //与application.yml中配置的数据权限一致
-        result.getJSONArray("excludes").getString(0) == "password"
-        result.getJSONArray("terms") != null
-        !result.getJSONArray("terms").isEmpty()
-    }
-
-    def "测试修改"() {
-        given: "登录"
-        def token = doLogin("admin", "admin")
-        when: "登录成功"
-        token != null
-        then: "进行修改数据"
-        def resp = mockMvc.perform(put("/test")
-                .header("token", token)//登录返回的token
-                .contentType(MediaType.APPLICATION_JSON)
-                .content("""{"id":"test","name":"testName"}"""))
-                .andExpect(status().is(200))
-                .andReturn()
-                .getResponse()
-                .getContentAsString()
-        def result = JSON.parseObject(resp).getJSONObject("result");
-        println result
-        expect: "权限控制成功,name属性被修改为null"
-        //与application.yml中配置的数据权限一致
-        result.getString("name") == null
-        result.getString("id") != null
-    }
-
-    def "测试新增"() {
-        given: "登录"
-        def token = doLogin("admin", "admin")
-        when: "登录成功"
-        token != null
-        then: "进行新增数据"
-        def resp = mockMvc.perform(post("/test")
-                .header("token", token)//登录返回的token
-                .contentType(MediaType.APPLICATION_JSON)
-                .content("""{"id":"test","name":"testName"}"""))
-                .andExpect(status().is(200))
-                .andReturn()
-                .getResponse()
-                .getContentAsString()
-        def result = JSON.parseObject(resp).getJSONObject("result");
-        expect: "权限控制成功,id不能进行insert操作"
-        //与application.yml中配置的数据权限一致
-        result.getString("id") == null
-        result.getString("name") != null
-    }
-
-    def "测试删除"() {
-        given: "登录"
-        def token = doLogin("admin", "admin")
-        when: "登录成功"
-        token != null
-        then: "进行新增数据"
-        def resp = mockMvc.perform(delete("/test/{id}", "test")
-                .header("token", token))//登录返回的token
-                .andReturn()
-                .getResponse()
-                .getContentAsString()
-        def status = JSON.parseObject(resp).getInteger("status");
-        expect:
-        "权限控制成功,不能进行delete操作"
-        //与application.yml中配置的数据权限一致
-        status == 403
-    }
-}

+ 0 - 39
hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/full/controller/CrudController.java

@@ -1,39 +0,0 @@
-package org.hswebframework.web.authorization.full.controller;
-
-import org.hswebframework.web.authorization.Permission;
-import org.hswebframework.web.authorization.annotation.Authorize;
-import org.hswebframework.web.authorization.annotation.RequiresDataAccess;
-import org.hswebframework.web.commons.entity.param.QueryParamEntity;
-import org.hswebframework.web.controller.message.ResponseMessage;
-import org.springframework.web.bind.annotation.*;
-
-/**
- * @author zhouhao
- * @since 3.0.2
- */
-public interface CrudController<T> {
-
-    @GetMapping
-    @Authorize(action = Permission.ACTION_QUERY, dataAccess = @RequiresDataAccess)
-    default ResponseMessage<QueryParamEntity> query(QueryParamEntity param) {
-        return ResponseMessage.ok(param);
-    }
-
-    @PutMapping
-    @Authorize(action = Permission.ACTION_UPDATE, dataAccess = @RequiresDataAccess)
-    default ResponseMessage<T> update(@RequestBody T entity) {
-        return ResponseMessage.ok(entity);
-    }
-
-    @PostMapping
-    @Authorize(action = Permission.ACTION_ADD, dataAccess = @RequiresDataAccess)
-    default ResponseMessage<T> insert(@RequestBody T entity) {
-        return ResponseMessage.ok(entity);
-    }
-
-    @DeleteMapping("/{id}")
-    @Authorize(action = Permission.ACTION_DELETE, dataAccess = @RequiresDataAccess)
-    ResponseMessage<T> delete(@PathVariable String id);
-
-
-}

+ 0 - 32
hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/full/controller/TestCrudController.java

@@ -1,32 +0,0 @@
-package org.hswebframework.web.authorization.full.controller;
-
-import org.hswebframework.web.authorization.annotation.Authorize;
-import org.hswebframework.web.authorization.annotation.TwoFactor;
-import org.hswebframework.web.authorization.full.controller.model.TestModel;
-import org.hswebframework.web.controller.message.ResponseMessage;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
-
-/**
- * @author zhouhao
- * @since 3.0.2
- */
-@RequestMapping("/test")
-@RestController
-@Authorize(permission = "test")
-public class TestCrudController implements CrudController<TestModel> {
-
-    @Override
-    public ResponseMessage<TestModel> delete(@PathVariable String id) {
-
-        return ResponseMessage.ok();
-    }
-
-    @TwoFactor(value = "test", provider = "test")
-    @GetMapping("/two-factor")
-    public ResponseMessage<String> testTowFactor() {
-        return ResponseMessage.ok();
-    }
-}

+ 0 - 39
hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/full/controller/TestTwoFactorValidatorProvider.java

@@ -1,39 +0,0 @@
-package org.hswebframework.web.authorization.full.controller;
-
-import org.hswebframework.web.authorization.twofactor.TwoFactorValidator;
-import org.hswebframework.web.authorization.twofactor.TwoFactorValidatorProvider;
-import org.springframework.stereotype.Component;
-
-/**
- * @author zhouhao
- * @since 3.0.4
- */
-@Component
-public class TestTwoFactorValidatorProvider implements TwoFactorValidatorProvider {
-    @Override
-    public String getProvider() {
-        return "test";
-    }
-
-    @Override
-    public TwoFactorValidator createTwoFactorValidator(String userId, String operation) {
-        return new TwoFactorValidator() {
-            boolean success = false;
-
-            @Override
-            public String getProvider() {
-                return "test";
-            }
-
-            @Override
-            public boolean verify(String code, long timeout) {
-                return success = code.equalsIgnoreCase("test");
-            }
-
-            @Override
-            public boolean expired() {
-                return !success;
-            }
-        };
-    }
-}

+ 0 - 21
hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/full/controller/model/TestModel.java

@@ -1,21 +0,0 @@
-package org.hswebframework.web.authorization.full.controller.model;
-
-import lombok.Data;
-import org.hswebframework.web.commons.model.Model;
-
-/**
- * @author zhouhao
- * @since 3.0.2
- */
-@Data
-public class TestModel implements Model {
-    private String id;
-
-    private String name;
-
-    private int age;
-
-    private String orgId;
-
-    private String password;
-}

+ 0 - 68
hsweb-authorization/hsweb-authorization-basic/src/test/groovy/org/hswebframework/web/authorization/full/token/TestTokenGeneratorAndParser.java

@@ -1,68 +0,0 @@
-package org.hswebframework.web.authorization.full.token;
-
-import org.hswebframework.web.authorization.Authentication;
-import org.hswebframework.web.authorization.basic.web.GeneratedToken;
-import org.hswebframework.web.authorization.basic.web.ParsedToken;
-import org.hswebframework.web.authorization.basic.web.UserTokenGenerator;
-import org.hswebframework.web.authorization.basic.web.UserTokenParser;
-import org.hswebframework.web.id.IDGenerator;
-import org.springframework.stereotype.Component;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.Collections;
-import java.util.Map;
-import java.util.Optional;
-
-/**
- * @author zhouhao
- * @since 3.0.2
- */
-@Component
-public class TestTokenGeneratorAndParser implements UserTokenGenerator, UserTokenParser {
-    @Override
-    public String getSupportTokenType() {
-        return "test-token";
-    }
-
-    @Override
-    public GeneratedToken generate(Authentication authentication) {
-        String token = IDGenerator.MD5.generate();
-        return new GeneratedToken() {
-            @Override
-            public Map<String, Object> getResponse() {
-                return Collections.singletonMap("token", token);
-            }
-
-            @Override
-            public String getToken() {
-                return token;
-            }
-
-            @Override
-            public String getType() {
-                return getSupportTokenType();
-            }
-
-            @Override
-            public int getTimeout() {
-                return -1;
-            }
-        };
-    }
-
-    @Override
-    public ParsedToken parseToken(HttpServletRequest request) {
-        return Optional.ofNullable(request.getHeader("token"))
-                .map(token -> new ParsedToken() {
-                    @Override
-                    public String getToken() {
-                        return token;
-                    }
-
-                    @Override
-                    public String getType() {
-                        return getSupportTokenType();
-                    }
-                }).orElse(null);
-    }
-}

+ 0 - 60
hsweb-authorization/hsweb-authorization-basic/src/test/resources/application.yml

@@ -1,60 +0,0 @@
-spring:
-  aop:
-    auto: true
-    proxy-target-class: true
-  datasource:
-    url: jdbc:h2:mem:example-oauth2-client
-    username: sa
-    password:
-    type: com.alibaba.druid.pool.DruidDataSource
-    driver-class-name: org.h2.Driver
-  cache:
-    type: simple
-hsweb:
-  app:
-    name: hsweb-oauth2 客户端示例
-    version: 3.0.0
-  authorize:
-    allows:
-      users:
-        admin: "**.TestController.*"
-    two-factor:
-      enable: true
-  users:
-    admin:
-      name: 超级管理员
-      username: admin
-      password: admin
-      roles: #用户的角色
-      - id: admin
-        name: 管理员
-      - id: user
-        name: 用户
-      permissions-simple:
-        test: query,get
-      permissions:
-      - id: user-manager
-        actions: query,get,update,delete
-        dataAccesses:
-        - action: query
-          type: DENY_FIELDS
-          fields:
-          - password
-          - salt
-      - id: test
-        actions: query,add,update
-        dataAccesses:
-        - action: query
-          type: DENY_FIELDS
-          fields:
-          - password
-        - action: update
-          type: DENY_FIELDS
-          fields:
-          - name
-        - action: add
-          type: DENY_FIELDS
-          fields:
-          - id
-server:
-  port: 8808

+ 0 - 37
hsweb-authorization/hsweb-authorization-jwt/README.md

@@ -1,37 +0,0 @@
-# 简单的jwt权限拓展
-
-登录时,传入参数: token_type=jwt
-```bash
-    $ POST http://localhost:8081/authorize/login?username=admin&password=admin&token_type=jwt
-```
-返回jwt token
-```json
-{
-    "result": {
-        "userId": "f947788cd922f16a9e58727e13e4b806",
-        "token": "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJ0ZXN0IiwiaWF0IjoxNTA0MTYxNDM2LCJzdWIiOiJ7XCJ0b2tlblwiOlwiZDU1MmVjZDgyZGFjY2EwMWJiZWI3ZmMxNmU2NmQ1OTNcIixcInVzZXJJZFwiOlwiZjk0Nzc4OGNkOTIyZjE2YTllNTg3MjdlMTNlNGI4MDZcIn0iLCJleHAiOjE1MDQxNjUwMzZ9.LP7Eb0cqmpbMXBjM7yPM0vZ8T3tDd3Zmme3j-e3HTvs",
-    },
-    "status": 200,
-    "timestamp": 1504161444051
-}
-```
-
-在调用api时,设置http header:
-```bash
-    Authorization: jwt {登录时获取的token}
-```
-
-## 自定义jwt 密钥
-使用base64生成密钥如: 
-```java
-Base64.encodeBase64String("密钥内容".getBytes())
-```
-
-修改application.yml
-```yaml
-hsweb:
-    authorize:
-      jwt:
-        id: your_jwt_id
-        secret: 上一步生成的base64密钥
-```

+ 0 - 42
hsweb-authorization/hsweb-authorization-jwt/pom.xml

@@ -1,42 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-    <parent>
-        <artifactId>hsweb-authorization</artifactId>
-        <groupId>org.hswebframework.web</groupId>
-        <version>4.0.0-SNAPSHOT</version>
-    </parent>
-    <modelVersion>4.0.0</modelVersion>
-
-    <artifactId>hsweb-authorization-jwt</artifactId>
-
-    <description>使用jwt实现简单的token策略</description>
-
-    <dependencies>
-        <dependency>
-            <groupId>org.hswebframework.web</groupId>
-            <artifactId>hsweb-authorization-api</artifactId>
-            <version>${project.version}</version>
-        </dependency>
-
-        <dependency>
-            <groupId>org.hswebframework.web</groupId>
-            <artifactId>hsweb-authorization-basic</artifactId>
-            <version>${project.version}</version>
-        </dependency>
-
-        <!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->
-        <dependency>
-            <groupId>io.jsonwebtoken</groupId>
-            <artifactId>jjwt</artifactId>
-            <version>0.7.0</version>
-        </dependency>
-
-        <dependency>
-            <groupId>javax.servlet</groupId>
-            <artifactId>javax.servlet-api</artifactId>
-            <scope>provided</scope>
-        </dependency>
-    </dependencies>
-</project>

+ 0 - 47
hsweb-authorization/hsweb-authorization-jwt/src/main/java/org/hswebframework/web/authorization/jwt/JwtAuthorizedToken.java

@@ -1,47 +0,0 @@
-package org.hswebframework.web.authorization.jwt;
-
-import org.hswebframework.web.authorization.basic.web.AuthorizedToken;
-
-/**
- *
- * @author zhouhao
- */
-public class JwtAuthorizedToken implements AuthorizedToken {
-
-    public static final String TOKEN_TYPE = "jwt";
-
-    private String token;
-
-    private String userId;
-
-    public JwtAuthorizedToken() {
-    }
-
-    public JwtAuthorizedToken(String token, String userId) {
-        this.token = token;
-        this.userId = userId;
-    }
-
-    @Override
-    public String getToken() {
-        return token;
-    }
-
-    public void setToken(String token) {
-        this.token = token;
-    }
-
-    @Override
-    public String getUserId() {
-        return userId;
-    }
-
-    public void setUserId(String userId) {
-        this.userId = userId;
-    }
-
-    @Override
-    public String getType() {
-        return TOKEN_TYPE;
-    }
-}

+ 0 - 28
hsweb-authorization/hsweb-authorization-jwt/src/main/java/org/hswebframework/web/authorization/jwt/JwtAutoConfiguration.java

@@ -1,28 +0,0 @@
-package org.hswebframework.web.authorization.jwt;
-
-import org.springframework.boot.context.properties.ConfigurationProperties;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-
-/**
- * @author zhouhao
- */
-@Configuration
-public class JwtAutoConfiguration  {
-
-    @Bean
-    @ConfigurationProperties(prefix = "hsweb.authorize.jwt")
-    public JwtConfig jwtConfig(){
-        return new JwtConfig();
-    }
-
-    @Bean
-    public JwtTokenGenerator jwtTokenGenerator(JwtConfig config){
-        return new JwtTokenGenerator(config);
-    }
-
-    @Bean
-    public JwtTokenParser jwtTokenParser(JwtConfig config){
-        return new JwtTokenParser(config);
-    }
-}

+ 0 - 57
hsweb-authorization/hsweb-authorization-jwt/src/main/java/org/hswebframework/web/authorization/jwt/JwtConfig.java

@@ -1,57 +0,0 @@
-package org.hswebframework.web.authorization.jwt;
-
-import org.apache.commons.codec.binary.Base64;
-
-import javax.crypto.SecretKey;
-import javax.crypto.spec.SecretKeySpec;
-
-/**
- * jwt
- */
-public class JwtConfig {
-
-    private String id = "hsweb-jwt";
-
-    private String secret = Base64.encodeBase64String("hsweb.jwt.secret".getBytes());
-
-    private int ttl = 60 * 60 * 1000;
-
-    private int refreshTtl = 12 * 60 * 60 * 1000;
-
-    public String getSecret() {
-        return secret;
-    }
-
-    public void setSecret(String secret) {
-        this.secret = secret;
-    }
-
-    public int getTtl() {
-        return ttl;
-    }
-
-    public void setTtl(int ttl) {
-        this.ttl = ttl;
-    }
-
-    public int getRefreshTtl() {
-        return refreshTtl;
-    }
-
-    public void setRefreshTtl(int refreshTtl) {
-        this.refreshTtl = refreshTtl;
-    }
-
-    public SecretKey generalKey() {
-        byte[] encodedKey = Base64.decodeBase64(secret);
-        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
-    }
-
-    public String getId() {
-        return id;
-    }
-
-    public void setId(String id) {
-        this.id = id;
-    }
-}

+ 0 - 95
hsweb-authorization/hsweb-authorization-jwt/src/main/java/org/hswebframework/web/authorization/jwt/JwtTokenGenerator.java

@@ -1,95 +0,0 @@
-package org.hswebframework.web.authorization.jwt;
-
-import com.alibaba.fastjson.JSON;
-import io.jsonwebtoken.JwtBuilder;
-import io.jsonwebtoken.Jwts;
-import io.jsonwebtoken.SignatureAlgorithm;
-import org.hswebframework.web.authorization.Authentication;
-import org.hswebframework.web.authorization.basic.web.GeneratedToken;
-import org.hswebframework.web.authorization.basic.web.UserTokenGenerator;
-import org.hswebframework.web.id.IDGenerator;
-
-import javax.crypto.SecretKey;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.hswebframework.web.authorization.jwt.JwtAuthorizedToken.TOKEN_TYPE;
-
-public class JwtTokenGenerator implements UserTokenGenerator {
-
-    private JwtConfig jwtConfig;
-
-    public JwtTokenGenerator(JwtConfig jwtConfig) {
-        this.jwtConfig = jwtConfig;
-    }
-
-    @Override
-    public String getSupportTokenType() {
-        return TOKEN_TYPE;
-    }
-
-    private String createToken() {
-        return IDGenerator.MD5.generate();
-    }
-
-    @Override
-    public GeneratedToken generate(Authentication authentication) {
-        String token = createToken();
-        String userId = authentication.getUser().getId();
-
-        String subject = JSON.toJSONString(new JwtAuthorizedToken(token, userId));
-
-        String jwtToken = createJWT(jwtConfig.getId(), subject, jwtConfig.getTtl());
-
-//        String refreshToken = createJWT(jwtConfig.getId(), userId, jwtConfig.getRefreshTtl());
-
-        int timeout = jwtConfig.getTtl();
-
-        return new GeneratedToken() {
-            private static final long serialVersionUID = -4362122360342275321L;
-
-            @Override
-            public Map<String, Object> getResponse() {
-                Map<String, Object> map = new HashMap<>();
-                map.put("token", jwtToken);
-//                map.put("refreshToken", refreshToken);
-                return map;
-            }
-
-            @Override
-            public String getToken() {
-                return token;
-            }
-
-            @Override
-            public String getType() {
-                return TOKEN_TYPE;
-            }
-
-            @Override
-            public int getTimeout() {
-                return timeout;
-            }
-        };
-    }
-
-
-    public String createJWT(String id, String subject, long ttlMillis) {
-        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
-        long nowMillis = System.currentTimeMillis();
-        Date now = new Date(nowMillis);
-        SecretKey key = jwtConfig.generalKey();
-        JwtBuilder builder = Jwts.builder()
-                .setId(id)
-                .setIssuedAt(now)
-                .setSubject(subject)
-                .signWith(signatureAlgorithm, key);
-        if (ttlMillis >= 0) {
-            long expMillis = nowMillis + ttlMillis;
-            Date exp = new Date(expMillis);
-            builder.setExpiration(exp);
-        }
-        return builder.compact();
-    }
-}

+ 0 - 72
hsweb-authorization/hsweb-authorization-jwt/src/main/java/org/hswebframework/web/authorization/jwt/JwtTokenParser.java

@@ -1,72 +0,0 @@
-package org.hswebframework.web.authorization.jwt;
-
-import com.alibaba.fastjson.JSON;
-import io.jsonwebtoken.Claims;
-import io.jsonwebtoken.ExpiredJwtException;
-import io.jsonwebtoken.Jwts;
-import org.hswebframework.web.authorization.basic.web.ParsedToken;
-import org.hswebframework.web.authorization.basic.web.UserTokenParser;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.util.StringUtils;
-
-import javax.crypto.SecretKey;
-import javax.servlet.http.HttpServletRequest;
-
-/**
- * @see UserTokenParser
- * @since 3.0
- */
-public class JwtTokenParser implements UserTokenParser {
-
-    private static final Logger logger = LoggerFactory.getLogger(JwtTokenParser.class);
-
-    private JwtConfig jwtConfig;
-
-    public JwtTokenParser(JwtConfig jwtConfig) {
-        this.jwtConfig = jwtConfig;
-    }
-
-    @Override
-    public ParsedToken parseToken(HttpServletRequest request) {
-        String headerToken = request.getHeader("jwt-token");
-        if (StringUtils.isEmpty(headerToken)) {
-            headerToken = request.getHeader("Authorization");
-            if (!StringUtils.isEmpty(headerToken)) {
-                if (headerToken.contains(" ")) {
-                    String[] auth = headerToken.split("[ ]");
-                    if (auth[0].equalsIgnoreCase("jwt") || auth[0].equalsIgnoreCase("Bearer")) {
-                        headerToken = auth[1];
-                    }else{
-                        return null;
-                    }
-                }
-            }
-        }
-        if (headerToken != null) {
-            try {
-                Claims claims = parseJWT(headerToken);
-                if (claims.getExpiration().getTime() <= System.currentTimeMillis()) {
-
-                    return null;
-                }
-                return JSON.parseObject(claims.getSubject(), JwtAuthorizedToken.class);
-            } catch (ExpiredJwtException e) {
-                return null;
-            } catch (Exception e) {
-                logger.debug("parse token [{}] error", headerToken, e);
-                return null;
-            }
-        }
-        return null;
-    }
-
-    public Claims parseJWT(String jwt) {
-        SecretKey key = jwtConfig.generalKey();
-        return Jwts.parser()
-                .setSigningKey(key)
-                .parseClaimsJws(jwt).getBody();
-    }
-
-
-}

+ 0 - 3
hsweb-authorization/hsweb-authorization-jwt/src/main/resources/META-INF/spring.factories

@@ -1,3 +0,0 @@
-# Auto Configure
-org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
-org.hswebframework.web.authorization.jwt.JwtAutoConfiguration

+ 0 - 7
hsweb-authorization/hsweb-authorization-oauth2/README.md

@@ -1,7 +0,0 @@
-# oauth2 认证模块
-
-# 模块说明
-| 模块       | 说明          |   进度 |
-| ------------- |:-------------:| ----|
-|[hsweb-authorization-oauth2-client](hsweb-authorization-oauth2-client)|OAuth2 客户端API| 90%|
-|[hsweb-authorization-oauth2-server](hsweb-authorization-oauth2-server)|OAuth2 服务端API| 90%|

+ 0 - 76
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/pom.xml

@@ -1,76 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-  ~  Copyright 2019 http://www.hswebframework.org
-  ~
-  ~  Licensed under the Apache License, Version 2.0 (the "License");
-  ~  you may not use this file except in compliance with the License.
-  ~  You may obtain a copy of the License at
-  ~
-  ~        http://www.apache.org/licenses/LICENSE-2.0
-  ~
-  ~  Unless required by applicable law or agreed to in writing, software
-  ~  distributed under the License is distributed on an "AS IS" BASIS,
-  ~  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-  ~  See the License for the specific language governing permissions and
-  ~  limitations under the License.
-  ~
-  ~
-  -->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-    <parent>
-        <artifactId>hsweb-authorization-oauth2</artifactId>
-        <groupId>org.hswebframework.web</groupId>
-        <version>4.0.0-SNAPSHOT</version>
-    </parent>
-    <modelVersion>4.0.0</modelVersion>
-
-    <artifactId>hsweb-authorization-oauth2-auth-server</artifactId>
-
-    <description>OAuth2授权服务器实现</description>
-
-    <dependencies>
-        <dependency>
-            <groupId>org.hswebframework.web</groupId>
-            <artifactId>hsweb-commons-entity</artifactId>
-            <version>${project.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.hswebframework.web</groupId>
-            <artifactId>hsweb-authorization-oauth2-core</artifactId>
-            <version>${project.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>javax.servlet</groupId>
-            <artifactId>javax.servlet-api</artifactId>
-            <optional>true</optional>
-        </dependency>
-        <dependency>
-            <groupId>org.hswebframework.web</groupId>
-            <artifactId>hsweb-commons-utils</artifactId>
-            <version>${project.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.hswebframework.web</groupId>
-            <artifactId>hsweb-concurrent-lock-api</artifactId>
-            <version>${project.version}</version>
-        </dependency>
-
-        <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-starter</artifactId>
-            <optional>true</optional>
-        </dependency>
-        <dependency>
-            <groupId>org.springframework</groupId>
-            <artifactId>spring-webmvc</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.hswebframework.web</groupId>
-            <artifactId>hsweb-commons-controller</artifactId>
-            <version>${project.version}</version>
-        </dependency>
-    </dependencies>
-</project>

+ 0 - 31
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/AuthorizationService.java

@@ -1,31 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server;
-
-/**
- * 授权服务
- * @author zhouhao
- * @see org.hswebframework.web.authorization.oauth2.server.support.code.AuthorizationCodeGranter
- * @see org.hswebframework.web.authorization.oauth2.server.support.client.ClientCredentialGranter
- * @see org.hswebframework.web.authorization.oauth2.server.support.refresh.RefreshTokenGranter
- * @see org.hswebframework.web.authorization.oauth2.server.support.implicit.ImplicitGranter
- * @see org.hswebframework.web.authorization.oauth2.server.support.password.PasswordGranter
- */
-public interface AuthorizationService {
-}

+ 0 - 74
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/OAuth2AccessToken.java

@@ -1,74 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server;
-
-import org.hibernate.validator.constraints.NotBlank;
-
-import javax.validation.constraints.NotNull;
-import java.io.Serializable;
-import java.util.Set;
-
-/**
- * @author zhouhao
- */
-public interface OAuth2AccessToken extends Serializable {
-
-    @NotBlank
-    String getClientId();
-
-    void setClientId(String clientId);
-
-    @NotBlank
-    String getAccessToken();
-
-    void setAccessToken(String accessToken);
-
-    @NotBlank
-    String getRefreshToken();
-
-    void setRefreshToken(String refreshToken);
-
-    @NotNull
-    Long getCreateTime();
-
-    void setCreateTime(Long createTime);
-
-    Long getUpdateTime();
-
-    void setUpdateTime(Long updateTime);
-
-    @NotNull
-    String getOwnerId();
-
-    void setOwnerId(String ownerId);
-
-    @NotNull
-    Integer getExpiresIn();
-
-    void setExpiresIn(Integer expiresIn);
-
-    Set<String> getScope();
-
-    void setScope(Set<String> scope);
-
-    @NotNull
-    String getGrantType();
-
-    void setGrantType(String grantType);
-}

+ 0 - 29
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/OAuth2Authorization.java

@@ -1,29 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server;
-
-/**
- * TODO 完成注释
- *
- * @author zhouhao
- */
-public class OAuth2Authorization {
-    private String userId;
-
-}

+ 0 - 32
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/OAuth2ServerAutoConfiguration.java

@@ -1,32 +0,0 @@
-package org.hswebframework.web.authorization.oauth2.server;
-
-import org.hswebframework.web.authorization.oauth2.server.exception.GrantTokenException;
-import org.hswebframework.web.controller.message.ResponseMessage;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.http.HttpStatus;
-import org.springframework.web.bind.annotation.ExceptionHandler;
-import org.springframework.web.bind.annotation.ResponseStatus;
-import org.springframework.web.bind.annotation.RestControllerAdvice;
-@Configuration
-public class OAuth2ServerAutoConfiguration{
-
-    @Bean
-    public OAuth2ServerErrorControllerAdvice oAuth2ServerErrorControllerAdvice(){
-        return new OAuth2ServerErrorControllerAdvice();
-    }
-    /**
-     * @author zhouhao
-     */
-    @RestControllerAdvice
-    public static class OAuth2ServerErrorControllerAdvice {
-
-        @ExceptionHandler(GrantTokenException.class)
-        @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
-        public ResponseMessage<String> error(GrantTokenException e) {
-            return ResponseMessage.<String>error(e.getErrorType().code(),e.getMessage())
-                    .result(e.getErrorType().message());
-        }
-    }
-}
-

+ 0 - 33
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/TokenRequest.java

@@ -1,33 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server;
-
-import java.util.Map;
-import java.util.Optional;
-
-/**
- * @author zhouhao
- */
-public interface TokenRequest {
-    default Optional<String> getParameter(String name) {
-        return Optional.ofNullable(getParameters().get(name));
-    }
-
-    Map<String, String> getParameters();
-}

+ 0 - 51
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/client/MemoryOAuth2ClientConfigRepository.java

@@ -1,51 +0,0 @@
-package org.hswebframework.web.authorization.oauth2.server.client;
-
-import org.hswebframework.web.id.IDGenerator;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class MemoryOAuth2ClientConfigRepository implements OAuth2ClientConfigRepository {
-    private Map<String, OAuth2Client> clients = new HashMap<>();
-
-    public void setClients(Map<String, OAuth2Client> clients) {
-        this.clients = clients;
-    }
-
-    @Override
-    public OAuth2Client getClientById(String id) {
-        return clients.get(id);
-    }
-
-    @Override
-    public OAuth2Client getClientByOwnerId(String ownerId) {
-        return clients.values().stream().filter(client -> ownerId.equals(client.getOwnerId())).findFirst().orElse(null);
-    }
-
-    @Override
-    public OAuth2Client save(OAuth2Client oAuth2Client) {
-        clients.put(oAuth2Client.getId(), oAuth2Client);
-        return oAuth2Client;
-    }
-
-    @Override
-    public OAuth2Client newClient() {
-        return SimpleOAuth2Client.builder()
-                .id(IDGenerator.MD5.generate())
-                .secret(IDGenerator.MD5.generate())
-                .build();
-    }
-
-    @Override
-    public OAuth2Client remove(String id) {
-        return clients.remove(id);
-    }
-
-    @Override
-    public List<OAuth2Client> getAll() {
-        return new ArrayList<>(clients.values());
-    }
-
-}

+ 0 - 58
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/client/OAuth2Client.java

@@ -1,58 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.client;
-
-import java.io.Serializable;
-import java.util.Set;
-
-/**
- * @author zhouhao
- */
-public interface OAuth2Client extends Serializable {
-    String getId();
-
-    String getSecret();
-
-    String getName();
-
-    String getRedirectUri();
-
-    String getOwnerId();
-
-    Long getCreateTime();
-
-    /**
-     * @return 状态
-     * @see org.hswebframework.web.commons.entity.DataStatus
-     */
-    Byte getStatus();
-
-    /**
-     * @return 客户端支持的认证类型
-     * @see org.hswebframework.web.oauth2.core.GrantType
-     */
-    Set<String> getSupportGrantTypes();
-
-    Set<String> getDefaultGrantScope();
-
-    default boolean isSupportGrantType(String grantType) {
-        Set<String> supports = getSupportGrantTypes();
-        return supports != null && (supports.contains(grantType) || supports.contains("*"));
-    }
-}

+ 0 - 38
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/client/OAuth2ClientConfigRepository.java

@@ -1,38 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.client;
-
-import java.util.List;
-
-/**
- * @author zhouhao
- */
-public interface OAuth2ClientConfigRepository {
-    OAuth2Client getClientById(String id);
-
-    OAuth2Client getClientByOwnerId(String ownerId);
-
-    OAuth2Client save(OAuth2Client oAuth2Client);
-
-    OAuth2Client remove(String id);
-
-    OAuth2Client newClient();
-
-    List<OAuth2Client> getAll();
-}

+ 0 - 31
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/client/SimpleOAuth2Client.java

@@ -1,31 +0,0 @@
-package org.hswebframework.web.authorization.oauth2.server.client;
-
-import lombok.*;
-
-import java.util.Set;
-
-@Getter
-@Setter
-@NoArgsConstructor
-@AllArgsConstructor
-@Builder
-public class SimpleOAuth2Client implements OAuth2Client {
-    private static final long serialVersionUID = -9179482283099879369L;
-    private String id;
-
-    private String secret;
-
-    private String name;
-
-    private String redirectUri;
-
-    private String ownerId;
-
-    private Long createTime;
-
-    private Byte status;
-
-    private Set<String> supportGrantTypes;
-
-    private Set<String> DefaultGrantScope;
-}

+ 0 - 15
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/event/OAuth2GrantEvent.java

@@ -1,15 +0,0 @@
-package org.hswebframework.web.authorization.oauth2.server.event;
-
-import lombok.AllArgsConstructor;
-import lombok.Getter;
-import org.hswebframework.web.authorization.oauth2.server.OAuth2AccessToken;
-
-/**
- * @author zhouhao
- * @since 1.0
- */
-@Getter
-@AllArgsConstructor
-public class OAuth2GrantEvent {
-    private OAuth2AccessToken accessToken;
-}

+ 0 - 41
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/exception/GrantTokenException.java

@@ -1,41 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.exception;
-
-import org.hswebframework.web.oauth2.core.ErrorType;
-
-/**
- * @author zhouhao
- */
-public class GrantTokenException extends RuntimeException {
-    private ErrorType errorType;
-
-    public GrantTokenException(ErrorType errorType) {
-        this(errorType, errorType.message());
-    }
-
-    public GrantTokenException(ErrorType errorType, String message) {
-        super(message);
-        this.errorType = errorType;
-    }
-
-    public ErrorType getErrorType() {
-        return errorType;
-    }
-}

+ 0 - 91
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/AbstractAuthorizationService.java

@@ -1,91 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support;
-
-import org.hswebframework.web.authorization.oauth2.server.client.OAuth2Client;
-import org.hswebframework.web.authorization.oauth2.server.client.OAuth2ClientConfigRepository;
-import org.hswebframework.web.authorization.oauth2.server.exception.GrantTokenException;
-import org.hswebframework.web.authorization.oauth2.server.token.AccessTokenService;
-import org.hswebframework.web.commons.entity.DataStatus;
-import org.hswebframework.web.oauth2.core.ErrorType;
-
-import static org.hswebframework.web.oauth2.core.ErrorType.*;
-
-/**
- * @author zhouhao
- */
-public abstract class AbstractAuthorizationService {
-    protected AccessTokenService  accessTokenService;
-    protected OAuth2ClientConfigRepository repository;
-
-    public AccessTokenService getAccessTokenService() {
-        return accessTokenService;
-    }
-
-    public void setAccessTokenService(AccessTokenService accessTokenService) {
-        this.accessTokenService = accessTokenService;
-    }
-
-    public OAuth2ClientConfigRepository getRepository() {
-        return repository;
-    }
-
-    public void setRepository(OAuth2ClientConfigRepository repository) {
-        this.repository = repository;
-    }
-
-    protected void assertGrantTypeSupport(OAuth2Client client, String grantType) {
-        if (!client.isSupportGrantType(grantType)) {
-            throw new GrantTokenException(UNSUPPORTED_GRANT_TYPE);
-        }
-    }
-
-    protected void assertParameterNotBlank(String parameter, ErrorType type) {
-        if (null == parameter || parameter.isEmpty()) {
-            throw new GrantTokenException(type);
-        }
-    }
-
-    protected OAuth2Client getClient(String clientId, String clientSecret) {
-        OAuth2Client client = getClient(clientId);
-        if (!client.getSecret().equals(clientSecret)) {
-            throw new GrantTokenException(ILLEGAL_CLIENT_SECRET);
-        }
-        return client;
-    }
-
-    protected OAuth2Client checkClient(OAuth2Client client) {
-        if (client == null) {
-            throw new GrantTokenException(CLIENT_NOT_EXIST);
-        }
-        if (!DataStatus.STATUS_ENABLED.equals(client.getStatus())) {
-            throw new GrantTokenException(CLIENT_DISABLED);
-        }
-        return client;
-    }
-
-    protected OAuth2Client getClientByOwnerId(String ownerId) {
-        return checkClient(repository.getClientByOwnerId(ownerId));
-    }
-
-    protected OAuth2Client getClient(String clientId) {
-        return checkClient(repository.getClientById(clientId));
-    }
-
-}

+ 0 - 115
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/DefaultOAuth2Granter.java

@@ -1,115 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support;
-
-import org.hswebframework.web.authorization.oauth2.server.TokenRequest;
-import org.hswebframework.web.authorization.oauth2.server.OAuth2AccessToken;
-import org.hswebframework.web.authorization.oauth2.server.exception.GrantTokenException;
-import org.hswebframework.web.authorization.oauth2.server.support.code.AuthorizationCodeTokenRequest;
-import org.hswebframework.web.authorization.oauth2.server.support.code.AuthorizationCodeGranter;
-import org.hswebframework.web.authorization.oauth2.server.support.client.ClientCredentialRequest;
-import org.hswebframework.web.authorization.oauth2.server.support.client.ClientCredentialGranter;
-import org.hswebframework.web.authorization.oauth2.server.support.implicit.ImplicitRequest;
-import org.hswebframework.web.authorization.oauth2.server.support.implicit.ImplicitGranter;
-import org.hswebframework.web.authorization.oauth2.server.support.password.PasswordRequest;
-import org.hswebframework.web.authorization.oauth2.server.support.password.PasswordGranter;
-import org.hswebframework.web.authorization.oauth2.server.support.refresh.RefreshTokenRequest;
-import org.hswebframework.web.authorization.oauth2.server.support.refresh.RefreshTokenGranter;
-import org.hswebframework.web.oauth2.core.ErrorType;
-import org.hswebframework.web.oauth2.core.GrantType;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.function.Function;
-
-import static org.hswebframework.web.oauth2.core.ErrorType.ILLEGAL_GRANT_TYPE;
-import static org.hswebframework.web.oauth2.core.ErrorType.UNSUPPORTED_GRANT_TYPE;
-
-/**
- * TODO 完成注释
- *
- * @author zhouhao
- */
-public class DefaultOAuth2Granter implements OAuth2Granter {
-
-    private Map<String, Granter> supportGranter = new HashMap<>(5);
-
-    public DefaultOAuth2Granter addAuthorizationCodeSupport(AuthorizationCodeGranter authorizationCodeService) {
-        return addGranter(GrantType.authorization_code, AuthorizationCodeTokenRequest.class, authorizationCodeService::requestToken);
-    }
-
-    public DefaultOAuth2Granter addRefreshTokenSupport(RefreshTokenGranter refreshTokenGranter) {
-        return addGranter(GrantType.refresh_token, RefreshTokenRequest.class, refreshTokenGranter::refreshToken);
-    }
-
-    public DefaultOAuth2Granter addClientCredentialSupport(ClientCredentialGranter clientCredentialGranter) {
-        return addGranter(GrantType.client_credentials, ClientCredentialRequest.class, clientCredentialGranter::requestToken);
-    }
-
-    public DefaultOAuth2Granter addPasswordSupport(PasswordGranter passwordGranter) {
-        return addGranter(GrantType.password, PasswordRequest.class, passwordGranter::requestToken);
-    }
-
-    public DefaultOAuth2Granter addImplicitSupport(ImplicitGranter implicitGranter) {
-        return addGranter(GrantType.implicit, ImplicitRequest.class, implicitGranter::requestToken);
-    }
-
-    private <R extends TokenRequest> DefaultOAuth2Granter addGranter(String grantType, Class<R> tokenRequestType, Function<R, OAuth2AccessToken> granterService) {
-        supportGranter.put(grantType, Granter.build(tokenRequestType, granterService));
-        return this;
-    }
-
-    @Override
-    public OAuth2AccessToken grant(String grantType, TokenRequest request) {
-        assertParameterNotBlank(grantType, ILLEGAL_GRANT_TYPE);
-        Granter granter = supportGranter.get(grantType);
-        if (granter == null) {
-            throw new GrantTokenException(UNSUPPORTED_GRANT_TYPE);
-        }
-        return granter.grant(request);
-    }
-
-    private void assertParameterNotBlank(String parameter, ErrorType type) {
-        if (null == parameter || parameter.isEmpty()) {
-            throw new GrantTokenException(type);
-        }
-    }
-
-    static class Granter<R extends TokenRequest> {
-        Class<R> tokenRequestType;
-
-        Function<R, OAuth2AccessToken> granterService;
-
-        OAuth2AccessToken grant(TokenRequest request) {
-            if (!tokenRequestType.isInstance(request)) {
-                throw new UnsupportedOperationException("AuthorizationRequest must instanceof  " + tokenRequestType);
-            }
-            return granterService.apply(tokenRequestType.cast(request));
-        }
-
-        static <R extends TokenRequest> Granter<R> build(Class<R> tokenRequestType, Function<R, OAuth2AccessToken> granterService) {
-            Granter<R> granter = new Granter<>();
-            granter.tokenRequestType = tokenRequestType;
-            granter.granterService = granterService;
-            return granter;
-        }
-
-    }
-
-}

+ 0 - 124
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/HttpTokenRequest.java

@@ -1,124 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support;
-
-import org.hswebframework.web.WebUtil;
-import org.hswebframework.web.authorization.oauth2.server.TokenRequest;
-import org.hswebframework.web.authorization.oauth2.server.exception.GrantTokenException;
-import org.hswebframework.web.oauth2.core.ErrorType;
-import org.hswebframework.web.oauth2.core.OAuth2Constants;
-import org.hswebframework.utils.StringUtils;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.*;
-
-/**
- * @author zhouhao
- */
-public class HttpTokenRequest implements TokenRequest {
-
-    protected Map<String, String> parameters;
-    protected Map<String, String> headers;
-    protected Set<String>         scope;
-
-    protected ClientCredentials clientCredentials;
-
-    public HttpTokenRequest(HttpServletRequest request) {
-        this.parameters = WebUtil.getParameters(request);
-        this.headers = WebUtil.getHeaders(request);
-        String clientId = parameters.get(OAuth2Constants.client_id);
-        String clientSecret = parameters.get(OAuth2Constants.client_secret);
-        String authorization = headers.get(OAuth2Constants.authorization);
-        clientCredentials = getClientCredentials(clientId, clientSecret, authorization);
-
-        this.scope = getParameter(OAuth2Constants.scope)
-                .filter(scopeStr -> !StringUtils.isNullOrEmpty(scopeStr))
-                .map(scopeStr -> new HashSet<>(Arrays.asList(scopeStr.split("[, \n]"))))
-                .orElseGet(HashSet::new);
-    }
-
-    @Override
-    public Map<String, String> getParameters() {
-        return parameters;
-    }
-
-    protected class ClientCredentials {
-        private String principal;
-        private String credentials;
-
-        public ClientCredentials(String principal, String credentials) {
-            this.principal = principal;
-            this.credentials = credentials;
-        }
-
-        public String getPrincipal() {
-            return principal;
-        }
-
-        public String getCredentials() {
-            return credentials;
-        }
-    }
-
-    protected ClientCredentials getClientCredentials(String principal, String credentials, String authorization) {
-        if ((principal == null || credentials == null) && authorization == null) {
-            return null;
-        }
-        if (authorization != null && !authorization.isEmpty()) {
-            String[] decodeCredentials = decodeClientAuthenticationHeader(authorization);
-            //fix #63
-            if (decodeCredentials == null) {
-                return null;
-            }
-            if (decodeCredentials.length > 1) {
-                principal = decodeCredentials[0];
-                credentials = decodeCredentials[1];
-            } else {
-                credentials = decodeCredentials[0];
-            }
-        }
-        return new ClientCredentials(principal, credentials);
-    }
-
-
-    protected String[] decodeClientAuthenticationHeader(String authenticationHeader) {
-        if (StringUtils.isNullOrEmpty(authenticationHeader)) {
-            return null;
-        } else {
-            String[] tokens = authenticationHeader.split(" ");
-            if (tokens.length != 2) {
-                return null;
-            } else {
-                String authType = tokens[0];
-                if (!"basic".equalsIgnoreCase(authType)) {
-                    return ErrorType.OTHER.throwThis(GrantTokenException::new, "authentication " + authType + " not support!");
-                } else {
-                    String encodedCreds = tokens[1];
-                    return decodeBase64EncodedCredentials(encodedCreds);
-                }
-            }
-        }
-    }
-
-    protected String[] decodeBase64EncodedCredentials(String encodedCredentials) {
-        String decodedCredentials = new String(Base64.getDecoder().decode(encodedCredentials));
-        String[] credentials = decodedCredentials.split(":", 2);
-        return credentials.length != 2 ? null : (!StringUtils.isNullOrEmpty(credentials[0]) && !StringUtils.isNullOrEmpty(credentials[1]) ? credentials : null);
-    }
-}

+ 0 - 29
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/OAuth2Granter.java

@@ -1,29 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support;
-
-import org.hswebframework.web.authorization.oauth2.server.TokenRequest;
-import org.hswebframework.web.authorization.oauth2.server.OAuth2AccessToken;
-
-/**
- * @author zhouhao
- */
-public interface OAuth2Granter {
-    OAuth2AccessToken grant(String grantType, TokenRequest request);
-}

+ 0 - 40
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/client/ClientCredentialGranter.java

@@ -1,40 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.client;
-
-import org.hswebframework.web.authorization.oauth2.server.AuthorizationService;
-import org.hswebframework.web.authorization.oauth2.server.OAuth2AccessToken;
-import org.hswebframework.web.authorization.oauth2.server.exception.GrantTokenException;
-
-/**
- * client_credential方式认证器
- *
- * @author zhouhao
- * @see org.hswebframework.web.oauth2.core.GrantType#client_credentials
- */
-public interface ClientCredentialGranter extends AuthorizationService {
-    /**
-     * 申请token
-     * @param request 请求参数
-     * @return 申请成功的token信息
-     * @throws GrantTokenException
-     * @see org.hswebframework.web.oauth2.core.ErrorType
-     */
-    OAuth2AccessToken requestToken(ClientCredentialRequest request);
-}

+ 0 - 31
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/client/ClientCredentialRequest.java

@@ -1,31 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.client;
-
-import org.hswebframework.web.authorization.oauth2.server.TokenRequest;
-
-/**
- *
- * @author zhouhao
- */
-public interface ClientCredentialRequest extends TokenRequest {
-    String getClientId();
-
-    String getClientSecret();
-}

+ 0 - 63
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/client/DefaultClientCredentialGranter.java

@@ -1,63 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.client;
-
-import org.hswebframework.web.authorization.oauth2.server.OAuth2AccessToken;
-import org.hswebframework.web.authorization.oauth2.server.client.OAuth2Client;
-import org.hswebframework.web.authorization.oauth2.server.support.AbstractAuthorizationService;
-import org.hswebframework.web.oauth2.core.GrantType;
-
-import static org.hswebframework.web.oauth2.core.ErrorType.*;
-
-/**
- * @author zhouhao
- */
-public class DefaultClientCredentialGranter extends AbstractAuthorizationService implements ClientCredentialGranter {
-
-    @Override
-    public OAuth2AccessToken requestToken(ClientCredentialRequest request) {
-        String clientId = request.getClientId();
-        String clientSecret = request.getClientSecret();
-
-        assertParameterNotBlank(clientId, ILLEGAL_CLIENT_ID);
-        assertParameterNotBlank(clientSecret, ILLEGAL_CLIENT_SECRET);
-
-        OAuth2Client client = getClient(clientId, clientSecret);
-        assertGrantTypeSupport(client, GrantType.client_credentials);
-
-        OAuth2AccessToken accessToken = accessTokenService.createToken();
-        // 设置自定义的属性,其他属性在create的时候已经被设置
-        accessToken.setOwnerId(client.getOwnerId());
-        accessToken.setExpiresIn(3600);
-        accessToken.setScope(client.getDefaultGrantScope());
-        accessToken.setClientId(client.getId());
-        accessToken.setGrantType(GrantType.client_credentials);
-
-        OAuth2AccessToken old = accessTokenService.tryGetOldToken(accessToken);
-        //如果已存在token并且距离上次更新时间小于10秒
-        if(old!=null&&System.currentTimeMillis()-old.getUpdateTime()<10000){
-
-            return old;
-        }
-
-
-        //保存token
-        return accessTokenService.saveOrUpdateToken(accessToken);
-    }
-}

+ 0 - 50
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/client/HttpClientCredentialRequest.java

@@ -1,50 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.client;
-
-import org.hswebframework.web.authorization.oauth2.server.exception.GrantTokenException;
-import org.hswebframework.web.authorization.oauth2.server.support.HttpTokenRequest;
-import org.hswebframework.web.oauth2.core.ErrorType;
-import org.hswebframework.web.oauth2.core.OAuth2Constants;
-
-import javax.servlet.http.HttpServletRequest;
-
-/**
- * @author zhouhao
- */
-public class HttpClientCredentialRequest extends HttpTokenRequest implements ClientCredentialRequest {
-    public HttpClientCredentialRequest(HttpServletRequest request) {
-        super(request);
-        if (clientCredentials == null) {
-            ErrorType.OTHER.throwThis(GrantTokenException::new, "missing parameter:" + OAuth2Constants.client_id + "," + OAuth2Constants.client_secret + "," + OAuth2Constants.authorization);
-
-            //throw new GrantTokenException(ErrorType.OTHER, "missing parameter:" + OAuth2Constants.client_id + "," + OAuth2Constants.client_secret + "," + OAuth2Constants.authorization);
-        }
-    }
-
-    @Override
-    public String getClientId() {
-        return clientCredentials.getPrincipal();
-    }
-
-    @Override
-    public String getClientSecret() {
-        return clientCredentials.getCredentials();
-    }
-}

+ 0 - 51
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/AuthorizationCode.java

@@ -1,51 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.code;
-
-import java.util.Set;
-
-/**
- *
- * @author zhouhao
- */
-public interface AuthorizationCode {
-    String getClientId();
-
-    void setClientId(String clientId);
-
-    String getUserId();
-
-    void setUserId(String userId);
-
-    String getCode();
-
-    void setCode(String code);
-
-    Long getCreateTime();
-
-    void setCreateTime(Long createTime);
-
-    Set<String> getScope();
-
-    void setScope(Set<String> scope);
-
-    String getRedirectUri();
-
-    void setRedirectUri(String redirectUri);
-}

+ 0 - 37
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/AuthorizationCodeGranter.java

@@ -1,37 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.code;
-
-import org.hswebframework.web.authorization.oauth2.server.AuthorizationService;
-import org.hswebframework.web.authorization.oauth2.server.OAuth2AccessToken;
-
-/**
- * authorization_code方式申请token
- *
- * @author zhouhao
- * @see org.hswebframework.web.oauth2.core.GrantType#authorization_code
- */
-public interface AuthorizationCodeGranter extends AuthorizationService {
-    /**
-     * 申请token
-     * @param request
-     * @return
-     */
-    OAuth2AccessToken requestToken(AuthorizationCodeTokenRequest request);
-}

+ 0 - 55
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/AuthorizationCodeRequest.java

@@ -1,55 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.code;
-
-import org.hswebframework.web.authorization.User;
-import org.hswebframework.web.authorization.oauth2.server.client.OAuth2Client;
-
-import java.util.Set;
-
-/**
- * 授权码请求
- *
- * @author zhouhao
- */
-public interface AuthorizationCodeRequest {
-    /**
-     * @return oauth2客户端id
-     * @see org.hswebframework.web.oauth2.core.OAuth2Constants#client_id
-     * @see OAuth2Client#getId()
-     */
-    String getClientId();
-
-    /**
-     * @return 与授权码关联的用户ID
-     * @see User#getId()
-     */
-    String getUserId();
-
-    /**
-     * @return 允许授权的范围
-     */
-    Set<String> getScope();
-
-    /**
-     * @return 重定向地址
-     * @see org.hswebframework.web.oauth2.core.OAuth2Constants#redirect_uri
-     */
-    String getRedirectUri();
-}

+ 0 - 29
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/AuthorizationCodeService.java

@@ -1,29 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.code;
-
-/**
- *
- * @author zhouhao
- */
-public interface AuthorizationCodeService {
-    String createAuthorizationCode(AuthorizationCodeRequest request);
-
-    AuthorizationCode consumeAuthorizationCode(String code);
-}

+ 0 - 55
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/AuthorizationCodeTokenRequest.java

@@ -1,55 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.code;
-
-import org.hswebframework.web.authorization.oauth2.server.TokenRequest;
-
-import java.util.Set;
-
-/**
- * 授权码方式token请求
- *
- * @author zhouhao
- */
-public interface AuthorizationCodeTokenRequest extends TokenRequest {
-    /**
-     * @return 搜权码
-     */
-    String getCode();
-
-    /**
-     * @return oauth2客户端id
-     */
-    String getClientId();
-
-    /**
-     * @return oauth2客户端密钥
-     */
-    String getClientSecret();
-
-    /**
-     * @return 申请授权范围
-     */
-    Set<String> getScope();
-
-    /**
-     * @return 重定向地址
-     */
-    String getRedirectUri();
-}

+ 0 - 86
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/DefaultAuthorizationCodeGranter.java

@@ -1,86 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.code;
-
-import org.hswebframework.web.authorization.oauth2.server.OAuth2AccessToken;
-import org.hswebframework.web.authorization.oauth2.server.client.OAuth2Client;
-import org.hswebframework.web.authorization.oauth2.server.exception.GrantTokenException;
-import org.hswebframework.web.authorization.oauth2.server.support.AbstractAuthorizationService;
-import org.hswebframework.web.oauth2.core.ErrorType;
-import org.hswebframework.web.oauth2.core.GrantType;
-
-import static org.hswebframework.web.oauth2.core.ErrorType.*;
-
-/**
- * @author zhouhao
- * @see AuthorizationCodeGranter
- * @since 3.0
- */
-public class DefaultAuthorizationCodeGranter extends AbstractAuthorizationService implements AuthorizationCodeGranter {
-
-    //默认有效时间为10分钟
-    private long codeTimeOut = 10 * 60 * 1000L;
-
-    private AuthorizationCodeService authorizationCodeService;
-
-    public DefaultAuthorizationCodeGranter(AuthorizationCodeService authorizationCodeService) {
-        this.authorizationCodeService = authorizationCodeService;
-    }
-
-    public void setCodeTimeOut(long codeTimeOut) {
-        this.codeTimeOut = codeTimeOut;
-    }
-
-    @Override
-    public OAuth2AccessToken requestToken(AuthorizationCodeTokenRequest request) {
-        String clientId = request.getClientId();
-        String clientSecret = request.getClientSecret();
-        String code = request.getCode();
-        String redirectUri = request.getRedirectUri();
-
-        assertParameterNotBlank(clientId, ILLEGAL_CLIENT_ID);
-        assertParameterNotBlank(clientSecret, ILLEGAL_CLIENT_SECRET);
-        assertParameterNotBlank(code, ILLEGAL_CODE);
-        assertParameterNotBlank(redirectUri, ILLEGAL_REDIRECT_URI);
-
-        OAuth2Client client = getClient(clientId, clientSecret);
-        assertGrantTypeSupport(client, GrantType.authorization_code);
-
-        AuthorizationCode authorizationCode = authorizationCodeService.consumeAuthorizationCode(code);
-        if (authorizationCode == null) {
-            throw new GrantTokenException(ErrorType.ILLEGAL_CODE);
-        }
-        if (System.currentTimeMillis() - authorizationCode.getCreateTime() > codeTimeOut) {
-            throw new GrantTokenException(ErrorType.EXPIRED_CODE);
-        }
-        // TODO: 17-5-3  验证redirect_uri
-        //验证redirect_uri
-        //if (!redirectUri.equals(authorizationCode.getRedirectUri())) {
-            //   throw new GrantTokenException(ILLEGAL_REDIRECT_URI);
-       // }
-
-        OAuth2AccessToken accessToken = accessTokenService.createToken();
-        accessToken.setGrantType(GrantType.authorization_code);
-        accessToken.setScope(authorizationCode.getScope());
-        accessToken.setOwnerId(authorizationCode.getUserId());
-        accessToken.setExpiresIn(3600);
-        accessToken.setClientId(clientId);
-        return accessTokenService.saveOrUpdateToken(accessToken);
-    }
-}

+ 0 - 63
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/HttpAuthorizationCodeRequest.java

@@ -1,63 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.code;
-
-import org.hswebframework.web.authorization.oauth2.server.exception.GrantTokenException;
-import org.hswebframework.web.authorization.oauth2.server.support.HttpTokenRequest;
-import org.hswebframework.web.oauth2.core.ErrorType;
-import org.hswebframework.web.oauth2.core.OAuth2Constants;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.Set;
-
-/**
- * TODO 完成注释
- *
- * @author zhouhao
- */
-public class HttpAuthorizationCodeRequest extends HttpTokenRequest implements AuthorizationCodeRequest {
-    private String userId;
-
-    public HttpAuthorizationCodeRequest(String userId, HttpServletRequest request) {
-        super(request);
-        this.userId = userId;
-    }
-
-    @Override
-    public String getClientId() {
-        return getParameter(OAuth2Constants.client_id)
-                .orElseThrow(() -> new GrantTokenException(ErrorType.ILLEGAL_CLIENT_ID));
-    }
-
-    @Override
-    public String getUserId() {
-        return userId;
-    }
-
-    @Override
-    public Set<String> getScope() {
-        return scope;
-    }
-
-    @Override
-    public String getRedirectUri() {
-        return getParameter(OAuth2Constants.redirect_uri).orElse(null);
-    }
-
-}

+ 0 - 67
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/HttpAuthorizationCodeTokenRequest.java

@@ -1,67 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.code;
-
-import org.hswebframework.web.authorization.oauth2.server.exception.GrantTokenException;
-import org.hswebframework.web.authorization.oauth2.server.support.HttpTokenRequest;
-import org.hswebframework.web.oauth2.core.ErrorType;
-import org.hswebframework.web.oauth2.core.OAuth2Constants;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.Set;
-
-/**
- * TODO 完成注释
- *
- * @author zhouhao
- */
-public class HttpAuthorizationCodeTokenRequest extends HttpTokenRequest implements AuthorizationCodeTokenRequest {
-
-    public HttpAuthorizationCodeTokenRequest(HttpServletRequest request) {
-        super(request);
-        if (clientCredentials == null) {
-            ErrorType.OTHER.throwThis(GrantTokenException::new, "missing parameter:" + OAuth2Constants.client_id + "," + OAuth2Constants.client_secret + "," + OAuth2Constants.authorization);
-        }
-    }
-
-    @Override
-    public String getCode() {
-        return getParameter(OAuth2Constants.code).orElse(null);
-    }
-
-    @Override
-    public String getClientId() {
-        return clientCredentials.getPrincipal();
-    }
-
-    @Override
-    public String getClientSecret() {
-        return clientCredentials.getCredentials();
-    }
-
-    @Override
-    public Set<String> getScope() {
-        return scope;
-    }
-
-    @Override
-    public String getRedirectUri() {
-        return getParameter(OAuth2Constants.redirect_uri).orElse(null);
-    }
-}

+ 0 - 73
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/implicit/DefaultImplicitGranter.java

@@ -1,73 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.implicit;
-
-import org.hswebframework.web.authorization.oauth2.server.OAuth2AccessToken;
-import org.hswebframework.web.authorization.oauth2.server.client.OAuth2Client;
-import org.hswebframework.web.authorization.oauth2.server.exception.GrantTokenException;
-import org.hswebframework.web.authorization.oauth2.server.support.AbstractAuthorizationService;
-import org.hswebframework.web.authorization.oauth2.server.support.code.AuthorizationCode;
-import org.hswebframework.web.authorization.oauth2.server.support.code.AuthorizationCodeGranter;
-import org.hswebframework.web.authorization.oauth2.server.support.code.AuthorizationCodeService;
-import org.hswebframework.web.authorization.oauth2.server.support.code.AuthorizationCodeTokenRequest;
-import org.hswebframework.web.oauth2.core.ErrorType;
-import org.hswebframework.web.oauth2.core.GrantType;
-
-import java.util.Set;
-
-import static org.hswebframework.web.oauth2.core.ErrorType.*;
-
-/**
- * @author zhouhao
- */
-public class DefaultImplicitGranter extends AbstractAuthorizationService implements ImplicitGranter {
-
-    @Override
-    public OAuth2AccessToken requestToken(ImplicitRequest request) {
-        String clientId = request.getClientId();
-        Set<String> scope = request.getScope();
-
-        assertParameterNotBlank(clientId, ILLEGAL_CLIENT_ID);
-
-        OAuth2Client client = getClient(clientId);
-        assertGrantTypeSupport(client, GrantType.implicit);
-        if (scope == null || scope.isEmpty()) {
-            scope = client.getDefaultGrantScope();
-        }
-        if (!client.getDefaultGrantScope().containsAll(scope)) {
-            throw new GrantTokenException(SCOPE_OUT_OF_RANGE);
-        }
-        if (!client.getRedirectUri().equals(request.getRedirectUri())) {
-            throw new GrantTokenException(ILLEGAL_REDIRECT_URI);
-        }
-
-        OAuth2AccessToken accessToken = accessTokenService.createToken();
-        accessToken.setGrantType(GrantType.implicit);
-        accessToken.setScope(scope);
-        accessToken.setOwnerId(client.getOwnerId());
-        accessToken.setExpiresIn(3600);
-        accessToken.setClientId(clientId);
-        OAuth2AccessToken old = accessTokenService.tryGetOldToken(accessToken);
-        //如果已存在token并且距离上次更新时间小于10秒
-        if(old!=null&&System.currentTimeMillis()-old.getUpdateTime()<10000){
-            return old;
-        }
-        return accessTokenService.saveOrUpdateToken(accessToken);
-    }
-}

+ 0 - 53
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/implicit/HttpImplicitRequest.java

@@ -1,53 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.implicit;
-
-import org.hswebframework.web.authorization.oauth2.server.exception.GrantTokenException;
-import org.hswebframework.web.authorization.oauth2.server.support.HttpTokenRequest;
-import org.hswebframework.web.oauth2.core.ErrorType;
-import org.hswebframework.web.oauth2.core.OAuth2Constants;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.Set;
-
-/**
- * @author zhouhao
- */
-public class HttpImplicitRequest extends HttpTokenRequest implements ImplicitRequest {
-
-    public HttpImplicitRequest(HttpServletRequest request) {
-        super(request);
-    }
-
-    @Override
-    public String getClientId() {
-        return getParameter(OAuth2Constants.client_id)
-                .orElseGet(()->ErrorType.ILLEGAL_CLIENT_ID.throwThis(GrantTokenException::new));
-    }
-
-    @Override
-    public Set<String> getScope() {
-        return scope;
-    }
-
-    @Override
-    public String getRedirectUri() {
-        return getParameter(OAuth2Constants.redirect_uri).orElse(null);
-    }
-}

+ 0 - 31
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/implicit/ImplicitGranter.java

@@ -1,31 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.implicit;
-
-import org.hswebframework.web.authorization.oauth2.server.AuthorizationService;
-import org.hswebframework.web.authorization.oauth2.server.OAuth2AccessToken;
-
-/**
- * TODO 完成注释
- *
- * @author zhouhao
- */
-public interface ImplicitGranter extends AuthorizationService {
-    OAuth2AccessToken requestToken(ImplicitRequest request);
-}

+ 0 - 34
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/implicit/ImplicitRequest.java

@@ -1,34 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.implicit;
-
-import org.hswebframework.web.authorization.oauth2.server.TokenRequest;
-
-import java.util.Set;
-
-/**
- * @author zhouhao
- */
-public interface ImplicitRequest extends TokenRequest {
-    String getClientId();
-
-    Set<String> getScope();
-
-    String getRedirectUri();
-}

+ 0 - 80
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/password/DefaultPasswordGranter.java

@@ -1,80 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.password;
-
-import org.hswebframework.web.authorization.oauth2.server.OAuth2AccessToken;
-import org.hswebframework.web.authorization.oauth2.server.client.OAuth2Client;
-import org.hswebframework.web.authorization.oauth2.server.exception.GrantTokenException;
-import org.hswebframework.web.authorization.oauth2.server.support.AbstractAuthorizationService;
-import org.hswebframework.web.authorization.oauth2.server.support.implicit.ImplicitGranter;
-import org.hswebframework.web.authorization.oauth2.server.support.implicit.ImplicitRequest;
-import org.hswebframework.web.oauth2.core.GrantType;
-
-import java.util.Set;
-
-import static org.hswebframework.web.oauth2.core.ErrorType.*;
-
-/**
- * @author zhouhao
- */
-public class DefaultPasswordGranter extends AbstractAuthorizationService implements PasswordGranter {
-    private PasswordService passwordService;
-
-    public DefaultPasswordGranter(PasswordService passwordService) {
-        this.passwordService = passwordService;
-    }
-
-    @Override
-    public OAuth2AccessToken requestToken(PasswordRequest request) {
-        String username = request.getUsername();
-        String password = request.getPassword();
-        Set<String> scope = request.getScope();
-
-        assertParameterNotBlank(username, ILLEGAL_USERNAME);
-        assertParameterNotBlank(password, ILLEGAL_PASSWORD);
-
-        String userId = passwordService.getUserIdByUsernameAndPassword(username, password);
-
-        assertParameterNotBlank(userId, USER_NOT_EXIST);
-
-        OAuth2Client client = getClientByOwnerId(userId);
-        assertGrantTypeSupport(client, GrantType.implicit);
-        if (scope == null || scope.isEmpty()) {
-            scope = client.getDefaultGrantScope();
-        }
-        if (!client.getDefaultGrantScope().containsAll(scope)) {
-            throw new GrantTokenException(SCOPE_OUT_OF_RANGE);
-        }
-
-        OAuth2AccessToken accessToken = accessTokenService.createToken();
-        accessToken.setGrantType(GrantType.password);
-        accessToken.setScope(scope);
-        accessToken.setOwnerId(userId);
-        accessToken.setExpiresIn(3600);
-        accessToken.setClientId(client.getId());
-        OAuth2AccessToken old = accessTokenService.tryGetOldToken(accessToken);
-        //如果已存在token并且距离上次更新时间小于10秒
-        if(old!=null&&System.currentTimeMillis()-old.getUpdateTime()<10000){
-
-            return old;
-        }
-
-        return accessTokenService.saveOrUpdateToken(accessToken);
-    }
-}

+ 0 - 58
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/password/HttpPasswordRequest.java

@@ -1,58 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.password;
-
-import org.hswebframework.web.authorization.oauth2.server.exception.GrantTokenException;
-import org.hswebframework.web.authorization.oauth2.server.support.HttpTokenRequest;
-import org.hswebframework.web.oauth2.core.ErrorType;
-import org.hswebframework.web.oauth2.core.OAuth2Constants;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.Set;
-
-/**
- * @author zhouhao
- */
-public class HttpPasswordRequest extends HttpTokenRequest implements PasswordRequest {
-    public HttpPasswordRequest(HttpServletRequest request) {
-        super(request);
-        clientCredentials = getClientCredentials(
-                parameters.get(OAuth2Constants.username),
-                parameters.get(OAuth2Constants.password),
-                headers.get(OAuth2Constants.authorization));
-        if (clientCredentials == null) {
-            ErrorType.OTHER.throwThis(GrantTokenException::new, "missing parameter:" + OAuth2Constants.username + "," + OAuth2Constants.password + "," + OAuth2Constants.authorization);
-        }
-    }
-
-    @Override
-    public String getUsername() {
-        return clientCredentials.getPrincipal();
-    }
-
-    @Override
-    public String getPassword() {
-        return clientCredentials.getCredentials();
-    }
-
-    @Override
-    public Set<String> getScope() {
-        return scope;
-    }
-}

+ 0 - 30
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/password/PasswordGranter.java

@@ -1,30 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.password;
-
-import org.hswebframework.web.authorization.oauth2.server.AuthorizationService;
-import org.hswebframework.web.authorization.oauth2.server.OAuth2AccessToken;
-
-/**
- * 密码方式授权
- * @author zhouhao
- */
-public interface PasswordGranter extends AuthorizationService {
-    OAuth2AccessToken requestToken(PasswordRequest request);
-}

+ 0 - 34
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/password/PasswordRequest.java

@@ -1,34 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.password;
-
-import org.hswebframework.web.authorization.oauth2.server.TokenRequest;
-
-import java.util.Set;
-
-/**
- * @author zhouhao
- */
-public interface PasswordRequest extends TokenRequest {
-    String getUsername();
-
-    String getPassword();
-
-    Set<String> getScope();
-}

+ 0 - 26
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/password/PasswordService.java

@@ -1,26 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.password;
-
-/**
- * @author zhouhao
- */
-public interface PasswordService {
-    String getUserIdByUsernameAndPassword(String username, String password);
-}

+ 0 - 82
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/refresh/DefaultRefreshTokenGranter.java

@@ -1,82 +0,0 @@
-/*
- *  Copyright 2019 http://www.hswebframework.org
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
- *
- */
-
-package org.hswebframework.web.authorization.oauth2.server.support.refresh;
-
-import org.hswebframework.web.authorization.oauth2.server.OAuth2AccessToken;
-import org.hswebframework.web.authorization.oauth2.server.client.OAuth2Client;
-import org.hswebframework.web.authorization.oauth2.server.exception.GrantTokenException;
-import org.hswebframework.web.authorization.oauth2.server.support.AbstractAuthorizationService;
-import org.hswebframework.web.authorization.oauth2.server.support.code.AuthorizationCode;
-import org.hswebframework.web.authorization.oauth2.server.support.code.AuthorizationCodeGranter;
-import org.hswebframework.web.authorization.oauth2.server.support.code.AuthorizationCodeService;
-import org.hswebframework.web.authorization.oauth2.server.support.code.AuthorizationCodeTokenRequest;
-import org.hswebframework.web.oauth2.core.ErrorType;
-import org.hswebframework.web.oauth2.core.GrantType;
-
-import java.util.Set;
-
-import static org.hswebframework.web.oauth2.core.ErrorType.*;
-
-/**
- * @author zhouhao
- * @see RefreshTokenGranter
- * @since 3.0
- */
-public class DefaultRefreshTokenGranter extends AbstractAuthorizationService implements RefreshTokenGranter {
-
-    //默认有效时间为1年
-    private long refreshTokenTimeOut = 365_24_60_60_1000L;
-
-    public void setRefreshTokenTimeOut(long refreshTokenTimeOut) {
-        this.refreshTokenTimeOut = refreshTokenTimeOut;
-    }
-
-    @Override
-    public OAuth2AccessToken refreshToken(RefreshTokenRequest request) {
-        String clientId = request.getClientId();
-        String clientSecret = request.getClientSecret();
-        String refreshToken = request.getRefreshToken();
-        assertParameterNotBlank(clientId, ILLEGAL_CLIENT_ID);
-        assertParameterNotBlank(clientSecret, ILLEGAL_CLIENT_SECRET);
-        assertParameterNotBlank(refreshToken, ILLEGAL_REFRESH_TOKEN);
-
-        OAuth2Client client = getClient(clientId, clientSecret);
-        assertGrantTypeSupport(client, GrantType.refresh_token);
-
-        OAuth2AccessToken accessToken = accessTokenService.getTokenByRefreshToken(refreshToken);
-        if (accessToken == null) {
-            throw new GrantTokenException(EXPIRED_REFRESH_TOKEN);
-        }
-        if (System.currentTimeMillis() - accessToken.getCreateTime() > refreshTokenTimeOut) {
-            throw new GrantTokenException(EXPIRED_REFRESH_TOKEN);
-        }
-        //更新间隔小于10秒 返回原始token
-        if (System.currentTimeMillis() - accessToken.getUpdateTime() < 10000) {
-            return accessToken;
-        }
-        Set<String> newRange = request.getScope() != null ? request.getScope() : accessToken.getScope();
-        if (accessToken.getScope() != null && !accessToken.getScope().containsAll(newRange)) {
-            throw new GrantTokenException(ErrorType.SCOPE_OUT_OF_RANGE);
-        }
-        accessToken.setAccessToken(accessTokenService.createToken().getAccessToken());
-        accessToken.setScope(newRange);
-        accessToken.setUpdateTime(System.currentTimeMillis());
-        return accessTokenService.saveOrUpdateToken(accessToken);
-    }
-}

+ 0 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/refresh/HttpRefreshTokenRequest.java


Niektoré súbory nie sú zobrazené, pretože je v týchto rozdielových dátach zmenené mnoho súborov