Example usage for org.springframework.security.core GrantedAuthority getAuthority

List of usage examples for org.springframework.security.core GrantedAuthority getAuthority

Introduction

In this page you can find the example usage for org.springframework.security.core GrantedAuthority getAuthority.

Prototype

String getAuthority();

Source Link

Document

If the GrantedAuthority can be represented as a String and that String is sufficient in precision to be relied upon for an access control decision by an AccessDecisionManager (or delegate), this method should return such a String.

Usage

From source file:org.cloudifysource.security.CloudifyUser.java

@Override
public Collection<String> getRoles() {
    Collection<String> roles = new ArrayList<String>();
    for (GrantedAuthority authority : this.getAuthorities()) {
        roles.add(authority.getAuthority());
    }/*from   w  ww .j a va2 s. c  om*/

    return roles;
}

From source file:org.cms.config.CustomUrlAuthenticationSuccessHandler.java

protected String determineTargetUrl(Authentication authentication) {
    boolean isUser = false;
    boolean isAdmin = false;
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    for (GrantedAuthority grantedAuthority : authorities) {
        if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
            isUser = true;//from   w  w  w.  j ava2  s. c o m
            break;
        } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
            isAdmin = true;
            break;
        }
    }
    if (isUser) {
        return "/pocetna";
    } else if (isAdmin) {
        return "/admin/home";
    } else {
        throw new IllegalStateException();
    }
}

From source file:org.encuestame.core.security.EnMeRoleVoter.java

/**
 *
 *///from w  ww .jav  a  2 s  .  c om
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
    int result = ACCESS_GRANTED;
    final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    log.debug("Authoritiez size " + authorities.size());
    for (ConfigAttribute attribute : attributes) {
        if (this.supports(attribute)) {
            result = ACCESS_DENIED;
            // Attempt to find a matching granted authority
            log.debug("Attribute" + attribute.getAttribute());
            for (GrantedAuthority authority : authorities) {
                log.debug("authority.getAuthority())" + authority.getAuthority());
                if (attribute.getAttribute().equals(authority.getAuthority())) {
                    return ACCESS_GRANTED;
                }
            }
        }
    }
    log.debug("Result " + result);
    return result;
}

From source file:org.encuestame.mvc.interceptor.SignInInterceptor.java

@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
    String context = arg0.getContextPath();
    StringBuilder path = new StringBuilder(context);
    path.append(PathUtil.signIn);/*ww w. j  av a 2  s .  c  om*/
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    log.trace("Sign In Auth:{ " + authentication);
    if (arg0.getRequestURI().equals(path.toString())) {
        log.debug("Sign In are equals:{ " + arg0.getRequestURI());
        if (authentication != null) {
            if (!SecurityUtils.checkIsSessionIsAnonymousUser(authentication)) {
                log.debug("Sign In session is valid");
                for (GrantedAuthority auth : authentication.getAuthorities()) {
                    log.debug("Sign In Auth:{ " + auth.getAuthority());
                    if (EnumerationUtils.getEnumFromString(EnMePermission.class, auth.getAuthority())
                            .equals(EnMePermission.ENCUESTAME_USER)) {
                        log.debug("User is logged, redirec to dashboard");
                        arg1.sendRedirect(arg0.getContextPath() + "/user/dashboard");
                        break;
                    }
                }
            }
        }
    }
    return true;
}

From source file:org.fao.geonet.kernel.security.ldap.LdapUserDetailsManager.java

private String convertAuthorityToGroup(GrantedAuthority authority) {
    String group = authority.getAuthority();

    if (group.startsWith(rolePrefix)) {
        group = group.substring(rolePrefix.length());
    }/* www . jav  a 2  s .  c  om*/

    return group;
}

From source file:org.finra.dm.app.AbstractAppTest.java

/**
 * Retrieves the user from the current spring security context and asserts that each of the properties of the user matches the given expected values.
 * Asserts that the principal stored in the current security context user is an instance of {@link SecurityUserWrapper}.
 *
 * @param expectedUserId the expected user Id.
 * @param expectedFirstName the expected first name.
 * @param expectedLastName the expected last name.
 * @param expectedEmail the expected e-mail.
 * @param expectedRoles the expected roles.
 * @param expectedSessionInitTime the expected session init time.
 * @param expectedFunctions the expected functions.
 *
 * @throws Exception if any errors were encountered.
 *///from   w  w  w  . j  a v a2  s . c  om
