Example usage for org.springframework.security.openid OpenIDAttribute getValues

List of usage examples for org.springframework.security.openid OpenIDAttribute getValues

Introduction

In this page you can find the example usage for org.springframework.security.openid OpenIDAttribute getValues.

Prototype

public List<String> getValues() 

Source Link

Document

The values obtained from an attribute exchange.

Usage

From source file:com.wisemapping.security.UserDetailsService.java

@NotNull
private User buildUserFromToken(@NotNull OpenIDAuthenticationToken token) {
    final User result = new User();

    String lastName = null;//from ww  w  . ja  va  2  s. c  o m
    String firstName = null;
    String email = null;
    String fullName = null;

    final List<OpenIDAttribute> attributes = token.getAttributes();
    for (OpenIDAttribute attribute : attributes) {
        if (attribute.getName().equals("email")) {
            email = attribute.getValues().get(0);
        }

        if (attribute.getName().equals("firstname")) {
            firstName = attribute.getValues().get(0);

        }

        if (attribute.getName().equals("lastname")) {
            lastName = attribute.getValues().get(0);
        }

        if (attribute.getName().equals("fullname")) {
            fullName = attribute.getValues().get(0);
        }

    }
    if (lastName == null || firstName == null) {
        result.setFirstname(fullName);
        result.setLastname("");
    } else {
        result.setLastname(lastName);
        result.setFirstname(firstName);
    }
    result.setEmail(email);
    result.setPassword("");

    final Calendar now = Calendar.getInstance();
    result.setActivationDate(now);
    return result;
}

From source file:net.triptech.buildulator.service.OpenIdAuthenticationFailureHandler.java

/**
 * Creates the person object based on the supplied OpenID attributes.
 *
 * @param token the token/*  w  ww. j a v  a2  s  . co m*/
 * @return the person
 */
private Person createPerson(final OpenIDAuthenticationToken token) {

    Person person = new Person();

    // The person does not exist, create
    String email = null;
    String firstName = null;
    String lastName = null;

    String id = token.getIdentityUrl();
    List<OpenIDAttribute> attributes = token.getAttributes();

    for (OpenIDAttribute attribute : attributes) {
        if (attribute.getName().equals("email")) {
            email = attribute.getValues().get(0);
        }
        if (attribute.getName().equals("firstName")) {
            firstName = attribute.getValues().get(0);
        }
        if (attribute.getName().equals("lastName")) {
            lastName = attribute.getValues().get(0);
        }
    }

    if (StringUtils.isBlank(email)) {
        Random generator = new Random();
        email = String.valueOf(generator.nextInt()) + "@"
                + String.valueOf(Calendar.getInstance().getTimeInMillis());
    }
    if (StringUtils.isBlank(firstName)) {
        firstName = "New";
    }
    if (StringUtils.isBlank(lastName)) {
        lastName = "User";
    }

    UserRole role = UserRole.ROLE_USER;
    if (Person.countPeople() == 0) {
        role = UserRole.ROLE_ADMIN;
    }

    person = new Person();
    person.setOpenIdIdentifier(id);

    person.setEmailAddress(email);
    person.setFirstName(firstName);
    person.setLastName(lastName);
    person.setUserRole(role);
    person.setUserStatus(UserStatus.ACTIVE);

    person.persist();

    return person;
}

From source file:net.triptech.metahive.service.OpenIdAuthenticationFailureHandler.java

/**
 * Creates the person object based on the supplied OpenID attributes.
 *
 * @param token the token/*from ww w.ja v  a  2 s .com*/
 * @return the person
 */
private Person createPerson(final OpenIDAuthenticationToken token) {

    Person person = new Person();

    // The person does not exist, create
    String email = null;
    String firstName = null;
    String lastName = null;

    String id = token.getIdentityUrl();
    List<OpenIDAttribute> attributes = token.getAttributes();

    for (OpenIDAttribute attribute : attributes) {
        if (attribute.getName().equals("email")) {
            email = attribute.getValues().get(0);
        }
        if (attribute.getName().equals("firstName")) {
            firstName = attribute.getValues().get(0);
        }
        if (attribute.getName().equals("lastName")) {
            lastName = attribute.getValues().get(0);
        }
    }

    if (StringUtils.isBlank(email)) {
        Random generator = new Random();
        email = String.valueOf(generator.nextInt()) + "@"
                + String.valueOf(Calendar.getInstance().getTimeInMillis());
    }
    if (StringUtils.isBlank(firstName)) {
        firstName = "New";
    }
    if (StringUtils.isBlank(lastName)) {
        lastName = "User";
    }

    person = new Person();
    person.setOpenIdIdentifier(id);

    person.setEmailAddress(email);
    person.setFirstName(firstName);
    person.setLastName(lastName);
    person.setUserRole(UserRole.ROLE_USER);
    person.setUserStatus(UserStatus.ACTIVE);

    person.persist();

    sendNotificationEmail(person);

    return person;
}

