Java 类org.springframework.security.core.authority.GrantedAuthorityImpl 实例源码

项目:esup-nfc-tag-server    文件:ErrorLongPoolController.java   
@RequestMapping(value = "/tagerror")
@ResponseBody
public DeferredResult<List<TagError>> tagError(@RequestParam Long errorDateTimestamp, @RequestParam(required=false) String numeroId) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if(numeroId==null && !auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_ADMIN")) && !auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_SUPERVISOR"))) {
        return null;
    }
    LiveQuery liveQuery = new LiveQuery(errorDateTimestamp, numeroId);
    final DeferredResult<List<TagError>> tagErrors = new DeferredResult<List<TagError>>(null, Collections.emptyList());

    this.suspendedTagErrorsRequests.put(tagErrors, liveQuery);

    tagErrors.onCompletion(new Runnable() {
        public void run() {
            suspendedTagErrorsRequests.remove(tagErrors);
        }
    });

    return tagErrors;
}
项目:madsonic-server-5.1    文件:SecurityService.java   
/**
    * Locates the user based on the username.
    *
    * @param username The username presented to the {@link DaoAuthenticationProvider}
    * @return A fully populated user record (never <code>null</code>)
    * @throws UsernameNotFoundException if the user could not be found or the user has no GrantedAuthority.
    * @throws DataAccessException       If user could not be found for a repository-specific reason.
    */
   @SuppressWarnings("deprecation")
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {

    boolean unlocked = true;
       User user = getUserByName(username);

       if (user == null) {
           throw new UsernameNotFoundException("User \"" + username + "\" was not found.");
       }
       // block disabled user at logon
       if (username.equalsIgnoreCase("default") || user.isLocked()) {
        unlocked = false;
       }
       String[] roles = userDao.getRolesForUser(username);
       List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(roles.length);
       for (int i = 0; i < roles.length; i++) {
           authorities.add(new GrantedAuthorityImpl("ROLE_" + roles[i].toUpperCase()));
       }
       // If user is LDAP authenticated, disable user. The proper authentication should in that case
       // be done by SubsonicLdapBindAuthenticator.
       boolean enabled = !user.isLdapAuthenticated();

       return new org.springframework.security.core.userdetails.User(username, user.getPassword(), enabled, true, true, unlocked, authorities);
   }
项目:modinvreg    文件:UserManagerImpl.java   
@Override
public List<GrantedAuthority> findGroupAuthorities( String groupName ) {

    String groupToSearch = groupName;
    if ( groupName.startsWith( rolePrefix ) ) {
        groupToSearch = groupToSearch.replaceFirst( rolePrefix, "" );
    }

    UserGroup group = loadGroup( groupToSearch );

    List<GrantedAuthority> result = new ArrayList<GrantedAuthority>();
    for ( gemma.gsec.model.GroupAuthority ga : group.getAuthorities() ) {
        result.add( new GrantedAuthorityImpl( ga.getAuthority() ) );
    }

    return result;
}
项目:modinvreg    文件:UserGroupServiceTest.java   
/**
 * Test for deleting a user group
 */
