예제 #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;
 }
예제 #2
0
 @RequestMapping("/")
 public String index(Model model, OpenIDAuthenticationToken authentication) {
   model.addAttribute(
       "authenticated",
       authentication != null
           ? OpenIDAuthenticationStatus.SUCCESS.equals(authentication.getStatus())
           : Boolean.FALSE);
   return "index";
 }
  @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;
  }
  @Override
  public UserDetails loadUserDetails(final OpenIDAuthenticationToken token)
      throws UsernameNotFoundException {
    final String identityUrl = token.getIdentityUrl();
    Option<OpenIDMember> openIDMemberOption = repository.getOpenIdMember(identityUrl);
    OpenIDMember openIDMember =
        openIDMemberOption.getValueOr(
            OpenIDMember.class,
            new Option.DefaultCreator<OpenIDMember>() {
              @Override
              public void init(OpenIDMember openIDMember) {
                openIDMember.identityUrl(identityUrl);
                openIDMember.addRoles("ROLE_MEMBER");
                List<OpenIDAttribute> attributes = token.getAttributes();
                boolean fullnameHasBeenSet = false;
                for (OpenIDAttribute attribute : attributes) {
                  switch (attribute.getName()) {
                    case "email":
                      openIDMember.email(attribute.getValues().get(0));
                      break;
                    case "fullname":
                      openIDMember.displayName(attribute.getValues().get(0));
                      fullnameHasBeenSet = true;
                      break;
                    case "firstname":
                      if (!fullnameHasBeenSet)
                        openIDMember.displayName(attribute.getValues().get(0));
                      break;
                  }
                }
                repository.add(openIDMember);
              }
            });

    return new Member(openIDMember, String.valueOf(random.nextInt()));
  }
  /**
   * {@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;
  }