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:org.apache.coheigea.cxf.spring.security.authentication.SpringSecurityUTValidator.java

public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    if (credential == null || credential.getUsernametoken() == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential");
    }//from w w w .  j  av  a 2s  . co m

    // Validate the UsernameToken
    UsernameToken usernameToken = credential.getUsernametoken();
    String pwType = usernameToken.getPasswordType();
    if (log.isDebugEnabled()) {
        log.debug("UsernameToken user " + usernameToken.getName());
        log.debug("UsernameToken password type " + pwType);
    }
    if (!WSConstants.PASSWORD_TEXT.equals(pwType)) {
        if (log.isDebugEnabled()) {
            log.debug("Authentication failed - digest passwords are not accepted");
        }
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }
    if (usernameToken.getPassword() == null) {
        if (log.isDebugEnabled()) {
            log.debug("Authentication failed - no password was provided");
        }
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }

    // Validate it via Spring Security

    // Set a Subject up
    UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
            usernameToken.getName(), usernameToken.getPassword());
    Subject subject = new Subject();
    subject.getPrincipals().add(authToken);

    Set<Authentication> authentications = subject.getPrincipals(Authentication.class);
    Authentication authenticated = null;
    try {
        authenticated = authenticationManager.authenticate(authentications.iterator().next());
    } catch (AuthenticationException ex) {
        if (log.isDebugEnabled()) {
            log.debug(ex.getMessage(), ex);
        }
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }

    if (!authenticated.isAuthenticated()) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }

    for (GrantedAuthority authz : authenticated.getAuthorities()) {
        System.out.println("Granted: " + authz.getAuthority());
    }

    // Authorize request
    if (accessDecisionManager != null && !requiredRoles.isEmpty()) {
        List<ConfigAttribute> attributes = SecurityConfig
                .createList(requiredRoles.toArray(new String[requiredRoles.size()]));
        for (ConfigAttribute attr : attributes) {
            System.out.println("Attr: " + attr.getAttribute());
        }
        accessDecisionManager.decide(authenticated, this, attributes);
    }

    credential.setSubject(subject);
    return credential;
}

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:edu.zipcloud.cloudstreetmarket.core.authentication.CustomOAuth2RequestFilter.java

private boolean authenticationIsRequired(String username) {
    // Only reauthenticate if username doesn't match SecurityContextHolder and user
    // isn't authenticated
    // (see SEC-53)
    Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();

    if (existingAuth == null || !existingAuth.isAuthenticated()) {
        return true;
    }//from   w ww  .  ja  va 2  s. c  o m

    // Limit username comparison to providers which use usernames (ie
    // UsernamePasswordAuthenticationToken)
    // (see SEC-348)

    if (existingAuth instanceof UsernamePasswordAuthenticationToken
            && !existingAuth.getName().equals(username)) {
        return true;
    }

    if (!UserDetailsUtil.hasRole(existingAuth.getAuthorities(), ROLE_OAUTH2)) {
        return true;
    }

    // Handle unusual condition where an AnonymousAuthenticationToken is already
    // present
    // This shouldn't happen very often, as BasicProcessingFitler is meant to be
    // earlier in the filter
    // chain than AnonymousAuthenticationFilter. Nevertheless, presence of both an
    // AnonymousAuthenticationToken
    // together with a BASIC authentication request header should indicate
    // reauthentication using the
    // BASIC protocol is desirable. This behaviour is also consistent with that
    // provided by form and digest,
    // both of which force re-authentication if the respective header is detected (and
    // in doing so replace
    // any existing AnonymousAuthenticationToken). See SEC-610.
    if (existingAuth instanceof AnonymousAuthenticationToken) {
        return true;
    }

    return false;
}

From source file:org.xaloon.wicket.security.spring.SpringSecurityFacade.java

private AuthenticationToken authenticateInternal(AbstractAuthenticationToken authenticationRequestToken) {
    boolean authenticated = false;
    String name = authenticationRequestToken.getName();
    String errorMessage = null;//from   w  ww .j  a v a 2  s.co m
    try {
        Authentication authentication = authenticationManager.authenticate(authenticationRequestToken);
        authenticated = authentication.isAuthenticated();
        if (authenticated && authentication.getDetails() == null) {
            // Try to load user details. Copy information into new token
            UsernamePasswordAuthenticationToken authenticationWithDetails = new UsernamePasswordAuthenticationToken(
                    authentication.getPrincipal(), authentication.getCredentials(),
                    authentication.getAuthorities());
            authenticationWithDetails.setDetails(userDao.getUserByUsername(authentication.getName()));
            authentication = authenticationWithDetails;
        }
        SecurityContextHolder.getContext().setAuthentication(authentication);
        name = authentication.getName();
    } catch (AuthenticationException e) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("User " + name + " failed to login. Reason: ", e);
        }
        authenticated = false;
        errorMessage = e.getMessage();
    }
    if (authenticated) {
        return new AuthenticationToken(name, new ArrayList<AuthenticationAttribute>());
    }
    return new AuthenticationToken(name, errorMessage);
}

