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:io.gravitee.management.idp.ldap.authentication.UserDetailsContextPropertiesMapper.java

@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username,
        Collection<? extends GrantedAuthority> authorities) {
    List<GrantedAuthority> mappedAuthorities = new ArrayList<>();
    try {//from   ww w . ja  v a  2 s  .c o  m
        for (GrantedAuthority granted : authorities) {
            String mappedAuthority = environment.getProperty("role-mapper." + granted.getAuthority());
            if (!StringUtils.isEmpty(mappedAuthority)) {
                mappedAuthorities.add(new SimpleGrantedAuthority(mappedAuthority));
            }
        }
    } catch (Exception e) {
        LOGGER.error("Failed to load mapped authorities", e);
    }
    return new io.gravitee.management.idp.api.authentication.UserDetails(username, "", mappedAuthorities,
            ctx.getStringAttribute("mail"), ctx.getStringAttribute("givenName"), ctx.getStringAttribute("sn"));
}

From source file:org.opentides.bean.user.SessionUser.java

/**
 * Checks if user has permission to the specified 
 * permission string/*from ww w .  j  ava 2  s.  c  o m*/
 * 
 * @param permission
 * @return
 */
public boolean hasPermission(String permission) {
    for (GrantedAuthority auth : this.getAuthorities()) {
        if (permission.equals(auth.getAuthority()))
            return true;
    }
    return false;
}

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  w w.j  a v a 2s .  c o m

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

    return availGadgets;
}

From source file:org.apache.cxf.fediz.service.idp.service.security.GrantedAuthorityEntitlements.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    try {//from  ww w.  jav a 2  s .  c  om
        Authentication currentAuth = SecurityContextHolder.getContext().getAuthentication();
        if (currentAuth == null) {
            chain.doFilter(request, response);
            return;
        }

        final Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        if (currentAuth.getAuthorities() != null) {
            authorities.addAll(currentAuth.getAuthorities());
        }

        Iterator<? extends GrantedAuthority> authIt = currentAuth.getAuthorities().iterator();
        while (authIt.hasNext()) {
            GrantedAuthority ga = authIt.next();
            String roleName = ga.getAuthority();

            try {
                Role role = roleDAO.getRole(roleName.substring(5), Arrays.asList("all"));
                for (Entitlement e : role.getEntitlements()) {
                    authorities.add(new SimpleGrantedAuthority(e.getName()));
                }
            } catch (Exception ex) {
                LOG.error("Role '" + roleName + "' not found");
            }
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug(authorities.toString());
        }
        UsernamePasswordAuthenticationToken enrichedAuthentication = new UsernamePasswordAuthenticationToken(
                currentAuth.getName(), currentAuth.getCredentials(), authorities);
        enrichedAuthentication.setDetails(currentAuth.getDetails());

        SecurityContextHolder.getContext().setAuthentication(enrichedAuthentication);
        LOG.info("Enriched AuthenticationToken added");

    } catch (Exception ex) {
        LOG.error("Failed to enrich security context with entitlements", ex);
    }

    chain.doFilter(request, response);
}

From source file:org.apigw.authserver.shibboleth.ShibbolethSamlUserDetailsServiceTest.java

@Test
public void testLoadUserDetailsAlwaysGrantedAuthorities() throws Exception {
    shibbolethSamlUserDetailsService.setGrantedAuthorities(new HashSet<String>() {
        {/* w ww . j  av a 2 s.c om*/
            add("ROLE_USER");
            add("ROLE_TEST_USER");
        }
    });
    Map<String, String> principal = new HashMap<>();
    principal.put("subjectSerialNumber", "188801010101");
    principal.put("subjectCommonName", "subject common name");
    when(authentication.getPrincipal()).thenReturn(principal);
    final UserDetails userDetails = shibbolethSamlUserDetailsService.loadUserDetails(authentication);
    assertEquals(2, userDetails.getAuthorities().size());
    boolean roleUserFound = false;
    boolean roleTestUserFound = false;
    final Iterator<? extends GrantedAuthority> iterator = userDetails.getAuthorities().iterator();
    while (iterator.hasNext()) {
        final GrantedAuthority grantedAuthority = iterator.next();
        if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
            roleUserFound = true;
        }
        if (grantedAuthority.getAuthority().equals("ROLE_TEST_USER")) {
            roleTestUserFound = true;
        }
    }
    assertTrue("Expected ROLE_USER among granted authorities", roleUserFound);
    assertTrue("Expected ROLE_TEST_USER among granted authorities", roleTestUserFound);
    assertEquals("188801010101", userDetails.getUsername());
    assertEquals("subject common name", ((User) userDetails).getFullName());
}

