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:com.googlecode.fascinator.portal.security.FascinatorWebSecurityExpressionRoot.java

/**
 * Check whether user has the correct role to edit
 *///from www . j a  v a2 s  . c om
public boolean isInAllowedRoles(String oid) {
    List<String> allowedRoles;
    try {
        allowedRoles = accessControl.getRoles(oid);
        if (allowedRoles != null) {
            Collection<GrantedAuthority> userRoles = authentication.getAuthorities();
            for (GrantedAuthority grantedAuthority : userRoles) {
                if (allowedRoles.contains(grantedAuthority.getAuthority())) {
                    return true;
                }
            }
        }
    } catch (Exception e) {
        log.error("Failed to check allowed roles", e);
    }
    return false;
}

From source file:it.geosolutions.geoserver.sira.security.config.Rule.java

/**
 * Checks if the rule applies to at least one of the roles granted to the user.
 *
 * @param user the user accessing the resource
 * @return {@code true} if the rule applies to this user (based on granted roles), {@code false} otherwise
 *//*w  w w .  j av a  2 s.com*/
public boolean matchRole(Authentication user) {
    if (this.matchesAnyRole()) {
        return true;
    }

    final Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
    // should never be null, but you never know...
    if (authorities != null) {
        for (final GrantedAuthority authority : authorities) {
            final String role = authority.getAuthority();
            if (role != null && this.getRoles().contains(role)) {
                return true;
            }
        }
    }

    return false;
}

From source file:org.dawnsci.marketplace.services.MarketplaceDAO.java

/**
 * Tests whether or not the current user have access to edit the solution
 * with the given identifier. The user must be an administrator or own the
 * solution.//from ww  w . jav a 2  s. c o m
 *
 * @param identifier
 *            the identifier of the solution
 * @return <code>true</code> if editable
 */
public boolean canEdit(Long identifier) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
        return false;
    }
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    for (GrantedAuthority grantedAuthority : authorities) {
        if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
            return true;
        }
    }
    // new solution
    if (identifier == null) {
        return true;
    }
    Account account = accountRepository.findOne(authentication.getName());
    Account a = accountRepository.findAccountBySolutionId(identifier);
    if (account.getUsername().equals(a.getUsername())) {
        return true;
    }
    return false;
}

From source file:org.opendatakit.security.server.SecurityServiceUtil.java

public static void setAuthenticationListsForSpecialUser(UserSecurityInfo userInfo,
        GrantedAuthorityName specialGroup, CallingContext cc) throws DatastoreFailureException {
    RoleHierarchy hierarchy = (RoleHierarchy) cc.getHierarchicalRoleRelationships();
    Set<GrantedAuthority> badGrants = new TreeSet<GrantedAuthority>();
    // The assigned groups are the specialGroup that this user defines
    // (i.e., anonymous or daemon) plus all directly-assigned assignable
    // permissions.
    TreeSet<GrantedAuthorityName> groups = new TreeSet<GrantedAuthorityName>();
    TreeSet<GrantedAuthorityName> authorities = new TreeSet<GrantedAuthorityName>();
    groups.add(specialGroup);//from   w  ww .  j  a  va  2  s.com
    GrantedAuthority specialAuth = new SimpleGrantedAuthority(specialGroup.name());
    try {
        Set<GrantedAuthority> auths = GrantedAuthorityHierarchyTable
                .getSubordinateGrantedAuthorities(specialAuth, cc);
        for (GrantedAuthority auth : auths) {
            GrantedAuthorityName name = mapName(auth, badGrants);
            if (name != null) {
                groups.add(name);
            }
        }
    } catch (ODKDatastoreException e) {
        e.printStackTrace();
        throw new DatastoreFailureException("Unable to retrieve granted authorities of " + specialGroup.name());
    }

    Collection<? extends GrantedAuthority> auths = hierarchy
            .getReachableGrantedAuthorities(Collections.singletonList(specialAuth));
    for (GrantedAuthority auth : auths) {
        GrantedAuthorityName name = mapName(auth, badGrants);
        if (name != null && !GrantedAuthorityName.permissionsCanBeAssigned(auth.getAuthority())) {
            authorities.add(name);
        }
    }
    userInfo.setAssignedUserGroups(groups);
    userInfo.setGrantedAuthorities(authorities);
    try {
        removeBadGrantedAuthorities(badGrants, cc);
    } catch (ODKDatastoreException e) {
        e.printStackTrace();
    }
}

