Exemplo n.º 1
0
 @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);
       }
     }
     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;
 }
 /**
  * @param supportedAttribute
  * @return
  */
 public static OpenIDAttribute toOpenIDAttribute(SupportedOpenIDAttribute supportedAttribute) {
   OpenIDAttribute openIDAttribute =
       new OpenIDAttribute(
           supportedAttribute.getAttributeName(), supportedAttribute.getAttributeType());
   openIDAttribute.setRequired(true);
   return openIDAttribute;
 }
  @Override
  public UserDetails loadUserDetails(OpenIDAuthenticationToken token)
      throws UsernameNotFoundException {
    LOGGER.info("Got OpenIdAuth with token {}", token);

    Map<String, String> attributes = new HashMap<>();

    UserEntity user = null;
    for (OpenIDAttribute attribute : token.getAttributes()) {
      attributes.put(
          attribute.getName().toLowerCase(), StringUtils.join(attribute.getValues(), " "));
      if (attribute.getName().equalsIgnoreCase("email")) {
        for (String attributeValue : attribute.getValues()) {
          user = repository.findByEmail(attributeValue);
          if (user != null) {
            break;
          }
        }
        break;
      }
    }

    if (user == null) {
      user = new UserEntity();
      user.setUsername(attributes.get("email"));
      user.setEmail(attributes.get("email"));
      //      user.setFirstName(attributes.get("firstname"));
      //      user.setFirstName(attributes.get("lastname"));
      user.getRoles().add(Role.USER);

      LOGGER.info("Saving user " + attributes.get("email"));
      LOGGER.info("User Attributes {}", attributes);

      user = repository.save(user);

    } else {
      // TODO: remove this - users were imported without any role.
      if (user.getRoles().size() == 0) {
        user.getRoles().add(Role.USER);
        user = repository.save(user);
      }
    }

    LOGGER.info("returning user {}", user);
    return user;
  }
  /**
   * {@inheritDoc}
   *
   * @see org.springframework.security.providers.openid.OpenIDAuthenticationProvider#authenticate(
   *     org.springframework.security.Authentication)
   */
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    if (!supports(authentication.getClass())) {
      return null;
    }

    if (authentication instanceof OpenIDAuthenticationToken) {
      OpenIDAuthenticationToken response = (OpenIDAuthenticationToken) authentication;
      OpenIDAuthenticationStatus status = response.getStatus();

      // handle the various possibilites
      if (status == OpenIDAuthenticationStatus.SUCCESS) {
        // Lookup user details
        final UserDetails userDetails;
        try {
          userDetails = this.userDetailsService.loadUserByUsername(response.getIdentityUrl());
        } catch (final UsernameNotFoundException e) {

          LOGGER.error("OpenID authentication successful but but no account exists.");

          final User user = new User();
          user.setUsername(response.getIdentityUrl());

          for (OpenIDAttribute attribute : response.getAttributes()) {

            LOGGER.debug(
                "OpenIDAttribute: "
                    + attribute.getType()
                    + "; "
                    + attribute.getName()
                    + "; "
                    + attribute.getValues());

            if (UsedOpenIdAttribute.AX_FIRST_NAME
                .getOpenIdAttribute()
                .getName()
                .equals(attribute.getName())) {
              user.setFirstName(attribute.getValues().get(0));
            } else if (UsedOpenIdAttribute.AX_LAST_NAME
                .getOpenIdAttribute()
                .getName()
                .equals(attribute.getName())) {
              user.setLastName(attribute.getValues().get(0));
            } else if (UsedOpenIdAttribute.EMAIL
                .getOpenIdAttribute()
                .getName()
                .equals(attribute.getName())) {
              user.setEmail(attribute.getValues().get(0));
            } else if (UsedOpenIdAttribute.FIRST_NAME
                    .getOpenIdAttribute()
                    .getName()
                    .equals(attribute.getName())
                && user.getFirstName() == null) {
              user.setFirstName(attribute.getValues().get(0));
            } else if (UsedOpenIdAttribute.LAST_NAME
                    .getOpenIdAttribute()
                    .getName()
                    .equals(attribute.getName())
                && user.getLastName() == null) {
              user.setLastName(attribute.getValues().get(0));
            }
          }

          if (StringUtils.isBlank(user.getFirstName()) && StringUtils.isBlank(user.getLastName())) {
            for (OpenIDAttribute attribute : response.getAttributes()) {
              if (UsedOpenIdAttribute.NAME_PERSON
                  .getOpenIdAttribute()
                  .getName()
                  .equals(attribute.getName())) {
                user.setFirstName(attribute.getValues().get(0));
              }
            }
          }

          throw new AuthenticationSucessButMissingRegistrationException(
              "User is authenticated via OpenID but no account exists, yet.", user);
        }

        return new OpenIDAuthenticationToken(
            userDetails,
            userDetails.getAuthorities(),
            response.getIdentityUrl(),
            response.getAttributes());
      }

      if (status == OpenIDAuthenticationStatus.CANCELLED) {
        throw new AuthenticationCancelledException("Log in cancelled");
      }

      if (status == OpenIDAuthenticationStatus.ERROR) {
        throw new AuthenticationServiceException("Error message from server: $response.message");
      }

      if (status == OpenIDAuthenticationStatus.FAILURE) {
        throw new BadCredentialsException("Log in failed - identity could not be verified");
      }

      if (status == OpenIDAuthenticationStatus.SETUP_NEEDED) {
        throw new AuthenticationServiceException(
            "The server responded setup was needed, which shouldn't happen");
      }

      throw new AuthenticationServiceException("Unrecognized return value $status");
    }

    return null;
  }