去shiro 基本完成

This commit is contained in:
zhouhao
2017-08-16 22:44:07 +08:00
parent eccb37128f
commit 12847e4cf9
27 changed files with 125 additions and 188 deletions

View File

@@ -16,24 +16,17 @@
*
*/
package org.hswebframework.web;
package org.hswebframework.web.authorization.exception;
public class AuthorizeException extends BusinessException {
public class UnAuthorizedException extends RuntimeException {
private static final long serialVersionUID = 2422918455013900645L;
public AuthorizeException() {
this("{no_authorization}");
public UnAuthorizedException() {
this("{un_authorization}");
}
public AuthorizeException(String message) {
this(message, 401);
public UnAuthorizedException(String message) {
super(message);
}
public AuthorizeException(String message, int status) {
super(message, status);
}
public AuthorizeException(String message, Throwable cause, int status) {
super(message, cause, status);
}
}

View File

@@ -50,6 +50,11 @@
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hswebframework.web</groupId>
<artifactId>hsweb-commons-entity</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View File

@@ -3,10 +3,11 @@ package org.hswebframework.web.authorization.basic.aop;
import org.aopalliance.intercept.MethodInterceptor;
import org.hswebframework.web.AopUtils;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.authorization.basic.handler.AuthorizingContext;
import org.hswebframework.web.authorization.define.AuthorizingContext;
import org.hswebframework.web.authorization.basic.handler.AuthorizingHandler;
import org.hswebframework.web.authorization.define.AuthorizeDefinition;
import org.hswebframework.web.authorization.exception.AuthorizationException;
import org.hswebframework.web.authorization.exception.UnAuthorizedException;
import org.hswebframework.web.boost.aop.context.MethodInterceptorHolder;
import org.hswebframework.web.boost.aop.context.MethodInterceptorParamContext;
import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor;
@@ -31,7 +32,7 @@ public class AopAuthorizingController extends StaticMethodMatcherPointcutAdvisor
if (null != definition) {
AuthorizingContext context = new AuthorizingContext();
context.setAuthentication(Authentication.current().orElseThrow(AuthorizationException::new));
context.setAuthentication(Authentication.current().orElseThrow(UnAuthorizedException::new));
context.setDefinition(definition);
context.setParamContext(paramContext);
authorizingHandler.handle(context);

View File

@@ -1,5 +1,7 @@
package org.hswebframework.web.authorization.basic.handler;
import org.hswebframework.web.authorization.define.AuthorizingContext;
/**
* aop方式权限控制处理器
* @author zhouhao

View File

@@ -10,6 +10,7 @@ import org.hswebframework.web.authorization.access.DataAccessConfig;
import org.hswebframework.web.authorization.access.DataAccessController;
import org.hswebframework.web.authorization.annotation.Logical;
import org.hswebframework.web.authorization.define.AuthorizeDefinition;
import org.hswebframework.web.authorization.define.AuthorizingContext;
import org.hswebframework.web.authorization.exception.AuthorizationException;
import org.hswebframework.web.boost.aop.context.MethodInterceptorParamContext;
import org.slf4j.Logger;
@@ -47,21 +48,21 @@ public class DefaultAuthorizingHandler implements AuthorizingHandler {
handleRdac(context.getAuthentication(), context.getDefinition());
//进行数据权限控制
handleDataAccess(context.getAuthentication(), context.getDefinition(), context.getParamContext());
handleDataAccess(context);
//表达式权限控制
handleExpression(context.getAuthentication(), context.getDefinition(), context.getParamContext());
}
protected void handleDataAccess(Authentication authentication, AuthorizeDefinition definition, MethodInterceptorParamContext paramContext) {
protected void handleDataAccess(AuthorizingContext context) {
if (dataAccessController == null) {
logger.warn("dataAccessController is null,skip data access control!");
return;
}
List<Permission> permission = authentication.getPermissions()
List<Permission> permission = context.getAuthentication().getPermissions()
.stream()
.filter(per -> definition.getPermissions().contains(per.getId()))
.filter(per -> context.getDefinition().getPermissions().contains(per.getId()))
.collect(Collectors.toList());
DataAccessController finalAccessController = dataAccessController;
@@ -70,18 +71,16 @@ public class DefaultAuthorizingHandler implements AuthorizingHandler {
Set<DataAccessConfig> accesses = permission
.stream().map(Permission::getDataAccesses)
.flatMap(Collection::stream)
.filter(access -> definition.getActions().contains(access.getAction()))
.filter(access -> context.getDefinition().getActions().contains(access.getAction()))
.collect(Collectors.toSet());
//无规则,则代表不进行控制
if (accesses.isEmpty()) return;
//单个规则验证函数
Function<Predicate<DataAccessConfig>, Boolean> function =
definition.getLogical() == Logical.AND ?
accesses.stream()::allMatch : accesses.stream()::anyMatch;
Function<Predicate<DataAccessConfig>, Boolean> function = accesses.stream()::allMatch;
//调用控制器进行验证
boolean isAccess = function.apply(access -> finalAccessController.doAccess(access, paramContext));
boolean isAccess = function.apply(access -> finalAccessController.doAccess(access, context));
if (!isAccess) {
throw new AuthorizationException(definition.getMessage());
throw new AuthorizationException(context.getDefinition().getMessage());
}
}
@@ -113,8 +112,10 @@ public class DefaultAuthorizingHandler implements AuthorizingHandler {
protected void handleRdac(Authentication authentication, AuthorizeDefinition definition) {
boolean access = true;
//多个设置时的判断逻辑
Logical logical = definition.getLogical() == Logical.DEFAULT ? Logical.OR : definition.getLogical();
boolean logicalIsOr = logical == Logical.OR;
Set<String> permissionsDef = definition.getPermissions();
Set<String> actionsDef = definition.getActions();
Set<String> rolesDef = definition.getRoles();

View File

@@ -21,6 +21,7 @@ package org.hswebframework.web.authorization.basic.handler.access;
import org.hswebframework.web.authorization.access.CustomDataAccessConfig;
import org.hswebframework.web.authorization.access.DataAccessConfig;
import org.hswebframework.web.authorization.access.DataAccessHandler;
import org.hswebframework.web.authorization.define.AuthorizingContext;
import org.hswebframework.web.boost.aop.context.MethodInterceptorParamContext;
/**
@@ -37,7 +38,7 @@ public class CustomDataAccessHandler implements DataAccessHandler {
}
@Override
public boolean handle(DataAccessConfig access, MethodInterceptorParamContext context) {
public boolean handle(DataAccessConfig access, AuthorizingContext context) {
CustomDataAccessConfig custom = ((CustomDataAccessConfig) access);
return custom.getController().doAccess(access, context);
}

View File

@@ -3,6 +3,7 @@ package org.hswebframework.web.authorization.basic.handler.access;
import org.hswebframework.web.authorization.access.DataAccessConfig;
import org.hswebframework.web.authorization.access.DataAccessController;
import org.hswebframework.web.authorization.access.DataAccessHandler;
import org.hswebframework.web.authorization.define.AuthorizingContext;
import org.hswebframework.web.boost.aop.context.MethodInterceptorParamContext;
import java.util.LinkedList;
@@ -36,12 +37,12 @@ public final class DefaultDataAccessController implements DataAccessController {
}
@Override
public boolean doAccess(DataAccessConfig access, MethodInterceptorParamContext params) {
if (parent != null) parent.doAccess(access, params);
public boolean doAccess(DataAccessConfig access, AuthorizingContext context) {
if (parent != null) parent.doAccess(access, context);
return handlers.stream()
// TODO: 17-3-28 可以换成access对应的handler以提高效率
.filter(handler -> handler.isSupport(access))
.allMatch(handler -> handler.handle(access, params));
.allMatch(handler -> handler.handle(access, context));
}
public DefaultDataAccessController addHandler(DataAccessHandler handler) {

View File

@@ -5,6 +5,7 @@ import org.hswebframework.web.authorization.Permission;
import org.hswebframework.web.authorization.access.DataAccessConfig;
import org.hswebframework.web.authorization.access.DataAccessHandler;
import org.hswebframework.web.authorization.access.FieldFilterDataAccessConfig;
import org.hswebframework.web.authorization.define.AuthorizingContext;
import org.hswebframework.web.boost.aop.context.MethodInterceptorParamContext;
import org.hswebframework.web.commons.entity.Entity;
import org.hswebframework.web.commons.entity.param.QueryParamEntity;
@@ -12,6 +13,8 @@ import org.hswebframework.web.commons.model.Model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/**
* 数据权限字段过滤处理,目前仅支持deny. {@link DataAccessConfig.DefaultType#DENY_FIELDS}
*
@@ -22,11 +25,11 @@ public class FieldFilterDataAccessHandler implements DataAccessHandler {
@Override
public boolean isSupport(DataAccessConfig access) {
return access instanceof FieldFilterDataAccessConfig && DataAccessConfig.DefaultType.DENY_FIELDS.equals(access.getType());
return access instanceof FieldFilterDataAccessConfig;
}
@Override
public boolean handle(DataAccessConfig access, MethodInterceptorParamContext context) {
public boolean handle(DataAccessConfig access, AuthorizingContext context) {
FieldFilterDataAccessConfig filterDataAccessConfig = ((FieldFilterDataAccessConfig) access);
switch (access.getAction()) {
@@ -48,10 +51,11 @@ public class FieldFilterDataAccessHandler implements DataAccessHandler {
* @see BeanUtilsBean
* @see org.apache.commons.beanutils.PropertyUtilsBean
*/
protected boolean doUpdateAccess(FieldFilterDataAccessConfig accesses, MethodInterceptorParamContext params) {
Object supportParam = params.getParams().values().stream()
.filter(param -> (param instanceof Entity) | (param instanceof Model))
.findAny().orElse(null);
protected boolean doUpdateAccess(FieldFilterDataAccessConfig accesses, AuthorizingContext params) {
Object supportParam = params.getParamContext().getParams().values().stream()
.filter(param -> (param instanceof Entity) || (param instanceof Model)||(param instanceof Map))
.findAny()
.orElse(null);
if (null != supportParam) {
for (String field : accesses.getFields()) {
try {
@@ -64,14 +68,14 @@ public class FieldFilterDataAccessHandler implements DataAccessHandler {
}
}
} else {
logger.warn("doUpdateAccess skip ,because can not found any entity in param!");
logger.warn("doUpdateAccess skip ,because can not found any support entity in param!");
}
return true;
}
protected boolean doQueryAccess(FieldFilterDataAccessConfig access, MethodInterceptorParamContext context) {
QueryParamEntity entity = context.getParams()
protected boolean doQueryAccess(FieldFilterDataAccessConfig access, AuthorizingContext context) {
QueryParamEntity entity = context.getParamContext().getParams()
.values().stream()
.filter(QueryParamEntity.class::isInstance)
.map(QueryParamEntity.class::cast)

View File

@@ -9,6 +9,7 @@ import org.hswebframework.web.authorization.access.DataAccessConfig;
import org.hswebframework.web.authorization.access.DataAccessHandler;
import org.hswebframework.web.authorization.access.FieldScopeDataAccessConfig;
import org.hswebframework.web.authorization.annotation.RequiresDataAccess;
import org.hswebframework.web.authorization.define.AuthorizingContext;
import org.hswebframework.web.boost.aop.context.MethodInterceptorParamContext;
import org.hswebframework.web.commons.entity.param.QueryParamEntity;
import org.hswebframework.web.controller.QueryController;
@@ -33,9 +34,9 @@ public class FieldScopeDataAccessHandler implements DataAccessHandler {
}
@Override
public boolean handle(DataAccessConfig access, MethodInterceptorParamContext context) {
public boolean handle(DataAccessConfig access, AuthorizingContext context) {
FieldScopeDataAccessConfig own = ((FieldScopeDataAccessConfig) access);
Object controller = context.getTarget();
Object controller = context.getParamContext().getTarget();
if (controller != null) {
switch (access.getAction()) {
case Permission.ACTION_QUERY:
@@ -55,10 +56,9 @@ public class FieldScopeDataAccessHandler implements DataAccessHandler {
}
@SuppressWarnings("unchecked")
protected boolean doRWAccess(FieldScopeDataAccessConfig access, MethodInterceptorParamContext context, Object controller) {
protected boolean doRWAccess(FieldScopeDataAccessConfig access, AuthorizingContext context, Object controller) {
//获取注解
RequiresDataAccess dataAccess = context.getAnnotation(RequiresDataAccess.class);
Object id = context.<String>getParameter(dataAccess.idParamName()).orElse(null);
Object id = context.getParamContext().<String>getParameter(context.getDefinition().getDataAccessDefinition().getIdParameterName()).orElse(null);
//通过QueryController获取QueryService
//然后调用selectByPk 查询旧的数据,进行对比
if (controller instanceof QueryController) {
@@ -80,8 +80,8 @@ public class FieldScopeDataAccessHandler implements DataAccessHandler {
}
protected boolean doQueryAccess(FieldScopeDataAccessConfig access, MethodInterceptorParamContext context) {
QueryParamEntity entity = context.getParams()
protected boolean doQueryAccess(FieldScopeDataAccessConfig access, AuthorizingContext context) {
QueryParamEntity entity = context.getParamContext().getParams()
.values().stream()
.filter(QueryParamEntity.class::isInstance)
.map(QueryParamEntity.class::cast)

View File

@@ -2,14 +2,11 @@ package org.hswebframework.web.authorization.basic.handler.access;
import org.hsweb.ezorm.core.param.Term;
import org.hswebframework.utils.ClassUtils;
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;
import org.hswebframework.web.authorization.access.OwnCreatedDataAccessConfig;
import org.hswebframework.web.authorization.annotation.RequiresDataAccess;
import org.hswebframework.web.boost.aop.context.MethodInterceptorParamContext;
import org.hswebframework.web.authorization.define.AuthorizingContext;
import org.hswebframework.web.commons.entity.Entity;
import org.hswebframework.web.commons.entity.RecordCreationEntity;
import org.hswebframework.web.commons.entity.param.QueryParamEntity;
@@ -35,9 +32,9 @@ public class OwnCreatedDataAccessHandler implements DataAccessHandler {
}
@Override
public boolean handle(DataAccessConfig access, MethodInterceptorParamContext context) {
public boolean handle(DataAccessConfig access, AuthorizingContext context) {
OwnCreatedDataAccessConfig own = ((OwnCreatedDataAccessConfig) access);
Object controller = context.getTarget();
Object controller = context.getParamContext().getTarget();
if (controller != null) {
switch (access.getAction()) {
case Permission.ACTION_QUERY:
@@ -45,7 +42,7 @@ public class OwnCreatedDataAccessHandler implements DataAccessHandler {
case Permission.ACTION_GET:
case Permission.ACTION_DELETE:
case Permission.ACTION_UPDATE:
return doRWAccess(own, context, controller);
return doRWAccess(own, context,controller);
case Permission.ACTION_ADD:
//put creator_id to data
return putCreatorId(own, context);
@@ -58,16 +55,14 @@ public class OwnCreatedDataAccessHandler implements DataAccessHandler {
return true;
}
public boolean putCreatorId(OwnCreatedDataAccessConfig access, MethodInterceptorParamContext context) {
RecordCreationEntity entity = context.getParams()
public boolean putCreatorId(OwnCreatedDataAccessConfig access, AuthorizingContext context) {
RecordCreationEntity entity = context.getParamContext().getParams()
.values().stream()
.filter(RecordCreationEntity.class::isInstance)
.map(RecordCreationEntity.class::cast)
.findAny().orElse(null);
if (entity != null) {
entity.setCreatorId(Authentication.current()
.orElseThrow(AuthorizeException::new)
.getUser().getId());
entity.setCreatorId(context.getAuthentication().getUser().getId());
} else {
logger.warn("try put creatorId property,but not found any RecordCreationEntity!");
}
@@ -75,10 +70,9 @@ public class OwnCreatedDataAccessHandler implements DataAccessHandler {
}
@SuppressWarnings("unchecked")
protected boolean doRWAccess(OwnCreatedDataAccessConfig access, MethodInterceptorParamContext context, Object controller) {
protected boolean doRWAccess(OwnCreatedDataAccessConfig access, AuthorizingContext context, Object controller) {
//获取注解
RequiresDataAccess dataAccess = context.getAnnotation(RequiresDataAccess.class);
Object id = context.<String>getParameter(dataAccess.idParamName()).orElse(null);
Object id = context.getParamContext().<String>getParameter(context.getDefinition().getDataAccessDefinition().getIdParameterName()).orElse(null);
//通过QueryController获取QueryService
//然后调用selectByPk 查询旧的数据,进行对比
if (controller instanceof QueryController) {
@@ -88,7 +82,7 @@ public class OwnCreatedDataAccessHandler implements DataAccessHandler {
QueryService<RecordCreationEntity, Object> queryService =
((QueryController<RecordCreationEntity, Object, Entity>) controller).getService();
RecordCreationEntity oldData = queryService.selectByPk(id);
if (oldData != null && !Authentication.current().orElseThrow(AuthorizeException::new).getUser().getId().equals(oldData.getCreatorId())) {
if (oldData != null &&context.getAuthentication().getUser().getId().equals(oldData.getCreatorId())) {
return false;
}
}
@@ -96,8 +90,8 @@ public class OwnCreatedDataAccessHandler implements DataAccessHandler {
return true;
}
protected boolean doQueryAccess(OwnCreatedDataAccessConfig access, MethodInterceptorParamContext context) {
Entity entity = context.getParams()
protected boolean doQueryAccess(OwnCreatedDataAccessConfig access, AuthorizingContext context) {
Entity entity = context.getParamContext().getParams()
.values().stream()
.filter(Entity.class::isInstance)
.map(Entity.class::cast)
@@ -116,11 +110,11 @@ public class OwnCreatedDataAccessHandler implements DataAccessHandler {
queryParamEntity.setTerms(new ArrayList<>());
//添加一个查询条件
queryParamEntity
.where(RecordCreationEntity.creatorId, Authentication.current().orElseThrow(AuthorizeException::new).getUser().getId())
.where(RecordCreationEntity.creatorId,context.getAuthentication().getUser().getId())
//客户端提交的参数 作为嵌套参数
.nest().setTerms(oldParam);
} else if (entity instanceof RecordCreationEntity) {
((RecordCreationEntity) entity).setCreatorId(Authentication.current().orElseThrow(AuthorizeException::new).getUser().getId());
((RecordCreationEntity) entity).setCreatorId(context.getAuthentication().getUser().getId());
} else {
logger.warn("try validate query access,but entity not support, QueryParamEntity and RecordCreationEntity support now!");
}

View File

@@ -8,6 +8,7 @@ import org.hswebframework.web.BusinessException;
import org.hswebframework.web.authorization.access.DataAccessConfig;
import org.hswebframework.web.authorization.access.DataAccessHandler;
import org.hswebframework.web.authorization.access.ScriptDataAccessConfig;
import org.hswebframework.web.authorization.define.AuthorizingContext;
import org.hswebframework.web.boost.aop.context.MethodInterceptorParamContext;
/**
@@ -22,7 +23,7 @@ public class ScriptDataAccessHandler implements DataAccessHandler {
}
@Override
public boolean handle(DataAccessConfig access, MethodInterceptorParamContext context) {
public boolean handle(DataAccessConfig access, AuthorizingContext context) {
ScriptDataAccessConfig dataAccess = ((ScriptDataAccessConfig) access);
DynamicScriptEngine engine = DynamicScriptEngineFactory.getEngine(dataAccess.getScriptLanguage());
if (engine == null) throw new UnsupportedOperationException(dataAccess.getScriptLanguage() + " {not_support}");
@@ -31,7 +32,7 @@ public class ScriptDataAccessHandler implements DataAccessHandler {
if (!engine.compiled(scriptId)) {
engine.compile(scriptId, dataAccess.getScript());
}
Object success = engine.execute(scriptId, context.getParams()).getIfSuccess();
Object success = engine.execute(scriptId, context.getParamContext().getParams()).getIfSuccess();
return StringUtils.isTrue(success);
} catch (Exception e) {
throw new BusinessException("{script_error}", e);

View File

@@ -34,9 +34,7 @@ import org.hswebframework.web.authorization.AuthenticationHolder;
import org.hswebframework.web.authorization.AuthenticationManager;
import org.hswebframework.web.authorization.AuthenticationSupplier;
import org.hswebframework.web.authorization.access.DataAccessController;
import org.hswebframework.web.authorization.access.DataAccessHandler;
import org.hswebframework.web.authorization.shiro.boost.BoostAuthorizationAttributeSourceAdvisor;
import org.hswebframework.web.authorization.shiro.boost.DefaultDataAccessController;
import org.hswebframework.web.authorization.shiro.cache.SpringCacheManagerWrapper;
import org.hswebframework.web.authorization.shiro.remember.SimpleRememberMeManager;
import org.hswebframework.web.controller.message.ResponseMessage;
@@ -145,31 +143,6 @@ public class ShiroAutoConfiguration {
return securityManager;
}
@Bean
@ConditionalOnMissingBean
public DefaultDataAccessController defaultDataAccessController() {
return new DefaultDataAccessController();
}
@Bean
@ConditionalOnBean(DefaultDataAccessController.class)
public BeanPostProcessor dataAccessControllerProcessor(DefaultDataAccessController defaultDataAccessController) {
return new BeanPostProcessor() {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof DataAccessHandler) {
defaultDataAccessController.addHandler(((DataAccessHandler) bean));
}
return bean;
}
};
}
@Bean
public BoostAuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager,

View File

@@ -1,38 +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;
/**
* Created by 浩 on 2015-12-23 0023.
*/
public class AuthorizeForbiddenException extends BusinessException {
private static final long serialVersionUID = 2422918455013900645L;
public AuthorizeForbiddenException(String message) {
this(message, 403);
}
public AuthorizeForbiddenException(String message, int status) {
super(message, status);
}
public AuthorizeForbiddenException(String message, Throwable cause, int status) {
super(message, cause, status);
}
}

View File

@@ -1,11 +1,11 @@
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.Permission;
import org.hswebframework.web.authorization.annotation.Authorize;
import org.hswebframework.web.authorization.annotation.RequiresDataAccess;
import org.hswebframework.web.authorization.exception.UnAuthorizedException;
import org.hswebframework.web.commons.entity.Entity;
import org.hswebframework.web.commons.entity.PagerResult;
import org.hswebframework.web.commons.entity.param.QueryParamEntity;
@@ -94,7 +94,7 @@ public class TestController implements QueryController<UserEntity, String, Query
public UserEntity selectByPk(String id) {
SimpleUserEntity userEntity = new SimpleUserEntity();
// 同一个用户
userEntity.setCreatorId(Authentication.current().orElseThrow(AuthorizeException::new).getUser().getId());
userEntity.setCreatorId(Authentication.current().orElseThrow(UnAuthorizedException::new).getUser().getId());
return userEntity;
}

View File

@@ -18,10 +18,10 @@
package org.hswebframework.web.starter;
import com.alibaba.fastjson.JSONException;
import org.hswebframework.web.AuthorizeException;
import org.hswebframework.web.AuthorizeForbiddenException;
import org.hswebframework.web.BusinessException;
import org.hswebframework.web.NotFoundException;
import org.hswebframework.web.authorization.exception.AuthorizationException;
import org.hswebframework.web.authorization.exception.UnAuthorizedException;
import org.hswebframework.web.controller.message.ResponseMessage;
import org.hswebframework.web.validate.SimpleValidateResults;
import org.hswebframework.web.validate.ValidateResults;
@@ -29,10 +29,7 @@ import org.hswebframework.web.validate.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.BindingResultUtils;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@@ -79,21 +76,20 @@ public class RestControllerExceptionTranslator {
return ResponseMessage.error(exception.getStatus(), exception.getMessage());
}
@ExceptionHandler(AuthorizeException.class)
@ExceptionHandler(UnAuthorizedException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody
ResponseMessage handleException(AuthorizeException exception) {
return ResponseMessage.error(exception.getStatus(), exception.getMessage());
ResponseMessage handleException(UnAuthorizedException exception) {
return ResponseMessage.error(401, exception.getMessage());
}
@ExceptionHandler(AuthorizeForbiddenException.class)
@ExceptionHandler(AuthorizationException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
@ResponseBody
ResponseMessage handleException(AuthorizeForbiddenException exception) {
return ResponseMessage.error(exception.getStatus(), exception.getMessage());
ResponseMessage handleException(AuthorizationException exception) {
return ResponseMessage.error(403, exception.getMessage());
}
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody

View File

@@ -17,11 +17,9 @@
package org.hswebframework.web.starter.resolver;
import org.hswebframework.web.AuthorizeException;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.authorization.AuthenticationSupplier;
import org.hswebframework.web.authorization.exception.UnAuthorizedException;
import org.springframework.core.MethodParameter;
import org.springframework.util.Assert;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
@@ -51,6 +49,6 @@ public class AuthorizationArgumentResolver implements HandlerMethodArgumentResol
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
return Authentication.current().orElseThrow(AuthorizeException::new);
return Authentication.current().orElseThrow(UnAuthorizedException::new);
}
}

View File

@@ -66,7 +66,7 @@ public class AuthorizationController {
@Autowired
private AuthorizationListenerDispatcher authorizationListenerDispatcher;
@GetMapping("/login-out")
@GetMapping({"/login-out","/sign-out","/exit"})
@Authorize
@ApiOperation("退出当前登录")
public ResponseMessage exit(@ApiParam(hidden = true) Authentication authentication) {

View File

@@ -19,10 +19,10 @@ 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.Permission;
import org.hswebframework.web.authorization.annotation.Authorize;
import org.hswebframework.web.authorization.exception.UnAuthorizedException;
import org.hswebframework.web.commons.entity.PagerResult;
import org.hswebframework.web.commons.entity.param.QueryParamEntity;
import org.hswebframework.web.controller.CreateController;
@@ -31,7 +31,6 @@ import org.hswebframework.web.controller.message.ResponseMessage;
import org.hswebframework.web.entity.authorization.UserEntity;
import org.hswebframework.web.entity.authorization.bind.BindRoleUserEntity;
import org.hswebframework.web.logging.AccessLogger;
import org.hswebframework.web.model.authorization.UserModel;
import org.hswebframework.web.service.authorization.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@@ -40,8 +39,7 @@ import org.springframework.web.bind.annotation.*;
import static org.hswebframework.web.controller.message.ResponseMessage.ok;
/**
* TODO 完成注释
*
* 用户管理控制器
* @author zhouhao
*/
@RestController
@@ -96,7 +94,7 @@ public class UserController implements
public ResponseMessage<Void> updateLoginUserPassword(@RequestParam String password,
@RequestParam String oldPassword) {
Authentication authentication = Authentication.current().orElseThrow(AuthorizeException::new);
Authentication authentication = Authentication.current().orElseThrow(UnAuthorizedException::new);
getService().updatePassword(authentication.getUser().getId(), oldPassword, password);
return ok();
}

View File

@@ -18,16 +18,12 @@
package org.hswebframework.web.starter.authorization;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.hswebframework.expands.security.Encrypt;
import org.hswebframework.expands.security.rsa.RSAPublicEncrypt;
import org.hswebframework.web.entity.authorization.UserEntity;
import org.hswebframework.web.service.authorization.UserService;
import org.hswebframework.web.tests.SimpleWebApplicationTests;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import java.sql.SQLException;
@@ -61,6 +57,7 @@ public class LoginTests extends SimpleWebApplicationTests {
builder.param("password", "password_1234");
}).exec().resultAsJson();
org.junit.Assert.assertEquals(json.get("result"), userEntity.getId());
org.junit.Assert.assertEquals(userEntity.getId(), json.getJSONObject("result").getString("userId"));
}
}

View File

@@ -20,9 +20,9 @@ package org.hswebframework.web.authorization.oauth2.controller;
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.annotation.Authorize;
import org.hswebframework.web.authorization.exception.UnAuthorizedException;
import org.hswebframework.web.authorization.oauth2.server.OAuth2AccessToken;
import org.hswebframework.web.authorization.oauth2.server.support.OAuth2Granter;
import org.hswebframework.web.authorization.oauth2.server.support.code.AuthorizationCodeRequest;
@@ -62,7 +62,7 @@ public class OAuth2AuthorizeController {
@RequestParam("redirect_uri") String redirectUri,
@RequestParam(value = "state", required = false) String state,
HttpServletRequest request) {
Authentication authentication = Authentication.current().orElseThrow(AuthorizeException::new);
Authentication authentication = Authentication.current().orElseThrow(UnAuthorizedException::new);
AuthorizationCodeRequest codeRequest = new HttpAuthorizationCodeRequest(authentication.getUser().getId(), request);

View File

@@ -20,9 +20,9 @@ package org.hswebframework.web.authorization.oauth2.controller;
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.exception.UnAuthorizedException;
import org.hswebframework.web.authorization.oauth2.server.OAuth2AccessToken;
import org.hswebframework.web.authorization.oauth2.server.token.AccessTokenService;
import org.springframework.web.bind.annotation.*;
@@ -48,7 +48,7 @@ public class OAuth2UserInfoController {
public Authentication getLoginUser(@RequestParam("access_token") String access_token) {
OAuth2AccessToken auth2AccessEntity = accessTokenService.getTokenByAccessToken(access_token);
if (null == auth2AccessEntity) {
throw new AuthorizeException();
throw new UnAuthorizedException();
}
return AuthenticationHolder.get(auth2AccessEntity.getOwnerId());
}
@@ -60,7 +60,7 @@ public class OAuth2UserInfoController {
@RequestParam("access_token") String access_token) {
OAuth2AccessToken auth2AccessEntity = accessTokenService.getTokenByAccessToken(access_token);
if (null == auth2AccessEntity) {
throw new AuthorizeException();
throw new UnAuthorizedException();
}
return AuthenticationHolder.get(userId);
}

View File

@@ -7,6 +7,7 @@ import org.hswebframework.web.authorization.access.DataAccessConfig;
import org.hswebframework.web.authorization.access.DataAccessHandler;
import org.hswebframework.web.authorization.access.ScopeDataAccessConfig;
import org.hswebframework.web.authorization.annotation.RequiresDataAccess;
import org.hswebframework.web.authorization.define.AuthorizingContext;
import org.hswebframework.web.boost.aop.context.MethodInterceptorHolder;
import org.hswebframework.web.boost.aop.context.MethodInterceptorParamContext;
import org.hswebframework.web.commons.entity.Entity;
@@ -43,7 +44,7 @@ public abstract class AbstractScopeDataAccessHandler<E> implements DataAccessHan
protected abstract void applyScopeProperty(E entity, String value);
protected abstract Term createQueryTerm(Set<String> scope);
protected abstract Term createQueryTerm(Set<String> scope,AuthorizingContext context);
protected abstract Set<String> getTryOperationScope(String scopeType, PersonnelAuthorization authorization);
@@ -53,7 +54,7 @@ public abstract class AbstractScopeDataAccessHandler<E> implements DataAccessHan
}
@Override
public boolean handle(DataAccessConfig access, MethodInterceptorParamContext context) {
public boolean handle(DataAccessConfig access, AuthorizingContext context) {
ScopeDataAccessConfig accessConfig = ((ScopeDataAccessConfig) access);
switch (accessConfig.getAction()) {
case Permission.ACTION_QUERY:
@@ -73,7 +74,7 @@ public abstract class AbstractScopeDataAccessHandler<E> implements DataAccessHan
.orElseThrow(UnsupportedOperationException::new); // TODO: 17-5-23 其他异常?
}
protected boolean handleAdd(ScopeDataAccessConfig access, MethodInterceptorParamContext context) {
protected boolean handleAdd(ScopeDataAccessConfig access, AuthorizingContext context) {
PersonnelAuthorization authorization = getPersonnelAuthorization();
Set<String> scopes = authorization.getRootOrgId();
String scope = null;
@@ -86,7 +87,7 @@ public abstract class AbstractScopeDataAccessHandler<E> implements DataAccessHan
}
if (scope != null) {
String finalScopeId = scope;
context.getParams().values().stream()
context.getParamContext().getParams().values().stream()
.filter(getEntityClass()::isInstance)
.map(getEntityClass()::cast)
.forEach(entity -> applyScopeProperty(entity, finalScopeId));
@@ -96,11 +97,16 @@ public abstract class AbstractScopeDataAccessHandler<E> implements DataAccessHan
return defaultSuccessOnError;
}
protected boolean handleRW(ScopeDataAccessConfig access, MethodInterceptorParamContext context) {
protected boolean handleRW(ScopeDataAccessConfig access, AuthorizingContext context) {
//获取注解
RequiresDataAccess dataAccess = context.getAnnotation(RequiresDataAccess.class);
Object id = context.<String>getParameter(dataAccess.idParamName()).orElse(null);
Object controller = context.getTarget();
Object id = context.getParamContext()
.<String>getParameter(
context.getDefinition()
.getDataAccessDefinition()
.getIdParameterName())
.orElse(null);
Object controller = context.getParamContext().getTarget();
Set<String> ids = getTryOperationScope(access);
String errorMsg;
//通过QueryController获取QueryService
@@ -133,8 +139,8 @@ public abstract class AbstractScopeDataAccessHandler<E> implements DataAccessHan
return getTryOperationScope(access.getScopeType(), getPersonnelAuthorization());
}
protected boolean handleQuery(ScopeDataAccessConfig access, MethodInterceptorParamContext context) {
Entity entity = context.getParams()
protected boolean handleQuery(ScopeDataAccessConfig access, AuthorizingContext context) {
Entity entity = context.getParamContext().getParams()
.values().stream()
.filter(Entity.class::isInstance)
.map(Entity.class::cast)
@@ -160,7 +166,7 @@ public abstract class AbstractScopeDataAccessHandler<E> implements DataAccessHan
queryParamEntity.setTerms(new ArrayList<>());
//添加一个查询条件
queryParamEntity
.addTerm(createQueryTerm(scope))
.addTerm(createQueryTerm(scope,context))
//客户端提交的参数 作为嵌套参数
.nest().setTerms(oldParam);
} else {
@@ -169,9 +175,8 @@ public abstract class AbstractScopeDataAccessHandler<E> implements DataAccessHan
return true;
}
protected boolean genericTypeInstanceOf(Class type) {
MethodInterceptorHolder holder = MethodInterceptorHolder.current();
Class entity = ClassUtils.getGenericType(holder.getTarget().getClass());
protected boolean genericTypeInstanceOf(Class type, AuthorizingContext context) {
Class entity = ClassUtils.getGenericType(context.getParamContext().getTarget().getClass());
return null != entity && ClassUtils.instanceOf(entity, type);
}
}

View File

@@ -2,6 +2,7 @@ package org.hswebframework.web.organizational.authorization.simple.handler;
import org.hsweb.ezorm.core.param.Term;
import org.hsweb.ezorm.core.param.TermType;
import org.hswebframework.web.authorization.define.AuthorizingContext;
import org.hswebframework.web.entity.organizational.authorization.DistrictAttachEntity;
import org.hswebframework.web.organizational.authorization.PersonnelAuthorization;
@@ -49,7 +50,7 @@ public class AreaScopeDataAccessHandler extends AbstractScopeDataAccessHandler<D
}
@Override
protected Term createQueryTerm(Set<String> scope) {
protected Term createQueryTerm(Set<String> scope, AuthorizingContext context) {
Term term = new Term();
term.setColumn(DistrictAttachEntity.districtId);
term.setTermType(TermType.in);

View File

@@ -2,6 +2,7 @@ package org.hswebframework.web.organizational.authorization.simple.handler;
import org.hsweb.ezorm.core.param.Term;
import org.hsweb.ezorm.core.param.TermType;
import org.hswebframework.web.authorization.define.AuthorizingContext;
import org.hswebframework.web.entity.organizational.DepartmentEntity;
import org.hswebframework.web.entity.organizational.OrganizationalEntity;
import org.hswebframework.web.entity.organizational.authorization.DepartmentAttachEntity;
@@ -54,9 +55,9 @@ public class DepartmentScopeDataAccessHandler extends AbstractScopeDataAccessHan
}
@Override
protected Term createQueryTerm(Set<String> scope) {
protected Term createQueryTerm(Set<String> scope, AuthorizingContext context) {
Term term = new Term();
if (genericTypeInstanceOf(DepartmentEntity.class)) {
if (genericTypeInstanceOf(DepartmentEntity.class,context)) {
term.setColumn(DepartmentEntity.id);
} else {
term.setColumn(DepartmentAttachEntity.departmentId);

View File

@@ -3,6 +3,7 @@ package org.hswebframework.web.organizational.authorization.simple.handler;
import org.hsweb.ezorm.core.param.Term;
import org.hsweb.ezorm.core.param.TermType;
import org.hswebframework.utils.ClassUtils;
import org.hswebframework.web.authorization.define.AuthorizingContext;
import org.hswebframework.web.boost.aop.context.MethodInterceptorHolder;
import org.hswebframework.web.boost.aop.context.MethodInterceptorParamContext;
import org.hswebframework.web.entity.organizational.OrganizationalEntity;
@@ -56,9 +57,9 @@ public class OrgScopeDataAccessHandler extends AbstractScopeDataAccessHandler<Or
}
@Override
protected Term createQueryTerm(Set<String> scope) {
protected Term createQueryTerm(Set<String> scope, AuthorizingContext context) {
Term term = new Term();
if (genericTypeInstanceOf(OrganizationalEntity.class)) {
if (genericTypeInstanceOf(OrganizationalEntity.class,context)) {
term.setColumn(OrganizationalEntity.id);
} else {
term.setColumn(OrgAttachEntity.orgId);

View File

@@ -2,6 +2,7 @@ package org.hswebframework.web.organizational.authorization.simple.handler;
import org.hsweb.ezorm.core.param.Term;
import org.hsweb.ezorm.core.param.TermType;
import org.hswebframework.web.authorization.define.AuthorizingContext;
import org.hswebframework.web.entity.organizational.authorization.PersonAttachEntity;
import org.hswebframework.web.organizational.authorization.PersonnelAuthorization;
import org.hswebframework.web.organizational.authorization.access.DataAccessType;
@@ -51,7 +52,7 @@ public class PersonScopeDataAccessHandler extends AbstractScopeDataAccessHandler
}
@Override
protected Term createQueryTerm(Set<String> scope) {
protected Term createQueryTerm(Set<String> scope, AuthorizingContext context) {
Term term = new Term();
term.setColumn(PersonAttachEntity.personId);
term.setTermType(TermType.in);

View File

@@ -2,6 +2,7 @@ package org.hswebframework.web.organizational.authorization.simple.handler;
import org.hsweb.ezorm.core.param.Term;
import org.hsweb.ezorm.core.param.TermType;
import org.hswebframework.web.authorization.define.AuthorizingContext;
import org.hswebframework.web.entity.organizational.PositionEntity;
import org.hswebframework.web.entity.organizational.authorization.PositionAttachEntity;
import org.hswebframework.web.organizational.authorization.PersonnelAuthorization;
@@ -52,9 +53,9 @@ public class PositionScopeDataAccessHandler extends AbstractScopeDataAccessHandl
}
@Override
protected Term createQueryTerm(Set<String> scope) {
protected Term createQueryTerm(Set<String> scope, AuthorizingContext context) {
Term term = new Term();
if (genericTypeInstanceOf(PositionEntity.class)) {
if (genericTypeInstanceOf(PositionEntity.class,context)) {
term.setColumn(PositionEntity.id);
} else {
term.setColumn(PositionAttachEntity.positionId);