From source file:de.uni_koeln.spinfo.maalr.webapp.controller.WebMVCController.java

@RequestMapping(value = "/persona/login", method = RequestMethod.POST)
@ResponseBody// www.  jav a  2 s. c o  m
public String authenticateWithPersona(@RequestParam String assertion, HttpServletRequest request, Model model)
        throws IOException {

    String contextPath = Configuration.getInstance().getDictContext();

    if (SecurityContextHolder.getContext().getAuthentication() != null) {
        if (!SecurityContextHolder.getContext().getAuthentication().getName().equals("anonymousUser")) {
            Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext()
                    .getAuthentication().getAuthorities();
            for (GrantedAuthority grantedAuthority : authorities) {
                logger.info("GrantedAuthority: " + grantedAuthority.getAuthority());
                if (grantedAuthority.getAuthority().equals("ROLE_ADMIN"))
                    return contextPath + "/admin/admin";
                if (grantedAuthority.getAuthority().equals("ROLE_TRUSTED_IN"))
                    return contextPath + "/editor/editor";
                return contextPath;
            }
        }
    }

    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.add("assertion", assertion);
    params.add("audience", request.getScheme() + "://" + request.getServerName() + ":"
            + (request.getServerPort() == 80 ? "" : request.getServerPort()));

    // Initialize RestTamplate
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

    PersonaVerificationResponse response = restTemplate.postForObject(
            "https://verifier.login.persona.org/verify", params, PersonaVerificationResponse.class);

    logger.info("PersonaAuth: PersonaVerificationResponse={}", response.toString());

    if (response.getStatus().equals("okay")) {
        request.getSession().setMaxInactiveInterval(30 * 60); // Set session timeout to 30 minutes
        MaalrUserInfo user = users.getByEmail(response.getEmail());
        if (user == null) {
            user = register(response);
            logger.info("PersonaAuth: signed up new user for email={}", user.getEmail());
            authUser(user);
            return contextPath;
        } else {
            logger.info("PersonaAuth: user found by email={}", user.getEmail());
            authUser(user);
            return contextPath;
        }
    } else {
        logger.warn("Persona authentication failed due to reason: " + response.getReason());
        throw new IllegalStateException("Authentication failed");
    }
}

From source file:com.bac.accountserviceapp.data.AccountServiceUserDetailsTest.java

@Test
public void testGetAuthorities_TwoValidAuthorities() {

    logger.info("testGetAuthorities_TwoValidAuthorities");
    ////from  w  w w  .  j ava  2  s . c  o  m
    //  Valid authority 1
    //
    String expApplicationName1 = UUID.randomUUID().toString();
    Integer expAccessLevelId1 = new Double(Math.random()).intValue();
    String expAuthority1 = expApplicationName1 + authoritySeparator + accessLevelRole.name();
    Application application1 = getApplication(expApplicationName1, true);
    //        AccountUser accountUser1 = getAccountUser(expAccessLevelId1, true);
    AccessLevel accessLevel1 = getAccessLevel(expAccessLevelId1);
    userDetailsAuthorities.add(new UserDetailsAuthority(application1, accessLevel1));
    //
    //  Valid authority 2
    //
    String expApplicationName2 = UUID.randomUUID().toString();
    Integer expAccessLevelId2 = new Double(Math.random()).intValue();
    String expAuthority2 = expApplicationName2 + authoritySeparator + ADMIN.name();
    Application application2 = getApplication(expApplicationName2, true);
    //       AccountUser accountUser2 = getAccountUser(expAccessLevelId2, true);
    AccessLevel accessLevel2 = getAccessLevel(expAccessLevelId2);
    when(accessLevel2.getAccountServiceRole()).thenReturn(ADMIN);
    userDetailsAuthorities.add(new UserDetailsAuthority(application2, accessLevel2));

    instance = new AccountServiceUserDetails(null, userDetailsAuthorities);
    Collection<? extends GrantedAuthority> result = instance.getAuthorities();
    assertNotNull(result);
    assertTrue(result instanceof Set<?>);
    int expSize = 2;
    int resultSize = result.size();
    assertEquals(expSize, resultSize);
    //
    //
    //
    String[] authorities = new String[expSize];
    int index = 0;
    for (GrantedAuthority authority : result) {
        authorities[index++] = authority.getAuthority();
    }
    List<String> authoritiesList = Arrays.asList(authorities);
    assertTrue(authoritiesList.contains(expAuthority1));
    assertTrue(authoritiesList.contains(expAuthority2));
}

