@Override
  public Authentication attemptAuthentication(
      HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

    try {
      // call to daoAuthenticationProvider
      Authentication auth = super.attemptAuthentication(request, response);

      // store currentUser in HttpSession
      UserCredentials currentUser = userService.findByName(auth.getName());
      request.getSession().setAttribute(Constants.CURRENT_USER, currentUser);

      // display info about currentUser
      Collection<GrantedAuthority> gs = auth.getAuthorities();
      StringBuilder sb =
          new StringBuilder("===== Authentification Succesful : userName = "******" with roles: ");
      for (GrantedAuthority x : gs) {
        sb.append(x.getAuthority()).append(",");
      }
      log.info(sb.toString());
      return auth;
    } catch (AuthenticationException e) {
      log.info("Login wasn't successful for " + obtainUsername(request));
      throw e;
    }
  }
Пример #2
0
  @Override
  public UserProfile getUser(Authentication authentication) {
    Object userName = authentication.getPrincipal();
    String login;
    User auth = null;
    if (userName instanceof String) login = (String) userName;
    else {
      login = ((User) authentication.getPrincipal()).getUsername();
      auth = (User) authentication.getPrincipal();
    }

    UserProfile userProfile = new UserProfile();
    userProfile.setUserId(login);
    userProfile.setStatus("ENABLED");

    if (auth != null && !auth.getAuthorities().isEmpty()) {
      for (GrantedAuthority grantedAuthority : auth.getAuthorities()) {
        userProfile.addUserRole(grantedAuthority.getAuthority());
      }
    }
    if (auth != null) {
      SystemUser sysUser = systemUserService.findByLogin(login);
      if (sysUser != null) {
        userProfile.setApiKey(sysUser.getApiKey());
        userProfile.setCompany(sysUser.getCompany().getName());
      }
    }

    return userProfile;
  }
 @Override
 public void updateUser(UserDetails user) {
   inMemManager.updateUser(user);
   User userToUpdate = userRepository.findFirstByUsername(user.getUsername());
   userToUpdate.setPassword(user.getPassword());
   for (GrantedAuthority authority : user.getAuthorities()) {
     StringTokenizer stringTokenizer = new StringTokenizer(authority.getAuthority(), ":");
     String rl = stringTokenizer.nextToken();
     String pj = stringTokenizer.nextToken();
     boolean found = false;
     for (Role role : userToUpdate.getRoles()) {
       if (role.getProject().equals(pj)) {
         role.setRole(Role.RoleEnum.valueOf(rl));
         found = true;
       }
     }
     if (!found) {
       Role role = new Role();
       role.setRole(Role.RoleEnum.valueOf(rl));
       role.setProject(pj);
       userToUpdate.getRoles().add(role);
     }
   }
   userRepository.save(userToUpdate);
 }
 public GrantedAuthoritySid(GrantedAuthority grantedAuthority) {
   Assert.notNull(grantedAuthority, "GrantedAuthority required");
   Assert.notNull(
       grantedAuthority.getAuthority(),
       "This Sid is only compatible with GrantedAuthoritys that provide a non-null getAuthority()");
   this.grantedAuthority = grantedAuthority.getAuthority();
 }
 private boolean isRolePresent(Collection<GrantedAuthority> authorities, String role) {
   boolean isRolePresent = false;
   for (GrantedAuthority grantedAuthority : authorities) {
     isRolePresent = grantedAuthority.getAuthority().equals(role);
     if (isRolePresent) break;
   }
   return isRolePresent;
 }
 /**
  * Check to see if the given auth object has ROLE_ADMIN assigned to it or not
  *
  * @param auth
  * @return
  */
 private boolean isAdmin(Authentication auth) {
   for (GrantedAuthority grantedAuthority : auth.getAuthorities()) {
     if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
       return true;
     }
   }
   return false;
 }
Пример #7
0
 private boolean containsRole(String role) {
   for (GrantedAuthority authority : authorities) {
     if (authority.getAuthority().equals(role)) {
       return true;
     }
   }
   return false;
 }