@Test
public void testDeleteUserGroup() {

    runAsAdmin();
    List<GrantedAuthority> authos = new ArrayList<GrantedAuthority>();
    authos.add( new GrantedAuthorityImpl( "GROUP_TESTING" ) );
    this.userManager.createGroup( this.groupName, authos );

    // add another user to group
    this.userManager.addUserToGroup( this.userName1, this.groupName );
    this.userManager.addUserToGroup( this.userName2, this.groupName );

    // delete the group
    this.userManager.deleteGroup( this.groupName );

}
项目:esup-dematec    文件:PosteAPourvoirController.java   
@RequestMapping(produces = "text/html")
  @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER') or hasRole('ROLE_MEMBRE')")
  public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, @RequestParam(value = "sortFieldName", required = false) String sortFieldName, @RequestParam(value = "sortOrder", required = false) String sortOrder, Model uiModel) {

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    boolean isMembre = auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_MEMBRE"));

    if(isMembre) {
        String emailAddress = auth.getName();
        User user = User.findUsersByEmailAddress(emailAddress, null, null).getSingleResult();
        List<PosteAPourvoir> posteapourvoirs = PosteAPourvoir.findPosteAPourvoirsByMembre(user);
        uiModel.addAttribute("posteapourvoirs", posteapourvoirs);
    } else if (page != null || size != null) {
          int sizeNo = size == null ? 10 : size.intValue();
          final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
          uiModel.addAttribute("posteapourvoirs", PosteAPourvoir.findPosteAPourvoirEntries(firstResult, sizeNo, sortFieldName, sortOrder));
          float nrOfPages = (float) PosteAPourvoir.countPosteAPourvoirs() / sizeNo;
          uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
      } else {
          uiModel.addAttribute("posteapourvoirs", PosteAPourvoir.findAllPosteAPourvoirs(sortFieldName, sortOrder));
      }
    uiModel.addAttribute("textePostesMenu4Members", AppliConfig.getCacheTextePostesMenu4Members());
      addDateTimeFormatPatterns(uiModel);
      return "posteapourvoirs/list";
  }
项目:esup-dematec    文件:ProfilChoiceController.java   
@RequestMapping
  public String profilChoice(@RequestParam(required=false) String profil) {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(auth.getAuthorities());

    if(profil!=null) {
    logger.info(auth.getName() + " a sélectionné le profil " + profil);
        if("membre".equals(profil)) {
            authorities.remove(new GrantedAuthorityImpl("ROLE_CANDIDAT"));
        }
        if("candidat".equals(profil)) {
            authorities.remove(new GrantedAuthorityImpl("ROLE_MEMBRE"));
        }
        auth = new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(), authorities);
        SecurityContextHolder.getContext().setAuthentication(auth);
    }

    if(auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_CANDIDAT")) && auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_MEMBRE"))) {
        return "profilChoice";
    } else {
        return "index";
    }
  }
