org.springframework.security.access.AccessDeniedException Java Examples
The following examples show how to use
org.springframework.security.access.AccessDeniedException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VoTaxServiceImpl.java From yes-cart with Apache License 2.0 | 6 votes |
/** * {@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"); } }
Example #2
Source File: ItemController.java From apollo with Apache License 2.0 | 6 votes |
@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)); }
Example #3
Source File: NamespaceSecurityAdviceTest.java From herd with Apache License 2.0 | 6 votes |
@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()); } }
Example #4
Source File: RightAccessValidatorTest.java From secure-data-service with Apache License 2.0 | 6 votes |
@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)); }
Example #5
Source File: VoManagementServiceImpl.java From yes-cart with Apache License 2.0 | 6 votes |
/** {@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"); } } }
Example #6
Source File: FiatAccessDeniedExceptionHandler.java From fiat with Apache License 2.0 | 6 votes |
@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); }
Example #7
Source File: AccessDecisionManager.java From hermes with Apache License 2.0 | 6 votes |
@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."); }
Example #8
Source File: AuthorizationCheckingServerInterceptor.java From grpc-spring-boot-starter with MIT License | 6 votes |
@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); }
Example #9
Source File: IoTPErrorResponseHandler.java From iotplatform with Apache License 2.0 | 5 votes |
@Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { if (!response.isCommitted()) { response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.setStatus(HttpStatus.FORBIDDEN.value()); mapper.writeValue(response.getWriter(), IoTPErrorResponse.of("You don't have permission to perform this operation!", IoTPErrorCode.PERMISSION_DENIED, HttpStatus.FORBIDDEN)); } }
Example #10
Source File: VoShopServiceImpl.java From yes-cart with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ @Override public VoShopLocations update(VoShopLocations vo) throws Exception { if (vo != null && federationFacade.isShopAccessibleByCurrentManager(vo.getShopId())) { dtoShopService.updateSupportedBillingCountries(vo.getShopId(), StringUtils.join(vo.getSupportedBilling().toArray(), ",")); dtoShopService.updateSupportedShippingCountries(vo.getShopId(), StringUtils.join(vo.getSupportedShipping().toArray(), ",")); return getShopLocations(vo.getShopId()); } else { throw new AccessDeniedException("Access is denied"); } }
Example #11
Source File: AjaxSupportedAccessDeniedHandler.java From onetwo with Apache License 2.0 | 5 votes |
@Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { String url = request.getMethod() + "|" + request.getRequestURI(); String errorMsg = getErrorMessage(accessDeniedException); if(RequestUtils.isAjaxRequest(request)){ SimpleResultBuilder<?> builder = DataResults.error(errorMsg+ ", at "+request.getRequestURI()) .code(SecurityErrors.ACCESS_DENIED) .data(url); DataResult<?> rs = WebUtils.buildErrorCode(builder, request, accessDeniedException).build(); String text = mapper.toJson(rs); logger.info("[] AccessDenied, render json: {}", url, text); ResponseUtils.render(response, text, ResponseUtils.JSON_TYPE, true); }else if(!response.isCommitted() && StringUtils.isNotBlank(redirectErrorUrl)) { String rurl = redirectErrorUrl; if(rurl.contains("?")){ rurl += "&"; }else{ rurl += "?"; } rurl += "accessDenied=true&status="+HttpServletResponse.SC_FORBIDDEN+"&message="; rurl += URLEncoder.encode(errorMsg, Charsets.UTF_8.name());//encode value, otherwise will redirect failed logger.info("{} AccessDenied, redirect to {}", url, rurl); response.sendRedirect(rurl); }else{ defaultHandle(request, response, accessDeniedException); } }
Example #12
Source File: VoCustomerServiceImpl.java From yes-cart with Apache License 2.0 | 5 votes |
@Override public void resetPassword(final long customerId, final long shopId) throws Exception { if (federationFacade.isManageable(customerId, CustomerDTO.class) && federationFacade.isShopAccessibleByCurrentManager(shopId)) { dtoCustomerService.resetPassword(dtoCustomerService.getById(customerId), shopId); } else { throw new AccessDeniedException("Access is denied"); } }
Example #13
Source File: VoContentServiceImpl.java From yes-cart with Apache License 2.0 | 5 votes |
/** {@inheritDoc} */ @Override public VoContentWithBody getContentById(final long id) throws Exception { final ContentDTO content = dtoContentService.getById(id); if (content != null && federationFacade.isManageable(id, ContentDTO.class)){ final VoContentWithBody contentWithBody = voAssemblySupport.assembleVo(VoContentWithBody.class, ContentDTO.class, new VoContentWithBody(), content); contentWithBody.setContentBodies(getContentBody(id)); return contentWithBody; } else { throw new AccessDeniedException("Access is denied"); } }
Example #14
Source File: RestfulAccessDeniedHandler.java From mall-learning with Apache License 2.0 | 5 votes |
@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(); }
Example #15
Source File: VoPriceServiceImpl.java From yes-cart with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ @Override public VoPriceList createPrice(final VoPriceList vo) throws Exception { if (federationFacade.isManageable(vo.getShopCode(), ShopDTO.class)) { PriceListDTO dto = new PriceListDTOImpl(); dto = dtoPriceListsService.createPrice( voAssemblySupport.assembleDto(PriceListDTO.class, VoPriceList.class, dto, vo) ); return getPriceById(dto.getSkuPriceId()); } else { throw new AccessDeniedException("Access is denied"); } }
Example #16
Source File: NamespaceSecurityAdviceTest.java From herd with Apache License 2.0 | 5 votes |
/** * Test where a method with multiple annotation is called, but the user does not have permission to one of the namespaces. Asserts that the check throws * AccessDenied. */ @Test public void checkPermissionAssertAccessDeniedWhenMultipleAnnotationsAndUserHasOneWrongPermission() throws Exception { // Mock a join point of the method call // mockMethodMultipleAnnotations("foo", "bar"); JoinPoint joinPoint = mock(JoinPoint.class); MethodSignature methodSignature = mock(MethodSignature.class); Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethodMultipleAnnotations", String.class, String.class); when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace1", "namespace2"}); when(methodSignature.getMethod()).thenReturn(method); when(joinPoint.getSignature()).thenReturn(methodSignature); when(joinPoint.getArgs()).thenReturn(new Object[] {"foo", "bar"}); String userId = "userId"; ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(userId); applicationUser.setNamespaceAuthorizations(new HashSet<>()); 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); fail(); } catch (Exception e) { assertEquals(AccessDeniedException.class, e.getClass()); assertEquals(String.format("User \"%s\" does not have \"[WRITE]\" permission(s) to the namespace \"bar\"", userId), e.getMessage()); } }
Example #17
Source File: VoShippingServiceImpl.java From yes-cart with Apache License 2.0 | 5 votes |
@Override public VoCarrier createShopCarrier(final VoCarrierInfo vo, final long shopId) throws Exception { if (federationFacade.isManageable(shopId, ShopDTO.class)) { CarrierDTO dto = dtoCarrierService.getNew(); dto = dtoCarrierService.create( voAssemblySupport.assembleDto(CarrierDTO.class, VoCarrierInfo.class, dto, vo) ); dtoCarrierService.assignToShop(dto.getCarrierId(), shopId, false); return getCarrierById(dto.getCarrierId()); } else { throw new AccessDeniedException("Access is denied"); } }
Example #18
Source File: AclEvaluate.java From kylin with Apache License 2.0 | 5 votes |
public boolean hasProjectOperationPermission(ProjectInstance project) { boolean _hasProjectOperationPermission = false; try { _hasProjectOperationPermission = aclUtil.hasProjectOperationPermission(project); } catch (AccessDeniedException e) { //ignore to continue } return _hasProjectOperationPermission; }
Example #19
Source File: DatabaseServerConfigServiceTest.java From cloudbreak with Apache License 2.0 | 5 votes |
@Test public void testCreateFailure() { thrown.expect(AccessDeniedException.class); server.setConnectionDriver("org.postgresql.MyCustomDriver"); Crn serverCrn = TestData.getTestCrn("databaseServer", "myserver"); when(crnService.createCrn(server)).thenReturn(serverCrn); AccessDeniedException e = new AccessDeniedException("no way"); when(repository.save(server)).thenThrow(e); underTest.create(server, 0L, false); }
Example #20
Source File: VoPaymentGatewayServiceImpl.java From yes-cart with Apache License 2.0 | 5 votes |
/** {@inheritDoc} */ @Override public List<MutablePair<String, String>> getAllowedPaymentGatewaysForShop(final String lang, final String shopCode) throws Exception { if (federationFacade.isManageable(shopCode, ShopDTO.class)) { return getAllowedPaymentGatewaysForShopInternal(lang, shopCode); } else { throw new AccessDeniedException("Access is denied"); } }
Example #21
Source File: CustomAccessDecisionManager.java From spring-security with Apache License 2.0 | 5 votes |
/** * 判定是否拥有权限的决策方法 * @param authentication CustomUserDetailsService类loadUserByUsername()方法中返回值 * @param o 包含客户端发起的请求的request信息。 * @param collection CustomFilterInvocationSecurityMetadataSource类的getAttribute()方法返回值 * @throws AccessDeniedException * @throws InsufficientAuthenticationException */ @Override public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException { HttpServletRequest request = ((FilterInvocation) o).getHttpRequest(); String url; for (GrantedAuthority ga : authentication.getAuthorities()) { url = ga.getAuthority(); if(url.equals(request.getRequestURI())){ return; } } throw new AccessDeniedException("没有权限访问"); }
Example #22
Source File: SharingControllerTest.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test( expected = AccessDeniedException.class ) public void systemDefaultMetadataNoAccess() throws Exception { final Category category = new Category(); category.setName( Category.DEFAULT_NAME + "x" ); Mockito.doReturn( Category.class ).when( aclService ).classForType( Mockito.eq( "category" ) ); Mockito.when( aclService.isShareable( Mockito.eq( Category.class ) ) ).thenReturn( true ); Mockito.when( manager.get( Mockito.eq( Category.class ), Mockito.eq( "kkSjhdhks" ) ) ).thenReturn( category ); sharingController.setSharing( "category", "kkSjhdhks", response, request ); }
Example #23
Source File: AccessDeniedExceptionHandler.java From secure-data-service with Apache License 2.0 | 5 votes |
@Override public Response toResponse(AccessDeniedException e) { //There are a few jax-rs resources that generate HTML content, and we want the //default web-container error handler pages to get used in those cases. if (headers.getAcceptableMediaTypes().contains(MediaType.TEXT_HTML_TYPE)) { try { response.sendError(403, e.getMessage()); return null; //the error page handles the response, so no need to return a response } catch (IOException ex) { LOG.error("Error displaying error page", ex); } } Response.Status errorStatus = Response.Status.FORBIDDEN; SLIPrincipal principal = null ; String message = e.getMessage(); if (SecurityContextHolder.getContext().getAuthentication() != null) { principal = (SLIPrincipal)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); LOG.warn("Access has been denied to user: {}",principal ); } else { LOG.warn("Access has been denied to user for being incorrectly associated"); } LOG.warn("Cause: {}", e.getMessage()); MediaType errorType = MediaType.APPLICATION_JSON_TYPE; if(this.headers.getMediaType() == MediaType.APPLICATION_XML_TYPE) { errorType = MediaType.APPLICATION_XML_TYPE; } return Response.status(errorStatus).entity(new ErrorResponse(errorStatus.getStatusCode(), errorStatus.getReasonPhrase(), "Access DENIED: " + e.getMessage())).type(errorType).build(); }
Example #24
Source File: CustomAccessDeniedHandler.java From oauth2-server with MIT License | 5 votes |
@Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException { //服务器地址 String toUrl = ClientIpUtil.getFullRequestUrl(request); boolean isAjax = "XMLHttpRequest".equals(request .getHeader("X-Requested-With")) || "apiLogin".equals(request .getHeader("api-login")); if (isAjax) { response.setHeader("Content-Type", "application/json;charset=UTF-8"); try { ResponseResult<Object> responseMessage = new ResponseResult<>(); responseMessage.setStatus(GlobalConstant.ERROR_DENIED); responseMessage.setMessage(toUrl); ObjectMapper objectMapper = new ObjectMapper(); JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(response.getOutputStream(), JsonEncoding.UTF8); objectMapper.writeValue(jsonGenerator, responseMessage); } catch (Exception ex) { throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex); } } else { /// response.sendRedirect(accessDeniedUrl + "?toUrl=" + toUrl); response.sendRedirect(accessDeniedUrl); } }
Example #25
Source File: VoManagementServiceImpl.java From yes-cart with Apache License 2.0 | 5 votes |
private void allowUpdateOnlyBySysAdmin(String manager) throws UnmappedInterfaceException, UnableToCreateInstanceException { final List<RoleDTO> roles = managementService.getAssignedManagerRoles(manager); for (final RoleDTO role : roles) { if ("ROLE_SMADMIN".equals(role.getCode()) && !federationFacade.isCurrentUserSystemAdmin()) { throw new AccessDeniedException("Access is denied"); } } }
Example #26
Source File: VoProductTypeServiceImpl.java From yes-cart with Apache License 2.0 | 5 votes |
/** * {@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"); } }
Example #27
Source File: NamespaceSecurityHelper.java From herd with Apache License 2.0 | 5 votes |
/** * 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); } }
Example #28
Source File: UserService.java From vics with MIT License | 5 votes |
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")); } }
Example #29
Source File: MyAuthorizationCodeAccessTokenProvider.java From springboot-security-wechat with Apache License 2.0 | 5 votes |
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)); }
Example #30
Source File: RestfulAccessDeniedHandler.java From xmall with MIT License | 5 votes |
@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(); }