Пример #8
0
 public int compare(GrantedAuthority g1, GrantedAuthority g2) {
   if (g2.getAuthority() == null) {
     return -1;
   }
   if (g1.getAuthority() == null) {
     return 1;
   }
   return g1.getAuthority().compareTo(g2.getAuthority());
 }
Пример #9
0
 public static Set<String> getStringsFromAuthorities(
     Collection<? extends GrantedAuthority> authorities) {
   Set<String> result = new HashSet<>();
   if (authorities != null) {
     for (GrantedAuthority authority : authorities) {
       result.add(authority.getAuthority());
     }
   }
   return result;
 }
 public Collection<GrantedAuthority> getGrantedAuthorities(
     DirContextOperations context, String username) {
   log.debug("ALL AUTHORITY ");
   Collection<GrantedAuthority> auth =
       userDetailsService.loadUserByUsername(username).getAuthorities();
   for (GrantedAuthority a : auth) {
     log.debug("authority = " + a.toString());
   }
   return auth;
 }
Пример #11
0
  @Override
  public Collection<? extends GrantedAuthority> getReachableGrantedAuthorities(
      Collection<? extends GrantedAuthority> authorities) {
    Collection<GrantedAuthority> hierarchicalAuthorities = new ArrayList<GrantedAuthority>();
    for (GrantedAuthority authority : authorities) {
      if (authority.getAuthority().startsWith(AUTHORITY_ENTITY_WRITE_PREFIX)) {
        String entity = authority.getAuthority().substring(AUTHORITY_ENTITY_WRITE_PREFIX.length());
        hierarchicalAuthorities.add(
            new SimpleGrantedAuthority(AUTHORITY_ENTITY_READ_PREFIX + entity));
        hierarchicalAuthorities.add(
            new SimpleGrantedAuthority(AUTHORITY_ENTITY_COUNT_PREFIX + entity));
      } else if (authority.getAuthority().startsWith(AUTHORITY_ENTITY_READ_PREFIX)) {
        String entity = authority.getAuthority().substring(AUTHORITY_ENTITY_READ_PREFIX.length());
        hierarchicalAuthorities.add(
            new SimpleGrantedAuthority(AUTHORITY_ENTITY_COUNT_PREFIX + entity));
      } else if (authority.getAuthority().startsWith(AUTHORITY_PLUGIN_WRITE_PREFIX)) {
        String entity = authority.getAuthority().substring(AUTHORITY_PLUGIN_WRITE_PREFIX.length());
        hierarchicalAuthorities.add(
            new SimpleGrantedAuthority(AUTHORITY_PLUGIN_READ_PREFIX + entity));
        hierarchicalAuthorities.add(
            new SimpleGrantedAuthority(AUTHORITY_PLUGIN_COUNT_PREFIX + entity));
      } else if (authority.getAuthority().startsWith(AUTHORITY_PLUGIN_READ_PREFIX)) {
        String entity = authority.getAuthority().substring(AUTHORITY_PLUGIN_READ_PREFIX.length());
        hierarchicalAuthorities.add(
            new SimpleGrantedAuthority(AUTHORITY_PLUGIN_COUNT_PREFIX + entity));
      }

      hierarchicalAuthorities.add(authority);
    }
    return hierarchicalAuthorities;
  }
Пример #12
0
 public int compare(GrantedAuthority g1, GrantedAuthority g2) {
     // Neither should ever be null as each entry is checked before adding it to the set.
     // If the authority is null, it is a custom authority and should precede others.
     if (g2.getAuthority() == null) {
         return -1;
     }
     if (g1.getAuthority() == null) {
         return 1;
     }
     return g1.getAuthority().compareTo(g2.getAuthority());
 }
Пример #13
0
  @Override
  public void enter(ViewChangeListener.ViewChangeEvent event) {
    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    List<String> roles = new ArrayList<String>();
    for (GrantedAuthority grantedAuthority : user.getAuthorities()) {
      roles.add(grantedAuthority.getAuthority());
    }

    usernameLabel.setValue(user.getUsername());
    rolesLabel.setValue(StringUtils.join(roles, ","));
  }