项目:esup-dematec    文件:CheckProfilSpringSecurityFilter.java   
@Override
public void doFilter(ServletRequest req, ServletResponse res,
        FilterChain chain) throws IOException, ServletException {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    HttpServletRequest request = (HttpServletRequest) req;

    if(!request.getServletPath().startsWith("/resources/") && !"/profilChoice".equals(request.getServletPath())
        && auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_CANDIDAT")) 
        && auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_MEMBRE"))) {
            logger.info(auth.getName() + " est authentifié et est à la fois membre et candidat, il faut qu'il choisisse un profil.");
            HttpServletResponse response = (HttpServletResponse) res;      
        response.sendRedirect(request.getContextPath() + "/profilChoice");
    } else {
        chain.doFilter(req, res);
    }
}
项目:threadfixRack    文件:PermissionServiceImpl.java   
@Override
public Set<Integer> getAuthenticatedAppIds() {
    Object auth = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (auth != null && auth instanceof ThreadFixUserDetails) {
        if (((ThreadFixUserDetails) auth).getAuthorities().contains(
                new GrantedAuthorityImpl(Permission.READ_ACCESS.getText()))) {
            return null;
        }

        if (((ThreadFixUserDetails) auth).getApplicationMap() != null) {
            return ((ThreadFixUserDetails) auth).getApplicationMap().keySet();
        }
    }

    return null;
}
项目:threadfixRack    文件:PermissionServiceImpl.java   
@Override
public Set<Integer> getAuthenticatedTeamIds() {
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (principal instanceof ThreadFixUserDetails) {
        ThreadFixUserDetails customDetails = ((ThreadFixUserDetails) principal);

        if (customDetails.getAuthorities().contains(
                new GrantedAuthorityImpl(Permission.READ_ACCESS.getText()))) {
            return null;
        }

        if (customDetails.getTeamMap() != null) {
            return customDetails.getTeamMap().keySet();
        }
    }

    return null;
}
项目:termitaria    文件:TSUserDetailsService.java   
private UserAuth _USER02() {
    logger.debug("_USER02");
    UserAuth userAuth = new UserAuth();
    userAuth.setUsername("user02");
    userAuth.setPersonId(3);
    userAuth.setPassword("7c4a8d09ca3762af61e59520943dc26494f8941b");
    userAuth.setFirstName("Andrei");
    userAuth.setLastName("Vidreanu");

    //Permisiuni
    List<GrantedAuthority> authories = new ArrayList<GrantedAuthority>();
    authories.add(new GrantedAuthorityImpl("SUPER"));
    authories.add(new GrantedAuthorityImpl("DM_BASIC"));
    authories.add(new GrantedAuthorityImpl("DM_CategoryDelete"));
    authories.add(new GrantedAuthorityImpl("DM_CategoryAdd"));
    authories.add(new GrantedAuthorityImpl("DM_CategoryUpdate"));
    authories.add(new GrantedAuthorityImpl("DM_DocumentAdd"));
    authories.add(new GrantedAuthorityImpl("DM_CollectionZoneView"));

    userAuth.setAuthorities(authories);

    return userAuth;
}
项目:termitaria    文件:TSUserDetailsService.java   
private UserAuth _USER03() {
    logger.debug("_USER03");
    UserAuth userAuth = new UserAuth();
    userAuth.setUsername("user03");
    userAuth.setPersonId(3);
    userAuth.setPassword("7c4a8d09ca3762af61e59520943dc26494f8941b");
    userAuth.setFirstName("Ilie");
    userAuth.setLastName("Nastasescu");

    //Permisiuni
    List<GrantedAuthority> authories = new ArrayList<GrantedAuthority>();
    authories.add(new GrantedAuthorityImpl("AUDIT_BASIC"));
    userAuth.setAuthorities(authories);

    return userAuth;
}
项目:termitaria    文件:TSUserDetailsService.java   
private UserAuth _USER04() {
    logger.debug("_USER04");
    UserAuth userAuth = new UserAuth();
    userAuth.setUsername("user04");
    userAuth.setPersonId(4);
    userAuth.setPassword("7c4a8d09ca3762af61e59520943dc26494f8941b");
    userAuth.setFirstName("Grabriel");
    userAuth.setLastName("Contabitza");

    //Permisiuni
    List<GrantedAuthority> authories = new ArrayList<GrantedAuthority>();
    authories.add(new GrantedAuthorityImpl("DM_BASIC"));

    userAuth.setAuthorities(authories);

    return userAuth;
}
项目:termitaria    文件:TSUserDetailsService.java   
private UserAuth _USER05() {
    logger.debug("_USER05");
    UserAuth userAuth = new UserAuth();
    userAuth.setUsername("user05");
    userAuth.setPersonId(5);
    userAuth.setPassword("7c4a8d09ca3762af61e59520943dc26494f8941b");
    userAuth.setFirstName("Mircea");
    userAuth.setLastName("Badescu");

    //Permisiuni
    List<GrantedAuthority> authories = new ArrayList<GrantedAuthority>();
    authories.add(new GrantedAuthorityImpl("DM_BASIC"));

    userAuth.setAuthorities(authories);

    return userAuth;
}
项目:SpringBBS    文件:MyUserDetailsServiceImpl.java   
private Set<GrantedAuthority> obtainGrantedAuthorities(AcctUser user) {
    Set<GrantedAuthority> authSet = Sets.newHashSet();
    for (AcctRole role : user.getRoleList()) {
        for (AcctAuthority authority : role.getAuthorityList()) {
            authSet.add(new GrantedAuthorityImpl(authority.getPrefixedName()));
        }
    }
    return authSet;
}
项目:SpringBBS    文件:UserDetailsServiceImpl.java   
/**
 * 获得用户�?有角色的权限集合.
 */
