/*
   * (non-Javadoc)
   *
   * @see
   * org.springframework.security.authentication.AuthenticationProvider#authenticate
   * (org.springframework.security.Authentication)
   */
  public Authentication authenticate(final 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 possibilities
      if (status == OpenIDAuthenticationStatus.SUCCESS) {
        // Lookup user details
        UserDetails userDetails = userDetailsService.loadUserDetails(response);

        return createSuccessfulAuthentication(userDetails, response);

      } else if (status == OpenIDAuthenticationStatus.CANCELLED) {
        throw new AuthenticationCancelledException("Log in cancelled");
      } else if (status == OpenIDAuthenticationStatus.ERROR) {
        throw new AuthenticationServiceException(
            "Error message from server: " + response.getMessage());
      } else if (status == OpenIDAuthenticationStatus.FAILURE) {
        throw new BadCredentialsException("Log in failed - identity could not be verified");
      } else if (status == OpenIDAuthenticationStatus.SETUP_NEEDED) {
        throw new AuthenticationServiceException(
            "The server responded setup was needed, which shouldn't happen");
      } else {
        throw new AuthenticationServiceException("Unrecognized return value " + status.toString());
      }
    }

    return null;
  }
예제 #2
0
  /**
   * 判断用户是否从Remember Me Cookie自动登录
   *
   * @return
   */
  private boolean isRememberMeAuthenticated() {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
      return false;
    }
    return RememberMeAuthenticationToken.class.isAssignableFrom(authentication.getClass());
  }