From source file:net.firejack.platform.web.security.spring.openid.OpenIDAuthenticationManager.java

private Map<SupportedOpenIDAttribute, String> findAttributeValues(List<OpenIDAttribute> attributes) {
    Map<SupportedOpenIDAttribute, String> values = new HashMap<SupportedOpenIDAttribute, String>();
    for (OpenIDAttribute attribute : attributes) {
        String name = attribute.getName();
        SupportedOpenIDAttribute supportedOpenIDAttribute = SupportedOpenIDAttribute
                .lookForSupportedAttribute(name);
        if (supportedOpenIDAttribute != null && attribute.getValues() != null
                && !attribute.getValues().isEmpty()) {
            String value = attribute.getValues().get(0);
            if (value != null) {
                values.put(supportedOpenIDAttribute, value);
            }//  www. j a  v  a  2  s .com
        }
    }
    return values;
}

From source file:org.mitre.provenance.openid.OpenIDInterceptorFilter.java

/**
 * Handle turning an OpenID (2) token into a user.
 *//*  w  w w  .j a va 2 s. co  m*/
protected User handle(OpenIDAuthenticationToken oidToken) {
    String oid2UniqueId = oidToken.getName();

    System.err.println("FILTER: OpenID2 Token ID " + oid2UniqueId + " cred " + oidToken.getCredentials()
            + " details " + oidToken.getDetails() + " principal " + oidToken.getPrincipal() + " message "
            + oidToken.getMessage());

    User existingUser = null;

    try {
        PLUSActor a = Neo4JPLUSObjectFactory.getActor(oid2UniqueId);
        if (a instanceof User)
            existingUser = (User) a;
    } catch (PLUSException exc) {
        log.severe("Could not load actor by ID " + oid2UniqueId);
        exc.printStackTrace();
    }

    if (existingUser != null) {
        // System.err.println("FILTER: OpenID2 existing user " + existingUser);
        return existingUser;
    } else {
        List<OpenIDAttribute> attributes = oidToken.getAttributes();

        System.err.println("FILTER: OpenID2 new user with " + attributes.size() + " attributes.");

        String oid2DisplayName = null;
        String oid2FirstName = null;
        String oid2LastName = null;
        String email = null;

        for (OpenIDAttribute attr : attributes) {
            String attrName = attr.getName();

            StringBuffer vals = new StringBuffer("");
            for (String val : attr.getValues())
                vals.append(val + "/");
            System.err.println("OPEN ID ATTRIBUTE:  " + attrName + " type " + attr.getType() + " vals " + vals);

            if (attrName.equals("name")) {
                //This is the OpenID 2.0 display name.
                //OpenID 2.0 Attribute Exchange (AX) is a little finicky, so this value
                //may not be populated or may be stored uner a different attribute name.
                oid2DisplayName = attr.getValues().get(0);
            } else if (attrName.equals("firstName")) {
                oid2FirstName = attr.getValues().get(0);
            } else if (attrName.equals("lastName")) {
                oid2LastName = attr.getValues().get(0);
            } else if (attrName.equals("email")) {
                email = attr.getValues().get(0);
            }
        }

        if (oid2DisplayName == null) {
            // Google sends first and last rather than "name"
            oid2DisplayName = oid2FirstName + oid2LastName;
        }

        OpenIDUser oid2User = new OpenIDUser(oid2UniqueId,
                (oid2DisplayName != null) ? oid2DisplayName : "Name Not Provided");
        oid2User.setEmail(email);

        // TODO:  Remove
        oid2User.addPrivilege(PrivilegeClass.ADMIN);
        oid2User.addPrivilege(PrivilegeClass.PUBLIC);

        try {
            if (client.actorExists(oid2User.getId()) == null)
                client.report(ProvenanceCollection.collect(oid2User));
        } catch (PLUSException exc) {
            log.severe("Could not save new user entry " + oid2User);
            exc.printStackTrace();
        }

        System.err.println("FILTER: set new OpenID2 user " + oid2User);
        return oid2User;
    }
}

From source file:org.apache.rave.portal.web.controller.handler.OpenIDAuthenticationFailureHandler.java