protected void validateHttpHeaderApplicationUser(String expectedUserId, String expectedFirstName,
        String expectedLastName, String expectedEmail, Set<String> expectedRoles,
        String expectedSessionInitTime, String[] expectedFunctions) throws Exception {

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

    Object principal = authentication.getPrincipal();
    assertNotNull("expected principal to be not null, but was null", principal);
    assertTrue(
            "expected principal to be an instance of " + SecurityUserWrapper.class
                    + ", but was an instance of  " + principal.getClass(),
            principal instanceof SecurityUserWrapper);
    SecurityUserWrapper user = (SecurityUserWrapper) principal;
    ApplicationUser applicationUser = user.getApplicationUser();
    assertEquals(expectedUserId, applicationUser.getUserId());
    assertEquals(expectedFirstName, applicationUser.getFirstName());
    assertEquals(expectedLastName, applicationUser.getLastName());
    assertEquals(expectedEmail, applicationUser.getEmail());

    assertEquals(expectedRoles, applicationUser.getRoles());
    if (StringUtils.isNotBlank(expectedSessionInitTime)) {
        assertEquals(
                DateUtils.parseDate(expectedSessionInitTime,
                        HttpHeaderApplicationUserBuilder.CALENDAR_PATTERNS),
                applicationUser.getSessionInitTime());
    }

    assertNotNull(applicationUser.getSessionId());

    assertEquals(HttpHeaderApplicationUserBuilder.class, applicationUser.getGeneratedByClass());

    // Validate functions.
    if (expectedFunctions != null) {
        Set<String> functions = new HashSet<>();
        for (GrantedAuthority grantedAuthority : user.getAuthorities()) {
            functions.add(grantedAuthority.getAuthority());
        }

        assertArrayEquals(expectedFunctions, functions.toArray(new String[user.getAuthorities().size()]));
    }
}

From source file:org.finra.herd.app.AbstractAppTest.java

/**
 * Retrieves the user from the current spring security context and asserts that each of the properties of the user matches the given expected values.
 * Asserts that the principal stored in the current security context user is an instance of {@link SecurityUserWrapper}.
 *
 * @param expectedUserId the expected user Id.
 * @param expectedFirstName the expected first name.
 * @param expectedLastName the expected last name.
 * @param expectedEmail the expected e-mail.
 * @param expectedRoles the expected roles.
 * @param expectedSessionInitTime the expected session init time.
 * @param expectedFunctions the expected functions.
 *
 * @throws Exception if any errors were encountered.
 *//*  www  .  j av a2  s . c o m*/
protected void validateHttpHeaderApplicationUser(String expectedUserId, String expectedFirstName,
        String expectedLastName, String expectedEmail, Set<String> expectedRoles,
        String expectedSessionInitTime, String[] expectedFunctions,
        Set<NamespaceAuthorization> expectedNamespaceAuthorizations) throws Exception {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    assertNotNull(authentication);

    Object principal = authentication.getPrincipal();
    assertNotNull("expected principal to be not null, but was null", principal);
    assertTrue(
            "expected principal to be an instance of " + SecurityUserWrapper.class
                    + ", but was an instance of  " + principal.getClass(),
            principal instanceof SecurityUserWrapper);
    SecurityUserWrapper user = (SecurityUserWrapper) principal;
    ApplicationUser applicationUser = user.getApplicationUser();
    assertEquals(expectedUserId, applicationUser.getUserId());
    assertEquals(expectedFirstName, applicationUser.getFirstName());
    assertEquals(expectedLastName, applicationUser.getLastName());
    assertEquals(expectedEmail, applicationUser.getEmail());

    assertEquals(expectedRoles, applicationUser.getRoles());
    if (StringUtils.isNotBlank(expectedSessionInitTime)) {
        assertEquals(
                DateUtils.parseDate(expectedSessionInitTime,
                        HttpHeaderApplicationUserBuilder.CALENDAR_PATTERNS),
                applicationUser.getSessionInitTime());
    }

    assertNotNull(applicationUser.getSessionId());

    assertEquals(HttpHeaderApplicationUserBuilder.class, applicationUser.getGeneratedByClass());

    // Validate functions.
    if (expectedFunctions != null) {
        Set<String> functions = new HashSet<>();
        for (GrantedAuthority grantedAuthority : user.getAuthorities()) {
            functions.add(grantedAuthority.getAuthority());
        }

        for (String expectedFunction : expectedFunctions) {
            assertTrue(functions.contains(expectedFunction));
        }
    }

    // Validate namespace authorizations.
    if (expectedNamespaceAuthorizations != null) {
        assertEquals(expectedNamespaceAuthorizations, applicationUser.getNamespaceAuthorizations());
    }
}

From source file:org.flowable.app.filter.FlowableCookieFilter.java