Пример #14
0
 /**
  * Turns the users password, granted authorities and enabled state into a property file value
  *
  * @param user
  * @return
  */
 String serializeUser(User user) {
   StringBuffer sb = new StringBuffer();
   sb.append(user.getPassword());
   sb.append(",");
   for (GrantedAuthority ga : user.getAuthorities()) {
     sb.append(ga.getAuthority());
     sb.append(",");
   }
   sb.append(user.isEnabled() ? "enabled" : "disabled");
   return sb.toString();
 }
Пример #15
0
 /**
  * Check if a user is authenticated.
  *
  * @return true if the user is authenticated, false otherwise
  */
 public static boolean isAuthenticated() {
     SecurityContext securityContext = SecurityContextHolder.getContext();
     Collection<? extends GrantedAuthority> authorities = securityContext.getAuthentication().getAuthorities();
     if (authorities != null) {
         for (GrantedAuthority authority : authorities) {
             if (authority.getAuthority().equals(AuthoritiesConstants.ANONYMOUS)) {
                 return false;
             }
         }
     }
     return true;
 }
 @Override
 public boolean hasRole(String role) {
   try {
     Collection<GrantedAuthority> auth =
         SecurityContextHolder.getContext().getAuthentication().getAuthorities();
     for (GrantedAuthority ga : auth) {
       if (ga.getAuthority().equals(role)) return true;
     }
   } catch (NullPointerException e) {
   }
   return false;
 }
Пример #17
0
  /**
   * Get the list of roles currently known by users (there's guarantee the well known
   * ROLE_ADMINISTRATOR will be part of the lot)
   */
  public List<String> getRoles() {
    checkUserMap();

    Set<String> roles = new TreeSet<String>();
    roles.add("ROLE_ADMINISTRATOR");
    for (User user : getUsers()) {
      for (GrantedAuthority ga : user.getAuthorities()) {
        roles.add(ga.getAuthority());
      }
    }
    return new ArrayList<String>(roles);
  }
Пример #18
0
  @Override
  public int compareTo(final GrantedAuthority other) {
    Validate.notNull(other);

    if (other.getAuthority() == null) {
      return -1;
    } else if (this.getAuthority() == null) {
      return 1;
    } else {
      return this.getAuthority().compareTo(other.getAuthority());
    }
  }
Пример #19
0
 public String redirect() {
   for (GrantedAuthority ga : getUserAuth().getAuthorities()) {
     if (ga.getAuthority().equals("NIVEL_ASSOCIADO")) {
       return "associado";
     } else if (ga.getAuthority().equals("NIVEL_FUNCIONARIO")) {
       return "funcionario";
     } else if (ga.getAuthority().equals("NIVEL_TECNICO")) {
       return "tecnico";
     }
   }
   return ERROR;
 }
Пример #20
0
  /**
   * Check if current user has specified role.
   *
   * @param privilege the role to check if user has.
   * @return true if user has specified role, otherwise false.
   */
  public static boolean hasPrivilege(final String privilege) {
    final UserDetails userDetails = SpringSecurityUtil.getCurrentUserDetails();
    if (userDetails != null) {
      for (final GrantedAuthority each : userDetails.getAuthorities()) {
        if (each.getAuthority().equals(privilege)) {
          return true;
        }
      }
    }

    return false;
  }
 private void testGetGrantedAuthorities(
     MapBasedAttributes2GrantedAuthoritiesMapper mapper, String[] roles, String[] expectedGas) {
   List<GrantedAuthority> result = mapper.getGrantedAuthorities(Arrays.asList(roles));
   Collection resultColl = new ArrayList(result.size());
   for (GrantedAuthority auth : result) {
     resultColl.add(auth.getAuthority());
   }
   Collection expectedColl = Arrays.asList(expectedGas);
   assertTrue(
       "Role collections should match; result: " + resultColl + ", expected: " + expectedColl,
       expectedColl.containsAll(resultColl) && resultColl.containsAll(expectedColl));
 }
Пример #22
0
  /**
   * Return current roles bound to the current thread by Spring Security
   *
   * @return roles list
   */
  public static List<String> getRoles() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
      List<String> result = newArrayList();

      for (GrantedAuthority grantedAuthority : auth.getAuthorities()) {
        result.add(grantedAuthority.getAuthority());
      }
      return result;
    }
    return Collections.emptyList();
  }