예제 #3
0
 @RequestMapping(value = "/logout", method = RequestMethod.POST)
 @AccessUser
 public void logout() {
   Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
   if (authentication instanceof SecurityToken) {
     SecurityToken token = (SecurityToken) authentication;
     tokenService.evict(token.getToken());
   } else {
     throw new InvalidSubtypeTypeException(Authentication.class, authentication.getClass());
   }
 }
  @Override
  public Authentication authenticate(final Authentication authentication)
      throws AuthenticationException {
    if (!supports(authentication.getClass())) {
      return null;
    }

    if (authentication.isAuthenticated() || authentication.getCredentials() == null) {
      return authentication;
    }

    final String code = (String) ((MailAuthenticationToken) authentication).getCredentials();

    UserDetails user =
        new TransactionTemplate(transactionManager)
            .execute(
                new TransactionCallback<UserDetails>() {
                  @Override
                  public UserDetails doInTransaction(TransactionStatus transactionStatus) {
                    Account account = accountService.findByCode(code);
                    if (account != null) {
                      account.setEnabled(true);
                      return userDetailsService.loadUserByUsername(account.getMail());
                    } else {
                      return null;
                    }
                  }
                });

    if (user != null) {
      if (!user.isAccountNonLocked()) {
        throw new LockedException("User account is locked.", user);
      }

      if (!user.isEnabled()) {
        throw new DisabledException("User account is disabled.", user);
      }

      if (!user.isAccountNonExpired()) {
        throw new AccountExpiredException("User account has expired.");
      }

      return new MailAuthenticationToken(code, user, user.getAuthorities());
    } else {
      throw new BadCredentialsException("Can't find user account by code.");
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see org.springframework.security.authentication.AuthenticationProvider#
   * authenticate(org.springframework.security.core.Authentication)
   */
  @Override
  public Authentication authenticate(final Authentication authentication)
      throws AuthenticationException {

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

    if (authentication instanceof OIDCAuthenticationToken) {

      // Default authorities set
      // TODO: let this be configured
      Collection<SimpleGrantedAuthority> authorities =
          Sets.newHashSet(new SimpleGrantedAuthority("ROLE_USER"));

      OIDCAuthenticationToken token = (OIDCAuthenticationToken) authentication;

      UserInfo userInfo = userInfoFetcher.loadUserInfo(token);

      if (userInfo == null) {
        // TODO: user Info not found -- error?
      } else {
        if (!Strings.isNullOrEmpty(userInfo.getSub())
            && !userInfo.getSub().equals(token.getUserId())) {
          // the userinfo came back and the user_id fields don't match what was in the id_token
          throw new UsernameNotFoundException(
              "user_id mismatch between id_token and user_info call: "
                  + userInfo.getSub()
                  + " / "
                  + token.getUserId());
        }
      }

      return new OIDCAuthenticationToken(
          token.getUserId(),
          token.getIssuer(),
          userInfo,
          authoritiesMapper.mapAuthorities(authorities),
          token.getIdTokenValue(),
          token.getAccessTokenValue(),
          token.getRefreshTokenValue());
    }

    return null;
  }
 @Override
 public String retrieveSourceOrcid() {
   Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
   if (authentication == null) {
     return null;
   }
   // API
   if (OAuth2Authentication.class.isAssignableFrom(authentication.getClass())) {
     AuthorizationRequest authorizationRequest =
         ((OAuth2Authentication) authentication).getAuthorizationRequest();
     return authorizationRequest.getClientId();
   }
   // Delegation mode
   String realUserIfInDelegationMode = getRealUserIfInDelegationMode(authentication);
   if (realUserIfInDelegationMode != null) {
     return realUserIfInDelegationMode;
   }
   // Normal web user
   return retrieveEffectiveOrcid(authentication);
 }
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
      return null;
    }
    UsernamePasswordAuthenticationToken token =
        (UsernamePasswordAuthenticationToken) authentication;
    String username = token.getName();
    String password = String.valueOf(token.getCredentials());
    FutureCallback<UserAccount> accountCallback = new FutureCallback<UserAccount>();
    AuthenticateUserCommand command = new AuthenticateUserCommand(username, password.toCharArray());
    try {
      commandBus.dispatch(
          new GenericCommandMessage<AuthenticateUserCommand>(command), accountCallback);
      // the bean validating interceptor is defined as a dispatch interceptor, meaning it is
      // executed before
      // the command is dispatched.
    } catch (StructuralCommandValidationFailedException e) {
      return null;
    }
    UserAccount account;
    try {
      account = accountCallback.get();
      if (account == null) {
        throw new BadCredentialsException("Invalid username and/or password");
      }
    } catch (InterruptedException e) {
      throw new AuthenticationServiceException("Credentials could not be verified", e);
    } catch (ExecutionException e) {
      throw new AuthenticationServiceException("Credentials could not be verified", e);
    }

    UsernamePasswordAuthenticationToken result =
        new UsernamePasswordAuthenticationToken(
            account, authentication.getCredentials(), userAuthorities);
    result.setDetails(authentication.getDetails());
    return result;
  }
 /*
  * (non-Javadoc)
  *
  * @seeorg.springframework.security.providers.AuthenticationProvider#authenticate(org.
  * springframework.security. Authentication)
  */
 public Authentication authenticate(Authentication input) throws AuthenticationException {
   try {
     if (input instanceof UsernamePasswordAuthenticationToken) {
       String username = (String) input.getPrincipal();
       String password = (String) input.getCredentials();
       IUser user =
           SiteWhereServer.getInstance().getUserManagement().authenticate(username, password);
       List<IGrantedAuthority> auths =
           SiteWhereServer.getInstance()
               .getUserManagement()
               .getGrantedAuthorities(user.getUsername());
       SitewhereUserDetails details = new SitewhereUserDetails(user, auths);
       return new SitewhereAuthentication(details, password);
     } else if (input instanceof SitewhereAuthentication) {
       return input;
     } else {
       throw new AuthenticationServiceException(
           "Unknown authentication: " + input.getClass().getName());
     }
   } catch (SiteWhereException e) {
     throw new BadCredentialsException("Unable to authenticate.", e);
   }
 }
  /* (non-Javadoc)
   * @see org.springframework.security.authentication.AuthenticationProvider#authenticate(org.springframework.security.Authentication)
   */
  public Authentication authenticate(final Authentication authentication)
      throws AuthenticationException {

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

    if (authentication instanceof OutOfBandAuthenticationToken) {
      OutOfBandAuthenticationToken response = (OutOfBandAuthenticationToken) authentication;
      // Lookup user details
      UserDetails userDetails =
          new User(
              response.getName(),
              UUID.randomUUID().toString(),
              true,
              true,
              true,
              true,
              new ArrayList<GrantedAuthority>());
      return createSuccessfulAuthentication(userDetails, response);
    }

    return null;
  }
  /**
   * {@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;
  }