Sfoglia il codice sorgente

修改权限获取方式

zhouhao 8 anni fa
parent
commit
ffef365da1
11 ha cambiato i file con 86 aggiunte e 40 eliminazioni
  1. 16 0
      hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/Authentication.java
  2. 2 2
      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
  3. 5 8
      hsweb-authorization/hsweb-authorization-shiro/src/main/java/org/hswebframework/web/authorization/shiro/boost/DataAccessAnnotationMethodInterceptor.java
  4. 4 6
      hsweb-authorization/hsweb-authorization-shiro/src/main/java/org/hswebframework/web/authorization/shiro/boost/FieldAccessAnnotationMethodInterceptor.java
  5. 2 2
      hsweb-authorization/hsweb-authorization-shiro/src/main/java/org/hswebframework/web/authorization/shiro/boost/SimpleAuthorizeMethodInterceptor.java
  6. 8 5
      hsweb-authorization/hsweb-authorization-shiro/src/main/java/org/hswebframework/web/authorization/shiro/boost/handler/OwnCreatedDataAccessHandler.java
  7. 4 0
      hsweb-core/src/main/java/org/hswebframework/web/AuthorizeException.java
  8. 0 10
      hsweb-examples/hsweb-examples-simple/pom.xml
  9. 4 3
      hsweb-examples/hsweb-examples-simple/src/main/java/org/hswebframework/web/example/simple/TestController.java
  10. 37 0
      hsweb-system/hsweb-system-authorization/hsweb-system-authorization-controller/src/main/java/org/hswebframework/web/controller/authorization/PermissionController.java
  11. 4 4
      hsweb-system/hsweb-system-authorization/hsweb-system-authorization-controller/src/main/java/org/hswebframework/web/controller/authorization/UserController.java

+ 16 - 0
hsweb-authorization/hsweb-authorization-api/src/main/java/org/hswebframework/web/authorization/Authentication.java

@@ -20,6 +20,7 @@ package org.hswebframework.web.authorization;
 import java.io.Serializable;
 import java.util.List;
 import java.util.Map;
+import java.util.NoSuchElementException;
 import java.util.Optional;
 
 /**
@@ -37,6 +38,21 @@ import java.util.Optional;
  */
 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());
     }

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

@@ -21,8 +21,8 @@ package org.hswebframework.web.authorization.oauth2.controller;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import org.apache.commons.codec.binary.Base64;
+import org.hswebframework.web.AuthorizeException;
 import org.hswebframework.web.authorization.Authentication;
-import org.hswebframework.web.authorization.AuthenticationHolder;
 import org.hswebframework.web.authorization.annotation.Authorize;
 import org.hswebframework.web.authorization.oauth2.api.OAuth2ServerService;
 import org.hswebframework.web.authorization.oauth2.model.AccessTokenModel;