Пример #23
0
 /** @param authorities the authorities to set */
 public void setAuthorities(Collection<? extends GrantedAuthority> authorities) {
   if (authorities == null) return;
   this.authorities = authorities;
   if (authoritiesHash != null) {
     authoritiesHash.clear();
   } else {
     authoritiesHash = new HashMap<String, Object>();
   }
   for (GrantedAuthority ga : authorities) {
     authoritiesHash.put(ga.getAuthority(), new Object());
   }
 }
 public void decide(
     Authentication authentication, Object object, Collection<ConfigAttribute> attributes)
     throws AccessDeniedException, InsufficientAuthenticationException {
   if (null == attributes) return;
   for (ConfigAttribute attribute : attributes) {
     String needRole = ((SecurityConfig) attribute).getAttribute();
     // authority为用户所被赋予的权限, needRole 为访问相应的资源应该具有的权限�?
     for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
       if (needRole.equals(grantedAuthority.getAuthority())) return;
     }
   }
   throw new AccessDeniedException("权限不足!");
 }
Пример #25
0
  /**
   * Check if current user has any role of specified.
   *
   * @param privileges the array of roles.
   * @return true if has any role, otherwise false.
   */
  public static boolean hasAnyPrivilege(final String... privileges) {
    final UserDetails userDetails = SpringSecurityUtil.getCurrentUserDetails();
    if (userDetails != null) {
      final Set<String> rolesSet = ImmutableSet.copyOf(privileges);
      for (final GrantedAuthority each : userDetails.getAuthorities()) {
        if (rolesSet.contains(each.getAuthority())) {
          return true;
        }
      }
    }

    return false;
  }
Пример #26
0
  /**
   * @param grantedRoles
   * @param granted
   * @return a Set of Authorities corresponding to the roles in the grantedRoles that are also in
   *     the granted Set of Authorities
   */
  private Set<GrantedAuthority> rolesToAuthorities(
      Set<String> grantedRoles, Collection<GrantedAuthority> granted) {
    Set<GrantedAuthority> target = new HashSet<GrantedAuthority>();

    for (String role : grantedRoles) {
      for (GrantedAuthority authority : granted) {
        if (authority.getAuthority().equals(role)) {
          target.add(authority);
          break;
        }
      }
    }

    return target;
  }
Пример #27
0
  private Set<String> authoritiesToRoles(Collection<GrantedAuthority> c) {
    Set<String> target = new HashSet<String>();

    for (GrantedAuthority authority : c) {
      if (null == authority.getAuthority()) {
        throw new IllegalArgumentException(
            "Cannot process GrantedAuthority objects which return null from getAuthority() - attempting to process "
                + authority.toString());
      }

      target.add(authority.getAuthority());
    }

    return target;
  }
Пример #28
0
  public static Role getUserRole() {
    UserDetails user = getUser();

    if (user == null) {
      return Role.ANONYMOUS;
    }

    for (GrantedAuthority authority : user.getAuthorities()) {
      if (authority.getAuthority().equals(UserRoles.ADMIN)) {
        return Role.ADMIN;
      }
    }

    return Role.ANONYMOUS;
  }
Пример #29
0
  @GET
  @Produces({MediaType.APPLICATION_JSON})
  public String getUserInfo() {
    LOG.debug(String.format("Getting current user info"));

    Authentication authentication = getAuthentication();
    String username = authentication.getName();

    StringBuilder rolesBuilder = new StringBuilder();
    for (GrantedAuthority ga : authentication.getAuthorities())
      rolesBuilder.append(",").append(ga.getAuthority());
    String roles = "";
    if (rolesBuilder.length() > 0) roles = rolesBuilder.substring(1);

    return String.format("{\"username\":\"%s\", \"roles\":\"%s\"}", username, roles);
  }
Пример #30
0
  public static Boolean ifAreAnyGranted(String roles) {

    UserDetails user = SecurityUtils.getUser();
    String[] arRoles = roles.split(",");
    boolean granted = true;

    for (String sRole : arRoles) {
      for (GrantedAuthority authority : user.getAuthorities()) {
        if (authority.getAuthority().equals(sRole)) {
          granted = true;
          break;
        }
      }
    }

    return granted;
  }