private User createTemporaryUser(OpenIDAuthenticationToken token, final String openId) {
    final List<OpenIDAttribute> attributes = token.getAttributes();
    String email = null;//from  ww w. j av a 2 s . c o  m
    String firstName = null;
    String lastName = null;
    String displayName = null;
    for (OpenIDAttribute attribute : attributes) {
        if ("email".equals(attribute.getName()) && !attribute.getValues().isEmpty()) {
            email = attribute.getValues().get(0);
        } else if ("firstname".equals(attribute.getName()) && !attribute.getValues().isEmpty()) {
            firstName = attribute.getValues().get(0);
        } else if ("lastname".equals(attribute.getName()) && !attribute.getValues().isEmpty()) {
            lastName = attribute.getValues().get(0);
        } else if ("fullname".equals(attribute.getName()) && !attribute.getValues().isEmpty()) {
            displayName = attribute.getValues().get(0);
        }
    }
    User user = new UserImpl();
    String username = StringUtils.substringAfter(openId, "://").replace("/", "");
    if (username.length() > 35) {
        username = username.substring(0, 35);
    }
    if (displayName == null && firstName != null && lastName != null) {
        displayName = firstName + " " + lastName;
    }
    user.setUsername(username);
    user.setEmail(email);
    user.setGivenName(firstName);
    user.setFamilyName(lastName);
    user.setDisplayName(displayName);
    user.setOpenId(openId);

    return user;
}

From source file:org.cbioportal.security.spring.authentication.openID.PortalUserDetailsService.java

/**
 * Implementation of {@code AuthenticationUserDetailsService}
 * which allows full access to the submitted {@code Authentication} object.
 * Used by the OpenIDAuthenticationProvider.
 *///from   w w w  . j av a  2  s  . c  o  m
public UserDetails loadUserDetails(OpenIDAuthenticationToken token) throws UsernameNotFoundException {

    // what we return
    PortalUserDetails toReturn = null;

    // get open id
    String id = token.getIdentityUrl();
    id = id.toLowerCase();

    // grab other open id attributes
    String email = null;
    String firstName = null;
    String lastName = null;
    String fullName = null;

    // myopenid does not return attributes in the token
    if (id.indexOf("myopenid") != -1) {
        email = id;
        fullName = id;
    } else {
        try {
            List<OpenIDAttribute> attributes = token.getAttributes();
            for (OpenIDAttribute attribute : attributes) {
                if (attribute.getName().equals("email")) {
                    email = attribute.getValues().get(0);
                    email = email.toLowerCase();
                }
                if (attribute.getName().equals("firstname")) {
                    firstName = attribute.getValues().get(0);
                }
                if (attribute.getName().equals("lastname")) {
                    lastName = attribute.getValues().get(0);
                }
                if (attribute.getName().equals("fullname")) {
                    fullName = attribute.getValues().get(0);
                }
            }
            if (fullName == null) {
                StringBuilder fullNameBldr = new StringBuilder();
                if (firstName != null) {
                    fullNameBldr.append(firstName);
                }
                if (lastName != null) {
                    fullNameBldr.append(" ").append(lastName);
                }
                fullName = fullNameBldr.toString();
            }
        } catch (NullPointerException ex) {
            log.warn("Attribute exchange failed using OpenID " + token.getIdentityUrl() + " for everything");
            fullName = email = token.getIdentityUrl();
        }
    }

    // check if this user exists in our backend db
    try {
        if (log.isDebugEnabled()) {
            log.debug("loadUserDetails(), attempting to fetch portal user, email: " + email);
        }
        User user = securityRepository.getPortalUser(email);
        if (user != null && user.isEnabled()) {
            if (log.isDebugEnabled()) {
                log.debug("loadUserDetails(), attempting to fetch portal user authorities, email: " + email);
            }
            UserAuthorities authorities = securityRepository.getPortalUserAuthorities(email);
            if (authorities != null) {
                List<GrantedAuthority> grantedAuthorities = AuthorityUtils.createAuthorityList(
                        authorities.getAuthorities().toArray(new String[authorities.getAuthorities().size()]));
                toReturn = new PortalUserDetails(id, grantedAuthorities);
                toReturn.setEmail(email);
                toReturn.setName(fullName);
            }
        }
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage());
        } else {
            e.printStackTrace();
        }
    }

    // outta here
    if (toReturn == null) {
        if (log.isDebugEnabled()) {
            log.debug("loadUserDetails(), user and/or user authorities is null, email: " + email);
        }
        throw new UsernameNotFoundException("Error:  Unknown user or account disabled");
    } else {
        if (log.isDebugEnabled()) {
            log.debug("loadUserDetails(), successfully authenticated user, email: " + email);
        }
        return toReturn;
    }
}

