下面列出了org.springframework.web.bind.annotation.ExceptionHandler#org.springframework.security.access.AccessDeniedException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@SuppressWarnings("unchecked")
@Test (expected = AccessDeniedException.class)
public void testCheckAccessStaffReadAccessDenied() {
securityContextInjector.setStaffContext();
mockRepo.createWithRetries(EntityNames.EDUCATION_ORGANIZATION, BAD_EDORG, new HashMap<String, Object>(),
new HashMap<String, Object>(), EntityNames.EDUCATION_ORGANIZATION, 1);
mockRepo.create(EntityNames.STUDENT_SCHOOL_ASSOCIATION, createStudentSchoolAssociation(BAD_STUDENT, BAD_EDORG));
Map<String, Object> eb = new HashMap<String, Object>();
eb.put("studentUniqueStateId", "1234");
Entity student = createEntity(EntityNames.STUDENT, BAD_STUDENT, eb);
service.checkAccess(false, false, student, EntityNames.STUDENT, service.getContextualAuthorities(false, student, SecurityUtil.UserContext.STAFF_CONTEXT, false));
}
@PutMapping(value = "/apps/{appId}/namespaces/{namespaceName}/items", consumes = {"application/json"})
public ResponseEntity<Void> update(@PathVariable String appId, @PathVariable String namespaceName,
@RequestBody NamespaceSyncModel model) {
checkModel(!model.isInvalid());
boolean hasPermission = permissionValidator.hasModifyNamespacePermission(appId, namespaceName);
Env envNoPermission = null;
// if uses has ModifyNamespace permission then he has permission
if (!hasPermission) {
// else check if user has every env's ModifyNamespace permission
hasPermission = true;
for (NamespaceIdentifier namespaceIdentifier : model.getSyncToNamespaces()) {
// once user has not one of the env's ModifyNamespace permission, then break the loop
hasPermission &= permissionValidator.hasModifyNamespacePermission(namespaceIdentifier.getAppId(), namespaceIdentifier.getNamespaceName(), namespaceIdentifier.getEnv().toString());
if (!hasPermission) {
envNoPermission = namespaceIdentifier.getEnv();
break;
}
}
}
if (hasPermission) {
configService.syncItems(model.getSyncToNamespaces(), model.getSyncItems());
return ResponseEntity.status(HttpStatus.OK).build();
}
throw new AccessDeniedException(String.format("You don't have the permission to modify environment: %s", envNoPermission));
}
@Test
public void checkPermissionAssertAccessDeniedWhenPrincipalIsNull() throws Exception
{
// Mock a join point of the method call
// mockMethod("foo");
JoinPoint joinPoint = mock(JoinPoint.class);
MethodSignature methodSignature = mock(MethodSignature.class);
Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class);
when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace"});
when(methodSignature.getMethod()).thenReturn(method);
when(joinPoint.getSignature()).thenReturn(methodSignature);
when(joinPoint.getArgs()).thenReturn(new Object[] {"foo"});
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(null, null));
try
{
namespaceSecurityAdvice.checkPermission(joinPoint);
fail();
}
catch (Exception e)
{
assertEquals(AccessDeniedException.class, e.getClass());
assertEquals("Current user does not have \"[READ]\" permission(s) to the namespace \"foo\"", e.getMessage());
}
}
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
// 判断目标是否在权限控制内
if (configAttributes == null) return;
// 遍历权限
for (ConfigAttribute configAttribute: configAttributes) {
// 将权限与用户角色进行匹配
String role = configAttribute.getAttribute();
for (GrantedAuthority grantedAuthority: authentication.getAuthorities()) {
Logger.debug("match between %s and %s.", role, grantedAuthority.getAuthority());
if (Strings.equals(role, grantedAuthority.getAuthority())) {
Logger.debug("matched! access allow.");
return;
}
}
}
// 无法匹配权限抛出异常
Logger.info("denied!");
throw new AccessDeniedException("no authority.");
}
/** {@inheritDoc} */
@Override
public void updateDashboard(final long id, final String dashboardWidgets) throws Exception {
final ManagerDTO managerDTO = managementService.getManagerById(id);
if (managerDTO != null && federationFacade.isManageable(managerDTO.getEmail(), ManagerDTO.class)) {
managementService.updateDashboard(managerDTO.getEmail(), dashboardWidgets);
} else {
final VoManager myself = getMyselfInternal();
if (myself != null && id == myself.getManagerId()) {
managementService.updateDashboard(myself.getEmail(), dashboardWidgets);
} else {
throw new AccessDeniedException("Access is denied");
}
}
}
@ExceptionHandler(AccessDeniedException.class)
public void handleAccessDeniedException(
AccessDeniedException e, HttpServletResponse response, HttpServletRequest request)
throws IOException {
storeException(request, response, e);
Map<String, String> headers = requestHeaders(request);
log.error(
"Encountered exception while processing request {}:{} with headers={}",
request.getMethod(),
request.getRequestURI(),
headers.toString(),
e);
String errorMessage =
FiatPermissionEvaluator.getAuthorizationFailure()
.map(this::authorizationFailureMessage)
.orElse("Access is denied");
response.sendError(HttpStatus.FORBIDDEN.value(), errorMessage);
}
@SuppressWarnings("unchecked")
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call, final Metadata headers,
final ServerCallHandler<ReqT, RespT> next) {
final MethodDescriptor<ReqT, RespT> methodDescriptor = call.getMethodDescriptor();
final InterceptorStatusToken token;
try {
token = beforeInvocation(methodDescriptor);
} catch (final AuthenticationException | AccessDeniedException e) {
log.debug("Access denied");
throw e;
}
log.debug("Access granted");
final Listener<ReqT> result;
try {
result = next.startCall(call, headers);
} finally {
finallyInvocation(token);
}
// TODO: Call that here or in onHalfClose?
return (Listener<ReqT>) afterInvocation(token, result);
}
/**
* {@inheritDoc}
*/
@Override
public VoTax createTax(final VoTax vo) throws Exception {
if (federationFacade.isManageable(vo.getShopCode(), ShopDTO.class)) {
final Shop shop = shopService.getShopByCode(vo.getShopCode());
if (shop.getMaster() != null) {
vo.setShopCode(shop.getMaster().getCode());
}
TaxDTO dto = dtoTaxService.getNew();
dto = dtoTaxService.create(
voAssemblySupport.assembleDto(TaxDTO.class, VoTax.class, dto, vo)
);
return getTaxById(dto.getTaxId());
} else {
throw new AccessDeniedException("Access is denied");
}
}
public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails details, AccessTokenRequest request) throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException, OAuth2AccessDeniedException {
AuthorizationCodeResourceDetails resource = (AuthorizationCodeResourceDetails)details;
System.out.println(request.getCurrentUri());
if(request.getAuthorizationCode() == null) {
if(request.getStateKey() == null) {
throw this.getRedirectForAuthorization(resource, request);
}
this.obtainAuthorizationCode(resource, request);
}
System.out.println("code == " + request.getAuthorizationCode());
return this.retrieveToken(request,
resource, this.getParametersForTokenRequest(resource, request), this.getHeadersForTokenRequest(request));
}
@Test
public void checkPermissionAssertNoExceptionWhenHasPermissionsNamespaceIgnoreCase() throws Exception
{
// Mock a join point of the method call
// mockMethod("foo");
JoinPoint joinPoint = mock(JoinPoint.class);
MethodSignature methodSignature = mock(MethodSignature.class);
Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class);
when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace"});
when(methodSignature.getMethod()).thenReturn(method);
when(joinPoint.getSignature()).thenReturn(methodSignature);
when(joinPoint.getArgs()).thenReturn(new Object[] {"foo"});
String userId = "userId";
ApplicationUser applicationUser = new ApplicationUser(getClass());
applicationUser.setUserId(userId);
applicationUser.setNamespaceAuthorizations(new HashSet<>());
// user has permission to capital "FOO" and needs permission to lowercase "foo"
applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization("FOO", Arrays.asList(NamespacePermissionEnum.READ)));
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser), null));
try
{
namespaceSecurityAdvice.checkPermission(joinPoint);
}
catch (AccessDeniedException e)
{
fail();
}
}
@ResponseStatus(HttpStatus.FORBIDDEN)
@ExceptionHandler({AccessDeniedException.class, UsernameNotFoundException.class})
public Result accountException(final Throwable e) {
log.error("==> 账户异常: {}", e.getMessage());
e.printStackTrace();
return ResultGenerator.genFailedResult(e.getMessage());
}
@Override
@PreAuthorize("hasRole('ADMIN')")
public List<User> findAll() throws AccessDeniedException {
// List<User> result = userRepository.findAll();
// return result;
return null;
}
@Override
public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
httpServletResponse.setHeader("Content-type", "application/json;charset=UTF-8");
httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
// 如果这里状态改为HttpServletResponse.SC_UNAUTHORIZED 会导致feign之间调用异常 see https://xujin.org/sc/sc-feign-4xx/
// httpServletResponse.setStatus(HttpServletResponse.SC_OK);
JsonData jsonData = new JsonData(StatusEnum.UN_AUTHORIZED);
httpServletResponse.getWriter().write(JsonUtil.toJsonString(jsonData));
}
@Test
public void notAuthorized() {
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user",
"password", "ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(authentication);
assertThatCode(() -> this.messageService.getMessage())
.isInstanceOf(AccessDeniedException.class);
}
@Override
public void handle(HttpServletRequest request,
HttpServletResponse response,
AccessDeniedException e) throws IOException, ServletException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Cache-Control","no-cache");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().println(JSONUtil.parse(CommonResult.forbidden(e.getMessage())));
response.getWriter().flush();
}
/**
* Handle access denied exceptions.
*
* @param exception the exception.
*
* @return the error information.
*/
@ExceptionHandler(value = AccessDeniedException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
@ResponseBody
public ErrorInformation handleAccessDeniedException(Exception exception)
{
return getErrorInformation(HttpStatus.FORBIDDEN, exception);
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
if (isRestRequest(request)) {
RestUtils.returnStatusResponse(response, HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
} else {
super.handle(request, response, accessDeniedException);
}
}
@Override
public boolean hasPermissionAnyAuthority(UserContext user, Object targetObject, Right right, Qualifiable... filter) throws AccessDeniedException {
if (user == null) return false;
authorities: for (UserAuthority authority: user.getAuthorities()) {
for (Qualifiable q: filter)
if (!authority.hasQualifier(q)) continue authorities;
if (hasPermission(new UserContextWrapper(user, authority), targetObject, right)) return true;
}
return false;
}
@Override
public void handle(HttpServletRequest request,
HttpServletResponse response,
AccessDeniedException e) throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().println(JSONUtil.parse(CommonResult.forbidden(e.getMessage())));
response.getWriter().flush();
}
@Override
public Response toResponse(AccessDeniedException exception) {
log.info("Security exception",exception);
return Response.status(Response.Status.FORBIDDEN)
.entity(new OperationError(null,null,null,"Access denied"))
.type(MediaType.APPLICATION_JSON).build();
}
@Test(expected = AccessDeniedException.class)
public void testPatchBasedOnContextualRolesAccessDenied() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
securityContextInjector.setEducatorContext();
service = (BasicService) context.getBean("basicService", "student", new ArrayList<Treatment>(), securityRepo);
EntityDefinition studentDef = factory.makeEntity("student").exposeAs("students").build();
service.setDefn(studentDef);
EntityBody studentBody = new EntityBody();
studentBody.put("studentUniqueStateId", "123");
Entity student = securityRepo.create(EntityNames.STUDENT, studentBody);
EntityBody ssaBody = new EntityBody();
ssaBody.put(ParameterConstants.STUDENT_ID, student.getEntityId());
ssaBody.put(ParameterConstants.SCHOOL_ID, SecurityContextInjector.ED_ORG_ID);
securityRepo.create(EntityNames.STUDENT_SCHOOL_ASSOCIATION, ssaBody);
securityRepo.createWithRetries(EntityNames.EDUCATION_ORGANIZATION,SecurityContextInjector.ED_ORG_ID, new HashMap<String, Object>(), new HashMap<String, Object>(), EntityNames.EDUCATION_ORGANIZATION, 1);
EntityBody putEntity = new EntityBody();
putEntity.put("studentUniqueStateId", "456");
putEntity.put("schoolFoodServicesEligibility", "Yes");
boolean result = service.patch(student.getEntityId(), putEntity, true);
Assert.assertFalse(result);
}
/**
* AccessDeniedException异常处理返回json
* 状态码:403
* @param exception
* @return
*/
@ExceptionHandler({ AccessDeniedException.class })
@ResponseStatus(HttpStatus.FORBIDDEN)
public Map<String, Object> badMethodExpressException(AccessDeniedException exception) {
Map<String, Object> data = new HashMap<>();
data.put("resp_code", HttpStatus.FORBIDDEN.value());
data.put("resp_msg", exception.getMessage());
return data;
}
/**
* Checks the current user's permissions against the given object which may represent a single or multiple namespaces. Allowed types are String or
* Collection of String.
*
* @param object The string or collection of strings which represents the namespace
* @param permissions The set of permissions the current user must have for the given namespace(s)
* @param accessDeniedExceptions The list which any access denied exceptions will be gathered into. This list will be empty if no access denied exceptions
* occur.
*/
private void checkPermission(Object object, NamespacePermissionEnum[] permissions, List<AccessDeniedException> accessDeniedExceptions)
{
/*
* An infinite recursion is theoretically possible by passing in a collection which contains itself, but given our current usage it may be near
* impossible to achieve.
*/
if (object != null)
{
if (object instanceof Collection)
{
Collection<?> collection = (Collection<?>) object;
for (Object element : collection)
{
checkPermission(element, permissions, accessDeniedExceptions);
}
}
else if (object instanceof String)
{
try
{
checkPermission((String) object, permissions);
}
catch (AccessDeniedException accessDeniedException)
{
accessDeniedExceptions.add(accessDeniedException);
}
}
else
{
throw new IllegalStateException(
String.format("Object must be of type %s or %s. Actual object.class = %s", String.class, Collection.class, object.getClass()));
}
}
}
@Override
public OAuth2AccessToken obtainAccessToken(
OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails,
AccessTokenRequest accessTokenRequest) throws UserRedirectRequiredException,
UserApprovalRequiredException, AccessDeniedException {
return token;
}
/**
* {@inheritDoc}
*/
@Override
public VoShopLocations getShopLocations(long shopId) throws Exception {
if (federationFacade.isShopAccessibleByCurrentManager(shopId)) {
return getShopLocationsInternal(shopId);
} else {
throw new AccessDeniedException("Access is denied");
}
}
public boolean hasProjectOperationPermission(ProjectInstance project) {
boolean _hasProjectOperationPermission = false;
try {
_hasProjectOperationPermission = aclUtil.hasProjectOperationPermission(project);
} catch (AccessDeniedException e) {
//ignore to continue
}
return _hasProjectOperationPermission;
}
@Override
public void handle(HttpServletRequest request,
HttpServletResponse response,
AccessDeniedException e) throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().println(JsonUtil.objectToJson(new CommonResult().forbidden(e.getMessage())));
response.getWriter().flush();
}
public Try<CurrentUser> testRole(User user, String role) {
if (Role.hasRole(user.getRole(), Role.valueOf(role))) {
return Try.success(ImmutableCurrentUser.builder()
.withRole(user.getRole())
.withUsername(user.getUsername())
.withPermissions(user.getPermissions())
.build());
} else {
return Try.failure(new AccessDeniedException("Forbidden"));
}
}
/**
* Checks the current user's permissions against the given object which may represent a single or multiple namespaces. Allowed types are String or
* Collection of String.
*
* @param object The string or collection of strings which represents the namespace
* @param permissions The set of permissions the current user must have for the given namespace(s)
*/
public void checkPermission(Object object, NamespacePermissionEnum[] permissions)
{
List<AccessDeniedException> accessDeniedExceptions = new ArrayList<>();
checkPermission(object, permissions, accessDeniedExceptions);
if (!accessDeniedExceptions.isEmpty())
{
throw getAccessDeniedException(accessDeniedExceptions);
}
}
/**
* {@inheritDoc}
*/
@Override
public VoProductType getTypeById(final long id) throws Exception {
final ProductTypeDTO typeDTO = dtoProductTypeService.getById(id);
if (typeDTO != null /* && federationFacade.isCurrentUserSystemAdmin() */) {
final VoProductType type = voAssemblySupport.assembleVo(VoProductType.class, ProductTypeDTO.class, new VoProductType(), typeDTO);
final List<ProdTypeAttributeViewGroupDTO> groups = dtoProdTypeAttributeViewGroupService.getByProductTypeId(id);
final List<VoProductTypeViewGroup> voGroups = voAssemblySupport.assembleVos(VoProductTypeViewGroup.class, ProdTypeAttributeViewGroupDTO.class, groups);
type.setViewGroups(voGroups);
return type;
} else {
throw new AccessDeniedException("Access is denied");
}
}