private Set<GrantedAuthority> obtainGrantedAuthorities(AcctUser user) {
    Set<GrantedAuthority> authSet = Sets.newHashSet();
    for (AcctRole role : user.getRoleList()) {
        for (AcctAuthority authority : role.getAuthorityList()) {
            authSet.add(new GrantedAuthorityImpl(authority.getPrefixedName()));
        }
    }
    return authSet;
}
项目:jpasecurity    文件:SpringSecurityContextTest.java   
public void authenticate(Object principal, String... roles) {
    Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(roles.length);
    for (int i = 0; i < roles.length; i++) {
        grantedAuthorities.add(new GrantedAuthorityImpl(roles[i]));
    }
    Authentication authentication = mock(Authentication.class);
    when(authentication.getPrincipal()).thenReturn(principal);
    when(authentication.getAuthorities()).thenReturn(grantedAuthorities);

    SecurityContextHolder.getContext().setAuthentication(authentication);
}
项目:artifactory    文件:DaoLdapAuthoritiesPopulator.java   
@Override
public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData,
        String username) {
    try {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        return userDetails.getAuthorities();
    } catch (UsernameNotFoundException e) {
        return Sets.<GrantedAuthority>newHashSet(new GrantedAuthorityImpl(SecurityServiceImpl.ROLE_USER));
    }
}
项目:collabware    文件:Authenticator.java   
private Collection<GrantedAuthority> asList(String ...roles) {
    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    for (String role:roles) {
        authorities.add(new GrantedAuthorityImpl(role));
    }
    return authorities;
}
项目:modinvreg    文件:UserManagerImpl.java   
protected List<GrantedAuthority> loadGroupAuthorities( String username ) {
    User u = loadUser( username );

    Collection<GroupAuthority> authorities = userService.loadGroupAuthorities( u );

    List<GrantedAuthority> result = new ArrayList<GrantedAuthority>();
    for ( GroupAuthority ga : authorities ) {
        String roleName = getRolePrefix() + ga.getAuthority();
        result.add( new GrantedAuthorityImpl( roleName ) );
    }

    return result;

}
项目:modinvreg    文件:UserGroupServiceTest.java   
/**
 * Tests creating a UserGroup
 */