From source file:cn.net.withub.demo.bootsec.hello.security.CustomAccessDecisionManager.java

@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {
    if (configAttributes == null) {
        //??//from  w w w .  j  a va  2s  .  co  m
        throw new AccessDeniedException("Access Dendied");
    }

    //???(???)
    for (ConfigAttribute configAttribute : configAttributes) {
        //????
        String needPermission = configAttribute.getAttribute();

        System.out.println("needPermission is " + needPermission);

        //??authentication
        for (GrantedAuthority ga : authentication.getAuthorities()) {

            if (needPermission.equals(ga.getAuthority())) {
                return;
            }

        }

    }

    //??
    throw new AccessDeniedException("Access Dendied");
    //throw new InsufficientAuthenticationException("???");
}

From source file:info.fcrp.keepitsafe.security.KeepRoleEvaluator.java

private boolean checkRole(RoleMap roleMap, Authentication authentication, Object permission) {

    String[] roles = null;//from   w w w  .  j  a v  a 2 s. c o m
    if ("king".equals(permission)) {
        if (roleMap.getKing() != null) {
            roles = roleMap.getKing().split(";");
        }
    } else if ("commoner".equals(permission)) {
        if (roleMap.getCommoner() != null) {
            roles = roleMap.getCommoner().split(";");
        }
    }

    for (String role : roles) {
        if (role.startsWith("user:")) {
            User user = (User) authentication.getPrincipal();
            if (role.replaceFirst("user:", "").equals(user.getUsername())) {
                return true;
            }
        } else if (authentication.getAuthorities().contains(role)) {
            return true;
        }
    }

    return false;
}

From source file:it.geosolutions.geostore.services.rest.SecurityTest.java

protected void springAuthenticationTest() {
    doAutoLogin("admin", "admin", null);

    assertNotNull(SecurityContextHolder.getContext());
    assertNotNull(SecurityContextHolder.getContext().getAuthentication());

    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    authentication.getName();//w  ww  .j  a  v  a  2 s. c om

    assertEquals("admin", authentication.getCredentials());

    Object principal = authentication.getPrincipal();
    assertNotNull(principal);

    if (principal instanceof User) {
        User user = (User) principal;

        assertEquals("admin", user.getName());
    } else if (principal instanceof LdapUserDetailsImpl) {
        LdapUserDetailsImpl userDetails = (LdapUserDetailsImpl) principal;

        assertEquals("uid=admin,ou=people,dc=geosolutions,dc=it", userDetails.getDn());
    }

    assertEquals(authentication.getAuthorities().size(), 1);

    for (GrantedAuthority authority : authentication.getAuthorities()) {
        assertEquals("ROLE_ADMIN", authority.getAuthority());
    }

}

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

private Authentication createAuthentication(Long userId, Role role) {
    Authentication auth = EasyMock.createMock("Authentication", Authentication.class);
    DuracloudUser user = new DuracloudUser();
    user.setId(userId);//  w  ww .  j av  a 2 s.  c  om
    user.setUsername("username");
    user.setPassword("password");
    user.setFirstName("firstName");
    user.setLastName("lastName");
    user.setEmail("email");
    user.setSecurityQuestion("question");
    user.setSecurityAnswer("answer");
    EasyMock.expect(auth.getPrincipal()).andReturn(user);

    Collection<GrantedAuthority> userRoles = new HashSet<GrantedAuthority>();
    userRoles.add(new SimpleGrantedAuthority(role.name()));
    EasyMock.expect(auth.getAuthorities()).andReturn((Collection) userRoles);

    return auth;
}

From source file:se.kth.csc.auth.UserService.java

@Transactional
@Override/*from  w w  w .  java2s. c om*/
public UserDetails loadUserDetails(Authentication token) throws UsernameNotFoundException {
    if (!token.getName().startsWith("u1")) {
        // See http://intra.kth.se/it/driftsinformation-webbtjanster/anstallda/inloggning-maste-ske-med-sma-bokstaver-1.475521
        // which allows an exploit. Counter-measured by only allowing usernames starting with "u1"
        throw new UsernameNotFoundException("This username is not in the u1 realm and was probably forged");
    }

    Account account = accountStore.fetchAccountWithPrincipalName(token.getName());

    if (account == null) {
        account = new Account();
        account.setPrincipalName(token.getName());
        for (GrantedAuthority grantedAuthority : token.getAuthorities()) {
            if (Role.ADMIN.getAuthority().equals(grantedAuthority.getAuthority())) {
                account.setAdmin(true);
                break;
            }
        }
        accountStore.storeAccount(account);

        log.info("Created user called \"{}\" with id {} and principal {}", account.getName(), account.getId(),
                account.getPrincipalName());
    }
    String name = nameService.nameUser(token.getName());

    if (account.getName() == null || !account.getName().equals(name)) {
        account.setName(name);
        log.info("User with id {} and principal {} is now called \"{}\"", account.getId(),
                account.getPrincipalName(), name);
    }

    return createUser(account);
}