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

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

The attribute name

Usage

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

/**
 * Creates the person object based on the supplied OpenID attributes.
 *
 * @param token the token/*from   w w w .  j  a  va2  s.c  o 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. j  av a2s.  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";
    }

    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:de.uni_koeln.spinfo.maalr.login.PostLoginHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {

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

    // Set Session Timeout to one hour
    request.getSession().setMaxInactiveInterval(60 * 60);
    if (authentication != null && authentication instanceof JaasAuthenticationToken) {
        // TODO: Implement something similar for ldap...
        request.getSession().setAttribute("uname", authentication.getName());
    }// w ww  . j a  va2 s.  c o m
    if (authentication != null && authentication instanceof OpenIDAuthenticationToken) {
        // TODO: Optimize this - inefficient to query for each request...
        MaalrUserInfo userInfo = backend.getByLogin(authentication.getName());
        if (userInfo == null) {
            OpenIDAuthenticationToken token = (OpenIDAuthenticationToken) SecurityContextHolder.getContext()
                    .getAuthentication();
            List<OpenIDAttribute> attributes = token.getAttributes();
            userInfo = new MaalrUserInfo(authentication.getName(), Role.OPENID_2);
            for (OpenIDAttribute openIDAttribute : attributes) {
                if (openIDAttribute.getValues() != null && openIDAttribute.getValues().size() > 0) {
                    if ("axContactEmail".equals(openIDAttribute.getName()) && userInfo.getEmail() == null) {
                        userInfo.setEmail(openIDAttribute.getValues().get(0));
                    }
                    if ("oiContactEmail".equals(openIDAttribute.getName()) && userInfo.getEmail() == null) {
                        userInfo.setEmail(openIDAttribute.getValues().get(0));
                    }
                    if ("axNamePersonFirstName".equals(openIDAttribute.getName())
                            && userInfo.getFirstname() == null) {
                        userInfo.setFirstname(openIDAttribute.getValues().get(0));
                    }
                    if ("axNamePersonLastName".equals(openIDAttribute.getName())
                            && userInfo.getLastname() == null) {
                        userInfo.setLastname(openIDAttribute.getValues().get(0));
                    }
                }
            }
            try {
                backend.insert(userInfo);
            } catch (InvalidUserException e) {
                e.printStackTrace();
            }
        }
        request.getSession().setAttribute("uname", userInfo.getFirstname());
    }
    if (authentication != null) {
        Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
        if (roles.contains(Constants.Roles.ADMIN_5)) {
            response.sendRedirect(dictContext + "/admin/admin.html");
            return;
        } else if (roles.contains(Constants.Roles.TRUSTED_IN_4)) {
            response.sendRedirect(dictContext + "/editor/editor.html");
            return;
        }
    }
    response.sendRedirect(dictContext + "/index.html");
}

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

/**
 * Handle turning an OpenID (2) token into a user.
 */// ww w  . j av  a  2 s  .  c  o 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.mitre.provenance.openid.OpenId4JavaProxyConsumer.java

List<OpenIDAttribute> fetchAxAttributes(Message authSuccess, List<OpenIDAttribute> attributesToFetch)
        throws OpenIDConsumerException {

    if (attributesToFetch == null || !authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
        return Collections.emptyList();
    }/*from  w w  w  . j av  a2  s .  c  o m*/

    logger.debug("Extracting attributes retrieved by attribute exchange");

    List<OpenIDAttribute> attributes = Collections.emptyList();

    try {
        MessageExtension ext = authSuccess.getExtension(AxMessage.OPENID_NS_AX);
        if (ext instanceof FetchResponse) {
            FetchResponse fetchResp = (FetchResponse) ext;
            attributes = new ArrayList<OpenIDAttribute>(attributesToFetch.size());

            for (OpenIDAttribute attr : attributesToFetch) {
                List<String> values = fetchResp.getAttributeValues(attr.getName());
                if (!values.isEmpty()) {
                    OpenIDAttribute fetched = new OpenIDAttribute(attr.getName(), attr.getType(), values);
                    fetched.setRequired(attr.isRequired());
                    attributes.add(fetched);
                }
            }
        }
    } catch (MessageException e) {
        throw new OpenIDConsumerException("Attribute retrieval failed", e);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Retrieved attributes" + attributes);
    }

    return attributes;
}

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

public String beginConsumption(HttpServletRequest req, String identityUrl, String returnToUrl, String realm)
        throws OpenIDConsumerException {
    List<DiscoveryInformation> discoveries;

    try {//w w w  . j a  va 2 s  .  c o m
        discoveries = consumerManager.discover(identityUrl);
    } catch (DiscoveryException e) {
        throw new OpenIDConsumerException("Error during discovery", e);
    }

    DiscoveryInformation information = consumerManager.associate(discoveries);
    req.getSession().setAttribute(DISCOVERY_INFO_KEY, information);

    AuthRequest authReq;

    try {
        authReq = consumerManager.authenticate(information, returnToUrl, realm);

        logger.debug("Looking up attribute fetch list for identifier: " + identityUrl);

        List<OpenIDAttribute> attributesToFetch = attributesToFetchFactory.createAttributeList(identityUrl);

        if (!attributesToFetch.isEmpty()) {
            req.getSession().setAttribute(ATTRIBUTE_LIST_KEY, attributesToFetch);
            FetchRequest fetchRequest = FetchRequest.createFetchRequest();
            for (OpenIDAttribute attr : attributesToFetch) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Adding attribute " + attr.getType() + " to fetch request");
                }
                fetchRequest.addAttribute(attr.getName(), attr.getType(), attr.isRequired(), attr.getCount());
            }
            authReq.addExtension(fetchRequest);
        }
    } catch (MessageException e) {
        throw new OpenIDConsumerException("Error processing ConsumerManager authentication", e);
    } catch (ConsumerException e) {
        throw new OpenIDConsumerException("Error processing ConsumerManager authentication", e);
    }

    return authReq.getDestinationUrl(true);
}

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   w w  w.  j  av a  2  s .  c  om*/
    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 . jav  a2  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 = 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  w w  . ja v  a2 s .co  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 = 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.
 *//* www.  jav  a2  s.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;
    }
}