From source file:org.mskcc.cbio.portal.authentication.openID.PortalUserDetailsService.java

/**
 * Implementation of {@code AuthenticationUserDetailsService}
* which allows full access to the submitted {@code Authentication} object.
* Used by the OpenIDAuthenticationProvider.
 *///from w  ww.  jav a 2  s  .  c  om
public UserDetails loadUserDetails(OpenIDAuthenticationToken token) throws UsernameNotFoundException {

    // what we return
    PortalUserDetails toReturn = null;

    // get open id
    String id = token.getIdentityUrl();
    id = id.toLowerCase();

    // grab other open id attributes
    String email = null;
    String firstName = null;
    String lastName = null;
    String fullName = null;

    // myopenid does not return attributes in the token
    if (id.indexOf("myopenid") != -1) {
        email = id;
        fullName = id;
    } else {
        try {
            List<OpenIDAttribute> attributes = token.getAttributes();
            for (OpenIDAttribute attribute : attributes) {
                if (attribute.getName().equals("email")) {
                    email = attribute.getValues().get(0);
                    email = email.toLowerCase();
                }
                if (attribute.getName().equals("firstname")) {
                    firstName = attribute.getValues().get(0);
                }
                if (attribute.getName().equals("lastname")) {
                    lastName = attribute.getValues().get(0);
                }
                if (attribute.getName().equals("fullname")) {
                    fullName = attribute.getValues().get(0);
                }
            }
            if (fullName == null) {
                StringBuilder fullNameBldr = new StringBuilder();
                if (firstName != null) {
                    fullNameBldr.append(firstName);
                }
                if (lastName != null) {
                    fullNameBldr.append(" ").append(lastName);
                }
                fullName = fullNameBldr.toString();
            }
        } catch (NullPointerException ex) {
            log.warn("Attribute exchange failed using OpenID " + token.getIdentityUrl() + " for everything");
            fullName = email = token.getIdentityUrl();
        }
    }

    // check if this user exists in our backend db
    try {
        if (log.isDebugEnabled()) {
            log.debug("loadUserDetails(), attempting to fetch portal user, email: " + email);
        }
        User user = portalUserDAO.getPortalUser(email);
        if (user != null && user.isEnabled()) {
            if (log.isDebugEnabled()) {
                log.debug("loadUserDetails(), attempting to fetch portal user authorities, email: " + email);
            }
            UserAuthorities authorities = portalUserDAO.getPortalUserAuthorities(email);
            if (authorities != null) {
                List<GrantedAuthority> grantedAuthorities = AuthorityUtils.createAuthorityList(
                        authorities.getAuthorities().toArray(new String[authorities.getAuthorities().size()]));
                toReturn = new PortalUserDetails(id, grantedAuthorities);
                toReturn.setEmail(email);
                toReturn.setName(fullName);
            }
        }
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage());
        } else {
            e.printStackTrace();
        }
    }

    // outta here
    if (toReturn == null) {
        if (log.isDebugEnabled()) {
            log.debug("loadUserDetails(), user and/or user authorities is null, email: " + email);
        }
        throw new UsernameNotFoundException("Error:  Unknown user or account disabled");
    } else {
        if (log.isDebugEnabled()) {
            log.debug("loadUserDetails(), successfully authenticated user, email: " + email);
        }
        return toReturn;
    }
}

From source file:org.mskcc.cbio.portal.openIDlogin.OpenIDUserDetailsService.java

/**
 * Implementation of {@code AuthenticationUserDetailsService}
* which allows full access to the submitted {@code Authentication} object.
* Used by the OpenIDAuthenticationProvider.
 *//*w  w  w  . jav  a 2s .c o m*/
