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.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   www .  j a  va  2 s.c o 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:net.maritimecloud.identityregistry.security.x509.X509HeaderUserDetailsService.java

@Override
public UserDetails loadUserByUsername(String certificateHeader) throws UsernameNotFoundException {
    if (certificateHeader == null || certificateHeader.length() < 10) {
        logger.warn("No certificate header found");
        throw new UsernameNotFoundException("No certificate header found");
    }//  w  ww .jav a2s  .co  m
    X509Certificate userCertificate = certUtil.getCertFromString(certificateHeader);
    if (userCertificate == null) {
        logger.error("Extracting certificate from header failed");
        throw new UsernameNotFoundException("Extracting certificate from header failed");
    }

    // Actually authenticate certificate against root cert.
    if (!certUtil.verifyCertificate(userCertificate)) {
        logger.warn("Certificate could not be verified");
        throw new UsernameNotFoundException("Certificate could not be verified");
    }
    // Check that the certificate has not been revoked
    long certId = userCertificate.getSerialNumber().longValue();
    Certificate cert = certificateService.getCertificateById(certId);
    if (cert.isRevoked()) {
        Calendar cal = Calendar.getInstance();
        Date now = cal.getTime();
        if (cert.getRevokedAt() == null || cert.getRevokedAt().before(now)) {
            logger.warn("The certificate has been revoked! Cert #" + certId);
            throw new UsernameNotFoundException("The certificate has been revoked! Cert #" + certId);
        }
    }
    // Get user details from the certificate
    UserDetails user = certUtil.getUserFromCert(userCertificate);
    if (user == null) {
        logger.warn("Extraction of data from the certificate failed");
        throw new UsernameNotFoundException("Extraction of data from the client certificate failed");
    }
    // Convert the permissions extracted from the certificate to authorities in this API
    InetOrgPerson person = ((InetOrgPerson) user);
    String certOrg = person.getO();
    Organization org = organizationService.getOrganizationByMrn(certOrg);
    if (org == null) {
        logger.warn("Unknown Organization '" + certOrg + "' in client certificate");
        throw new UsernameNotFoundException("Unknown Organization in client certificate");
    }
    Collection<GrantedAuthority> newRoles = new ArrayList<>();
    logger.debug("Looking up roles");
    for (GrantedAuthority role : user.getAuthorities()) {
        logger.debug("Looking up roles");
        String auth = role.getAuthority();
        String[] auths = auth.split(",");
        for (String auth2 : auths) {
            logger.debug("Looking up role: " + auth2);
            List<Role> foundRoles = roleService.getRolesByIdOrganizationAndPermission(org.getId(), auth2);
            if (foundRoles != null) {
                for (Role foundRole : foundRoles) {
                    newRoles.add(new SimpleGrantedAuthority(foundRole.getRoleName()));
                }
            }
        }
    }
    // Add ROLE_USER as standard for authenticated users with no other role.
    if (newRoles.isEmpty()) {
        newRoles.add(new SimpleGrantedAuthority("ROLE_USER"));
    }
    InetOrgPerson.Essence essence = new InetOrgPerson.Essence((InetOrgPerson) user);
    essence.setAuthorities(newRoles);
    return essence.createUserDetails();
}

From source file:de.topicmapslab.majortom.server.security.MTSUserDetail.java

/**
 * Helper method for the UI/*w  ww . j  ava  2s  .  c  om*/
 * 
 * @return the plainAuthorities
 */
public List<String> getPlainAuthorities() {
    ArrayList<String> tmp = new ArrayList<String>();
    if (authorities != null) {
        for (GrantedAuthority a : getAuthorities()) {
            tmp.add(a.getAuthority());
        }
    }
    return tmp;
}

From source file:fr.xebia.springframework.security.core.userdetails.memory.ExtendedUserMapBuilderTest.java

@Test
public void testExtractExtendedUser() throws Exception {

    for (int i = 0; i < TC0.length; i++) {
        List<String> authorities = new ArrayList<String>();
        StringTokenizer tokenizer = new StringTokenizer(TC0[i][1], ",");
        while (tokenizer.hasMoreTokens()) {
            authorities.add(tokenizer.nextToken().trim());
        }//from  w ww .  j  a va2 s  .  c om

        String properties = assembleTestCases(TC0[i]);
        ExtendedUser user = ExtendedUserMapBuilder.buildExtendedUser(properties);
        assertNotNull(String.format("user is null (%s)", properties), user);
        assertEquals(String.format("username incorrect (%s)", properties), "bob", user.getUsername());
        assertEquals(String.format("password incorrect (%s)", properties), "password", user.getPassword());
        assertEquals(String.format("enabled parameter incorrect (%s)", properties), !DISABLED.equals(TC0[i][3]),
                user.isEnabled());
        assertEquals(String.format("incorrect number of authorities (%s)", properties), authorities.size(),
                user.getAuthorities().size());
        for (GrantedAuthority authority : user.getAuthorities()) {
            assertTrue(String.format("unexpected authority (%s) : %s", properties, authority.getAuthority()),
                    authorities.contains(authority.getAuthority()));
        }
        assertEquals(String.format("IP addresses incorrect (%s)", properties), TC0[i][2],
                user.getAllowedRemoteAddresses());
    }
}