@Test
public void testCreateUserGroup() {

    List<GrantedAuthority> authos = new ArrayList<GrantedAuthority>();
    authos.add( new GrantedAuthorityImpl( "GROUP_TESTING" ) );
    this.userManager.createGroup( this.groupName, authos );

    List<GrantedAuthority> findGroupAuthorities = this.userManager.findGroupAuthorities( this.groupName );

    for ( GrantedAuthority grantedAuthority : findGroupAuthorities ) {
        assertEquals( "GROUP_TESTING", grantedAuthority.getAuthority() );
    }

}
项目:zswxsqxt    文件:MyUserDetailServiceImpl.java   
private Set<GrantedAuthority> obtionGrantedAuthorities(User user) {
    Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
    List<Resources> resourcesList = resourcesManager.findByUser(user);
    for(Resources res : resourcesList) {

        if(res.getPermission()!=null){
            authSet.add(new GrantedAuthorityImpl(res.getPermission().getId()));
        }
    }
    return authSet;
}
项目:SIRME    文件:UsersServiceImpl.java   
@Transactional(readOnly=true)
@Override
public org.springframework.security.core.userdetails.User get(String codeUser) {
    MyLogger.info(log, CLASS_NAME, "getByCodeUser", "codeUser="+codeUser, "START");

    UserData user = usersDao.getByCode( codeUser );
    user = setProfileToUser( user );

    if (user == null) {
        throw new UsernameNotFoundException("Usuario no encontrado : [" + codeUser + "]");
    }

    boolean isAccountExpired = user.getExpirationDateUser() != null && (user.getExpirationDateUser()).before(new Date());
    boolean isCredentialsExpired = user.getExpirationDateUserPassword() != null && (user.getExpirationDateUserPassword()).before(new Date());

    /** A�adimos sus perfiles asociados a la info de usuario **/
    Collection<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
    list.addAll( user.getRoles() );

    /** A�adimos los permisos asociados a sus perfiles **/
    for(RoleData role : user.getRoles()){
        for( PermissionData permission: role.getPermissions() ){
            list.add(new GrantedAuthorityImpl("PERMISSION_" + permission.getCodePermission()));
        }
    }

    return new org.springframework.security.core.userdetails.User(
            user.getCodeUser(), 
            user.getPasswordUser(),
            user.isEnabled(),
            !isAccountExpired,
            !isCredentialsExpired,
            !user.isLocked(),
            list);
}
项目:pi    文件:PiOpsUserDetailsService.java   
@Override
public UserDetails loadUserByUsername(String username) {
    try {
        ManagementUsers users = (ManagementUsers) blockingDhtCache.get(piIdBuilder.getPId(new ManagementUsers()));
        if (users == null || !users.getUserMap().containsKey(username)) {
            LOG.info("Unable to find management user " + username);
            throw new UsernameNotFoundException(username + " is not a valid user");
        }
        ManagementUser mu = users.getUserMap().get(username);
        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (ManagementRoles role : mu.getRoles()) {
            authorities.add(new GrantedAuthorityImpl(role.name()));
        }
        User user = new User(mu.getUsername(), mu.getPassword(), true, true, true, true, authorities);
        StringBuilder sb = new StringBuilder("loaded management user ").append(username).append(" with authorities ");
        for (GrantedAuthority grantedAuthority : authorities) {
            sb.append(grantedAuthority.getAuthority()).append(" ");
        }
        LOG.debug(sb.toString());
        return user;
    } catch (UsernameNotFoundException e) {
        throw e;
    } catch (Throwable t) {
        LOG.error(t.getMessage(), t);
        throw new UsernameNotFoundException("Unexpected error when checking user credentials");
    }
}
项目:pi    文件:CurrentUserControllerTest.java   
@Test
public void shouldReturnUserDetailsForUserWithOneRole() {
    // / setup
    when(authentication.getName()).thenReturn("dick");
    when(authentication.getAuthorities()).thenReturn(Arrays.asList(new GrantedAuthority[] { new GrantedAuthorityImpl(ManagementRoles.ROLE_OPS.name()) }));

    // act
    String res = currentUserController.getUserInfo();

    // assert
    assertEquals("{\"username\":\"dick\", \"roles\":\"ROLE_OPS\"}", res);
}
项目:pi    文件:CurrentUserControllerTest.java   
@Test
public void shouldReturnUserDetailsForUserWithTwoRoles() {
    // / setup
    when(authentication.getName()).thenReturn("dick");
    when(authentication.getAuthorities()).thenReturn(
            Arrays.asList(new GrantedAuthority[] { new GrantedAuthorityImpl(ManagementRoles.ROLE_OPS.name()), new GrantedAuthorityImpl(ManagementRoles.ROLE_MIS.name()) }));

    // act
    String res = currentUserController.getUserInfo();

    // assert
    assertEquals("{\"username\":\"dick\", \"roles\":\"ROLE_OPS,ROLE_MIS\"}", res);
}
项目:esup-dematec    文件:DatabaseUserDetailsService.java   
public UserDetails loadUserByUser(User targetUser)
        throws UsernameNotFoundException {

    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    Boolean enabled;

    // Roles
    if (targetUser.getIsAdmin()) {
        authorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
    }
    if (targetUser.getIsCandidat()) {
        // TODO : check date
        authorities.add(new GrantedAuthorityImpl("ROLE_CANDIDAT"));
    }
    if (targetUser.getIsManager()) {
        authorities.add(new GrantedAuthorityImpl("ROLE_MANAGER"));
    }
    if (targetUser.getIsSuperManager()) {
        authorities.add(new GrantedAuthorityImpl("ROLE_MANAGER"));
        authorities.add(new GrantedAuthorityImpl("ROLE_SUPER_MANAGER"));
    }
    if (targetUser.getIsMembre()) {
        // TODO : check date
        authorities.add(new GrantedAuthorityImpl("ROLE_MEMBRE"));
    }

    // Enabled
    enabled = targetUser.getEnabled();

    return new org.springframework.security.core.userdetails.User(targetUser.getEmailAddress(), targetUser.getPassword() == null ? "dummy" : targetUser.getPassword(), enabled, // enabled
            true, // account not expired
            true, // credentials not expired
            true, // account not locked
            authorities);

}
项目:threadfixRack    文件:CustomUserMapper.java   
/**
 * Strategy is :
 * 1. Look up the user. 
 * 2. If present, load their permissions.
 * 3. If not present, give default permissions.
 */
