public Object authorize(AbstractSecurityContext context) throws Exception { log.debug("Authorize: %s", context); log.debug( "Is %s secured? %b", context.getDestination().getId(), context.getDestination().isSecured()); startAuthorization(context); HttpGraniteContext graniteContext = (HttpGraniteContext) GraniteContext.getCurrentInstance(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); SecurityContext securityContextBefore = null; int securityContextHashBefore = 0; if (graniteContext.getRequest().getAttribute(FILTER_APPLIED) == null) { securityContextBefore = loadSecurityContextFromSession(); if (securityContextBefore == null) securityContextBefore = SecurityContextHolder.getContext(); else securityContextHashBefore = securityContextBefore.hashCode(); SecurityContextHolder.setContext(securityContextBefore); authentication = securityContextBefore.getAuthentication(); } if (context.getDestination().isSecured()) { if (!isAuthenticated(authentication) || authentication instanceof AnonymousAuthenticationToken) { log.debug("Is not authenticated!"); throw SecurityServiceException.newNotLoggedInException("User not logged in"); } if (!userCanAccessService(context, authentication)) { log.debug("Access denied for: %s", authentication.getName()); throw SecurityServiceException.newAccessDeniedException("User not in required role"); } } try { Object returnedObject = securityInterceptor != null ? securityInterceptor.invoke(context) : endAuthorization(context); return returnedObject; } catch (AccessDeniedException e) { throw SecurityServiceException.newAccessDeniedException(e.getMessage()); } catch (InvocationTargetException e) { handleAuthorizationExceptions(e); throw e; } finally { if (graniteContext.getRequest().getAttribute(FILTER_APPLIED) == null) { // Do this only when not already filtered by Spring Security SecurityContext securityContextAfter = SecurityContextHolder.getContext(); SecurityContextHolder.clearContext(); saveSecurityContextInSession(securityContextAfter, securityContextHashBefore); } } }
protected void saveSecurityContextInSession( SecurityContext securityContext, int securityContextHashBefore) { if (securityContext.hashCode() != securityContextHashBefore && !(securityContext.getAuthentication() instanceof AnonymousAuthenticationToken)) { HttpGraniteContext context = (HttpGraniteContext) GraniteContext.getCurrentInstance(); HttpServletRequest request = context.getRequest(); request .getSession() .setAttribute( HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY, securityContext); } }