Ejemplo n.º 1
0
  public Principal login(Object credentials, String charset) {
    List<String> decodedCredentials = Arrays.asList(decodeBase64Credentials(credentials, charset));

    HttpGraniteContext context = (HttpGraniteContext) GraniteContext.getCurrentInstance();
    HttpServletRequest httpRequest = context.getRequest();

    String user = decodedCredentials.get(0);
    String password = decodedCredentials.get(1);
    Authentication auth = new UsernamePasswordAuthenticationToken(user, password);
    Principal principal = null;

    ApplicationContext ctx =
        WebApplicationContextUtils.getWebApplicationContext(
            httpRequest.getSession().getServletContext());
    if (ctx != null) {
      AbstractAuthenticationManager authenticationManager =
          BeanFactoryUtils.beanOfTypeIncludingAncestors(ctx, AbstractAuthenticationManager.class);
      try {
        Authentication authentication = authenticationManager.authenticate(auth);
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authentication);
        principal = authentication;
        SecurityContextHolder.setContext(securityContext);
        saveSecurityContextInSession(securityContext, 0);

        endLogin(credentials, charset);
      } catch (AuthenticationException e) {
        handleAuthenticationExceptions(e);
      }
    }

    log.debug("User %s logged in", user);

    return principal;
  }
Ejemplo n.º 2
0
  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);
      }
    }
  }
Ejemplo n.º 3
0
  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;
  }
Ejemplo n.º 4
0
 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);
   }
 }
Ejemplo n.º 5
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
Ejemplo n.º 6
0
  public void testAddUserAsAdmin() throws Exception {
    SecurityContext context = new SecurityContextImpl();
    User user = new User("admin");
    user.setId(2L);
    user.setPassword("password");
    user.addRole(new Role(Constants.ADMIN_ROLE));
    UsernamePasswordAuthenticationToken token =
        new UsernamePasswordAuthenticationToken(
            user.getUsername(), user.getPassword(), user.getAuthorities());
    token.setDetails(user);
    context.setAuthentication(token);
    SecurityContextHolder.setContext(context);

    UserManager userManager = makeInterceptedTarget();
    User adminUser = new User("admin");
    adminUser.setId(2L);

    userDao.expects(once()).method("saveUser");
    userManager.saveUser(adminUser);
  }
Ejemplo n.º 7
0
  @Override
  protected void setUp() throws Exception {
    super.setUp();

    // store initial security context for later restoration
    initialSecurityContext = SecurityContextHolder.getContext();

    SecurityContext context = new SecurityContextImpl();
    User user = new User("user");
    user.setId(1L);
    user.setPassword("password");
    user.addRole(new Role(Constants.USER_ROLE));

    UsernamePasswordAuthenticationToken token =
        new UsernamePasswordAuthenticationToken(
            user.getUsername(), user.getPassword(), user.getAuthorities());
    token.setDetails(user);
    context.setAuthentication(token);
    SecurityContextHolder.setContext(context);
  }
Ejemplo n.º 8
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() + "'");
        }
      }
    }
  }