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);
      }
    }
  }
  public User getUser() {
    // 取得登录用户
    SecurityContext ctx = SecurityContextHolder.getContext();
    Authentication auth = ctx.getAuthentication();
    User user = null;
    if (auth.getPrincipal() instanceof UserDetails) {
      user = (User) auth.getPrincipal();
    }

    return user;
  }
 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);
   }
 }
Esempio n. 4
0
 /**
  * Returns the connected user details.
  *
  * @return
  */
 public static Account getLoginAccount() {
   SecurityContext context = SecurityContextHolder.getContext();
   Authentication authen = context.getAuthentication();
   Object principal = null;
   if (authen != null) {
     principal = authen.getPrincipal();
   }
   if (principal != null && principal instanceof Account) {
     return (Account) principal;
   } else {
     return null;
   }
 } // - getLoginAccount
Esempio n. 5
0
  /**
   * Method to enforce security and only allow administrators to modify users. Regular users are
   * allowed to modify themselves.
   *
   * @param method the name of the method executed
   * @param args the arguments to the method
   * @param target the target class
   * @throws Throwable thrown when args[0] is null or not a User object
   */
  public void before(Method method, Object[] args, Object target) throws Throwable {
    SecurityContext ctx = SecurityContextHolder.getContext();

    if (ctx.getAuthentication() != null) {
      Authentication auth = ctx.getAuthentication();
      boolean administrator = false;
      GrantedAuthority[] roles = auth.getAuthorities();
      for (GrantedAuthority role1 : roles) {
        if (role1.getAuthority().equals(Constants.ADMIN_ROLE)) {
          administrator = true;
          break;
        }
      }

      User user = (User) args[0];

      AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
      // allow new users to signup - this is OK b/c Signup doesn't allow setting of roles
      boolean signupUser = resolver.isAnonymous(auth);

      if (!signupUser) {
        User currentUser = getCurrentUser(auth);

        if (user.getId() != null && !user.getId().equals(currentUser.getId()) && !administrator) {
          log.warn(
              "Access Denied: '"
                  + currentUser.getUsername()
                  + "' tried to modify '"
                  + user.getUsername()
                  + "'!");
          throw new AccessDeniedException(ACCESS_DENIED);
        } else if (user.getId() != null
            && user.getId().equals(currentUser.getId())
            && !administrator) {
          // get the list of roles the user is trying add
          Set<String> userRoles = new HashSet<String>();
          if (user.getRoles() != null) {
            for (Object o : user.getRoles()) {
              Role role = (Role) o;
              userRoles.add(role.getName());
            }
          }

          // get the list of roles the user currently has
          Set<String> authorizedRoles = new HashSet<String>();
          for (GrantedAuthority role : roles) {
            authorizedRoles.add(role.getAuthority());
          }

          // if they don't match - access denied
          // regular users aren't allowed to change their roles
          if (!CollectionUtils.isEqualCollection(userRoles, authorizedRoles)) {
            log.warn(
                "Access Denied: '"
                    + currentUser.getUsername()
                    + "' tried to change their role(s)!");
            throw new AccessDeniedException(ACCESS_DENIED);
          }
        }
      } else {
        if (log.isDebugEnabled()) {
          log.debug("Registering new user '" + user.getUsername() + "'");
        }
      }
    }
  }