@@ -55,7 +55,7 @@ public class OAuth2AuthorizationController {
             @RequestParam("redirect_uri") String redirectUri,
             @RequestParam(value = "scope", required = false) String scope,
             @RequestParam(value = "state", required = false) String state) {
-        Authentication authentication = AuthenticationHolder.get();
+        Authentication authentication = Authentication.current().orElseThrow(AuthorizeException::new);
         String code = oAuth2ServerService.requestCode(clientId, authentication.getUser().getId(), scope);
         AuthorizationCodeModel model = new AuthorizationCodeModel();
         model.setCode(code);

+ 5 - 8
hsweb-authorization/hsweb-authorization-shiro/src/main/java/org/hswebframework/web/authorization/shiro/boost/DataAccessAnnotationMethodInterceptor.java

@@ -22,8 +22,8 @@ import org.apache.shiro.authz.AuthorizationException;
 import org.apache.shiro.authz.aop.AuthorizingAnnotationHandler;
 import org.apache.shiro.authz.aop.AuthorizingAnnotationMethodInterceptor;
 import org.hswebframework.web.ApplicationContextHolder;
+import org.hswebframework.web.AuthorizeException;
 import org.hswebframework.web.authorization.Authentication;
-import org.hswebframework.web.authorization.AuthenticationHolder;
 import org.hswebframework.web.authorization.Permission;
 import org.hswebframework.web.authorization.access.DataAccessConfig;
 import org.hswebframework.web.authorization.access.DataAccessController;
@@ -49,12 +49,12 @@ import java.util.stream.Collectors;
  * @author zhouhao
  * @see DefaultDataAccessController
  * @see DataAccessAnnotationHandler#assertAuthorized(Annotation)
- * @since  3.0
+ * @since 3.0
  */
 public class DataAccessAnnotationMethodInterceptor extends AuthorizingAnnotationMethodInterceptor {
 
-    public DataAccessAnnotationMethodInterceptor(DataAccessController controller,AnnotationResolver resolver) {
-        super(new DataAccessAnnotationHandler(controller),resolver);
+    public DataAccessAnnotationMethodInterceptor(DataAccessController controller, AnnotationResolver resolver) {
+        super(new DataAccessAnnotationHandler(controller), resolver);
     }
 
     private static final Logger logger = LoggerFactory.getLogger(DataAccessAnnotationMethodInterceptor.class);
@@ -78,10 +78,7 @@ public class DataAccessAnnotationMethodInterceptor extends AuthorizingAnnotation
                 return;
             }
             //无权限信息
-            Authentication authentication = AuthenticationHolder.get();
-            if (authentication == null) {
-                throw new AuthorizationException("{no_authorization}");
-            }
+            Authentication authentication = Authentication.current().orElseThrow(AuthorizeException::new);
             RequiresDataAccess accessAnn = ((RequiresDataAccess) a);
             DataAccessController accessController = dataAccessController;
             //在注解上自定义的权限控制器

+ 4 - 6
hsweb-authorization/hsweb-authorization-shiro/src/main/java/org/hswebframework/web/authorization/shiro/boost/FieldAccessAnnotationMethodInterceptor.java

@@ -43,8 +43,8 @@ import java.util.stream.Collectors;
  */
 public class FieldAccessAnnotationMethodInterceptor extends AuthorizingAnnotationMethodInterceptor {
 
-    public FieldAccessAnnotationMethodInterceptor(FieldAccessController controller,AnnotationResolver resolver) {
-        super(new DataAccessAnnotationHandler(controller),resolver);
+    public FieldAccessAnnotationMethodInterceptor(FieldAccessController controller, AnnotationResolver resolver) {
+        super(new DataAccessAnnotationHandler(controller), resolver);
     }
 
     private static final Logger logger = LoggerFactory.getLogger(FieldAccessAnnotationMethodInterceptor.class);
@@ -67,10 +67,8 @@ public class FieldAccessAnnotationMethodInterceptor extends AuthorizingAnnotatio
             }
             RequiresFieldAccess accessAnn = ((RequiresFieldAccess) a);
             MethodInterceptorParamContext context = holder.createParamContext();
-            Authentication authentication = AuthenticationHolder.get();
-            if (authentication == null) {
-                throw new AuthorizationException("{no_authorization}");
-            }
+            Authentication authentication = Authentication.current().orElseThrow(AuthorizationException::new);
+            
             String permission = accessAnn.permission();
             Permission permissionInfo = authentication.getPermission(permission);
 

+ 2 - 2
hsweb-authorization/hsweb-authorization-shiro/src/main/java/org/hswebframework/web/authorization/shiro/boost/SimpleAuthorizeMethodInterceptor.java

@@ -80,8 +80,8 @@ public class SimpleAuthorizeMethodInterceptor extends AuthorizingAnnotationMetho
             }
             authorizeConfig.put(authorize);
 
-            Authentication authentication = AuthenticationHolder.get();
-            if (null == authentication) throw new UnauthenticatedException(authorizeConfig.message);
+            Authentication authentication = Authentication.current()
+                    .orElseThrow(() -> new UnauthenticatedException(authorizeConfig.message));
             boolean access = true;
             Logical logical = authorizeConfig.logical == Logical.DEFAULT ? Logical.OR : authorizeConfig.logical;
             boolean logicalIsOr = logical == Logical.OR;

+ 8 - 5
hsweb-authorization/hsweb-authorization-shiro/src/main/java/org/hswebframework/web/authorization/shiro/boost/handler/OwnCreatedDataAccessHandler.java

@@ -1,7 +1,8 @@
 package org.hswebframework.web.authorization.shiro.boost.handler;
 
 import org.hsweb.ezorm.core.param.Term;
-import org.hswebframework.web.authorization.AuthenticationHolder;
+import org.hswebframework.web.AuthorizeException;
+import org.hswebframework.web.authorization.Authentication;
 import org.hswebframework.web.authorization.Permission;
 import org.hswebframework.web.authorization.access.DataAccessConfig;
 import org.hswebframework.web.authorization.access.DataAccessHandler;
@@ -64,7 +65,9 @@ public class OwnCreatedDataAccessHandler implements DataAccessHandler {
                 .map(RecordCreationEntity.class::cast)
                 .findAny().orElse(null);
         if (entity != null) {
-            entity.setCreatorId(AuthenticationHolder.get().getUser().getId());
+            entity.setCreatorId(Authentication.current()
+                    .orElseThrow(AuthorizeException::new)
+                    .getUser().getId());
         } else {
             logger.warn("try put creatorId property,but not found any RecordCreationEntity!");
         }
@@ -85,7 +88,7 @@ public class OwnCreatedDataAccessHandler implements DataAccessHandler {
                 QueryService<RecordCreationEntity, Object> queryService =
                         ((QueryController<RecordCreationEntity, Object, Entity>) controller).getService();
                 RecordCreationEntity oldData = queryService.selectByPk(id);
-                if (oldData != null && !AuthenticationHolder.get().getUser().getId().equals(oldData.getCreatorId())) {
+                if (oldData != null && !Authentication.current().orElseThrow(AuthorizeException::new).getUser().getId().equals(oldData.getCreatorId())) {
                     return false;
                 }
             }
@@ -113,11 +116,11 @@ public class OwnCreatedDataAccessHandler implements DataAccessHandler {
             queryParamEntity.setTerms(new ArrayList<>());
             //添加一个查询条件
             queryParamEntity
-                    .where(RecordCreationEntity.creatorId, AuthenticationHolder.get().getUser().getId())
+                    .where(RecordCreationEntity.creatorId,Authentication.current().orElseThrow(AuthorizeException::new).getUser().getId())
                     //客户端提交的参数 作为嵌套参数
                     .nest().setTerms(oldParam);
         } else if (entity instanceof RecordCreationEntity) {
-            ((RecordCreationEntity) entity).setCreatorId(AuthenticationHolder.get().getUser().getId());
+            ((RecordCreationEntity) entity).setCreatorId(Authentication.current().orElseThrow(AuthorizeException::new).getUser().getId());
         } else {
             logger.warn("try validate query access,but entity not support, QueryParamEntity and RecordCreationEntity support now!");
         }

+ 4 - 0
hsweb-core/src/main/java/org/hswebframework/web/AuthorizeException.java

@@ -21,6 +21,10 @@ package org.hswebframework.web;
 public class AuthorizeException extends BusinessException {
     private static final long serialVersionUID = 2422918455013900645L;
 
+    public AuthorizeException() {
+        this("{no_authorization}");
+    }
+
     public AuthorizeException(String message) {
         this(message, 401);
     }

+ 0 - 10
hsweb-examples/hsweb-examples-simple/pom.xml

@@ -85,12 +85,6 @@
             <groupId>org.hswebframework.web</groupId>
             <artifactId>hsweb-spring-boot-starter</artifactId>
             <version>${project.version}</version>
-            <exclusions>
-                <exclusion>
-                    <groupId>com.fasterxml.jackson.core</groupId>
-                    <artifactId>jackson-databind</artifactId>
-                </exclusion>
-            </exclusions>
         </dependency>
 
         <dependency>
@@ -127,9 +121,5 @@
             <groupId>io.springfox</groupId>
             <artifactId>springfox-swagger-ui</artifactId>
         </dependency>
-        <dependency>
-            <groupId>com.fasterxml.jackson.core</groupId>
-            <artifactId>jackson-databind</artifactId>
-        </dependency>
     </dependencies>
 </project>

+ 4 - 3
hsweb-examples/hsweb-examples-simple/src/main/java/org/hswebframework/web/example/simple/TestController.java

@@ -1,11 +1,13 @@
 package org.hswebframework.web.example.simple;
 
 import io.swagger.annotations.ApiOperation;
+import org.hswebframework.web.AuthorizeException;
 import org.hswebframework.web.authorization.Authentication;
 import org.hswebframework.web.authorization.AuthenticationHolder;
 import org.hswebframework.web.authorization.Permission;
 import org.hswebframework.web.authorization.annotation.Authorize;
 import org.hswebframework.web.authorization.annotation.RequiresDataAccess;
+import org.hswebframework.web.authorization.annotation.RequiresExpression;
 import org.hswebframework.web.authorization.annotation.RequiresFieldAccess;
 import org.hswebframework.web.commons.entity.Entity;
 import org.hswebframework.web.commons.entity.PagerResult;
@@ -27,8 +29,8 @@ import java.util.List;
  * @author zhouhao
  */
 @RestController
-@Authorize(permission = "test")
 @RequestMapping("/test")
+@Authorize(permission = "test")
 public class TestController implements QueryController<UserEntity, String, QueryParamEntity> {
 
 
@@ -80,8 +82,7 @@ public class TestController implements QueryController<UserEntity, String, Query
         public UserEntity selectByPk(String id) {
             SimpleUserEntity userEntity = new SimpleUserEntity();
             // 同一个用户
-            userEntity.setCreatorId(AuthenticationHolder.get().getUser().getId());
-
+            userEntity.setCreatorId(Authentication.current().orElseThrow(AuthorizeException::new).getUser().getId());
             return userEntity;
         }
 

+ 37 - 0
hsweb-system/hsweb-system-authorization/hsweb-system-authorization-controller/src/main/java/org/hswebframework/web/controller/authorization/PermissionController.java

@@ -0,0 +1,37 @@
+/*
+ *  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.controller.authorization;
+
+import io.swagger.annotations.Api;
+import org.hswebframework.web.authorization.annotation.Authorize;
+import org.hswebframework.web.logging.AccessLogger;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * @author zhouhao
+ */
+@RestController
+@RequestMapping("${hsweb.web.mappings.permission:permission}")
+@AccessLogger("{permission_manager}")
+@Authorize(permission = "permission")
+@Api(tags = "permission-manager", description = "权限管理")
+public class PermissionController {
+
+}

+ 4 - 4
hsweb-system/hsweb-system-authorization/hsweb-system-authorization-controller/src/main/java/org/hswebframework/web/controller/authorization/UserController.java

@@ -19,8 +19,8 @@ package org.hswebframework.web.controller.authorization;
 
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
+import org.hswebframework.web.AuthorizeException;
 import org.hswebframework.web.authorization.Authentication;
-import org.hswebframework.web.authorization.AuthenticationHolder;
 import org.hswebframework.web.authorization.Permission;
 import org.hswebframework.web.authorization.annotation.Authorize;
 import org.hswebframework.web.commons.entity.PagerResult;
@@ -31,12 +31,11 @@ import org.hswebframework.web.controller.message.ResponseMessage;
 import org.hswebframework.web.entity.authorization.UserEntity;
 import org.hswebframework.web.logging.AccessLogger;
 import org.hswebframework.web.model.authorization.UserModel;
-import org.hswebframework.web.service.AbstractService;
 import org.hswebframework.web.service.authorization.UserService;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.util.Assert;
 import org.springframework.web.bind.annotation.*;
 
+
 import static org.hswebframework.web.controller.message.ResponseMessage.ok;
 
 /**
@@ -103,7 +102,8 @@ public class UserController implements
     @ApiOperation("修改当前用户的密码")
     public ResponseMessage<Void> updateLoginUserPassword(@RequestParam String password,
                                                          @RequestParam String oldPassword) {
-        Authentication authentication = Authentication.current().get();
+
+        Authentication authentication = Authentication.current().orElseThrow(AuthorizeException::new);
         getService().updatePassword(authentication.getUser().getId(), oldPassword, password);
         return ok();
     }