From source file:org.schedoscope.metascope.service.MetascopeUserService.java

public boolean isAdmin() {
    if (getUser().isAdmin()) {
        return true;
    }/* ww w .  j  av a  2  s  . c om*/

    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    if (principal instanceof LdapUserDetailsImpl) {
        LdapUserDetailsImpl ldapUser = (LdapUserDetailsImpl) principal;
        for (GrantedAuthority authoritiy : ldapUser.getAuthorities()) {
            for (String adminGroup : config.getAdminGroups().split(",")) {
                String role = "ROLE_" + adminGroup.toUpperCase();
                if (authoritiy.getAuthority().equalsIgnoreCase(role)) {
                    return true;
                }
            }
        }
    }

    return false;
}

From source file:com.bac.accountserviceapp.data.AccountServiceUserDetailsTest.java

@Test
public void testGetAuthorities_OneValidAuthority() {

    logger.info("testGetAuthorities_OneValidAuthority");
    //// w w w.j  av a 2  s  .  com
    //  
    //
    String expApplicationName = UUID.randomUUID().toString();
    Integer expAccessLevelId = new Double(Math.random()).intValue();
    String expAuthority = expApplicationName + authoritySeparator + accessLevelRole.name();
    Application application = getApplication(expApplicationName, true);
    //       AccountUser accountUser = getAccountUser(expAccessLevelId, true);
    AccessLevel accessLevel = getAccessLevel(expAccessLevelId);
    userDetailsAuthorities.add(new UserDetailsAuthority(application, accessLevel));

    instance = new AccountServiceUserDetails(null, userDetailsAuthorities);
    Collection<? extends GrantedAuthority> result = instance.getAuthorities();
    assertNotNull(result);
    assertTrue(result instanceof Set<?>);
    int expSize = 1;
    int resultSize = result.size();
    assertEquals(expSize, resultSize);
    //
    //
    //
    GrantedAuthority grantedAuthority0 = (GrantedAuthority) result.toArray()[0];
    String resultAuthority = grantedAuthority0.getAuthority();
    assertEquals(expAuthority, resultAuthority);
}

From source file:com.bac.accountserviceapp.data.AccountServiceUserDetailsTest.java

@Test
public void testGetAuthorities_OneValidOneInvalidAuthority() {

    logger.info("testGetAuthorities_OneValidOneInvalidAuthority");
    //// ww  w  .  ja v  a  2s  .c o m
    //  Valid authority
    //
    String expApplicationName = UUID.randomUUID().toString();
    Integer expAccessLevelId = new Double(Math.random()).intValue();
    String expAuthority = expApplicationName + authoritySeparator + accessLevelRole.name();
    Application application = getApplication(expApplicationName, true);
    //       AccountUser accountUser = getAccountUser(expAccessLevelId, true);
    AccessLevel accessLevel = getAccessLevel(expAccessLevelId);
    userDetailsAuthorities.add(new UserDetailsAuthority(application, accessLevel));
    //
    //  Invalid authority
    //
    application = getApplication(UUID.randomUUID().toString(), false);
    //       accountUser = getAccountUser(new Double(Math.random()).intValue(), false);
    accessLevel = getAccessLevel(expAccessLevelId);
    userDetailsAuthorities.add(new UserDetailsAuthority(application, accessLevel));

    instance = new AccountServiceUserDetails(null, userDetailsAuthorities);
    Collection<? extends GrantedAuthority> result = instance.getAuthorities();
    assertNotNull(result);
    assertTrue(result instanceof Set<?>);
    int expSize = 1;
    int resultSize = result.size();
    assertEquals(expSize, resultSize);
    //
    //
    //
    GrantedAuthority grantedAuthority0 = (GrantedAuthority) result.toArray()[0];
    String resultAuthority = grantedAuthority0.getAuthority();
    assertEquals(expAuthority, resultAuthority);
}