@Override
public UserDetails mapUserFromContext(DirContextOperations arg0,
        String userName, Collection<GrantedAuthority> arg2) {

    User dbUser = userService.loadLdapUser(userName);

    if (dbUser != null) {
        return customUserDetailService.loadUser(dbUser);
    }

    Set<GrantedAuthority> newAuthorities = new HashSet<GrantedAuthority>();

    newAuthorities.add(new GrantedAuthorityImpl(Role.USER));

    DefaultConfiguration config = defaultConfigService.loadCurrentConfiguration();

    if (config.getGlobalGroupEnabled()) {
        newAuthorities.add(new GrantedAuthorityImpl(Permission.READ_ACCESS.getText()));

        if (config.getDefaultRoleId() != null) {
            Role testRole = roleService.loadRole(config.getDefaultRoleId());
            if (testRole != null) {
                for (Permission permission : testRole.getPermissions()) {
                    newAuthorities.add(new GrantedAuthorityImpl(permission.getText()));
                }
            }
        }
    }

    return new ThreadFixUserDetails(userName, "ldap", true, true, true, true, 
            newAuthorities, "", true, true, 1, null, null);
}
项目:threadfixRack    文件:PermissionUtils.java   
public static boolean hasGlobalPermission(Permission permission) {
    if (permission == null || permission.getText() == null) {
        return false;
    }

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    return authentication != null && authentication
            .getAuthorities().contains(new GrantedAuthorityImpl(permission.getText()));
}
项目:autotrack    文件:Usuario.java   
@Transient
public Collection<GrantedAuthority> getAuthorities() {
    List<GrantedAuthority> result = new ArrayList<GrantedAuthority>();
    for (PerfilUsuario perfil : perfisUsuario) {
        result.add(new GrantedAuthorityImpl(perfil.getPerfil()
                .getNomePerfil()));
    }
    return result;
}
项目:opennaas-routing-nfv    文件:ACLManagerTest.java   
@Test
public void testAclManager() {
    // create Resource with generated ResourceIdentifier
    Resource resource = new Resource();
    ResourceIdentifier resourceIdentifier = new ResourceIdentifier();
    resource.setResourceIdentifier(resourceIdentifier);

    // create users
    String adminUser = "admin";
    String basicUser = "user";

    // create Authentication objects
    Collection<GrantedAuthority> adminAuthorities = new ArrayList<GrantedAuthority>();
    adminAuthorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
    Authentication adminAuthentication = new UsernamePasswordAuthenticationToken(adminUser, adminUser, adminAuthorities);

    Collection<GrantedAuthority> basicAuthorities = new ArrayList<GrantedAuthority>();
    basicAuthorities.add(new GrantedAuthorityImpl("ROLE_USER"));
    Authentication basicAuthentication = new UsernamePasswordAuthenticationToken(basicUser, basicUser, basicAuthorities);

    // secure Resource using ACLManager (admin credentials are necessary to create ACLs, set it)
    SecurityContextHolder.getContext().setAuthentication(adminAuthentication);
    aclManager.secureResource(resource.getResourceIdentifier().getId(), adminUser);

    /* check accessibility using ACLManager */

    // expect access granted
    SecurityContextHolder.getContext().setAuthentication(adminAuthentication);
    boolean accessible = aclManager.isResourceAccessible(resource.getResourceIdentifier().getId());
    Assert.assertEquals("Permission must be granted for admin user", true, accessible);

    // expect access NOT granted
    SecurityContextHolder.getContext().setAuthentication(basicAuthentication);
    accessible = aclManager.isResourceAccessible(resource.getResourceIdentifier().getId());
    Assert.assertEquals("Permission must be NOT granted for basic user", false, accessible);
}
项目:termitaria    文件:TSUserDetailsService.java   
private UserAuth _ADMIN() {
    logger.debug("ADMIN");
    UserAuth userAuth = new UserAuth();
    userAuth.setPersonId(1);
    userAuth.setUsername("admin");
    userAuth.setPassword("7c4a8d09ca3762af61e59520943dc26494f8941b");
    userAuth.setFirstName("Traian");
    userAuth.setLastName("Besescu");
    userAuth.setOrganisationId(27);
    userAuth.setOrganisationName("SIAD");

    //Permisiuni
    List<GrantedAuthority> authories = new ArrayList<GrantedAuthority>();
    authories.add(new GrantedAuthorityImpl("SUPER"));
    authories.add(new GrantedAuthorityImpl("DM_BASIC"));
    authories.add(new GrantedAuthorityImpl("DM_CategoryDelete"));
    authories.add(new GrantedAuthorityImpl("DM_CategoryAdd"));
    authories.add(new GrantedAuthorityImpl("DM_CategoryUpdate"));
    authories.add(new GrantedAuthorityImpl("DM_DocumentAdd"));
    authories.add(new GrantedAuthorityImpl("DM_CollectionZoneView"));
    authories.add(new GrantedAuthorityImpl("AUDIT_OMDelete"));
    authories.add(new GrantedAuthorityImpl("AUDIT_DMDelete"));
    authories.add( new GrantedAuthorityImpl("AUDIT_OMView"));
    authories.add( new GrantedAuthorityImpl("AUDIT_DMView"));
    authories.add( new GrantedAuthorityImpl("AUDIT_Basic"));

    userAuth.setAuthorities(authories);

    return userAuth;
}
项目:termitaria    文件:TSUserDetailsService.java   
private UserAuth _ADMINIT() {
    logger.debug("ADMIN_IT");
    UserAuth userAuth = new UserAuth();
    userAuth.setPersonId(1);
    userAuth.setUsername("adminIT");
    userAuth.setPassword("7c4a8d09ca3762af61e59520943dc26494f8941b");
    userAuth.setFirstName("Gica");
    userAuth.setLastName("Popescu");        
    userAuth.setAdminIT(true);

    //Permisiuni
    List<GrantedAuthority> authories = new ArrayList<GrantedAuthority>();
    authories.add(new GrantedAuthorityImpl("SUPER"));
    authories.add(new GrantedAuthorityImpl("DM_BASIC"));
    authories.add(new GrantedAuthorityImpl("DM_CategoryDelete"));
    authories.add(new GrantedAuthorityImpl("DM_CategoryAdd"));
    authories.add(new GrantedAuthorityImpl("DM_CategoryUpdate"));
    authories.add(new GrantedAuthorityImpl("DM_DocumentAdd"));
    authories.add(new GrantedAuthorityImpl("DM_CollectionZoneView"));
    authories.add(new GrantedAuthorityImpl("AUDIT_OMView"));
    authories.add(new GrantedAuthorityImpl("AUDIT_DMView"));
    authories.add( new GrantedAuthorityImpl("AUDIT_Basic"));

    userAuth.setAuthorities(authories);

    return userAuth;
}
项目:Opensheet    文件:CustomUser.java   
@SuppressWarnings("deprecation")
    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
        for (Authority role : roles) {
              list.add(new GrantedAuthorityImpl(role.getAuthority()));
        }
        return list;

}
项目:openhds-server    文件:UserDetailsService.java   
/**
 * Get a collection of {@link GrantedAuthority} which is required by {@link UserDetails} instance for Spring Security
 * @return a collection of {@link GrantedAuthority} instances
 */