From source file:eu.trentorise.smartcampus.permissionprovider.oauth.ClientCredentialsFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
    String clientId = request.getParameter("client_id");
    String clientSecret = request.getParameter("client_secret");

    // If the request is already authenticated we can assume that this filter is not needed
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.isAuthenticated()) {
        return authentication;
    }//from  w  w  w . ja  v a 2s  .c  o m

    if (clientId == null) {
        throw new BadCredentialsException("No client credentials presented");
    }

    if (clientSecret == null) {
        clientSecret = "";
    }

    clientId = clientId.trim();

    //      UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId, clientSecret);
    ClientDetailsEntity clientDetails = clientDetailsRepository.findByClientId(clientId);
    boolean isTrusted = false;
    if (clientDetails.getAuthorities() != null) {
        for (GrantedAuthority ga : clientDetails.getAuthorities())
            if (Config.AUTHORITY.ROLE_CLIENT_TRUSTED.toString().equals(ga.getAuthority())) {
                isTrusted = true;
                break;
            }
    }
    if (!isTrusted) {
        throw new InvalidGrantException("Unauthorized client access by client " + clientId);
    }

    String clientSecretServer = clientDetails.getClientSecret();
    ClientAppInfo info = ClientAppInfo.convert(clientDetails.getAdditionalInformation());
    String clientSecretMobile = clientDetails.getClientSecretMobile();
    if (clientSecretMobile.equals(clientSecret) && !info.isNativeAppsAccess()) {
        throw new InvalidGrantException("Native app access is not enabled");
    }

    if (!clientSecretServer.equals(clientSecret) && !clientSecretMobile.equals(clientSecret)) {
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }

    User user = new User(clientId, clientSecret, clientDetails.getAuthorities());

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(user,
            clientSecretServer, user.getAuthorities());
    //        result.setDetails(authRequest.getDetails());
    return result;
}

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();/*from   ww  w .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.openinfinity.sso.identityprovisioning.bpmn.IdentityProvisioningBridgeSpringActivitiImpl.java

private void addGrantedAuthoritiesAsRolesAndCreateMembershipWithUserAndGroup(IdentityService identityService,
        String userId, Collection<? extends GrantedAuthority> grantedAuthorities,
        Set<String> existiningGroupsFromMasterData) {
    for (GrantedAuthority grantedAuthority : grantedAuthorities) {
        Long countForGrantedAuthority = identityService.createGroupQuery()
                .groupId(grantedAuthority.getAuthority()).count();
        if (countForGrantedAuthority == 0) {
            LOGGER.debug("Provisioning of new role started [" + grantedAuthority.getAuthority() + "]");
            long startTime = System.currentTimeMillis();
            Group activitiGroup = identityService.newGroup(grantedAuthority.getAuthority());
            identityService.saveGroup(activitiGroup);
            identityService.createMembership(userId, activitiGroup.getId());
            existiningGroupsFromMasterData.add(activitiGroup.getName());
            LOGGER.debug("Role provisioning and membership creation finalized in "
                    + (System.currentTimeMillis() - startTime) + " ms to Activiti BPMN 2.0 engine.");
        }/*w  ww  .  java2 s  .  c om*/
    }
}

From source file:nu.localhost.tapestry5.springsecurity.components.IfRole.java

private Collection<GrantedAuthority> authoritiesToRoles(Collection<GrantedAuthority> c) {
    Collection<GrantedAuthority> target = new ArrayList<GrantedAuthority>();

    for (final GrantedAuthority authority : c) {

        if (null == authority.getAuthority()) {
            throw new IllegalArgumentException(
                    "Cannot process GrantedAuthority objects which return null from getAuthority() - attempting to process "
                            + authority.toString());
        }/*from   w w  w.j  a  v a 2 s .  co m*/

        target.add(authority);
    }

    return target;
}

From source file:py.una.pol.karaku.security.KarakuUserService.java

/**
 * Localiza al usuario basndose en el nombre del usuario.
 * //from   w  ww .  jav  a  2 s  .co m
 * @param username
 *            el nombre del usuario que identifica al usuario cuyos datos se
 *            requiere.
 * @return la informacin del usuario.
 */
@Override
public UserDetails loadUserByUsername(String uid) {

    KarakuUser user = new KarakuUser();
    user.setUserName(uid);
    user.addRoles(loadAuthoritiesByDn(uid));

    String permiso = propertiesUtil.get(BASIC_PERMISSION_KEY, BASIC_PERMISSION_KEY_DEFAULT);

    boolean allow = false;
    for (GrantedAuthority o : user.getAuthorities()) {
        if (o.getAuthority().equals(permiso)) {
            allow = true;
        }
    }
    if (!allow) {
        throw new InsufficientAuthenticationException("No posee privilegios para este sistema");
    }
    return user;
}

From source file:org.saiku.web.impl.SecurityAwareConnectionManager.java

private List<String> getSpringRoles() {
    List<String> roles = new ArrayList<String>();
    if (SecurityContextHolder.getContext() != null
            && SecurityContextHolder.getContext().getAuthentication() != null) {
        Collection<GrantedAuthority> auths = SecurityContextHolder.getContext().getAuthentication()
                .getAuthorities();/*from   w ww .j a v a 2  s . c  o m*/
        for (GrantedAuthority a : auths) {
            roles.add(a.getAuthority());
        }
    }
    return roles;
}