Browse Source

Merge pull request #4 from hs-web/3.0

Merge branch 3.0 from hsweb
YaZhou Gu 8 years ago
parent
commit
02297e7925
100 changed files with 3568 additions and 702 deletions
  1. 4 4
      hsweb-authorization/hsweb-authorization-api/README.md
  2. 7 1
      hsweb-authorization/hsweb-authorization-api/pom.xml
  3. 26 4
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/Authorization.java
  4. 102 0
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthenticationHolder.java
  5. 43 0
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthenticationInitializeService.java
  6. 50 0
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthenticationManager.java
  7. 4 3
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthorizationSupplier.java
  8. 0 53
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthorizationHolder.java
  9. 11 20
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/Permission.java
  10. 3 3
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/access/CustomDataAccess.java
  11. 11 14
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/access/DataAccess.java
  12. 3 1
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/access/DataAccessController.java
  13. 4 2
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/access/DataAccessHandler.java
  14. 0 27
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/access/FieldAccess.java
  15. 34 0
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/access/FieldAccessConfig.java
  16. 2 1
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/access/FieldAccessController.java
  17. 2 2
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/access/OwnCreatedDataAccess.java
  18. 2 2
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/access/ScriptDataAccess.java
  19. 2 2
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/annotation/Authorize.java
  20. 4 6
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/annotation/RequiresDataAccess.java
  21. 2 4
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/annotation/RequiresExpression.java
  22. 4 7
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/annotation/RequiresFieldAccess.java
  23. 6 6
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/listener/event/AuthorizationExitEvent.java
  24. 7 7
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/listener/event/AuthorizationSuccessEvent.java
  25. 5 1
      hsweb-authorization/hsweb-authorization-oauth2/README.md
  26. 14 5
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-entity/pom.xml
  27. 5 6
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-api/src/main/java/org/hswebframework/web/authorization/oauth2/api/OAuth2ServerService.java
  28. 30 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/api/entity/AuthorizationCodeEntity.java
  29. 28 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/api/entity/OAuth2AccessEntity.java
  30. 12 11
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-entity/src/main/java/org/hswebframework/web/entity/authorization/oauth2/OAuth2ClientEntity.java
  31. 16 4
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-entity/src/main/java/org/hswebframework/web/entity/authorization/oauth2/SimpleAuthorizationCodeEntity.java
  32. 27 16
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-entity/src/main/java/org/hswebframework/web/entity/authorization/oauth2/SimpleOAuth2AccessEntity.java
  33. 28 4
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-entity/src/main/java/org/hswebframework/web/entity/authorization/oauth2/SimpleOAuth2ClientEntity.java
  34. 27 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/AuthorizationService.java
  35. 28 14
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-entity/src/main/java/org/hswebframework/web/entity/authorization/oauth2/OAuth2AccessEntity.java
  36. 29 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/OAuth2Authorization.java
  37. 35 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/TokenRequest.java
  38. 55 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/client/OAuth2Client.java
  39. 30 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/client/OAuth2ClientService.java
  40. 41 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/exception/GrantTokenException.java
  41. 92 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/AbstractAuthorizationService.java
  42. 115 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/DefaultOAuth2Granter.java
  43. 122 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/HttpTokenRequest.java
  44. 31 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/OAuth2Granter.java
  45. 31 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/client/ClientCredentialGranter.java
  46. 31 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/client/ClientCredentialRequest.java
  47. 57 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/client/DefaultClientCredentialGranter.java
  48. 50 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/client/HttpClientCredentialRequest.java
  49. 9 6
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-entity/src/main/java/org/hswebframework/web/entity/authorization/oauth2/AuthorizationCodeEntity.java
  50. 31 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/AuthorizationCodeGranter.java
  51. 36 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/AuthorizationCodeRequest.java
  52. 29 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/AuthorizationCodeService.java
  53. 40 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/AuthorizationCodeTokenRequest.java
  54. 86 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/DefaultAuthorizationCodeGranter.java
  55. 63 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/HttpAuthorizationCodeRequest.java
  56. 67 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/code/HttpAuthorizationCodeTokenRequest.java
  57. 69 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/implicit/DefaultImplicitGranter.java
  58. 55 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/implicit/HttpImplicitRequest.java
  59. 31 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/implicit/ImplicitGranter.java
  60. 36 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/implicit/ImplicitRequest.java
  61. 74 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/password/DefaultPasswordGranter.java
  62. 58 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/password/HttpPasswordRequest.java
  63. 31 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/password/PasswordGranter.java
  64. 34 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/password/PasswordRequest.java
  65. 28 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/password/PasswordService.java
  66. 78 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/refresh/DefaultRefreshTokenGranter.java
  67. 66 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/refresh/HttpRefreshTokenRequest.java
  68. 31 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/refresh/RefreshTokenGranter.java
  69. 38 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/support/refresh/RefreshTokenRequest.java
  70. 36 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/token/AccessTokenService.java
  71. 59 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/README.md
  72. 12 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/pom.xml
  73. 124 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/AccessTokenInfo.java
  74. 30 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/GrantType.java
  75. 36 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/OAuth2Constants.java
  76. 30 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/OAuth2RequestBuilder.java
  77. 27 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/OAuth2RequestBuilderFactory.java
  78. 64 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/OAuth2RequestService.java
  79. 65 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/OAuth2SessionBuilder.java
  80. 45 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/exception/OAuth2RequestException.java
  81. 27 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/listener/AutoRegisterOAuth2Listener.java
  82. 51 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/listener/OAuth2CodeAuthBeforeEvent.java
  83. 27 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/listener/OAuth2Event.java
  84. 28 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/listener/OAuth2Listener.java
  85. 131 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/request/OAuth2Request.java
  86. 73 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/request/OAuth2Session.java
  87. 29 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/request/ReTry.java
  88. 28 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/request/TokenExpiredCallBack.java
  89. 86 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/response/OAuth2Response.java
  90. 28 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/response/ResponseConvert.java
  91. 34 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-core/pom.xml
  92. 99 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-core/src/main/java/org/hswebframework/web/oauth2/core/ErrorType.java
  93. 31 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-core/src/main/java/org/hswebframework/web/oauth2/core/GrantType.java
  94. 41 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-core/src/main/java/org/hswebframework/web/oauth2/core/OAuth2Constants.java
  95. 29 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-core/src/main/java/org/hswebframework/web/oauth2/core/ResponseType.java
  96. 33 0
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-resource-server/pom.xml
  97. 0 199
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-controller/src/main/java/org/hswebframework/web/authorization/oauth2/controller/OAuth2AuthorizationController.java
  98. 0 266
      hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-simple/src/main/java/org/hswebframework/web/authorization/oauth2/simple/SimpleOAuth2ServerService.java
  99. 3 1
      hsweb-authorization/hsweb-authorization-oauth2/pom.xml
  100. 0 0
      hsweb-authorization/hsweb-authorization-shiro/pom.xml

+ 4 - 4
hsweb-authorization/hsweb-authorization-api/README.md

@@ -21,8 +21,8 @@ _点击名称,查看源代码注释获得使用说明_
 
 | 类名       | 说明          | 
 | ------------- |:-------------:| 
-| [`Authorization`](src/main/java/org/hswebframework/web/authorization/Authorization.java)    | 用户的认证信息 | 
-| [`AuthorizationHolder`](src/main/java/org/hswebframework/web/authorization/AuthorizationHolder.java)      | 用于获取当前登录用户的认证信息      | 
+| [`Authentication`](src/main/java/org/hswebframework/web/authorization/Authentication.java)    | 用户的认证信息 | 
+| [`AuthenticationHolder`](src/main/java/org/hswebframework/web/authorization/AuthenticationHolder.java)      | 用于获取当前登录用户的认证信息      | 
 
 
 ### Listener