public UserDetails loadUserDetails(OpenIDAuthenticationToken token) throws UsernameNotFoundException {

    // what we return
    OpenIDUserDetails toReturn = null;

    // get open id
    String id = token.getIdentityUrl();
    id = id.toLowerCase();

    // grab other open id attributes
    String email = null;
    String firstName = null;
    String lastName = null;
    String fullName = null;

    // myopenid does not return attributes in the token
    if (id.indexOf("myopenid") != -1) {
        email = id;
        fullName = id;
    } else {
        List<OpenIDAttribute> attributes = token.getAttributes();
        for (OpenIDAttribute attribute : attributes) {
            if (attribute.getName().equals("email")) {
                email = attribute.getValues().get(0);
                email = email.toLowerCase();
            }
            if (attribute.getName().equals("firstname")) {
                firstName = attribute.getValues().get(0);
            }
            if (attribute.getName().equals("lastname")) {
                lastName = attribute.getValues().get(0);
            }
            if (attribute.getName().equals("fullname")) {
                fullName = attribute.getValues().get(0);
            }
        }
        if (fullName == null) {
            StringBuilder fullNameBldr = new StringBuilder();
            if (firstName != null) {
                fullNameBldr.append(firstName);
            }
            if (lastName != null) {
                fullNameBldr.append(" ").append(lastName);
            }
            fullName = fullNameBldr.toString();
        }
    }

    // check if this user exists in our backend db
    try {
        if (log.isDebugEnabled()) {
            log.debug("loadUserDetails(), attempting to fetch portal user, email: " + email);
        }
        User user = portalUserDAO.getPortalUser(email);
        if (user != null && user.isEnabled()) {
            if (log.isDebugEnabled()) {
                log.debug("loadUserDetails(), attempting to fetch portal user authorities, email: " + email);
            }
            UserAuthorities authorities = portalUserDAO.getPortalUserAuthorities(email);
            if (authorities != null) {
                List<GrantedAuthority> grantedAuthorities = AuthorityUtils
                        .createAuthorityList(authorities.getAuthorities().toArray(new String[0]));
                toReturn = new OpenIDUserDetails(id, grantedAuthorities);
                toReturn.setEmail(email);
                toReturn.setName(fullName);
            }
        }
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage());
        } else {
            e.printStackTrace();
        }
    }

    // outta here
    if (toReturn == null) {
        if (log.isDebugEnabled()) {
            log.debug("loadUserDetails(), user and/or user authorities is null, email: " + email);
        }
        throw new UsernameNotFoundException("Error:  Unknown user or account disabled");
    } else {
        if (log.isDebugEnabled()) {
            log.debug("loadUserDetails(), successfully authenticated user, email: " + email);
        }
        return toReturn;
    }
}

From source file:org.opendatakit.common.security.spring.WrappingOpenIDAuthenticationProvider.java

@Override
protected Authentication createSuccessfulAuthentication(UserDetails rawUserDetails,
        OpenIDAuthenticationToken auth) {
    String eMail = null;//from  w  w w.  j a  v  a  2s  . co m
    List<OpenIDAttribute> oAttrList = auth.getAttributes();
    for (OpenIDAttribute oAttr : oAttrList) {
        if ("email".equals(oAttr.getName())) {
            Object o = oAttr.getValues().get(0);
            if (o != null) {
                eMail = (String) o;
            }
        }
    }
    if (eMail == null) {
        logger.warn("OpenId attributes did not include an e-mail address! ");
        throw new UsernameNotFoundException("email address not supplied in OpenID attributes");
    }
    eMail = WrappingOpenIDAuthenticationProvider.normalizeMailtoAddress(eMail);
    String mailtoDomain = WrappingOpenIDAuthenticationProvider.getMailtoDomain(eMail);

    UserDetails userDetails = rawUserDetails;

    Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();

    authorities.addAll(userDetails.getAuthorities());
    // add the AUTH_OPENID granted authority,
    authorities.add(new SimpleGrantedAuthority(GrantedAuthorityName.AUTH_OPENID.toString()));

    // attempt to look user up in registered users table...
    String username = null;
    UserDetails partialDetails = null;
    boolean noRights = false;
    try {
        partialDetails = wrappingUserDetailsService.loadUserByUsername(eMail);
        // found the user in the table -- fold in authorizations and get uriUser.
        authorities.addAll(partialDetails.getAuthorities());
        // users are blacklisted by registering them and giving them no rights.
        noRights = partialDetails.getAuthorities().isEmpty();
        username = partialDetails.getUsername();
    } catch (Exception e) {
        e.printStackTrace();
        logger.warn("OpenId attribute e-mail: " + eMail + " did not match any known e-mail addresses! "
                + e.getMessage());
        throw new UsernameNotFoundException("account not recognized");
    }

    AggregateUser trueUser = new AggregateUser(username, partialDetails.getPassword(),
            UUID.randomUUID().toString(), // junk...
            mailtoDomain, partialDetails.isEnabled(), partialDetails.isAccountNonExpired(),
            partialDetails.isCredentialsNonExpired(), partialDetails.isAccountNonLocked(), authorities);
    if (noRights
            || !(trueUser.isEnabled() && trueUser.isAccountNonExpired() && trueUser.isAccountNonLocked())) {
        logger.warn("OpenId attribute e-mail: " + eMail + " account is blocked! ");
        throw new UsernameNotFoundException("account is blocked");
    }

    return new OpenIDAuthenticationToken(trueUser, trueUser.getAuthorities(), auth.getIdentityUrl(),
            auth.getAttributes());
}