private Collection<GrantedAuthority> convertAuthorities(Set<Role> roles) {
    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new GrantedAuthorityImpl(SPRING_ROLE));

    for(Role role : roles) {
        for(Privilege privilege: role.getPrivileges()) {
            authorities.add(new GrantedAuthorityImpl(privilege.getPrivilege()));
        }
    }

    return authorities;
}
项目:openhds-server    文件:CurrentUserImpl.java   
public void setProxyUser(String username, String password, String[] privileges) {
    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

    for(String privilege : privileges) {
        authorities.add(new GrantedAuthorityImpl(privilege));
    }

    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(username, password, authorities);
    SecurityContextHolder.getContext().setAuthentication(auth);
}
项目:esup-nfc-tag-server    文件:LiveLongPoolController.java   
private boolean isLiveLongPoolAuthorized(Authentication auth) {
    return auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_ADMIN")) || auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_SUPERVISOR")) || isIpCanBeUsed4LiveFullAnonymous(auth);
}
项目:omr    文件:SelfRegBean.java   
/**
     * Autentica a sess�o com o usu�rio recem registrado
     * @param empresaVO2
     * @param pessoaVO2
     */
    protected void autenticarSessao(EmpresaVO empresaVO2, PessoaVO pessoaVO2) {

        SecurityContext context = SecurityContextHolder.getContext();

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        GrantedAuthority authority = new GrantedAuthorityImpl(EAuthority.MASTER_ADM.toString());
        authorities.add(authority);

        UserDetails user = new User(pessoaVO2.getLogin(), "", true, true, true, true, authorities); 


        Authentication authentication = new AnonymousAuthenticationToken(pessoaVO2.getLogin(),user,authorities);


    context.setAuthentication(authentication);

}
项目:omr    文件:SelfRegBean.java   
/**
     * Autentica a sessão com o usuário recem registrado
     * @param empresaVO2
     * @param pessoaVO2
     */
    protected void autenticarSessao(EmpresaVO empresaVO2, PessoaVO pessoaVO2) {

        SecurityContext context = SecurityContextHolder.getContext();

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        GrantedAuthority authority = new GrantedAuthorityImpl(EAuthority.MASTER_ADM.toString());
        authorities.add(authority);

        UserDetails user = new User(pessoaVO2.getLogin(), "", true, true, true, true, authorities); 


        Authentication authentication = new AnonymousAuthenticationToken(pessoaVO2.getLogin(),user,authorities);


    context.setAuthentication(authentication);

}
项目:omr    文件:SelfRegBean.java   
/**
     * Autentica a sessão com o usuário recem registrado
     * @param empresaVO2
     * @param pessoaVO2
     */
    protected void autenticarSessao(EmpresaVO empresaVO2, PessoaVO pessoaVO2) {

        SecurityContext context = SecurityContextHolder.getContext();

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        GrantedAuthority authority = new GrantedAuthorityImpl(EAuthority.MASTER_ADM.toString());
        authorities.add(authority);

        UserDetails user = new User(pessoaVO2.getLogin(), "", true, true, true, true, authorities); 


        Authentication authentication = new AnonymousAuthenticationToken(pessoaVO2.getLogin(),user,authorities);


    context.setAuthentication(authentication);

}