Example usage for org.springframework.security.core Authentication getAuthorities

List of usage examples for org.springframework.security.core Authentication getAuthorities

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getAuthorities.

Prototype

Collection<? extends GrantedAuthority> getAuthorities();

Source Link

Document

Set by an AuthenticationManager to indicate the authorities that the principal has been granted.

Usage

From source file:eu.supersede.fe.rest.GadgetRest.java

@RequestMapping("/available")
public List<ApplicationGadget> getUserAuthenticatedAvailableApplicationsGadgets(Authentication auth) {
    // DatabaseUser user = (DatabaseUser)auth.getPrincipal();
    List<String> authNames = new ArrayList<>();
    Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();

    for (GrantedAuthority ga : authorities) {
        authNames.add(ga.getAuthority().substring(5));
    }//from  w ww.j ava 2s.  com

    List<ApplicationGadget> availGadgets = new ArrayList<>(
            applicationUtil.getApplicationsGadgetsByProfilesNames(authNames));
    Collections.sort(availGadgets, comparator);

    return availGadgets;
}

From source file:fr.univrouen.poste.utils.PostePermissionEvaluator.java

@Override
public boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission) {

    if (auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_ADMIN"))
            || auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_MANAGER")))
        return true;

    boolean isMembre = auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_MEMBRE"));
    boolean isCandidat = auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_CANDIDAT"));

    String permissionKey = (String) permission;

    if (auth == null || auth.getName() == null || "".equals(auth.getName()))
        return false;

    if (!(targetDomainObject instanceof PosteCandidature || targetDomainObject instanceof Long))
        return false;

    String email = auth.getName();

    if ("delFile".equals(permissionKey)) {
        Long id = (Long) targetDomainObject;
        PosteCandidatureFile pcFile = PosteCandidatureFile.findPosteCandidatureFile(id);
        return pcFile.getWriteable();
    }//from ww w. jav a  2s .  co m

    if ("delMemberReviewFile".equals(permissionKey)) {
        Boolean confSupprReviewFile = AppliConfig.getCacheMembreSupprReviewFile();
        if (!confSupprReviewFile) {
            return false;
        }
        Long id = (Long) targetDomainObject;
        MemberReviewFile reviewFile = MemberReviewFile.findMemberReviewFile(id);
        User user = User.findUsersByEmailAddress(email, null, null).getSingleResult();
        return reviewFile.getMember().equals(user);
    }

    if ("manageReporters".equals(permissionKey)) {
        Long id = (Long) targetDomainObject;
        PosteCandidature pc = PosteCandidature.findPosteCandidature(id);
        User user = User.findUsersByEmailAddress(email, null, null).getSingleResult();
        return pc.getPoste().getPresidents() != null && pc.getPoste().getPresidents().contains(user);
    }

    if ("viewposte".equals(permissionKey)) {
        Long id = (Long) targetDomainObject;
        PosteAPourvoir posteAPourvoir = PosteAPourvoir.findPosteAPourvoir(id);
        User user = User.findUsersByEmailAddress(email, null, null).getSingleResult();
        return posteAPourvoir.getMembres() != null && posteAPourvoir.getMembres().contains(user);
    }

    if ("manageposte".equals(permissionKey)) {
        Long id = (Long) targetDomainObject;
        PosteAPourvoir posteAPourvoir = PosteAPourvoir.findPosteAPourvoir(id);
        User user = User.findUsersByEmailAddress(email, null, null).getSingleResult();
        return posteAPourvoir.getPresidents() != null && posteAPourvoir.getPresidents().contains(user);
    }

    if (!"manage".equals(permissionKey) && !"view".equals(permissionKey) && !"review".equals(permissionKey))
        return false;

    PosteCandidature pc;

    if (targetDomainObject instanceof PosteCandidature) {
        pc = (PosteCandidature) targetDomainObject;
    } else {
        Long id = (Long) targetDomainObject;
        pc = PosteCandidature.findPosteCandidature(id);
    }

    if (pc != null) {
        User user = User.findUsersByEmailAddress(email, null, null).getSingleResult();

        if ("review".equals(permissionKey)) {
            PosteAPourvoir poste = pc.getPoste();
            return user.getIsAdmin() || user.getIsManager()
                    || user.getIsMembre() && poste.getMembres().contains(user) && pc.getRecevable();
        }

        if (isCandidat) {

            if (AppliConfig.getCacheCandidatCanSignup()) {
                Date currentTime = new Date();
                if ((pc.getAuditionnable() || (pc.getPoste().getDateEndSignupCandidat() == null
                        || currentTime.compareTo(pc.getPoste().getDateEndSignupCandidat()) > 0))
                        && (!pc.getAuditionnable()
                                || (pc.getPoste().getDateEndCandidatAuditionnable() == null || currentTime
                                        .compareTo(pc.getPoste().getDateEndCandidatAuditionnable()) > 0))) {
                    return false;
                } else {
                    return true;
                }
            } else {

                if (pc.getCandidat().equals(user)) {
                    // restrictions si phase auditionnable
                    Date currentTime = new Date();
                    if (currentTime.compareTo(AppliConfig.getCacheDateEndCandidat()) > 0
                            && currentTime.compareTo(AppliConfig.getCacheDateEndCandidatActif()) > 0) {
                        return pc.getAuditionnable()
                                && currentTime.compareTo(pc.getPoste().getDateEndCandidatAuditionnable()) < 0;
                    } else {
                        return true;
                    }
                }
            }
        }

        if ("view".equals(permissionKey) && isMembre) {
            PosteAPourvoir poste = pc.getPoste();
            return poste.getMembres().contains(user) && pc.getRecevable();
        }
    }

    return false;

}

From source file:org.mule.modules.basicauthsecurity.strategy.JDBCSecurityProvider.java

public void validate(String auth, List<String> acceptedRoles) throws UnauthorizedException {
    List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
    for (String role : acceptedRoles) {
        list.add(new SimpleGrantedAuthority(role));
    }/* w  ww.ja  v  a  2s.com*/
    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(getUser(auth),
            getPass(auth), list);
    Authentication authResult = providerManager.authenticate(authRequest);

    Boolean containsKey = false;
    for (GrantedAuthority grantedAuthority : authResult.getAuthorities()) {
        if (authRequest.getAuthorities().contains(grantedAuthority)) {
            containsKey = true;
        }
    }

    if (!containsKey) {
        throw new UnauthorizedException("result");
    }
    if (!authResult.isAuthenticated()) {
        throw new UnauthorizedException("result");
    }
}

From source file:org.socialsignin.springsocial.security.signin.SpringSocialSecurityAuthenticationFactory.java

private Collection<? extends GrantedAuthority> addAuthorities(Authentication authentication,
        Collection<GrantedAuthority> newAuthorities) {
    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.addAll(authentication.getAuthorities());
    if (newAuthorities != null) {
        for (GrantedAuthority newAuthority : newAuthorities) {
            if (!authorities.contains(newAuthority)) {
                authorities.add(newAuthority);
            }//from w ww . j  a  va  2 s.c  o  m
        }
    }

    return authorities;
}

From source file:com.hp.autonomy.frontend.configuration.authentication.CommunityAuthenticationProviderTest.java

@Test
public void testAuthenticateReturnsCorrectUser() {
    final UserRoles userRoles = mock(UserRoles.class);
    when(userRoles.getRoles()).thenReturn(Collections.singletonList(APP_ROLE));

    when(userService.getUser(anyString(), eq(true))).thenReturn(userRoles);

    final Authentication authentication = communityAuthenticationProvider.authenticate(springAuthentication);

    //noinspection unchecked
    assertThat((Iterable<GrantedAuthority>) authentication.getAuthorities(),
            hasItem(new SimpleGrantedAuthority(APP_ROLE)));
}

From source file:org.deegree.securityproxy.wps.responsefilter.capabilities.WpsCapabilitiesModificationManagerCreator.java

private List<String> collectAuthenticatedProcessIds(Authentication authentication) {
    Set<String> layerNamesToPreserve = new HashSet<String>();
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    for (GrantedAuthority grantedAuthority : authorities) {
        addLayerNameRule(layerNamesToPreserve, grantedAuthority);
    }// w w w.j  av a 2  s. com
    return new ArrayList<String>(layerNamesToPreserve);
}

From source file:com.goodhuddle.huddle.web.HuddleGlobalInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

    // anything under '/_huddles/' is not specific to a Huddle and is allowed at any time
    if (request.getRequestURI().startsWith("/_huddles")
            || request.getRequestURI().startsWith("/error/huddle-not-found")
            || request.getRequestURI().startsWith("/webhooks")) {
        return true;
    }/*ww  w. jav  a  2  s .  com*/

    Huddle huddle = huddleService.getHuddle();
    if (huddle == null) {
        if (huddleService.getHuddles().size() == 0) {
            response.sendRedirect("/_huddles/create");
        } else {
            response.sendRedirect("/error/huddle-not-found");
        }
        return false;
    }

    // check if admin setup wizard has been completed
    if (!huddle.isSetupWizardComplete()) {
        if (StringUtils.isNotBlank(request.getRequestURI()) && (request.getRequestURI().endsWith("/not-setup")
                || request.getRequestURI().startsWith("/admin")
                || request.getRequestURI().startsWith("/api"))) {
            return true;
        } else {
            response.sendRedirect("/not-setup");
            return false;
        }
    }

    // check if in coming soon mode
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    boolean isAdmin = false;
    if (auth != null) {
        for (GrantedAuthority grantedAuthority : auth.getAuthorities()) {
            if (Permissions.Admin.access.equals(grantedAuthority.getAuthority())) {
                isAdmin = true;
                break;
            }
        }
    }

    if (huddle.isComingSoon() && !isAdmin) {
        if (StringUtils.isNotBlank(request.getRequestURI()) && (request.getRequestURI().endsWith("/not-setup")
                || request.getRequestURI().startsWith("/coming-soon")
                || request.getRequestURI().startsWith("/admin") || request.getRequestURI().startsWith("/error")
                || request.getRequestURI().startsWith("/api"))) {
            return true;
        } else {
            response.sendRedirect("/coming-soon");
            return false;
        }
    }

    return true;
}

From source file:es.mdef.clientmanager.ui.GestionClientesUI.java

private String getNombreUsuario() {
    String nombre = "";
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    if (authentication != null && authentication.isAuthenticated()
            && !authentication.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))) {
        UserDetail userDetail = (UserDetail) authentication.getDetails();
        nombre = userDetail.getAppUser().getUserName();
    }//from   w ww  . ja va2  s. c o m
    return nombre;
}

From source file:org.musicrecital.service.UserSecurityAdvice.java

/**
 * 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//from  w  ww  . j  a va 2 s .  c o m
 * @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;
        Collection<? extends GrantedAuthority> roles = auth.getAuthorities();
        for (GrantedAuthority role : roles) {
            if (role.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) {
            UserManager userManager = (UserManager) target;
            User currentUser = getCurrentUser(auth, userManager);

            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() + "'");
            }
        }
    }
}

From source file:org.duracloud.account.security.vote.BaseAccessDecisionVoter.java

protected Collection<String> getUserRoles(Authentication authentication) {
    Set<String> roles = new HashSet<String>();
    for (GrantedAuthority authority : authentication.getAuthorities()) {
        roles.add(authority.getAuthority());
    }//from  www. ja  va 2 s. com
    return roles;
}