@@ -46,9 +46,9 @@ api提供[AuthorizationListener](src/main/java/org/hswebframework/web/authorizat
 public class CustomAuthorizationSuccessListener implements AuthorizationListener<AuthorizationSuccessEvent>{
         @Override
         public void on(AuthorizationSuccessEvent event) {
-            Authorization authorization=event.getAuthorization();
+            Authentication authentication=event.getAuthentication();
             //....
-            System.out.println(authorization.getUser().getName()+"登录啦");
+            System.out.println(authentication.getUser().getName()+"登录啦");
         }
 }
 ```

+ 7 - 1
hsweb-authorization/hsweb-authorization-api/pom.xml

@@ -10,5 +10,11 @@
     <modelVersion>4.0.0</modelVersion>
 
     <artifactId>hsweb-authorization-api</artifactId>
-
+    <dependencies>
+        <dependency>
+            <groupId>org.hswebframework.web</groupId>
+            <artifactId>hsweb-boost-aop</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+    </dependencies>
 </project>

+ 26 - 4
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/Authorization.java

@@ -20,9 +20,8 @@ package org.hswebframework.web.authorization;
 import java.io.Serializable;
 import java.util.List;
 import java.util.Map;
-import java.util.Objects;
+import java.util.NoSuchElementException;
 import java.util.Optional;
-import java.util.function.Supplier;
 
 /**
  * 用户授权信息,当前登录用户的权限信息,包括用户的基本信息,角色,权限集合等常用信息<br>
@@ -33,10 +32,30 @@ import java.util.function.Supplier;
  * </ul>
  *
  * @author zhouhao
- * @see AuthorizationHolder
+ * @see AuthenticationHolder
+ * @see AuthenticationManager
  * @since 3.0
  */
-public interface Authorization extends Serializable {
+public interface Authentication extends Serializable {
+
+    /**
+     * 获取当前登录的用户权限信息
+     * <pre>
+     *
+     *   Authentication auth= Authentication.current().get();
+     *   //如果权限信息不存在将抛出{@link NoSuchElementException}建议使用下面的方式获取
+     *   Authentication auth=Authentication.current().orElse(null);
+     *   //或者
+     *   Authentication auth=Authentication.current().orElseThrow(AuthorizeException::new);
+     * </pre>
+     *
+     * @return 返回Optional对象进行操作
+     * @see Optional
+     * @see AuthenticationHolder
+     */
+    static Optional<Authentication> current() {
+        return Optional.ofNullable(AuthenticationHolder.get());
+    }
 
     /**
      * @return 用户信息
@@ -97,6 +116,7 @@ public interface Authorization extends Serializable {
      *
      * @param name   属性名称
      * @param object 属性值
+     * @see AuthenticationManager#sync(Authentication)
      */
     void setAttribute(String name, Serializable object);
 
@@ -104,6 +124,7 @@ public interface Authorization extends Serializable {
      * 设置多个属性值,参数为map类型,key为属性名称,value为属性值
      *
      * @param attributes 属性值map
+     * @see AuthenticationManager#sync(Authentication)
      */
     void setAttributes(Map<String, Serializable> attributes);
 
@@ -113,6 +134,7 @@ public interface Authorization extends Serializable {
      * @param name 属性名
      * @param <T>  被删除的值类型
      * @return 被删除的值
+     * @see AuthenticationManager#sync(Authentication)
      */
     <T extends Serializable> T removeAttributes(String name);
 

+ 102 - 0
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthenticationHolder.java

@@ -0,0 +1,102 @@
+/*
+ *  Copyright 2016 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 org.hswebframework.web.ThreadLocalUtils;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.function.Function;
+
+/**
+ * 权限获取器,用于静态方式获取当前登录用户的权限信息.
+ * 例如:
+ * <pre>
+ *     &#064;RequestMapping("/example")
+ *     public ResponseMessage example(){
+ *         Authorization auth = AuthorizationHolder.get();
+ *         return ResponseMessage.ok();
+ *     }
+ * </pre>
+ *
+ * @author zhouhao
+ * @see AuthenticationSupplier
+ * @since 3.0
+ */
+public final class AuthenticationHolder {
+    private static final List<AuthenticationSupplier> suppliers = new ArrayList<>();
+
+    private static final String CURRENT_USER_ID_KEY = Authentication.class.getName() + "_current_id";
+
+    private static final ReadWriteLock lock = new ReentrantReadWriteLock();
+
+    private static Authentication get(Function<AuthenticationSupplier, Authentication> function) {
+        lock.readLock().lock();
+        try {
+            return suppliers.stream()
+                    .map(function)
+                    .filter(Objects::nonNull)
+                    .findFirst().orElse(null);
+        } finally {
+            lock.readLock().unlock();
+        }
+    }
+
+    /**
+     * @return 当前登录的用户权限信息
+     */
+    public static Authentication get() {
+        String currentId = ThreadLocalUtils.get(CURRENT_USER_ID_KEY);
+        if (currentId != null) {
+            return get(currentId);
+        }
+        return get(AuthenticationSupplier::get);
+    }
+
+    /**
+     * 获取指定用户的权限信息
+     *
+     * @param userId 用户ID
+     * @return 权限信息
+     */
+    public static Authentication get(String userId) {
+        return get(supplier -> supplier.get(userId));
+    }
+
+    /**
+     * 初始化 {@link AuthenticationSupplier}
+     *
+     * @param supplier
+     */
+    public static void addSupplier(AuthenticationSupplier supplier) {
+        lock.writeLock().lock();
+        try {
+            suppliers.add(supplier);
+        } finally {
+            lock.writeLock().unlock();
+        }
+    }
+
+    public static void setCureentUserId(String id) {
+        ThreadLocalUtils.put(AuthenticationHolder.CURRENT_USER_ID_KEY, id);
+    }
+}

+ 43 - 0
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthenticationInitializeService.java

@@ -0,0 +1,43 @@
+/*
+ *  Copyright 2016 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;
+
+/**
+ * 授权信息初始化服务接口,使用该接口初始化用的权限信息
+ *
+ * @author zhouhao
+ * @since 3.0
+ */
+public interface AuthenticationInitializeService {
+    /**
+     * 根据用户ID初始化权限信息
+     *
+     * @param userId 用户ID
+     * @return 权限信息
+     */
+    Authentication initUserAuthorization(String userId);
+
+    /**
+     * 将指定的用户初始化为超级管理员权限
+     *
+     * @param userId 用户ID
+     * @return 权限信息
+     */
+    Authentication initAdminAuthorization(String userId);
+}

+ 50 - 0
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthenticationManager.java

@@ -0,0 +1,50 @@
+/*
+ *  Copyright 2016 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 java.io.Serializable;
+import java.util.Map;
+
+/**
+ * 授权信息管理器,用于获取用户授权和同步授权信息
+ *
+ * @author zhouhao
+ * @see 3.0
+ */
+public interface AuthenticationManager {
+    /**
+     * 根据用户ID获取权限信息
+     *
+     * @param userId 用户ID
+     * @return 权限信息
+     */
+    Authentication getByUserId(String userId);
+
+    /**
+     * 同步授权信息,在调用了{@link Authentication#setAttribute(String, Serializable)}或者
+     * {@link Authentication#setAttributes(Map)} 后,需要调用次方法进行同步.
+     * 因为如果权限信息不是存在于内存中,而是redis或者其他方案.
+     * 在调用了上述方法后,实际的存储值并不会发生改变.
+     * 注意: Authentication的实现类应该实现自动同步功能。
+     *
+     * @param authentication 要同步的权限信息
+     * @return 同步后的权限信息
+     */
+    Authentication sync(Authentication authentication);
+}

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

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

+ 0 - 53
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/AuthorizationHolder.java

@@ -1,53 +0,0 @@
-/*
- *  Copyright 2016 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;
-
-/**
- * 权限获取器,用于静态方式获取当前登录用户的权限信息.
- * 例如:
- * <pre>
- *     &#064;RequestMapping("/example")
- *     public ResponseMessage example(){
- *         Authorization auth = AuthorizationHolder.get();
- *         return ResponseMessage.ok();
- *     }
- * </pre>
- *
- * @author zhouhao
- * @see AuthorizationSupplier
- * @since 3.0
- */
-public final class AuthorizationHolder {
-    private static AuthorizationSupplier supplier;
-
-    /**
-     * @return 当前登录用户信息
-     */
-    public static Authorization get() {
-        if (null == supplier) {
-            throw new UnsupportedOperationException("AuthorizationSupplier is null!");
-        }
-        return supplier.get();
-    }
-
-    public static void setSupplier(AuthorizationSupplier supplier) {
-        if (null == AuthorizationHolder.supplier)
-            AuthorizationHolder.supplier = supplier;
-    }
-}

+ 11 - 20
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/Permission.java

@@ -17,8 +17,8 @@
 
 package org.hswebframework.web.authorization;
 
-import org.hswebframework.web.authorization.access.DataAccess;
-import org.hswebframework.web.authorization.access.FieldAccess;
+import org.hswebframework.web.authorization.access.DataAccessConfig;
+import org.hswebframework.web.authorization.access.FieldAccessConfig;
 
 import java.io.Serializable;
 import java.util.Set;
@@ -28,11 +28,10 @@ import java.util.Set;
  * 是用户权限的重要接口。
  *
  * @author zhouhao
- * @see Authorization
+ * @see Authentication
  * @since 3.0
  */
 public interface Permission extends Serializable {
-
     /**
      * 查询
      */
@@ -73,32 +72,24 @@ public interface Permission extends Serializable {
     String ACTION_ENABLE = "enable";
 
     /**
-     * 获取权限ID,权限的唯一标识
-     *
-     * @return id
+     * @return 权限ID,权限的唯一标识
      */
     String getId();
 
     /**
-     * 获取用户对此权限的可操作事件(按钮)
-     *
-     * @return 操作事件(按钮)集合
+     * @return 用户对此权限的可操作事件(按钮)
      */
     Set<String> getActions();
 
     /**
-     * 获取用户对此权限持有的字段权限信息,用于字段级别的控制
-     *
-     * @return 可操作字段集合
-     * @see FieldAccess
+     * @return 用户对此权限持有的字段权限信息, 用于字段级别的控制
+     * @see FieldAccessConfig
      */
-    Set<FieldAccess> getFieldAccesses();
+    Set<FieldAccessConfig> getFieldAccesses();
 
     /**
-     * 获取用户对此权限持有的数据权限信息,用于数据级别的控制
-     *
-     * @return 数据权限信息
-     * @see DataAccess
+     * @return 用户对此权限持有的数据权限信息, 用于数据级别的控制
+     * @see DataAccessConfig
      */
-    Set<DataAccess> getDataAccesses();
+    Set<DataAccessConfig> getDataAccessConfigs();
 }

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

@@ -4,9 +4,9 @@ package org.hswebframework.web.authorization.access;
  * 自定义控制器的数据级权限控制器
  *
  * @author zhouhao
- * @see DataAccess.Type#CUSTOM
+ * @see DefaultType#CUSTOM
  */
-public interface CustomDataAccess extends DataAccess {
+public interface CustomDataAccess extends DataAccessConfig {
 
     /**
      * @return 自定义的控制器
@@ -14,6 +14,6 @@ public interface CustomDataAccess extends DataAccess {
     DataAccessController getController();
 
     default String getType() {
-        return Type.CUSTOM.name();
+        return DefaultType.CUSTOM;
     }
 }

+ 11 - 14
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/access/DataAccess.java

@@ -29,10 +29,10 @@ import java.io.Serializable;
  *
  * @author zhouhao
  * @see org.hswebframework.web.authorization.access.CustomDataAccess
- * @see org.hswebframework.web.authorization.access.OwnCreatedDataAccess
- * @see org.hswebframework.web.authorization.access.ScriptDataAccess
+ * @see OwnCreatedDataAccessConfig
+ * @see ScriptDataAccessConfig
  */
-public interface DataAccess extends Serializable {
+public interface DataAccessConfig extends Serializable {
 
     /**
      * 对数据的操作事件
@@ -50,22 +50,19 @@ public interface DataAccess extends Serializable {
      * 控制方式标识
      *
      * @return 控制方式
-     * @see Type#name()
+     * @see DefaultType
      */
     String getType();
 
     /**
      * 内置3中控制方式
      */
-    enum Type {
-        OWN_CREATED("自己创建的数据"),
-        SCRIPT("脚本"),
-        CUSTOM("自定义控制器");
-
-        public final String text;
-
-        Type(String text) {
-            this.text = text;
-        }
+    interface DefaultType {
+        //自己创建的数据
+        String OWN_CREATED = "OWN_CREATED";
+        //脚本
+        String SCRIPT      = "SCRIPT";
+        //自定义控制器
+        String CUSTOM      = "CUSTOM";
     }
 }

+ 3 - 1
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/access/DataAccessController.java

@@ -1,5 +1,7 @@
 package org.hswebframework.web.authorization.access;
 
+import org.hswebframework.web.boost.aop.context.MethodInterceptorParamContext;
+
 /**
  * 数据级别权限控制器,通过此控制器对当前登录用户进行的操作进行数据级别的权限控制。
  * 如:A用户只能查询自己创建的B数据,A用户只能修改自己创建的B数据
@@ -14,5 +16,5 @@ public interface DataAccessController {
      * @param params 当前操作的方法的参数上下文
      * @return 授权是否通过
      */
-    boolean doAccess(DataAccess access, ParamContext params);
+    boolean doAccess(DataAccessConfig access, MethodInterceptorParamContext params);
 }

+ 4 - 2
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/access/DataAccessHandler.java

@@ -1,5 +1,7 @@
 package org.hswebframework.web.authorization.access;
 
+import org.hswebframework.web.boost.aop.context.MethodInterceptorParamContext;
+
 /**
  * 数据级别权限控制处理器接口,负责处理支持的权限控制配置
  *
@@ -13,7 +15,7 @@ public interface DataAccessHandler {
      * @param access 控制配置
      * @return 是否支持
      */
-    boolean isSupport(DataAccess access);
+    boolean isSupport(DataAccessConfig access);
 
     /**
      * 执行处理,返回处理结果
@@ -22,5 +24,5 @@ public interface DataAccessHandler {
      * @param context 参数上下文
      * @return 处理结果
      */
-    boolean handle(DataAccess access, ParamContext context);
+    boolean handle(DataAccessConfig access, MethodInterceptorParamContext context);
 }

+ 0 - 27
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/access/FieldAccess.java

@@ -1,27 +0,0 @@
-package org.hswebframework.web.authorization.access;
-
-import java.io.Serializable;
-import java.util.Set;
-
-/**
- * 字段级别权限控制配置,表示此用户不能对字段{@link this#getField()} 执行 {@link this#getActions()}操作
- *
- * @author zhouhao
- * @see FieldAccessController
- */
-public interface FieldAccess extends Serializable {
-    /**
-     * 获取字段名称,字段名称支持嵌套如: user.info.name
-     * 此值为不能操作的字段
-     *
-     * @return 字段名称
-     */
-    String getField();
-
-    /**
-     * 对此字段的操作权限
-     *
-     * @return 操作权限集合
-     */
-    Set<String> getActions();
-}

+ 34 - 0
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/access/FieldAccessConfig.java

@@ -0,0 +1,34 @@
+package org.hswebframework.web.authorization.access;
+
+import java.io.Serializable;
+import java.util.Set;
+
+/**
+ * 字段级别权限控制配置,表示此用户不能对字段{@link this#getField()} 执行 {@link this#getActions()}操作
+ *
+ * @author zhouhao
+ * @see FieldAccessController
+ */
+public interface FieldAccessConfig extends Serializable {
+
+    /**
+     * @return 要控制的字段名称, 字段名称支持嵌套如: user.info.name
+     */
+    String getField();
+
+    /**
+     * @return 对此字段的操作权限
+     * @see org.hswebframework.web.authorization.Permission#ACTION_QUERY
+     * @see org.hswebframework.web.authorization.Permission#ACTION_UPDATE
+     */
+    Set<String> getActions();
+
+    default Type getType() {
+        return Type.DENY;
+    }
+
+    enum Type {
+        //目前之支持 deny
+        DENY
+    }
+}

+ 2 - 1
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/access/FieldAccessController.java

@@ -1,6 +1,7 @@
 package org.hswebframework.web.authorization.access;
 
 import org.hswebframework.web.authorization.Permission;
+import org.hswebframework.web.boost.aop.context.MethodInterceptorParamContext;
 
 import java.util.Set;
 
@@ -19,5 +20,5 @@ public interface FieldAccessController {
      * @param params   参数上下文
      * @return 验证是否通过
      */
-    boolean doAccess(String action, Set<FieldAccess> accesses, ParamContext params);
+    boolean doAccess(String action, Set<FieldAccessConfig> accesses, MethodInterceptorParamContext params);
 }

+ 2 - 2
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/access/OwnCreatedDataAccess.java

@@ -5,8 +5,8 @@ package org.hswebframework.web.authorization.access;
  *
  * @author zhouhao
  */
-public interface OwnCreatedDataAccess extends DataAccess {
+public interface OwnCreatedDataAccessConfig extends DataAccessConfig {
     default String getType() {
-        return Type.OWN_CREATED.name();
+        return DefaultType.OWN_CREATED;
     }
 }

+ 2 - 2
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/access/ScriptDataAccess.java

@@ -5,9 +5,9 @@ package org.hswebframework.web.authorization.access;
  *
  * @author zhouhao
  */
-public interface ScriptDataAccess extends DataAccess {
+public interface ScriptDataAccessConfig extends DataAccessConfig {
     default String getType() {
-        return Type.CUSTOM.name();
+        return DefaultType.SCRIPT;
     }
 
     /**

+ 2 - 2
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/annotation/Authorize.java

@@ -63,8 +63,8 @@ public @interface Authorize {
     /**
      * 验证是否为指定user
      *
-     * @return user id array
-     * @see User#getId()
+     * @return username array
+     * @see User#getUsername()
      */
     String[] user() default {};
 

+ 4 - 6
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/annotation/RequiresDataAccess.java

@@ -17,14 +17,11 @@
 
 package org.hswebframework.web.authorization.annotation;
 
-import org.hswebframework.web.authorization.access.DataAccess;
+import org.hswebframework.web.authorization.access.DataAccessConfig;
 import org.hswebframework.web.authorization.access.DataAccessController;
 import org.hswebframework.web.authorization.Permission;
 
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
+import java.lang.annotation.*;
 
 /**
  * 数据级权限控制注解,用于进行需要数据级别权限控制的声明.
@@ -38,6 +35,7 @@ import java.lang.annotation.Target;
  */
 @Target({ElementType.TYPE, ElementType.METHOD})
 @Retention(RetentionPolicy.RUNTIME)
+@Documented
 public @interface RequiresDataAccess {
 
     /**
@@ -48,7 +46,7 @@ public @interface RequiresDataAccess {
 
     /**
      * @return action array
-     * @see DataAccess#getAction()
+     * @see DataAccessConfig#getAction()
      */
     String[] action() default {};
 

+ 2 - 4
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/annotation/RequiresExpression.java

@@ -17,10 +17,7 @@
 
 package org.hswebframework.web.authorization.annotation;
 
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
+import java.lang.annotation.*;
 
 /**
  * 使用表达式进行验证,默认支持spel,ognl表达式。
@@ -30,6 +27,7 @@ import java.lang.annotation.Target;
  */
 @Target({ElementType.TYPE, ElementType.METHOD})
 @Retention(RetentionPolicy.RUNTIME)
+@Documented
 public @interface RequiresExpression {
 
     /**

+ 4 - 7
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/annotation/RequiresFieldAccess.java

@@ -18,13 +18,9 @@
 package org.hswebframework.web.authorization.annotation;
 
 import org.hswebframework.web.authorization.Permission;
-import org.hswebframework.web.authorization.access.DataAccessController;
-import org.hswebframework.web.authorization.access.FieldAccess;
+import org.hswebframework.web.authorization.access.FieldAccessConfig;
 
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
+import java.lang.annotation.*;
 
 /**
  * 字段级权限控制注解,用于进行需要字段级别权限控制的声明.
@@ -38,6 +34,7 @@ import java.lang.annotation.Target;
  */
 @Target({ElementType.TYPE, ElementType.METHOD})
 @Retention(RetentionPolicy.RUNTIME)
+@Documented
 public @interface RequiresFieldAccess {
 
     /**
@@ -48,7 +45,7 @@ public @interface RequiresFieldAccess {
 
     /**
      * @return action
-     * @see FieldAccess#getActions()
+     * @see FieldAccessConfig#getActions()
      */
     String action();
 

+ 6 - 6
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/listener/event/AuthorizationExitEvent.java

@@ -18,7 +18,7 @@
 
 package org.hswebframework.web.authorization.listener.event;
 
-import org.hswebframework.web.authorization.Authorization;
+import org.hswebframework.web.authorization.Authentication;
 
 /**
  * 退出登录事件
@@ -26,13 +26,13 @@ import org.hswebframework.web.authorization.Authorization;
  * @author zhouhao
  */
 public class AuthorizationExitEvent implements AuthorizationEvent {
-    private Authorization authorization;
+    private Authentication authentication;
 
-    public AuthorizationExitEvent(Authorization authorization) {
-        this.authorization = authorization;
+    public AuthorizationExitEvent(Authentication authentication) {
+        this.authentication = authentication;
     }
 
-    public Authorization getAuthorization() {
-        return authorization;
+    public Authentication getAuthentication() {
+        return authentication;
     }
 }

+ 7 - 7
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/listener/event/AuthorizationSuccessEvent.java

@@ -18,7 +18,7 @@
 
 package org.hswebframework.web.authorization.listener.event;
 
-import org.hswebframework.web.authorization.Authorization;
+import org.hswebframework.web.authorization.Authentication;
 
 import java.util.Optional;
 import java.util.function.Function;
@@ -27,21 +27,21 @@ import java.util.function.Function;
  * 授权成功事件,当授权成功时,触发此事件,并传入授权的信息
  *
  * @author zhouhao
- * @see Authorization
+ * @see Authentication
  * @since 3.0
  */
 public class AuthorizationSuccessEvent implements AuthorizationEvent {
-    private Authorization authorization;
+    private Authentication authentication;
 
     private Function<String,Object> parameterGetter;
 
-    public AuthorizationSuccessEvent(Authorization authorization, Function<String, Object> parameterGetter) {
-        this.authorization = authorization;
+    public AuthorizationSuccessEvent(Authentication authentication, Function<String, Object> parameterGetter) {
+        this.authentication = authentication;
         this.parameterGetter = parameterGetter;
     }
 
-    public Authorization getAuthorization() {
-        return authorization;
+    public Authentication getAuthentication() {
+        return authentication;
     }
 
     @SuppressWarnings("unchecked")

+ 5 - 1
hsweb-authorization/hsweb-authorization-oauth2/README.md

@@ -1,3 +1,7 @@
 # oauth2 认证模块
 
-暂未完成
+# 模块说明
+| 模块       | 说明          |   进度 |
+| ------------- |:-------------:| ----|
+|[hsweb-authorization-oauth2-client](hsweb-authorization-oauth2-client)|OAuth2 客户端API| 10%|
+|[hsweb-authorization-oauth2-server](hsweb-authorization-oauth2-server)|OAuth2 服务端API| 50%|

+ 14 - 5
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-entity/pom.xml

@@ -21,15 +21,13 @@
          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-server</artifactId>
+        <artifactId>hsweb-authorization-oauth2</artifactId>
         <groupId>org.hswebframework.web</groupId>
         <version>3.0-SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
 
-    <artifactId>hsweb-authorization-oauth2-server-entity</artifactId>
-
-
+    <artifactId>hsweb-authorization-oauth2-auth-server</artifactId>
     <dependencies>
         <dependency>
             <groupId>org.hswebframework.web</groupId>
@@ -38,8 +36,19 @@
         </dependency>
         <dependency>
             <groupId>org.hswebframework.web</groupId>
-            <artifactId>hsweb-authorization-api</artifactId>
+            <artifactId>hsweb-authorization-oauth2-core</artifactId>
             <version>${project.version}</version>
         </dependency>
+        <dependency>
+            <groupId>javax.servlet</groupId>
+            <artifactId>servlet-api</artifactId>
+            <version>2.5</version>
+            <optional>true</optional>
+        </dependency>
+        <dependency>
+            <groupId>org.hswebframework.web</groupId>
+            <artifactId>hsweb-commons-utils</artifactId>
+            <version>3.0-SNAPSHOT</version>
+        </dependency>
     </dependencies>
 </project>

+ 5 - 6
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-api/src/main/java/org/hswebframework/web/authorization/oauth2/api/OAuth2ServerService.java

@@ -18,8 +18,9 @@
 
 package org.hswebframework.web.authorization.oauth2.api;
 
-import org.hswebframework.web.entity.authorization.oauth2.OAuth2AccessEntity;
-import org.hswebframework.web.entity.authorization.oauth2.OAuth2ClientEntity;
+
+import org.hswebframework.web.authorization.oauth2.api.entity.OAuth2AccessEntity;
+import org.hswebframework.web.authorization.oauth2.api.entity.OAuth2ClientEntity;
 
 /**
  * @author zhouhao
@@ -30,11 +31,9 @@ public interface OAuth2ServerService {
 
     OAuth2ClientEntity getClient(String clientId, String clientSecret);
 
-    OAuth2AccessEntity getAccessByToken(String accessToken);
-
-    String requestCode(String clientId, String userId, String scope);
+    String requestCode(String clientId, String userId, String scope, String redirectUri);
 
-    OAuth2AccessEntity requestTokenByCode(String code, String clientId, String clientSecret, String scope);
+    OAuth2AccessEntity requestTokenByCode(String code, String clientId, String clientSecret, String scope, String redirectUri);
 
     OAuth2AccessEntity requestTokenByClientCredential(String clientId, String clientSecret);
 

+ 30 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/api/entity/AuthorizationCodeEntity.java

@@ -0,0 +1,30 @@
+/*
+ *  Copyright 2016 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.api.entity;
+
+import org.hswebframework.web.authorization.oauth2.server.support.code.AuthorizationCode;
+import org.hswebframework.web.commons.entity.Entity;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface AuthorizationCodeEntity extends AuthorizationCode, Entity {
+}

+ 28 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/api/entity/OAuth2AccessEntity.java

@@ -0,0 +1,28 @@
+/*
+ *  Copyright 2016 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.api.entity;
+
+import org.hswebframework.web.authorization.oauth2.server.OAuth2AccessToken;
+import org.hswebframework.web.commons.entity.Entity;
+
+/**
+ * @author zhouhao
+ */
+public interface OAuth2AccessEntity extends OAuth2AccessToken, Entity {
+}

+ 12 - 11
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-entity/src/main/java/org/hswebframework/web/entity/authorization/oauth2/OAuth2ClientEntity.java

@@ -16,18 +16,18 @@
  *
  */
 
-package org.hswebframework.web.entity.authorization.oauth2;
+package org.hswebframework.web.authorization.oauth2.api.entity;
 
-import org.hswebframework.web.authorization.User;
+import org.hswebframework.web.authorization.oauth2.server.client.OAuth2Client;
 import org.hswebframework.web.commons.entity.GenericEntity;
 import org.hswebframework.web.commons.entity.RecordCreationEntity;
 
-import java.util.List;
+import java.util.Set;
 
 /**
  * @author zhouhao
  */
-public interface OAuth2ClientEntity extends GenericEntity<String>, RecordCreationEntity {
+public interface OAuth2ClientEntity extends GenericEntity<String>, OAuth2Client, RecordCreationEntity {
 
     // client_id
     @Override
@@ -49,7 +49,7 @@ public interface OAuth2ClientEntity extends GenericEntity<String>, RecordCreatio
 
     /**
      * @return 客户端所有者
-     * @see User#getId()
+     * @see org.hswebframework.web.authorization.User#getId()
      */
     String getOwnerId();
 
@@ -63,12 +63,13 @@ public interface OAuth2ClientEntity extends GenericEntity<String>, RecordCreatio
 
     void setType(String type);
 
-    List<String> getSupportGrantType();
+    Set<String> getSupportGrantTypes();
 
-    void setSupportGrantType(List<String> supportGrantType);
+    Set<String> getDefaultGrantScope();
 
-    default boolean grantTypeIsSupport(String grantType) {
-        if (getSupportGrantType() == null) return false;
-        return getSupportGrantType().contains(grantType) || getSupportGrantType().contains("*");
-    }
+    void setDefaultGrantScope(Set<String> defaultGrantScope);
+
+    void setSupportGrantTypes(Set<String> supportGrantType);
+
+    void setEnabled(Boolean enabled);
 }

+ 16 - 4
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-entity/src/main/java/org/hswebframework/web/entity/authorization/oauth2/SimpleAuthorizationCodeEntity.java

@@ -16,9 +16,11 @@
  *
  */
 
-package org.hswebframework.web.entity.authorization.oauth2;
+package org.hswebframework.web.authorization.oauth2.api.entity;
 
 
+import java.util.Set;
+
 /**
  * @author zhouhao
  */
@@ -31,13 +33,23 @@ public class SimpleAuthorizationCodeEntity implements AuthorizationCodeEntity {
 
     private Long createTime;
 
-    private String scope;
+    private Set<String> scope;
+
+    private String redirectUri;
+
+    public String getRedirectUri() {
+        return redirectUri;
+    }
+
+    public void setRedirectUri(String redirectUri) {
+        this.redirectUri = redirectUri;
+    }
 
-    public String getScope() {
+    public Set<String> getScope() {
         return scope;
     }
 
-    public void setScope(String scope) {
+    public void setScope(Set<String> scope) {
         this.scope = scope;
     }
 

+ 27 - 16
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-entity/src/main/java/org/hswebframework/web/entity/authorization/oauth2/SimpleOAuth2AccessEntity.java

@@ -16,7 +16,9 @@
  *
  */
 
-package org.hswebframework.web.entity.authorization.oauth2;
+package org.hswebframework.web.authorization.oauth2.api.entity;
+
+import java.util.Set;
 
 /**
  * TODO 完成注释
@@ -27,19 +29,21 @@ public class SimpleOAuth2AccessEntity implements OAuth2AccessEntity {
 
     private String clientId;
 
-    private String userId;
+    private String ownerId;
 
     private String accessToken;
 
     private String refreshToken;
 
-    private Long expireIn;
+    private Integer expiresIn;
 
     private Long createTime;
 
     private Long updateTime;
 
-    private String scope;
+    private Set<String> scope;
+
+    private String grantType;
 
     @Override
     public String getClientId() {
@@ -52,13 +56,13 @@ public class SimpleOAuth2AccessEntity implements OAuth2AccessEntity {
     }
 
     @Override
-    public String getUserId() {
-        return userId;
+    public String getOwnerId() {
+        return ownerId;
     }
 
     @Override
-    public void setUserId(String userId) {
-        this.userId = userId;
+    public void setOwnerId(String ownerId) {
+        this.ownerId = ownerId;
     }
 
     @Override
@@ -81,14 +85,12 @@ public class SimpleOAuth2AccessEntity implements OAuth2AccessEntity {
         this.refreshToken = refreshToken;
     }
 
-    @Override
-    public Long getExpireIn() {
-        return expireIn;
+    public Integer getExpiresIn() {
+        return expiresIn;
     }
 
-    @Override
-    public void setExpireIn(Long expireIn) {
-        this.expireIn = expireIn;
+    public void setExpiresIn(Integer expiresIn) {
+        this.expiresIn = expiresIn;
     }
 
     @Override
@@ -112,13 +114,22 @@ public class SimpleOAuth2AccessEntity implements OAuth2AccessEntity {
     }
 
     @Override
-    public String getScope() {
+    public Set<String> getScope() {
         return scope;
     }
 
     @Override
-    public void setScope(String scope) {
+    public void setScope(Set<String> scope) {
         this.scope = scope;
     }
 
+    @Override
+    public String getGrantType() {
+        return grantType;
+    }
+
+    @Override
+    public void setGrantType(String grantType) {
+        this.grantType = grantType;
+    }
 }

+ 28 - 4
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-entity/src/main/java/org/hswebframework/web/entity/authorization/oauth2/SimpleOAuth2ClientEntity.java

@@ -16,11 +16,12 @@
  *
  */
 
-package org.hswebframework.web.entity.authorization.oauth2;
+package org.hswebframework.web.authorization.oauth2.api.entity;
 
 import org.hswebframework.web.commons.entity.SimpleGenericEntity;
 
 import java.util.List;
+import java.util.Set;
 
 /**
  * @author zhouhao
@@ -42,7 +43,11 @@ public class SimpleOAuth2ClientEntity extends SimpleGenericEntity<String> implem
 
     private String describe;
 
-    private List<String> supportGrantType;
+    private Set<String> supportGrantType;
+
+    private Set<String> defaultGrantScope;
+
+    private Boolean enabled;
 
     public String getDescribe() {
         return describe;
@@ -117,12 +122,31 @@ public class SimpleOAuth2ClientEntity extends SimpleGenericEntity<String> implem
     }
 
     @Override
-    public List<String> getSupportGrantType() {
+    public Set<String> getSupportGrantTypes() {
         return supportGrantType;
     }
 
     @Override
-    public void setSupportGrantType(List<String> supportGrantType) {
+    public void setSupportGrantTypes(Set<String> supportGrantType) {
         this.supportGrantType = supportGrantType;
     }
+
+    @Override
+    public Set<String> getDefaultGrantScope() {
+        return defaultGrantScope;
+    }
+
+    @Override
+    public void setDefaultGrantScope(Set<String> defaultGrantScope) {
+        this.defaultGrantScope = defaultGrantScope;
+    }
+
+    @Override
+    public Boolean isEnabled() {
+        return enabled;
+    }
+
+    public void setEnabled(Boolean enabled) {
+        this.enabled = enabled;
+    }
 }

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

@@ -0,0 +1,27 @@
+/*
+ *  Copyright 2016 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 interface AuthorizationService {
+}

+ 28 - 14
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-entity/src/main/java/org/hswebframework/web/entity/authorization/oauth2/OAuth2AccessEntity.java

@@ -16,35 +16,36 @@
  *
  */
 
-package org.hswebframework.web.entity.authorization.oauth2;
+package org.hswebframework.web.authorization.oauth2.server;
 
-import org.hswebframework.web.commons.entity.Entity;
+import org.hibernate.validator.constraints.NotBlank;
+
+import javax.validation.constraints.NotNull;
+import java.util.Set;
 
 /**
+ * TODO 完成注释
+ *
  * @author zhouhao
  */
-public interface OAuth2AccessEntity extends Entity {
+public interface OAuth2AccessToken {
 
+    @NotBlank
     String getClientId();
 
     void setClientId(String clientId);
 
-    String getUserId();
-
-    void setUserId(String userId);
-
+    @NotBlank
     String getAccessToken();
 
     void setAccessToken(String accessToken);
 
+    @NotBlank
     String getRefreshToken();
 
     void setRefreshToken(String refreshToken);
 
-    Long getExpireIn();
-
-    void setExpireIn(Long expireIn);
-
+    @NotNull
     Long getCreateTime();
 
     void setCreateTime(Long createTime);
@@ -53,9 +54,22 @@ public interface OAuth2AccessEntity extends Entity {
 
     void setUpdateTime(Long updateTime);
 
-    String getScope();
+    @NotNull
+    String getOwnerId();
+
+    void setOwnerId(String ownerId);
+
+    @NotNull
+    Integer getExpiresIn();
+
+    void setExpiresIn(Integer expiresIn);
+
+    Set<String> getScope();
 
-    void setScope(String scope);
+    void setScope(Set<String> scope);
 
+    @NotNull
+    String getGrantType();
 
-}
+    void setGrantType(String grantType);
+}

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

@@ -0,0 +1,29 @@
+/*
+ *  Copyright 2016 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;
+
+}

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

@@ -0,0 +1,35 @@
+/*
+ *  Copyright 2016 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;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface TokenRequest {
+    default Optional<String> getParameter(String name) {
+        return Optional.ofNullable(getParameters().get(name));
+    }
+
+    Map<String, String> getParameters();
+}

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

@@ -0,0 +1,55 @@
+/*
+ *  Copyright 2016 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.Set;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface OAuth2Client {
+    String getId();
+
+    String getSecret();
+
+    String getName();
+
+    String getRedirectUri();
+
+    String getOwnerId();
+
+    Long getCreateTime();
+
+    Boolean isEnabled();
+
+    /**
+     * @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("*"));
+    }
+}

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

@@ -0,0 +1,30 @@
+/*
+ *  Copyright 2016 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;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface OAuth2ClientService {
+    OAuth2Client getClientById(String id);
+
+    OAuth2Client getClientByOwnerId(String ownerId);
+}

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

@@ -0,0 +1,41 @@
+/*
+ *  Copyright 2016 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;
+    }
+}

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

@@ -0,0 +1,92 @@
+/*
+ *  Copyright 2016 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.OAuth2ClientService;
+import org.hswebframework.web.authorization.oauth2.server.exception.GrantTokenException;
+import org.hswebframework.web.authorization.oauth2.server.token.AccessTokenService;
+import org.hswebframework.web.oauth2.core.ErrorType;
+
+import static org.hswebframework.web.oauth2.core.ErrorType.*;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public abstract class AbstractAuthorizationService {
+    protected AccessTokenService  accessTokenService;
+    protected OAuth2ClientService clientService;
+
+    public AccessTokenService getAccessTokenService() {
+        return accessTokenService;
+    }
+
+    public void setAccessTokenService(AccessTokenService accessTokenService) {
+        this.accessTokenService = accessTokenService;
+    }
+
+    public OAuth2ClientService getClientService() {
+        return clientService;
+    }
+
+    public void setClientService(OAuth2ClientService clientService) {
+        this.clientService = clientService;
+    }
+
+    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 (Boolean.TRUE != client.isEnabled()) {
+            throw new GrantTokenException(CLIENT_DISABLED);
+        }
+        return client;
+    }
+
+    protected OAuth2Client getClientByOwnerId(String ownerId) {
+        return checkClient(clientService.getClientByOwnerId(ownerId));
+    }
+
+    protected OAuth2Client getClient(String clientId) {
+        return checkClient(clientService.getClientById(clientId));
+    }
+
+}

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

@@ -0,0 +1,115 @@
+/*
+ *  Copyright 2016 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;
+        }
+
+    }
+
+}

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

@@ -0,0 +1,122 @@
+/*
+ *  Copyright 2016 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.hswebframwork.utils.StringUtils;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.*;
+
+/**
+ * TODO 完成注释
+ *
+ * @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(Objects::nonNull)
+                .map(scope -> new HashSet<>(Arrays.asList(scope.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);
+            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);
+    }
+}

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

@@ -0,0 +1,31 @@
+/*
+ *  Copyright 2016 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;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface OAuth2Granter {
+    OAuth2AccessToken grant(String grantType, TokenRequest request);
+}

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

@@ -0,0 +1,31 @@
+/*
+ *  Copyright 2016 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;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface ClientCredentialGranter extends AuthorizationService {
+    OAuth2AccessToken requestToken(ClientCredentialRequest request);
+}

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

@@ -0,0 +1,31 @@
+/*
+ *  Copyright 2016 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();
+}

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

@@ -0,0 +1,57 @@
+/*
+ *  Copyright 2016 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.*;
+
+/**
+ * TODO 完成注释
+ *
+ * @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);
+
+        //保存token
+        return accessTokenService.saveOrUpdateToken(accessToken);
+    }
+}

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

@@ -0,0 +1,50 @@
+/*
+ *  Copyright 2016 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();
+    }
+}

+ 9 - 6
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-entity/src/main/java/org/hswebframework/web/entity/authorization/oauth2/AuthorizationCodeEntity.java

@@ -16,16 +16,15 @@
  *
  */
 
-package org.hswebframework.web.entity.authorization.oauth2;
+package org.hswebframework.web.authorization.oauth2.server.support.code;
 
-import org.hswebframework.web.commons.entity.Entity;
+import java.util.Set;
 
 /**
- * TODO 完成注释
  *
  * @author zhouhao
  */
-public interface AuthorizationCodeEntity extends Entity {
+public interface AuthorizationCode {
     String getClientId();
 
     void setClientId(String clientId);
@@ -42,7 +41,11 @@ public interface AuthorizationCodeEntity extends Entity {
 
     void setCreateTime(Long createTime);
 
-    String getScope();
+    Set<String> getScope();
 
-    void setScope(String scope);
+    void setScope(Set<String> scope);
+
+    String getRedirectUri();
+
+    void setRedirectUri(String redirectUri);
 }

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

@@ -0,0 +1,31 @@
+/*
+ *  Copyright 2016 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;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface AuthorizationCodeGranter extends AuthorizationService {
+    OAuth2AccessToken requestToken(AuthorizationCodeTokenRequest request);
+}

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

@@ -0,0 +1,36 @@
+/*
+ *  Copyright 2016 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;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface AuthorizationCodeRequest {
+    String getClientId();
+
+    String getUserId();
+
+    Set<String> getScope();
+
+    String getRedirectUri();
+}

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

@@ -0,0 +1,29 @@
+/*
+ *  Copyright 2016 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);
+}

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

@@ -0,0 +1,40 @@
+/*
+ *  Copyright 2016 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;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface AuthorizationCodeTokenRequest extends TokenRequest {
+    String getCode();
+
+    String getClientId();
+
+    String getClientSecret();
+
+    Set<String> getScope();
+
+    String getRedirectUri();
+}

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

@@ -0,0 +1,86 @@
+/*
+ *  Copyright 2016 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.*;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public class DefaultAuthorizationCodeGranter extends AbstractAuthorizationService implements AuthorizationCodeGranter {
+
+    //默认有效时间为10分钟
+    private long codeTimeOut = 10 * 60 * 1000;
+
+    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);
+    }
+}

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

@@ -0,0 +1,63 @@
+/*
+ *  Copyright 2016 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);
+    }
+
+}

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

@@ -0,0 +1,67 @@
+/*
+ *  Copyright 2016 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);
+    }
+}

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

@@ -0,0 +1,69 @@
+/*
+ *  Copyright 2016 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.*;
+
+/**
+ * TODO 完成注释
+ *
+ * @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);
+        return accessTokenService.saveOrUpdateToken(accessToken);
+    }
+}

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

@@ -0,0 +1,55 @@
+/*
+ *  Copyright 2016 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;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public class HttpImplicitRequest extends HttpTokenRequest implements ImplicitRequest {
+
+    public HttpImplicitRequest(HttpServletRequest request) {
+        super(request);
+    }
+
+    @Override
+    public String getClientId() {
+        return getParameter(OAuth2Constants.client_id)
+                .orElseThrow(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);
+    }
+}

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

@@ -0,0 +1,31 @@
+/*
+ *  Copyright 2016 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);
+}

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

@@ -0,0 +1,36 @@
+/*
+ *  Copyright 2016 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;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface ImplicitRequest extends TokenRequest {
+    String getClientId();
+
+    Set<String> getScope();
+
+    String getRedirectUri();
+}

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

@@ -0,0 +1,74 @@
+/*
+ *  Copyright 2016 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.*;
+
+/**
+ * TODO 完成注释
+ *
+ * @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());
+        return accessTokenService.saveOrUpdateToken(accessToken);
+    }
+}

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

@@ -0,0 +1,58 @@
+/*
+ *  Copyright 2016 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;
+    }
+}

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

@@ -0,0 +1,31 @@
+/*
+ *  Copyright 2016 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;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface PasswordGranter extends AuthorizationService {
+    OAuth2AccessToken requestToken(PasswordRequest request);
+}

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

@@ -0,0 +1,34 @@
+/*
+ *  Copyright 2016 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();
+}

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

@@ -0,0 +1,28 @@
+/*
+ *  Copyright 2016 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;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface PasswordService {
+    String getUserIdByUsernameAndPassword(String username, String password);
+}

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

@@ -0,0 +1,78 @@
+/*
+ *  Copyright 2016 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.*;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public class DefaultRefreshTokenGranter extends AbstractAuthorizationService implements RefreshTokenGranter {
+
+    //默认有效时间为1年
+    private long refreshTokenTimeOut = 1 * 365 * 24 * 60 * 60 * 1000;
+
+    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(ILLEGAL_REFRESH_TOKEN);
+        }
+        if (System.currentTimeMillis() - accessToken.getCreateTime() > refreshTokenTimeOut) {
+            throw new GrantTokenException(EXPIRED_REFRESH_TOKEN);
+        }
+        Set<String> newRange = request.getScope() != null ? request.getScope() : accessToken.getScope();
+        if (!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);
+    }
+}

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

@@ -0,0 +1,66 @@
+/*
+ *  Copyright 2016 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.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 HttpRefreshTokenRequest extends HttpTokenRequest implements RefreshTokenRequest {
+
+    public HttpRefreshTokenRequest(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 getClientId() {
+        return clientCredentials.getPrincipal();
+    }
+
+    @Override
+    public String getClientSecret() {
+        return clientCredentials.getCredentials();
+    }
+
+    @Override
+    public String getRefreshToken() {
+        return getParameter(OAuth2Constants.refresh_token).orElse(null);
+    }
+
+    @Override
+    public Set<String> getScope() {
+        return scope;
+    }
+}

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

@@ -0,0 +1,31 @@
+/*
+ *  Copyright 2016 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.AuthorizationService;
+import org.hswebframework.web.authorization.oauth2.server.OAuth2AccessToken;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface RefreshTokenGranter extends AuthorizationService {
+    OAuth2AccessToken refreshToken(RefreshTokenRequest request);
+}

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

@@ -0,0 +1,38 @@
+/*
+ *  Copyright 2016 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.TokenRequest;
+
+import java.util.Set;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface RefreshTokenRequest extends TokenRequest {
+    String getClientId();
+
+    String getClientSecret();
+
+    String getRefreshToken();
+
+    Set<String> getScope();
+}

+ 36 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-auth-server/src/main/java/org/hswebframework/web/authorization/oauth2/server/token/AccessTokenService.java

@@ -0,0 +1,36 @@
+/*
+ *  Copyright 2016 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.token;
+
+import org.hswebframework.web.authorization.oauth2.server.OAuth2AccessToken;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface AccessTokenService {
+    OAuth2AccessToken createToken();
+
+    OAuth2AccessToken getTokenByRefreshToken(String refreshToken);
+
+    OAuth2AccessToken getTokenByAccessToken(String accessToken);
+
+    OAuth2AccessToken saveOrUpdateToken(OAuth2AccessToken token);
+}

+ 59 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/README.md

@@ -0,0 +1,59 @@
+# OAuth2客户端API
+本模块只提供接口,未提供实现,使用时请自行引入相关实现模块
+
+## 处理OAuth2授权码方式的回调
+方式一、创建一个类并实现 `OAuth2Listener` 使用`OAuth2CodeAuthBeforeEvent`作为泛型,例如
+```java
+ public class MyOAuth2Listener
+         implements OAuth2Listener<OAuth2CodeAuthBeforeEvent> {
+     @Override
+     public void on(OAuth2CodeAuthBeforeEvent event) {
+          String authCode= event.getCode();
+     }
+ }
+```
+
+注册到对应的oauth2服务配置,例如:
+```java
+@Autowired
+OAuth2RequestService requestService;
+public void demo(){
+      requestService.registerListener("oauth2_server",new MyOAuth2Listener());
+}
+```
+
+方式二、使用`AutoRegisterOAuth2Listener`
+```java
+ @Component
+ public class MyOAuth2Listener
+         implements AutoRegisterOAuth2Listener<OAuth2CodeAuthBeforeEvent> {
+    @Override
+    public String getServerId(){
+        return "oauth2_server";
+    }
+    @Override
+    public void on(OAuth2CodeAuthBeforeEvent event) {
+        String authCode= event.getCode();
+    }
+ }
+```
+
+## 发起OAuth2请求
+```java
+@Autowired
+OAuth2RequestService requestService;
+
+public void demo(){
+   //第一步
+   OAuth2Session session = requestService
+                .create(oatuh2ServerId)
+                .byAuthorizationCode(authorizationCode); //使用授权码方式,将自动获取access_token信息并存入会话
+  
+    //第二步
+    String oauth2ApiUri = "oauth2/user-auth-info";
+    Authentication authentication = session
+                   .request(oauth2ApiUri)       // 创建api请求,将自动使用第一步获得的token
+                   .get().ifSuccess()           // http GET请求
+                   .as(Authentication.class);   // 响应结果转为Class
+}
+```

+ 12 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/pom.xml

@@ -30,4 +30,16 @@
     <artifactId>hsweb-authorization-oauth2-client</artifactId>
 
 
+    <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-oauth2-core</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+    </dependencies>
 </project>

+ 124 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/AccessTokenInfo.java

@@ -0,0 +1,124 @@
+/*
+ *  Copyright 2016 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.client;
+
+/**
+ * 默认的服务实现
+ *
+ * @author zhouhao
+ */
+public class AccessTokenInfo {
+    //授权码
+    private String  accessToken;
+    //更新码
+    private String  refreshToken;
+    //有效期
+    private Integer expiresIn;
+    //授权范围
+    private String  scope;
+
+    private Long createTime;
+
+    private Long updateTime;
+
+    private String tokenType;
+
+    public boolean isExpire() {
+        return updateTime != null && System.currentTimeMillis() - updateTime > expiresIn * 1000;
+    }
+
+    public String getTokenType() {
+        return tokenType;
+    }
+
+    public void setTokenType(String tokenType) {
+        this.tokenType = tokenType;
+    }
+
+    /**
+     * @return 授权码
+     */
+    public String getAccessToken() {
+        return this.accessToken;
+    }
+
+    /**
+     * 设置 授权码
+     */
+    public void setAccessToken(String accessToken) {
+        this.accessToken = accessToken;
+    }
+
+    /**
+     * @return 更新码
+     */
+    public String getRefreshToken() {
+        return this.refreshToken;
+    }
+
+    /**
+     * 设置 更新码
+     */
+    public void setRefreshToken(String refreshToken) {
+        this.refreshToken = refreshToken;
+    }
+
+    /**
+     * @return 有效期
+     */
+    public Integer getExpiresIn() {
+        return this.expiresIn;
+    }
+
+    /**
+     * 设置 有效期
+     */
+    public void setExpiresIn(Integer expiresIn) {
+        this.expiresIn = expiresIn;
+    }
+
+    /**
+     * @return 授权范围
+     */
+    public String getScope() {
+        return this.scope;
+    }
+
+    /**
+     * 设置 授权范围
+     */
+    public void setScope(String scope) {
+        this.scope = scope;
+    }
+
+    public Long getCreateTime() {
+        return createTime;
+    }
+
+    public void setCreateTime(Long createTime) {
+        this.createTime = createTime;
+    }
+
+    public Long getUpdateTime() {
+        return updateTime;
+    }
+
+    public void setUpdateTime(Long updateTime) {
+        this.updateTime = updateTime;
+    }
+}

+ 30 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/GrantType.java

@@ -0,0 +1,30 @@
+/*
+ *  Copyright 2016 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.client;
+
+/**
+ * @author zhouhao
+ */
+public interface GrantType {
+    String authorization_code = "authorization_code";
+    String implicit           = "implicit";
+    String password           = "password";
+    String client_credentials = "client_credentials";
+    String refresh_token      = "refresh_token";
+}

+ 36 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/OAuth2Constants.java

@@ -0,0 +1,36 @@
+/*
+ *  Copyright 2016 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.client;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface OAuth2Constants {
+    String access_token  = "access_token";
+    String grant_type    = "grant_type";
+    String scope         = "scope";
+    String client_id     = "client_id";
+    String client_secret = "client_secret";
+    String authorization = "Authorization";
+    String redirect_uri  = "redirect_uri";
+    String response_type = "response_type";
+    String state         = "state";
+}

+ 30 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/OAuth2RequestBuilder.java

@@ -0,0 +1,30 @@
+/*
+ *  Copyright 2016 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.client;
+
+import org.hswebframework.web.authorization.oauth2.client.request.OAuth2Request;
+
+/**
+ * @author zhouhao
+ */
+public interface OAuth2RequestBuilder {
+    OAuth2RequestBuilder url(String url);
+
+    OAuth2Request build();
+}

+ 27 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/OAuth2RequestBuilderFactory.java

@@ -0,0 +1,27 @@
+/*
+ *  Copyright 2016 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.client;
+
+/**
+ *
+ * @author zhouhao
+ */
+public interface OAuth2RequestBuilderFactory {
+    OAuth2RequestBuilder create(String serverId,String provider);
+}

+ 64 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/OAuth2RequestService.java

@@ -0,0 +1,64 @@
+/*
+ *  Copyright 2016 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.client;
+
+import org.hswebframework.web.authorization.oauth2.client.listener.OAuth2Event;
+import org.hswebframework.web.authorization.oauth2.client.listener.OAuth2Listener;
+
+/**
+ * OAuth2请求服务接口,用于创建OAuth2请求,注册监听器等操作
+ *
+ * @author zhouhao
+ * @@since 3.0
+ */
+public interface OAuth2RequestService {
+
+    /**
+     * 创建一个OAuth2服务的会话创建器
+     *
+     * @param serverId 服务ID,serverId是由接口的实现模块自行定义的
+     * @return OAuth2会话创建器
+     * @see OAuth2SessionBuilder
+     */
+    OAuth2SessionBuilder create(String serverId);
+
+    /**
+     * 注册一个监听器到指定的OAuth2服务
+     *
+     * @param serverId 服务ID
+     * @param listener 监听器
+     */
+    void registerListener(String serverId, OAuth2Listener<? extends OAuth2Event> listener);
+
+    /**
+     * 触发一个监听事件
+     *
+     * @param serverId 服务ID
+     * @param event    事件实例
+     */
+    void doEvent(String serverId, OAuth2Event event);
+
+    /**
+     * 触发一个指定类型的事件
+     * @param serverId
+     * @param event
+     * @param eventType
+     */
+    void doEvent(String serverId, OAuth2Event event, Class<? extends OAuth2Event> eventType);
+}

+ 65 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/OAuth2SessionBuilder.java

@@ -0,0 +1,65 @@
+/*
+ *  Copyright 2016 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.client;
+
+import org.hswebframework.web.authorization.oauth2.client.request.OAuth2Session;
+
+/**
+ * OAuth2会话创建器,根据各种方式创建 OAuth2会话
+ *
+ * @author zhouhao
+ * @see OAuth2Session
+ * @since 3.0
+ */
+public interface OAuth2SessionBuilder {
+
+    /**
+     * 根据授权码方式创建会话
+     *
+     * @param code 授权码
+     * @return 会话
+     * @see "grant_type=authorization_code"
+     */
+    OAuth2Session byAuthorizationCode(String code);
+
+    /**
+     * 根据密钥方式创建会话
+     *
+     * @return 会话
+     * @see "grant_type=client_credentials"
+     */
+    OAuth2Session byClientCredentials();
+
+    /**
+     * 根据密码方式创建会话
+     *
+     * @return 会话
+     * @see "grant_type=password"
+     */
+    OAuth2Session byPassword(String username, String password);
+
+    /**
+     * 直接指定accessToken创建会话
+     *
+     * @param accessToken
+     * @return 会话
+     */
+    OAuth2Session byAccessToken(String accessToken);
+
+}

+ 45 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/exception/OAuth2RequestException.java

@@ -0,0 +1,45 @@
+/*
+ *  Copyright 2016 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.client.exception;
+
+import org.hswebframework.web.authorization.oauth2.client.response.OAuth2Response;
+import org.hswebframework.web.oauth2.core.ErrorType;
+
+/**
+ * @author zhouhao
+ */
+public class OAuth2RequestException extends RuntimeException {
+    ErrorType errorType;
+
+    OAuth2Response response;
+
+    public OAuth2RequestException(ErrorType errorType, OAuth2Response response) {
+        super(errorType.name());
+        this.errorType = errorType;
+        this.response = response;
+    }
+
+    public ErrorType getErrorType() {
+        return errorType;
+    }
+
+    public OAuth2Response getResponse() {
+        return response;
+    }
+}

+ 27 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/listener/AutoRegisterOAuth2Listener.java

@@ -0,0 +1,27 @@
+/*
+ *  Copyright 2016 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.client.listener;
+
+/**
+ *
+ * @author zhouhao
+ */
+public interface AutoRegisterOAuth2Listener<T extends OAuth2Event> extends OAuth2Listener<T> {
+    String getServerId();
+}

+ 51 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/listener/OAuth2CodeAuthBeforeEvent.java

@@ -0,0 +1,51 @@
+/*
+ *  Copyright 2016 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.client.listener;
+
+
+import java.util.Optional;
+import java.util.function.Function;
+
+/**
+ * @author zhouhao
+ */
+public class OAuth2CodeAuthBeforeEvent implements OAuth2Event {
+    private String                   code;
+    private String                   state;
+    private Function<String, String> parameterGetter;
+
+    public OAuth2CodeAuthBeforeEvent(String code, String state, Function<String, String> parameterGetter) {
+        this.code = code;
+        this.state = state;
+        this.parameterGetter = parameterGetter;
+    }
+
+    public String getCode() {
+        return code;
+    }
+
+    public String getState() {
+        return state;
+    }
+
+    public Optional<String> getParameter(String name) {
+        return Optional.ofNullable(parameterGetter.apply(name));
+    }
+
+}

+ 27 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/listener/OAuth2Event.java

@@ -0,0 +1,27 @@
+/*
+ *  Copyright 2016 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.client.listener;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface OAuth2Event {
+}

+ 28 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/listener/OAuth2Listener.java

@@ -0,0 +1,28 @@
+/*
+ *  Copyright 2016 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.client.listener;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface OAuth2Listener<T extends OAuth2Event> {
+    void on(T event);
+}

+ 131 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/request/OAuth2Request.java

@@ -0,0 +1,131 @@
+/*
+ *  Copyright 2016 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.client.request;
+
+import org.hswebframework.web.authorization.oauth2.client.response.OAuth2Response;
+
+import java.util.function.Consumer;
+
+/**
+ * OAuth2请求接口,用于发起OAuth2请求
+ *
+ * @author zhouhao
+ */
+public interface OAuth2Request {
+
+    OAuth2Request onTokenExpired(TokenExpiredCallBack callback);
+
+    /**
+     * 设置请求参数,相当于/url?name=value
+     *
+     * @param name  参数名称
+     * @param value 参数值
+     * @return request自身
+     */
+    OAuth2Request param(String name, Object value);
+
+    /**
+     * 设置请求体,将内容根据contentType(默认application/json)序列化为对应的请求数据
+     *
+     * @param value 请求内容
+     * @return request自身
+     */
+    OAuth2Request requestBody(String value);
+
+    /**
+     * 设置请求头
+     *
+     * @param name  名称
+     * @param value 值
+     * @return request自身
+     */
+    OAuth2Request header(String name, String value);
+
+    /**
+     * 设置cookie
+     *
+     * @param cookie 值
+     * @return request自身
+     */
+    OAuth2Request cookie(String cookie);
+
+    /**
+     * 设置请求的contentType
+     *
+     * @param contentType
+     * @return request自身
+     * @see "application/json"
+     */
+    OAuth2Request contentType(String contentType);
+
+    /**
+     * 设置接受响应的格式,相当与请求头:Accept
+     *
+     * @param accept
+     * @return request自身
+     * @see "application/json"
+     */
+    OAuth2Request accept(String accept);
+
+    /**
+     * 设置请求超时时间,超时后回调 timeoutConsumer
+     *
+     * @param millisecond     超时时间(毫秒),小于0则不设置超时
+     * @param timeoutCallBack 超时后的处理回调
+     * @return request自身
+     * @see Consumer
+     */
+    OAuth2Request timeout(long millisecond, Consumer<OAuth2Request> timeoutCallBack);
+
+    /**
+     * 以GET方式请求,并返回请求结果
+     *
+     * @return 请求结果
+     */
+    OAuth2Response get();
+
+    /**
+     * 以PUT方式请求,并返回请求结果
+     *
+     * @return 请求结果
+     */
+    OAuth2Response put();
+
+    /**
+     * 以POST方式请求,并返回请求结果
+     *
+     * @return 请求结果
+     */
+    OAuth2Response post();
+
+    /**
+     * 以DELETE方式请求,并返回请求结果
+     *
+     * @return 请求结果
+     */
+    OAuth2Response delete();
+
+    /**
+     * 以PATCH方式请求,并返回请求结果
+     *
+     * @return 请求结果
+     */
+    OAuth2Response patch();
+
+}

+ 73 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/request/OAuth2Session.java

@@ -0,0 +1,73 @@
+/*
+ *  Copyright 2016 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.client.request;
+
+import org.hswebframework.web.authorization.annotation.Authorize;
+import org.hswebframework.web.authorization.oauth2.client.AccessTokenInfo;
+
+import java.io.Serializable;
+
+/**
+ * OAuth2会话,此会话保存的是 OAuth2授权成功后得到的access_token等相关信息.
+ * 通过会话发起的OAuth2请求将自动带上access_token信息.
+ *
+ * @author zhouhao
+ * @see OAuth2Request
+ * @since 3.0
+ */
+public interface OAuth2Session extends Serializable {
+    /**
+     * 尝试进行认证
+     *
+     * @return 会话自身
+     */
+    OAuth2Session authorize();
+
+    /**
+     * 发起一个OAuth2请求,参数为接口地址
+     *
+     * @param uriOrUrl 请求地址,可以为URI或者URL
+     * @return 请求接口
+     */
+    OAuth2Request request(String uriOrUrl);
+
+    /**
+     * 设置在请求OAuth2 授权的时候的参数(除了必要之外的参数),client_id,client_secret等信息不需要调用此方法设置
+     *
+     * @param name  参数名称
+     * @param value 参数值
+     * @return 会话自身
+     */
+    OAuth2Session param(String name, Object value);
+
+    OAuth2Session scope(String scope);
+
+    /**
+     * 关闭会话,将清空
+     */
+    void close();
+
+    /**
+     * @return 是否已关闭
+     */
+    boolean isClosed();
+
+    AccessTokenInfo getAccessToken();
+
+}

+ 29 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/request/ReTry.java

@@ -0,0 +1,29 @@
+/*
+ *  Copyright 2016 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.client.request;
+
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface ReTry {
+    void doReTry();
+}

+ 28 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/request/TokenExpiredCallBack.java

@@ -0,0 +1,28 @@
+/*
+ *  Copyright 2016 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.client.request;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface TokenExpiredCallBack {
+    void call(ReTry reTry);
+}

+ 86 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/response/OAuth2Response.java

@@ -0,0 +1,86 @@
+/*
+ *  Copyright 2016 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.client.response;
+
+import org.hswebframework.web.authorization.oauth2.client.exception.OAuth2RequestException;
+import org.hswebframework.web.oauth2.core.ErrorType;
+
+import java.util.List;
+import java.util.function.BiConsumer;
+
+/**
+ * OAuth2 请求结果
+ *
+ * @author zhouhao
+ */
+public interface OAuth2Response {
+
+    /**
+     * @return 结果转为字符串
+     */
+    String asString();
+
+    /**
+     * @return 结果转为byte数组
+     */
+    byte[] asBytes();
+
+    /**
+     * 自定义转换方式
+     *
+     * @param convert 转换函数
+     * @param <T>     转换结果类型
+     * @return 转换结果
+     */
+    <T> T as(ResponseConvert<T> convert);
+
+    /**
+     * 转换为指定的类型
+     *
+     * @param type 类型Class
+     * @param <T>  结果类型
+     * @return 结果
+     */
+    <T> T as(Class<T> type);
+
+    /**
+     * 转换为指定类型的结果集
+     *
+     * @param type 类型Class
+     * @param <T>  结果类型
+     * @return 结果集合
+     */
+    <T> List<T> asList(Class<T> type);
+
+    /**
+     * @return 响应状态码
+     */
+    int status();
+
+    /**
+     * 判断是否成功,如果不成功,则抛出异常
+     *
+     * @return 响应结果本身
+     */
+    OAuth2Response onError(BiConsumer<OAuth2Response, ErrorType> onError);
+
+    BiConsumer<OAuth2Response, ErrorType> throwOnError = (response, errorType) -> {
+        throw new OAuth2RequestException(errorType, response);
+    };
+}

+ 28 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-client/src/main/java/org/hswebframework/web/authorization/oauth2/client/response/ResponseConvert.java

@@ -0,0 +1,28 @@
+/*
+ *  Copyright 2016 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.client.response;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface ResponseConvert<T> {
+    T convert(OAuth2Response response);
+}

+ 34 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-core/pom.xml

@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~  Copyright 2016 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>3.0-SNAPSHOT</version>
+        <relativePath>../../pom.xml</relativePath>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+
+    <artifactId>hsweb-authorization-oauth2-core</artifactId>
+
+
+</project>

+ 99 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-core/src/main/java/org/hswebframework/web/oauth2/core/ErrorType.java

@@ -0,0 +1,99 @@
+/*
+ *  Copyright 2016 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.oauth2.core;
+
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+
+public enum ErrorType {
+    ILLEGAL_CODE(1001), //错误的授权码
+    ILLEGAL_ACCESS_TOKEN(1002), //错误的access_token
+    ILLEGAL_CLIENT_ID(1003),//客户端信息错误
+    ILLEGAL_CLIENT_SECRET(1004),//客户端密钥错误
+    ILLEGAL_GRANT_TYPE(1005), //错误的授权方式
+    ILLEGAL_RESPONSE_TYPE(1006),//response_type 错误
+    ILLEGAL_AUTHORIZATION(1007),//Authorization 错误
+    ILLEGAL_REFRESH_TOKEN(1008),//refresh_token 错误
+    ILLEGAL_REDIRECT_URI(1009), //redirect_url 错误
+    ILLEGAL_SCOPE(1010), //scope 错误
+    ILLEGAL_USERNAME(1011), //username 错误
+    ILLEGAL_PASSWORD(1012), //password 错误
+
+    SCOPE_OUT_OF_RANGE(2010), //scope超出范围
+
+    UNAUTHORIZED_CLIENT(4010), //无权限
+    EXPIRED_TOKEN(4011), //TOKEN过期
+    INVALID_TOKEN(4012), //TOKEN已失效
+    UNSUPPORTED_GRANT_TYPE(4013), //不支持的认证类型
+    UNSUPPORTED_RESPONSE_TYPE(4014), //不支持的响应类型
+
+    EXPIRED_CODE(4015), //AUTHORIZATION_CODE过期
+    EXPIRED_REFRESH_TOKEN(4020), //AUTHORIZATION_CODE过期
+
+    CLIENT_DISABLED(4016),//客户端已被禁用
+
+    CLIENT_NOT_EXIST(4040),//客户端不存在
+
+    USER_NOT_EXIST(4041),//客户端不存在
+
+    ACCESS_DENIED(503), //访问被拒绝
+    OTHER(5001); //其他错误 ;
+
+    private final String message;
+    private final int    code;
+    static final Map<Integer, ErrorType> codeMapping = Arrays.stream(ErrorType.values())
+            .collect(Collectors.toMap(ErrorType::code, type -> type));
+
+    ErrorType(int code) {
+        this.code = code;
+        message = this.name().toLowerCase();
+    }
+
+    ErrorType(int code, String message) {
+        this.message = message;
+        this.code = code;
+    }
+
+    public String message() {
+        if (message == null) return this.name();
+        return message;
+    }
+
+    public int code() {
+        return code;
+    }
+
+    public <T> T throwThis(Function<ErrorType, ? extends RuntimeException> errorTypeFunction) {
+        throw errorTypeFunction.apply(this);
+    }
+
+    public <T> T throwThis(BiFunction<ErrorType, String, ? extends RuntimeException> errorTypeFunction, String message) {
+        throw errorTypeFunction.apply(this, message);
+    }
+
+    public static Optional<ErrorType> fromCode(int code) {
+        return Optional.ofNullable(codeMapping.get(code));
+    }
+
+}

+ 31 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-core/src/main/java/org/hswebframework/web/oauth2/core/GrantType.java

@@ -0,0 +1,31 @@
+/*
+ *  Copyright 2016 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.oauth2.core;
+
+/**
+ *
+ * @author zhouhao
+ */
+public interface GrantType {
+    String authorization_code = "authorization_code";
+    String implicit           = "implicit";
+    String password           = "password";
+    String client_credentials = "client_credentials";
+    String refresh_token      = "refresh_token";
+}

+ 41 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-core/src/main/java/org/hswebframework/web/oauth2/core/OAuth2Constants.java

@@ -0,0 +1,41 @@
+/*
+ *  Copyright 2016 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.oauth2.core;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface OAuth2Constants {
+    String access_token  = "access_token";
+    String refresh_token = "refresh_token";
+    String grant_type    = "grant_type";
+    String scope         = "scope";
+    String client_id     = "client_id";
+    String client_secret = "client_secret";
+    String authorization = "Authorization";
+    String redirect_uri  = "redirect_uri";
+    String response_type = "response_type";
+    String state         = "state";
+    String code          = "code";
+    String username      = "username";
+    String password      = "password";
+
+}

+ 29 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-core/src/main/java/org/hswebframework/web/oauth2/core/ResponseType.java

@@ -0,0 +1,29 @@
+/*
+ *  Copyright 2016 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.oauth2.core;
+
+/**
+ * TODO 完成注释
+ *
+ * @author zhouhao
+ */
+public interface ResponseType {
+    String code  = "code";
+    String token = "token";
+}

+ 33 - 0
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-resource-server/pom.xml

@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~  Copyright 2016 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>3.0-SNAPSHOT</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+
+    <artifactId>hsweb-authorization-oauth2-resource-server</artifactId>
+
+
+</project>

+ 0 - 199
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-controller/src/main/java/org/hswebframework/web/authorization/oauth2/controller/OAuth2AuthorizationController.java

@@ -1,199 +0,0 @@
-/*
- *  Copyright 2016 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.controller;
-
-import io.swagger.annotations.*;
-import org.apache.commons.codec.binary.Base64;
-import org.hswebframework.web.authorization.Authorization;
-import org.hswebframework.web.authorization.AuthorizationHolder;
-import org.hswebframework.web.authorization.annotation.Authorize;
-import org.hswebframework.web.authorization.oauth2.api.OAuth2ServerService;
-import org.hswebframework.web.entity.authorization.oauth2.OAuth2AccessEntity;
-import org.hswebframework.web.authorization.oauth2.model.AccessTokenModel;
-import org.hswebframework.web.authorization.oauth2.model.AuthorizationCodeModel;
-import org.hswebframework.web.authorization.oauth2.model.ImplicitAccessTokenModel;
-import org.hswebframework.web.controller.message.ResponseMessage;
-import org.springframework.web.bind.annotation.*;
-
-import javax.annotation.Resource;
-
-import static org.springframework.util.StringUtils.isEmpty;
-
-/**
- *
- * @author zhouhao
- */
-@RestController
-@Api(tags = "hsweb-authorization", description = "OAuth2授权", hidden = true)
-@RequestMapping("${hsweb.web.mappings.authorize-oauth2:oauth2/authorize}")
-public class OAuth2AuthorizationController {
-
-    @Resource
-    private OAuth2ServerService oAuth2ServerService;
-
-    @RequestMapping(params = "response_type=code", method = RequestMethod.GET)
-    @ApiOperation("登录用户获取OAuth2.0授权码")
-    @Authorize
-    public AuthorizationCodeModel requestCode(
-            @RequestParam("client_id") String clientId,
-            @RequestParam("redirect_uri") String redirectUri,
-            @RequestParam(value = "scope", required = false) String scope,
-            @RequestParam(value = "state", required = false) String state) {
-        Authorization authorization = AuthorizationHolder.get();
-        String code = oAuth2ServerService.requestCode(clientId, authorization.getUser().getId(), scope);
-        AuthorizationCodeModel model = new AuthorizationCodeModel();
-        model.setCode(code);
-        model.setRedirectUri(redirectUri);
-        model.setState(state);
-        return model;
-    }
-
-
-    @RequestMapping(params = "response_type=token", method = RequestMethod.GET)
-    @ApiOperation("implicit方式授权")
-    public ImplicitAccessTokenModel authorizeByImplicit(
-            @RequestParam(value = "client_id") String client_id,
-            @RequestParam(value = "redirect_uri") String redirect_uri,
-            @RequestParam(value = "state") String state,
-            @RequestParam(value = "scope", required = false) String scope) {
-
-        // OAuth2ClientEntity clientEntity = oAuth2ServerService.getClient(client_id);
-        // TODO: 17-3-6  validate redirect_uri
-
-        OAuth2AccessEntity accessEntity = oAuth2ServerService.requestTokenByImplicit(client_id, scope);
-        ImplicitAccessTokenModel model = new ImplicitAccessTokenModel();
-        model.setState(state);
-        model.setToken_type("example");
-        model.setAccess_token(accessEntity.getAccessToken());
-        model.setExpire_in(accessEntity.getExpireIn());
-        return model;
-    }
-
-    @RequestMapping(params = "grant_type=authorization_code", method = RequestMethod.POST)
-    @ApiOperation("authorization_code方式授权")
-    public AccessTokenModel authorizeByCode(
-            @RequestParam("code") String code,
-            @RequestParam(value = "client_id", required = false) String clientId,
-            @RequestParam(value = "client_secret", required = false) String clientSecret,
-            @RequestHeader(value = "Authorization", required = false) String authorization,
-            @RequestParam(value = "scope", required = false) String scope) {
-
-        String[] clientCredentials = getClientCredentials(clientId, clientSecret, authorization);
-        clientId = clientCredentials[0];
-        clientSecret = clientCredentials[1];
-
-        AccessTokenModel model = entityToModel(oAuth2ServerService.requestTokenByCode(code, clientId, clientSecret, scope));
-        return model;
-    }
-
-    @RequestMapping(params = "grant_type=client_credentials", method = RequestMethod.POST)
-    @ApiOperation("client_credentials方式授权")
-    public AccessTokenModel authorizeByClientCredentials(
-            @RequestParam(value = "client_id", required = false) String clientId,
-            @RequestParam(value = "client_secret", required = false) String clientSecret,
-            @RequestHeader(value = "Authorization", required = false) String authorization) {
-        String[] clientCredentials = getClientCredentials(clientId, clientSecret, authorization);
-        clientId = clientCredentials[0];
-        clientSecret = clientCredentials[1];
-        AccessTokenModel model = entityToModel(oAuth2ServerService.requestTokenByClientCredential(clientId, clientSecret));
-        return model;
-    }
-
-    @RequestMapping(params = "grant_type=password", method = RequestMethod.POST)
-    @ApiOperation("password方式授权")
-    public AccessTokenModel authorizeByPassword(
-            @RequestParam(value = "username") String username,
-            @RequestParam(value = "password") String password,
-            @RequestHeader(value = "Authorization", required = false) String authorization) {
-        String[] clientCredentials = getClientCredentials(username, password, authorization);
-        username = clientCredentials[0];
-        password = clientCredentials[1];
-        AccessTokenModel model = entityToModel(oAuth2ServerService.requestTokenByPassword(username, password));
-        return model;
-    }
-
-    @RequestMapping(params = "grant_type=refresh_token", method = RequestMethod.POST)
-    @ApiOperation("刷新授权码")
-    public AccessTokenModel refreshToken(
-            @RequestHeader(value = "Authorization", required = false) String authorization,
-            @RequestParam(value = "client_id", required = false) String clientId,
-            @RequestParam(value = "client_secret", required = false) String clientSecret,
-            @RequestParam(value = "refresh_token") String refreshToken,
-            @RequestParam(value = "scope", required = false) String scope) {
-
-        String[] clientCredentials = getClientCredentials(clientId, clientSecret, authorization);
-        clientId = clientCredentials[0];
-        clientSecret = clientCredentials[1];
-
-        AccessTokenModel model = entityToModel(oAuth2ServerService.refreshToken(clientId, clientSecret, refreshToken, scope));
-        return model;
-    }
-
-    protected String[] getClientCredentials(String clientId, String clientSecret, String authorization) {
-        if ((clientId == null || clientSecret == null) && authorization == null) {
-            throw new IllegalArgumentException("authorization error!");
-        }
-        if (!isEmpty(authorization)) {
-            String[] creds = decodeClientAuthenticationHeader(authorization);
-            if (creds.length > 1) {
-                clientId = creds[0];
-                clientSecret = creds[1];
-            } else {
-                clientSecret = creds[0];
-            }
-        }
-        return new String[]{clientId, clientSecret};
-    }
-
-    protected AccessTokenModel entityToModel(OAuth2AccessEntity entity) {
-        AccessTokenModel model = new AccessTokenModel();
-        model.setAccess_token(entity.getAccessToken());
-        model.setRefresh_token(entity.getRefreshToken());
-        model.setExpire_in(entity.getExpireIn());
-        model.setScope(entity.getScope());
-        model.setToken_type("bearer");
-        return model;
-    }
-
-
-    protected static String[] decodeClientAuthenticationHeader(String authenticationHeader) {
-        if (isEmpty(authenticationHeader)) {
-            return null;
-        } else {
-            String[] tokens = authenticationHeader.split(" ");
-            if (tokens.length != 2) {
-                return null;
-            } else {
-                String authType = tokens[0];
-                if (!"basic".equalsIgnoreCase(authType)) {
-                    return null;
-                } else {
-                    String encodedCreds = tokens[1];
-                    return decodeBase64EncodedCredentials(encodedCreds);
-                }
-            }
-        }
-    }
-
-    protected static String[] decodeBase64EncodedCredentials(String encodedCreds) {
-        String decodedCreds = new String(Base64.decodeBase64(encodedCreds));
-        String[] creds = decodedCreds.split(":", 2);
-        return creds.length != 2 ? null : (!isEmpty(creds[0]) && !isEmpty(creds[1]) ? creds : null);
-    }
-}

+ 0 - 266
hsweb-authorization/hsweb-authorization-oauth2/hsweb-authorization-oauth2-server/hsweb-authorization-oauth2-server-simple/src/main/java/org/hswebframework/web/authorization/oauth2/simple/SimpleOAuth2ServerService.java

@@ -1,266 +0,0 @@
-/*
- *  Copyright 2016 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.simple;
-
-import org.hswebframework.web.AuthorizeForbiddenException;
-import org.hswebframework.web.NotFoundException;
-import org.hswebframework.web.authorization.oauth2.api.OAuth2ServerService;
-import org.hswebframework.web.dao.authorization.oauth2.AuthorizationCodeDao;
-import org.hswebframework.web.dao.authorization.oauth2.OAuth2AccessDao;
-import org.hswebframework.web.dao.authorization.oauth2.OAuth2ClientDao;
-import org.hswebframework.web.entity.authorization.oauth2.AuthorizationCodeEntity;
-import org.hswebframework.web.entity.authorization.oauth2.OAuth2AccessEntity;
-import org.hswebframework.web.entity.authorization.oauth2.OAuth2ClientEntity;
-import org.hswebframework.web.commons.entity.GenericEntity;
-import org.hswebframework.web.commons.entity.factory.EntityFactory;
-import org.hswebframework.web.entity.authorization.UserEntity;
-import org.hswebframework.web.id.IDGenerator;
-import org.hswebframework.web.service.DefaultDSLQueryService;
-import org.hswebframework.web.service.authorization.UserService;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-import javax.annotation.Resource;
-
-import static org.hswebframework.web.service.DefaultDSLDeleteService.createDelete;
-import static org.hswebframework.web.service.DefaultDSLQueryService.createQuery;
-import static org.hswebframework.web.service.DefaultDSLUpdateService.createUpdate;
-
-/**
- * TODO 完成注释
- *
- * @author zhouhao
- */
-@Service("oAuth2ServerService")
-@Transactional(rollbackFor = Throwable.class)
-public class SimpleOAuth2ServerService implements OAuth2ServerService {
-
-    private static final String cacheName = "hsweb.oauth2";
-    @Resource
-    private OAuth2ClientDao      oAuth2ClientDao;
-    @Resource
-    private OAuth2AccessDao      oAuth2AccessDao;
-    @Resource
-    private AuthorizationCodeDao authorizationCodeDao;
-    @Resource
-    private EntityFactory        entityFactory;
-
-    @Resource
-    private UserService userService;
-
-    @Override
-    public OAuth2ClientEntity getClient(String clientId) {
-        return createQuery(oAuth2ClientDao)
-                .where(GenericEntity.id, clientId)
-                .single();
-    }
-
-    @Override
-    public OAuth2ClientEntity getClient(String clientId, String clientSecret) {
-        return createQuery(oAuth2ClientDao)
-                .where(GenericEntity.id, clientId)
-                // TODO: 17-2-28 key (clientSecret) 应该为常量
-                .where("clientSecret", clientSecret)
-                .single();
-    }
-
-    @Override
-    public OAuth2AccessEntity getAccessByToken(String accessToken) {
-        return createQuery(oAuth2AccessDao)
-                // TODO: 17-2-28 key (accessToken) 应该为常量
-                .where("accessToken", accessToken)
-                .single();
-    }
-
-    @Override
-    public String requestCode(String clientId, String userId, String scope) {
-        String code = IDGenerator.MD5.generate();
-        //删除旧的code
-        createDelete(authorizationCodeDao)
-                // TODO: 17-2-28 key  应该为常量
-                .where("userId", userId)
-                .and("clientId", userId)
-                .exec();
-        AuthorizationCodeEntity codeEntity = entityFactory.newInstance(AuthorizationCodeEntity.class);
-        codeEntity.setCreateTime(System.currentTimeMillis());
-        codeEntity.setClientId(clientId);
-        codeEntity.setUserId(userId);
-        codeEntity.setCode(code);
-        codeEntity.setScope(scope);
-        authorizationCodeDao.insert(codeEntity);
-        return code;
-    }
-
-    protected OAuth2AccessEntity createNewAccess() {
-        OAuth2AccessEntity entity = entityFactory.newInstance(OAuth2AccessEntity.class);
-        entity.setCreateTime(System.currentTimeMillis());
-        entity.setAccessToken(IDGenerator.MD5.generate());
-        entity.setRefreshToken(IDGenerator.MD5.generate());
-        return entity;
-    }
-
-    @Override
-    public OAuth2AccessEntity requestTokenByCode(String code, String clientId, String clientSecret, String scope) {
-        AuthorizationCodeEntity codeEntity =
-                createQuery(authorizationCodeDao)
-                        .where("code", code)
-                        .and("clientId", clientId)
-                        .single();
-        if (codeEntity == null) {
-            throw new NotFoundException("code not found!");
-        }
-        try {
-            //授权码已经创建超时(20s)
-            if (System.currentTimeMillis() - codeEntity.getCreateTime() < 20 * 1000) {
-                throw new NotFoundException("time out!");
-            }
-            // TODO: 17-2-28  验证scope
-
-            OAuth2ClientEntity clientEntity = getClient(clientId, clientSecret);
-            if (null == clientEntity) {
-                // TODO: 17-2-28 自定义异常
-                throw new NotFoundException("client not found!");
-            }
-            if (!clientEntity.grantTypeIsSupport("authorization_code")) {
-                throw new UnsupportedOperationException("grant_type:authorization_code not support!");
-            }
-            OAuth2AccessEntity accessEntity = createNewAccess();
-            accessEntity.setUserId(codeEntity.getUserId());
-            accessEntity.setClientId(clientId);
-            // TODO: 17-2-28 过期时间应该可配置
-            accessEntity.setExpireIn(3600L);
-            accessEntity.setScope(scope);
-            oAuth2AccessDao.insert(accessEntity);
-            return accessEntity;
-        } finally {
-            //删除使用过的授权码
-            createDelete(authorizationCodeDao)
-                    .where("code", code)
-                    .and("clientId", clientId)
-                    .exec();
-        }
-    }
-
-    @Override
-    public OAuth2AccessEntity requestTokenByClientCredential(String clientId, String clientSecret) {
-        OAuth2ClientEntity clientEntity = getClient(clientId, clientSecret);
-        if (null == clientEntity) {
-            // TODO: 17-2-28 自定义异常
-            throw new NotFoundException("client not found!");
-        }
-        if (!clientEntity.grantTypeIsSupport("client_credential")) {
-            throw new UnsupportedOperationException("grant_type:client_credential not support!");
-        }
-        return createNewTokenAndRemoveOld(clientEntity);
-    }
-
-    protected OAuth2AccessEntity createNewTokenAndRemoveOld(OAuth2ClientEntity clientEntity) {
-        OAuth2AccessEntity oldEntity = DefaultDSLQueryService
-                .createQuery(oAuth2AccessDao)
-                .where("clientId", clientEntity.getId())
-                .and("userId", clientEntity.getOwnerId())
-                .single();
-        OAuth2AccessEntity newEntity = createNewAccess();
-        if (oldEntity != null) {
-            newEntity.setScope(oldEntity.getScope());
-            newEntity.setExpireIn(oldEntity.getExpireIn());
-            newEntity.setRefreshToken(oldEntity.getRefreshToken());
-        } else {
-            newEntity.setExpireIn(3600L);
-            newEntity.setScope("public");
-        }
-        newEntity.setClientId(clientEntity.getId());
-        newEntity.setUserId(clientEntity.getOwnerId());
-        oAuth2AccessDao.insert(newEntity);
-        return newEntity;
-    }
-
-    @Override
-    public OAuth2AccessEntity requestTokenByImplicit(String clientId, String scope) {
-        OAuth2ClientEntity clientEntity = getClient(clientId);
-        if (null == clientEntity) {
-            // TODO: 17-2-28 自定义异常
-            throw new NotFoundException("client not found!");
-        }
-        if (!clientEntity.grantTypeIsSupport("implicit")) {
-            throw new UnsupportedOperationException("grant_type:implicit not support!");
-        }
-        return createNewTokenAndRemoveOld(clientEntity);
-    }
-
-    @Override
-    public OAuth2AccessEntity requestTokenByPassword(String username, String password) {
-        UserEntity entity = userService.selectByUsername(username);
-        if (null == entity) throw new NotFoundException("user not found");
-        if (!userService.encodePassword(password, entity.getSalt()).equals(entity.getPassword()))
-            throw new AuthorizeForbiddenException("password error");
-        OAuth2ClientEntity clientEntity = DefaultDSLQueryService.createQuery(oAuth2ClientDao).where("user_id", entity.getId()).single();
-        if (clientEntity == null) {
-            throw new NotFoundException("client not found");
-        }
-        if (!clientEntity.grantTypeIsSupport("password")) {
-            throw new UnsupportedOperationException("grant_type:password not support!");
-        }
-        OAuth2AccessEntity accessEntity = createNewAccess();
-        accessEntity.setUserId(entity.getId());
-        accessEntity.setScope("public");
-        accessEntity.setExpireIn(3600L);
-        accessEntity.setClientId(clientEntity.getId());
-        oAuth2AccessDao.insert(accessEntity);
-        return accessEntity;
-    }
-
-    @Override
-    public OAuth2AccessEntity refreshToken(String clientId, String clientSecret, String refreshToken, String scope) {
-        OAuth2ClientEntity clientEntity = getClient(clientId, clientSecret);
-        if (null == clientEntity) {
-            // TODO: 17-2-28 自定义异常
-            throw new NotFoundException("client not found!");
-        }
-        if (!clientEntity.grantTypeIsSupport("refresh_token")) {
-            throw new UnsupportedOperationException("grant_type:refresh_token not support!");
-        }
-        OAuth2AccessEntity accessEntity = DefaultDSLQueryService.createQuery(oAuth2AccessDao)
-                .where("refreshToken", refreshToken)
-                .and("clientId", clientId)
-                .single();
-        if (null == accessEntity) {
-            throw new NotFoundException("access not found!");
-        }
-        //30天过期
-        long refreshTokenTimeOut = 30 * 24 * 60 * 60 * 1000L;
-        if (System.currentTimeMillis() - accessEntity.getCreateTime() > refreshTokenTimeOut) {
-            throw new NotFoundException("refresh_token time out");
-        }
-        accessEntity.setAccessToken(IDGenerator.MD5.generate());
-        accessEntity.setUpdateTime(System.currentTimeMillis());
-        accessEntity.setScope(scope);
-        createUpdate(oAuth2AccessDao, accessEntity)
-                .includes("accessToken", "updateTime", "scope")
-                .where("refreshToken", refreshToken)
-                .and("clientId", clientId)
-                .exec();
-        return accessEntity;
-    }
-
-    @Override
-    public OAuth2AccessEntity getAccessToken(String accessToken) {
-        return DefaultDSLQueryService.createQuery(oAuth2AccessDao).where("accessToken", accessToken).single();
-    }
-}

+ 3 - 1
hsweb-authorization/hsweb-authorization-oauth2/pom.xml

@@ -12,8 +12,10 @@
     <artifactId>hsweb-authorization-oauth2</artifactId>
     <packaging>pom</packaging>
     <modules>
-        <module>hsweb-authorization-oauth2-server</module>
+        <module>hsweb-authorization-oauth2-auth-server</module>
         <module>hsweb-authorization-oauth2-client</module>
+        <module>hsweb-authorization-oauth2-resource-server</module>
+        <module>hsweb-authorization-oauth2-core</module>
     </modules>
 
 

+ 0 - 0
hsweb-authorization/hsweb-authorization-shiro/pom.xml


Some files were not shown because too many files changed in this diff