Example usage for org.springframework.security.openid OpenIDAuthenticationToken getAttributes

List of usage examples for org.springframework.security.openid OpenIDAuthenticationToken getAttributes

Introduction

In this page you can find the example usage for org.springframework.security.openid OpenIDAuthenticationToken getAttributes.

Prototype

public List<OpenIDAttribute> getAttributes() 

Source Link

Usage

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

/**
 * Creates the person object based on the supplied OpenID attributes.
 *
 * @param token the token//from  w  w w  . j  a v  a  2  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";
    }

    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

@Override
protected Authentication doAuthentication(Authentication authentication) throws AuthenticationException {
    if (authentication instanceof OpenIDAuthenticationToken) {
        OpenIDAuthenticationToken token = (OpenIDAuthenticationToken) authentication;
        if (!OpenIDAuthenticationStatus.SUCCESS.equals(token.getStatus())) {
            String errorMessage = MessageResolver.messageFormatting("login.wrong.credentials", null);
            throw new BadCredentialsException(errorMessage);
        }//from www. j av a 2  s .c o  m
        String email = findAttributeValueByName(SupportedOpenIDAttribute.EMAIL, token.getAttributes());
        if (StringUtils.isBlank(email)) {
            String errorMessage = MessageResolver.messageFormatting("login.wrong.credentials", null);
            throw new BadCredentialsException(errorMessage);
        }

        HttpSession session = ((SessionContainerWebAuthenticationDetails) token.getDetails()).getSession();

        if (authenticator != null) {
            AuthenticatorFactory authenticatorFactory = AuthenticatorFactory.getInstance();
            Map<SupportedOpenIDAttribute, String> attributeValues = findAttributeValues(token.getAttributes());
            OpenIDAuthenticationSource openIDAuthenticationSource = (OpenIDAuthenticationSource) authenticatorFactory
                    .provideOpenIDAuthenticationSource(email, attributeValues);
            IAuthenticationDetails authenticationDetails = authenticator
                    .authenticate(openIDAuthenticationSource);
            if (authenticationDetails != null) {
                return generateDefaultToken(authenticationDetails, session);
            }
        }
    }

    String errorMessage = MessageResolver.messageFormatting("login.authentication.failure", null);
    throw new BadCredentialsException(errorMessage);
}

From source file:com.erudika.para.security.SimpleUserService.java

/**
 * Loads a user from the data store or creates a new user from an OpenID profile
 * @param token the OpenID authentication token holding the user profile
 * @return a user object or null if user is not found
 *//* w  w w  .j ava2 s . c  om*/
public UserDetails loadUserDetails(OpenIDAuthenticationToken token) {
    if (token == null) {
        return null;
    }

    User user = new User();
    user.setIdentifier(token.getIdentityUrl());
    user = loadUser(user);

    if (user == null) {
        // create new OpenID user
        String email = "email@domain.com";
        String firstName = null, lastName = null, fullName = null;
        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 (fullName == null) {
            if (firstName == null) {
                firstName = "No";
            }
            if (lastName == null) {
                lastName = "Name";
            }
            fullName = firstName.concat(" ").concat(lastName);
        }

        user = new User();
        user.setActive(true);
        user.setEmail(email);
        user.setName(fullName);
        user.setPassword(new UUID().toString());
        user.setIdentifier(token.getIdentityUrl());
        String id = user.create();
        if (id == null) {
            throw new BadCredentialsException("Authentication failed: cannot create new user.");
        }
    }

    return user;
}

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

/**
 * Called when an authentication attempt fails.
 *
 * @param request - the request during which the authentication attempt occurred.
 * @param response - the response./*from w  w  w .  j  a  va 2 s.c  om*/
 * @param exception - the exception which was thrown to reject the authentication
 * request.
 * @throws java.io.IOException
 * @throws javax.servlet.ServletException
 */
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authenticationException) throws IOException, ServletException {

    if (authenticationException instanceof DisabledException) {
        RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
        redirectStrategy.sendRedirect(request, response, "/accountDisabled");
    }

    if (isFailedDueToUserNotRegistered(authenticationException)) {

        OpenIDAuthenticationToken token = (OpenIDAuthenticationToken) authenticationException
                .getAuthentication();

        Person person = Person.findByOpenIdIdentifier(token.getIdentityUrl());

        if (person == null) {

            // The person does not exist, create
            person = createPerson(token);

            // Recreate OpenIDAuthentication token, transfer values from existing
            // token, and assign roles from retrieved user. Since grantedAuthorities
            // is unmodifiable list and no way to update the pre created token.

            OpenIDAuthenticationToken newToken = new OpenIDAuthenticationToken(person, person.getAuthorities(),
                    token.getIdentityUrl(), token.getAttributes());
            newToken.setAuthenticated(true);

            token.setDetails(person);
            SecurityContextHolder.getContext().setAuthentication(newToken);

            // Transfer any previous projects to the new user
            transferProjects(request, person);

            RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
            redirectStrategy.sendRedirect(request, response, "/user");
        }
    }
}

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

/**
 * Called when an authentication attempt fails.
 *
 * @param request - the request during which the authentication attempt occurred.
 * @param response - the response.//w  w  w  .  j  a  v a 2 s .  c o  m
 * @param exception - the exception which was thrown to reject the authentication
 * request.
 * @throws java.io.IOException
 * @throws javax.servlet.ServletException
 */
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authenticationException) throws IOException, ServletException {

    if (authenticationException instanceof DisabledException) {
        RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
        redirectStrategy.sendRedirect(request, response, "/accountDisabled");
    }

    if (isFailedDueToUserNotRegistered(authenticationException)) {

        OpenIDAuthenticationToken token = (OpenIDAuthenticationToken) authenticationException
                .getAuthentication();

        String id = token.getIdentityUrl();

        List<Person> people = Person.findPeopleByOpenIdIdentifier(id).getResultList();

        Person person = people.size() == 0 ? null : people.get(0);

        if (person == null) {

            // The person does not exist, create
            person = createPerson(token);

            // Recreate OpenIDAuthentication token, transfer values from existing
            // token, and assign roles from retrieved user. Since grantedAuthorities
            // is unmodifiable list and no way to update the pre created token.

            OpenIDAuthenticationToken newToken = new OpenIDAuthenticationToken(person, person.getAuthorities(),
                    token.getIdentityUrl(), token.getAttributes());
            newToken.setAuthenticated(true);

            token.setDetails(person);
            SecurityContextHolder.getContext().setAuthentication(newToken);

            RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
            redirectStrategy.sendRedirect(request, response, "/user");
        }
    }
}

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

/**
 * Handle turning an OpenID (2) token into a user.
 *//*from  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.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;//w ww .ja va 2s  .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 a v  a  2 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 = 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  . j a  v a 2s .  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.
 *///  w  w  w.  j a  va2 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;
    }
}