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

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

Introduction

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

Prototype

public String getIdentityUrl() 

Source Link

Usage

From source file:mx.edu.um.mateo.general.service.UserDetailsServiceImpl.java

@Override
public UserDetails loadUserDetails(OpenIDAuthenticationToken token) throws UsernameNotFoundException {
    log.debug("loadUserDetails: {}", token);
    String username = token.getIdentityUrl();
    String email = "";
    Usuario usuario = usuarioDao.obtienePorOpenId(username);
    log.debug("Usuario encontrado : {}", usuario);
    if (usuario == null) {
        log.debug("Buscando atributo email");
        List<OpenIDAttribute> attrs = token.getAttributes();
        for (OpenIDAttribute attr : attrs) {
            log.debug("Attr: {}", attr.getName());
            if (attr.getName().equals("email")) {
                email = attr.getValues().get(0);
            }//from  ww w.  j a  v  a 2  s  .c  o m
        }
        log.debug("Buscando por email {}", email);
        usuario = usuarioDao.obtienePorCorreo(email);
        if (usuario == null) {
            throw new UsernameNotFoundException("No se encontro al usuario " + username);
        }
        usuario.setOpenId(username);
        usuarioDao.actualiza(usuario);
    }
    log.debug("Regresando usuario: {}", usuario);
    return (UserDetails) usuario;
}

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 a va2  s  .c o m
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:org.smigo.user.JdbcUserDao.java

@Override
public List<User> getUsersByOpenIDAuthenticationToken(OpenIDAuthenticationToken token) {
    final String sql = "SELECT users.id, username FROM users JOIN openid ON openid.user_id = users.id WHERE openid.identity_url = ?";
    return jdbcTemplate.query(sql, userRowMapper, token.getIdentityUrl());
}

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  . ja v  a  2 s  .  com
 * @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./*from   ww  w  .j ava 2 s  . com*/
 * @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.smigo.user.authentication.OpenIdUserDetailsService.java

@Override
public UserDetails loadUserDetails(OpenIDAuthenticationToken token) throws UsernameNotFoundException {
    final List<User> users = userDao.getUsersByOpenIDAuthenticationToken(token);
    if (users.isEmpty()) {
        final User createdUser = userHandler.createUser();
        final int userId = createdUser.getId();
        userDao.addOpenId(userId, token.getIdentityUrl());
        return new AuthenticatedUser(userId, createdUser.getUsername(), "", AuthenticatedUser.USER_AUTHORITY);
    }//from   w  w  w .  j  a  v a2 s . c o  m
    final User user = users.get(0);
    return new AuthenticatedUser(user.getId(), user.getUsername(), "", user.getAuthority());
}

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

@Override
@NotNull//from  w w  w  .j  a  v  a2s  .c om
public UserDetails loadUserDetails(@NotNull OpenIDAuthenticationToken token) throws UsernameNotFoundException {

    final User tUser = buildUserFromToken(token);
    final User dbUser = userService.getUserBy(tUser.getEmail());

    final User result;
    if (dbUser != null) {
        if (!token.getIdentityUrl().equals(dbUser.getAuthenticatorUri())) {
            throw new IllegalStateException(
                    "Identity url for this user can not change:" + token.getIdentityUrl());
        }
        result = dbUser;
    } else {
        try {
            tUser.setAuthenticationType(AuthenticationType.OPENID);
            tUser.setAuthenticatorUri(token.getIdentityUrl());

            result = userService.createUser(tUser, false, false);
        } catch (WiseMappingException e) {
            throw new IllegalStateException(e);
        }

    }
    return new UserDetails(result, isAdmin(result.getEmail()));
}

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.  java  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";
    }

    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  www  .j  a  v 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:ar.edu.fesf.security.OpenIDAttributes2UserDetailsImpl.java

/**
 * {@inheritDoc}/*from   w w w  .  j a v  a2  s . c  o  m*/
 */
@Override
public UserDetails extract(final OpenIDAuthenticationToken token) {
    String email = "";
    String firstName = "";
    String lastName = "";
    String language = "";
    List<OpenIDAttribute> attributes = token.getAttributes();
    for (OpenIDAttribute openIDAttribute : attributes) {
        if (openIDAttribute.getName().equals("firstName")) {
            firstName = StringUtils.join(openIDAttribute.getValues(), "");
        }

        if (openIDAttribute.getName().equals("email")) {
            email = StringUtils.join(openIDAttribute.getValues(), "");
        }

        if (openIDAttribute.getName().equals("lastName")) {
            lastName = StringUtils.join(openIDAttribute.getValues(), "");
        }

        if (openIDAttribute.getName().equals("language")) {
            language = StringUtils.join(openIDAttribute.getValues(), "");
        }
    }
    return new UserDetailsImpl(token.getIdentityUrl(), firstName, lastName, email, language);
}