From source file:com.creativity.security.MySimpleUrlAuthenticationSuccessHandler.java

/**
 * Builds the target URL according to the logic defined in the main class
 * Javadoc.//from www . j  a v  a2s.c  o  m
 */
protected String determineTargetUrl(Authentication authentication) {
    boolean isUser = false;
    boolean isAdmin = false;
    boolean isAtendente = false;
    boolean isFinanceiro = false;
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    for (GrantedAuthority grantedAuthority : authorities) {
        if (grantedAuthority.getAuthority().equals("GESTOR")) {
            isUser = true;
            break;
        } else if (grantedAuthority.getAuthority().equals("ADMINISTRADOR")) {
            isAdmin = true;
            break;
        } else if (grantedAuthority.getAuthority().equals("FINANCEIRO")) {
            isFinanceiro = true;
            break;
        }
        if (grantedAuthority.getAuthority().equals("ATENDENTE")) {
            isAtendente = true;
            break;

        } else {

        }
    }

    if (isUser) {
        return "/DashboardGestor.xhtml";
    } else if (isAdmin) {
        return "/DashboardAdmin.xhtml";
    } else if (isFinanceiro) {
        return "/DashboardAdmin.xhtml";
    }
    if (isAtendente) {
        return "/DashboardAdmin.xhtml";

    } else {
        throw new IllegalStateException();
    }
}

From source file:org.cloudfoundry.identity.uaa.integration.util.IntegrationTestUtils.java

public static boolean hasAuthority(String authority, Collection<GrantedAuthority> authorities) {
    for (GrantedAuthority a : authorities) {
        if (authority.equals(a.getAuthority())) {
            return true;
        }/*from w  ww.  j a v a 2  s .  co m*/
    }
    return false;
}

From source file:eu.openanalytics.rsb.security.JmxSecurityAuthenticator.java

private boolean isRsbAdminRole(final User authenticatedUser) {
    if ((configuration.getRsbSecurityConfiguration() == null)
            || (configuration.getRsbSecurityConfiguration().getAdminRoles() == null)) {
        return false;
    }//from   ww w . j a  v a  2 s . com

    final Set<String> authoritiesNames = new HashSet<String>();
    for (final GrantedAuthority authority : authenticatedUser.getAuthorities()) {
        authoritiesNames.add(authority.getAuthority());
    }

    return CollectionUtils.containsAny(configuration.getRsbSecurityConfiguration().getAdminRoles(),
            authoritiesNames);
}

From source file:org.georchestra.security.SecurityRequestHeaderProvider.java

@Override
protected Collection<Header> getCustomRequestHeaders(HttpSession session, HttpServletRequest originalRequest) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    List<Header> headers = new ArrayList<Header>();
    if (authentication.getName().equals("anonymousUser"))
        return headers;
    headers.add(new BasicHeader(HeaderNames.SEC_USERNAME, authentication.getName()));
    StringBuilder roles = new StringBuilder();
    for (GrantedAuthority grantedAuthority : authorities) {
        if (roles.length() != 0)
            roles.append(";");

        roles.append(grantedAuthority.getAuthority());
    }/*from  w w w .jav a 2s . c om*/
    headers.add(new BasicHeader(HeaderNames.SEC_ROLES, roles.toString()));

    return headers;
}

From source file:gov.nih.nci.cacisweb.user.CacisUserService.java

public void updateUser(CacisUser cacisUser) throws UsernameNotFoundException {
    try {//from  www.  java 2  s. co m
        log.debug("Updating user...");
        String userProperty = CaCISUtil.getProperty(cacisUser.getUsername());
        if (userProperty == null) {
            log.error("User Not Found");
            throw new UsernameNotFoundException("User Not Found");
        }
        String userPropertyValue = cacisUser.getPassword() + "," + cacisUser.isAccountNonLocked() + ","
                + cacisUser.getFailedLoginAttempts() + "," + cacisUser.getLockOutTime() + ",";
        for (GrantedAuthority grantedAuthority : cacisUser.getAuthorities()) {
            userPropertyValue += grantedAuthority.getAuthority() + ",";
        }
        userPropertyValue = StringUtils.removeEnd(userPropertyValue, ",");
        log.debug("New User Property Value: " + userPropertyValue);
        CaCISUtil.setProperty(cacisUser.getUsername(), userPropertyValue);
    } catch (CaCISWebException e) {
        log.error("User update failed: " + e.getMessage());
        throw new UsernameNotFoundException("User update failed: " + e.getMessage());
    }
}