protected void validateRequiredPriviliges(HttpServletRequest request, HttpServletResponse response,
        FlowableAppUser user) {//from   w  w  w  .  j a  va  2 s. c  o m

    if (user == null) {
        return;
    }

    String pathInfo = request.getPathInfo();
    if (isRootPath(request) || !pathInfo.startsWith("/rest")) { // rest calls handled by Spring Security conf

        if (requiredPrivileges != null && requiredPrivileges.size() > 0) {

            if (user.getAuthorities() == null || user.getAuthorities().size() == 0) {
                redirectOrSendNotPermitted(request, response, user.getUserObject().getId());
            }

            int matchingPrivileges = 0;
            for (GrantedAuthority authority : user.getAuthorities()) {
                if (requiredPrivileges.contains(authority.getAuthority())) {
                    matchingPrivileges++;
                }
            }

            if (matchingPrivileges != requiredPrivileges.size()) {
                redirectOrSendNotPermitted(request, response, user.getUserObject().getId());
            }
        }

    }
}

From source file:org.geoserver.ftp.GSFTPUserManager.java

/**
 * @param ftpAuthRequest//from  www  .  ja  v a 2s .co  m
 *            one of {@link org.apache.ftpserver.usermanager.AnonymousAuthentication} or
 *            {@link org.apache.ftpserver.usermanager.UsernamePasswordAuthentication}
 * @throws AuthenticationFailedException
 *             if given an {@code AnonymousAuthentication}, or an invalid/disabled user
 *             credentials
 * @see UserManager#authenticate(Authentication)
 */
public User authenticate(final Authentication ftpAuthRequest) throws AuthenticationFailedException {
    if (!(ftpAuthRequest instanceof UsernamePasswordAuthentication)) {
        throw new AuthenticationFailedException();
    }
    final UsernamePasswordAuthentication upa = (UsernamePasswordAuthentication) ftpAuthRequest;
    final String principal = upa.getUsername();
    final String credentials = upa.getPassword();
    org.springframework.security.core.Authentication gsAuth = new UsernamePasswordAuthenticationToken(principal,
            credentials);
    try {
        gsAuth = authManager.authenticate(gsAuth);
    } catch (org.springframework.security.core.AuthenticationException authEx) {
        throw new AuthenticationFailedException(authEx);
    }

    try {
        // gather the user
        BaseUser user = getUserByName(principal);
        user.setPassword(credentials);
        // is the user enabled?
        if (!user.getEnabled()) {
            throw new AuthenticationFailedException();
        }

        // scary message for admins if the username/password has not
        // been changed
        if (DEFAULT_USER.equals(user.getName()) && DEFAULT_PASSWORD.equals(credentials)) {
            LOGGER.log(Level.SEVERE,
                    "The default admin/password combination has not been "
                            + "modified, this makes the embedded FTP server an "
                            + "open file host for everybody to use!!!");
        }

        final File dataRoot = dataDir.findOrCreateDataRoot();

        // enable only admins and non anonymous users
        boolean isGSAdmin = false;
        for (GrantedAuthority authority : gsAuth.getAuthorities()) {
            final String userRole = authority.getAuthority();
            if (ADMIN_ROLE.equals(userRole)) {
                isGSAdmin = true;
                break;
            }
        }

        final File homeDirectory;
        if (isGSAdmin) {
            homeDirectory = dataRoot;
        } else {
            /*
             * This resolves the user's home directory to data/incoming/<user name> but does not
             * create the directory if it does not already exist. That is left to when the user
             * is authenticated, check the authenticate() method above.
             */
            homeDirectory = new File(new File(dataRoot, "incoming"), user.getName());
        }
        String normalizedPath = homeDirectory.getAbsolutePath();
        normalizedPath = FilenameUtils.normalize(normalizedPath);
        user.setHomeDirectory(normalizedPath);
        if (!homeDirectory.exists()) {
            LOGGER.fine("Creating FTP home directory for user " + user.getName() + " at " + normalizedPath);
            homeDirectory.mkdirs();
        }

        return user;
    } catch (AuthenticationFailedException e) {
        throw e;
    } catch (Exception e) {
        LOGGER.log(Level.INFO, "FTP authentication failure", e);
        throw new AuthenticationFailedException(e);
    }
}

From source file:org.geoserver.security.GeoServerSecurityManager.java

/**
 * Checks if the specified authentication contains the specified role.
 * /*from w  ww .  j av a2  s .  c  om*/
 * If the current {@link HttpServletRequest} has security disabled,
 * this method always returns <code>true</code>.
 * 
 * @return <code>true</code> if the authenticated contains the role, otherwise <code>false</false>
 */
public boolean checkAuthenticationForRole(Authentication auth, GeoServerRole role) {

    if (GeoServerSecurityFilterChainProxy.isSecurityEnabledForCurrentRequest() == false)
        return true; // No security means any role is granted

    if (auth == null || !auth.isAuthenticated()) {
        return false;
    }
    for (GrantedAuthority authority : auth.getAuthorities()) {
        if (role.getAuthority().equals(authority.getAuthority())) {
            return true;
        }
    }
    return false;
}