Java Code Examples for org.apache.sshd.server.session.ServerSession

The following examples show how to use org.apache.sshd.server.session.ServerSession. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Bukkit-SSHD   Source File: ConfigPasswordAuthenticator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean authenticate(String username, String password, ServerSession serverSession) {
    if (SshdPlugin.instance.getConfig().getString("credentials." + username).equals(password)) {
        failCounts.put(username, 0);
        return true;
    }
    SshdPlugin.instance.getLogger().info("Failed login for " + username + " using password authentication.");

    try {
        Thread.sleep(3000);
        if (failCounts.containsKey(username)) {
            failCounts.put(username, failCounts.get(username) + 1);
        } else {
            failCounts.put(username, 1);
        }
        if (failCounts.get(username) >= 3) {
            failCounts.put(username, 0);
            serverSession.close(true);
        }
    } catch (InterruptedException e) {
        // do nothing
    }
    return false;
}
 
Example 2
Source Project: termd   Source File: SshTtyTestBase.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void server(final Consumer<TtyConnection> onConnect) {
  if (sshd != null) {
    throw failure("Already a server");
  }
  try {
    sshd = createServer();
    sshd.setPort(5000);
    sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("hostkey.ser").toPath()));
    sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
      @Override
      public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
        return true;
      }
    });
    sshd.setShellFactory(new Factory<Command>() {
      @Override
      public Command create() {
        return createConnection(onConnect);
      }
    });
    sshd.start();
  } catch (Exception e) {
    throw failure(e);
  }
}
 
Example 3
Source Project: termd   Source File: AsyncAuthTestBase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncAuthFailed() throws Exception {
  startServer();
  authenticator = new PasswordAuthenticator() {
    @Override
    public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
      final AsyncAuth auth = new AsyncAuth();
      new Thread() {
        @Override
        public void run() {
          try {
            Thread.sleep(200);
          } catch (InterruptedException ignore) {
          } finally {
            auth.setAuthed(false);
          }
        }
      }.start();
      throw auth;
    }
  };
  assertFalse(authenticate());
}
 
Example 4
Source Project: termd   Source File: AsyncAuthTestBase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncAuthSucceeded() throws Exception {
  startServer();
  authenticator = new PasswordAuthenticator() {
    @Override
    public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
      final AsyncAuth auth = new AsyncAuth();
      new Thread() {
        @Override
        public void run() {
          try {
            Thread.sleep(200);
          } catch (InterruptedException ignore) {
          } finally {
            auth.setAuthed(true);
          }
        }
      }.start();
      throw auth;
    }
  };
  assertTrue(authenticate());
}
 
Example 5
@Override
public boolean authenticate(String username, String pass,
                            ServerSession serverSession) throws PasswordChangeRequiredException {
    try {
        Authentication auth = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(username, pass));
        LOGGER.debug("User {} authenticated with authorities: {}", username, auth.getAuthorities());
        List<String> authorities =
                auth.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        serverSession.getIoSession().setAttribute(AUTHENTICATION_ATTRIBUTE, new SshAuthentication(username,
                auth.getPrincipal(), auth.getDetails(), auth.getCredentials(), authorities));
        return auth.isAuthenticated();
    } catch (AuthenticationException e) {
        LOGGER.error("Unable to authenticate user [{}] : {}", username, e.getMessage());
        LOGGER.debug("Unable to authenticate user [{}]", username, e);
        return false;
    }
}
 
Example 6
@Test
void authenticate() {
    ServerSession session = Mockito.mock(ServerSession.class);
    IoSession io = Mockito.mock(IoSession.class);
    Mockito.when(session.getIoSession()).thenReturn(io);
    Mockito.when(ctx.getBeansOfType(any())).thenReturn(Collections.singletonMap("sec", sec));
    ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
    Mockito.when(io.setAttribute(eq(AUTHENTICATION_ATTRIBUTE), captor.capture())).thenReturn(null);
    SshShellSecurityAuthenticationProvider provider = new SshShellSecurityAuthenticationProvider(ctx, null);
    provider.init();

    Mockito.when(sec.authenticate(any())).thenReturn(
            new UsernamePasswordAuthenticationToken("principal", "credentials",
                    Collections.singletonList(new SimpleGrantedAuthority("USER"))));
    assertTrue(provider.authenticate("user", "pass", session));
    SshAuthentication auth = (SshAuthentication) captor.getValue();
    assertEquals("principal", auth.getPrincipal());
    assertEquals("credentials", auth.getCredentials());
    assertEquals(1, auth.getAuthorities().size());
    assertNull(auth.getDetails());

    // fail auth
    Mockito.when(sec.authenticate(any())).thenThrow(new BadCredentialsException("[MOCK]"));
    assertFalse(provider.authenticate("user", "pass", session));
}
 
Example 7
@Test
public void testBuildSshRequestInfoObj() throws ArtifactNotFoundException, IOException,
                ArtifactMetaDataParseFailureException, ParseException {
    IoSession ioSession = Mockito.mock(IoSession.class);
    Mockito.when(ioSession.getRemoteAddress()).thenReturn(new InetSocketAddress("10.0.0.1", 9999));
    ServerSession session = Mockito.mock(ServerSession.class);
    Mockito.when(session.getUsername()).thenReturn("screwdrv");
    Mockito.when(session.getIoSession()).thenReturn(ioSession);

    SshRequestInfo request =
                    new SshRequestInfo.Builder(session).setStartTimestamp(1411455384909L)
                                    .setMethod(SshRequestStatus.CREATED.getReasonPhrase())
                                    .setStatus(SshRequestStatus.CREATED.getStatusCode()).setExitValue(0)
                                    .setRepoName("maven-local-release").setPath("/com/yahoo/sshd/util/Utils.java")
                                    .setSize(1024000L).build();

    Assert.assertEquals(request.getStartTimestamp(), 1411455384909L);
    Assert.assertEquals(request.getRemoteAddr(), "10.0.0.1");
    Assert.assertEquals(request.getRepoName(), "maven-local-release");
    Assert.assertEquals(request.getRequestPath(), "/com/yahoo/sshd/util/Utils.java");
    Assert.assertEquals(request.getStatus(), 201);
    Assert.assertEquals(request.getExitValue(), 0);
    Assert.assertEquals(request.getMethod(), "PUT");
    Assert.assertEquals(request.getUserName(), "screwdrv");
}
 
Example 8
Source Project: ExpectIt   Source File: AntHarnessTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void startSshServer() throws IOException {
    sshServer = SshServer.setUpDefaultServer();
    ServerSocket serverSocket = new ServerSocket(0);
    sshPort = serverSocket.getLocalPort();
    serverSocket.close();
    sshServer.setPort(sshPort);
    sshServer.setPasswordAuthenticator(
            new PasswordAuthenticator() {
                @Override
                public boolean authenticate(
                        String username,
                        String password,
                        ServerSession session) {
                    return "ssh".equals(username) && "secret".equals(password);
                }
            });
    sshServer.setShellFactory(new SshEchoCommandFactory());
    sshServer.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
    sshServer.start();
}
 
Example 9
Source Project: java-examples   Source File: EmbeddedSftpServer.java    License: MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    final PublicKey allowedKey = decodePublicKey();
    this.server.setPublickeyAuthenticator(new PublickeyAuthenticator() {

        @Override
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            return key.equals(allowedKey);
        }

    });
    this.server.setPort(this.port);
    this.server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Files.createTempFile("host_file", ".ser")));
    this.server.setSubsystemFactories(Collections.<NamedFactory<Command>>singletonList(new SftpSubsystemFactory()));
    server.setFileSystemFactory(new VirtualFileSystemFactory(Files.createTempDirectory("SFTP_TEMP")));
    server.setCommandFactory(new ScpCommandFactory());
}
 
Example 10
Source Project: java-examples   Source File: EmbeddedSftpServer.java    License: MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    final PublicKey allowedKey = decodePublicKey();
    this.server.setPublickeyAuthenticator(new PublickeyAuthenticator() {

        @Override
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            return key.equals(allowedKey);
        }

    });
    this.server.setPort(this.port);
    this.server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Files.createTempFile("host_file", ".ser")));
    this.server.setSubsystemFactories(Collections.<NamedFactory<Command>>singletonList(new SftpSubsystemFactory()));
    server.setFileSystemFactory(new VirtualFileSystemFactory(Files.createTempDirectory("SFTP_TEMP")));
    server.setCommandFactory(new ScpCommandFactory());
}
 
Example 11
Source Project: sftp-fs   Source File: FixedSftpSubsystem.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Command create() {
    SftpSubsystem subsystem = new FixedSftpSubsystem(getExecutorService(), isShutdownOnExit(), getUnsupportedAttributePolicy(),
            getFileSystemAccessor(), getErrorStatusDataHandler());
    Collection<? extends SftpEventListener> listeners = getRegisteredListeners();
    if (GenericUtils.size(listeners) > 0) {
        for (SftpEventListener l : listeners) {
            subsystem.addSftpEventListener(l);
        }
    }
    subsystem.addSftpEventListener(new AbstractSftpEventListenerAdapter() {
        @Override
        public void open(ServerSession session, String remoteHandle, Handle localHandle) {
            if (localHandle instanceof DirectoryHandle) {
                DirectoryHandle directoryHandle = (DirectoryHandle) localHandle;
                directoryHandle.markDotSent();
                directoryHandle.markDotDotSent();
            }
        }
    });

    return subsystem;
}
 
Example 12
@Test
public void testObjectEqual() throws ArtifactNotFoundException, IOException, ArtifactMetaDataParseFailureException,
                ParseException {
    IoSession ioSession = Mockito.mock(IoSession.class);
    Mockito.when(ioSession.getRemoteAddress()).thenReturn(new InetSocketAddress("10.0.0.1", 9999));
    ServerSession session = Mockito.mock(ServerSession.class);
    Mockito.when(session.getUsername()).thenReturn("screwdrv");
    Mockito.when(session.getIoSession()).thenReturn(ioSession);

    SshRequestInfo request1 =
                    new SshRequestInfo.Builder(session).setStartTimestamp(1411455384909L)
                                    .setMethod(SshRequestStatus.CREATED.getReasonPhrase())
                                    .setStatus(SshRequestStatus.CREATED.getStatusCode()).setExitValue(0)
                                    .setRepoName("maven-local-release").setPath("/com/yahoo/sshd/util/Utils.java")
                                    .setSize(1024000L).build();

    SshRequestInfo request2 =
                    new SshRequestInfo.Builder(session).setStartTimestamp(1411455384909L)
                                    .setMethod(SshRequestStatus.OK.getReasonPhrase())
                                    .setStatus(SshRequestStatus.OK.getStatusCode()).setExitValue(0)
                                    .setRepoName("maven-local-release").setPath("/com/yahoo/sshd/util/Utils.java")
                                    .setSize(1024000L).build();

    Assert.assertFalse(request1.equals(request2));
}
 
Example 13
Source Project: product-ei   Source File: SftpServerRunner.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    sshd.setPort(port);
    sshd.setSubsystemFactories(
            Arrays.<NamedFactory<Command>>asList(new SftpSubsystemFactory()));
    sshd.setCommandFactory(new ScpCommandFactory());
    sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
    sshd.setFileSystemFactory(new VirtualFileSystemFactory(Paths.get(path)));
    sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
        @Override
        public boolean authenticate(final String username, final String password, final ServerSession session) {
            return StringUtils.equals(username, ftpUser) && StringUtils.equals(password, ftpPassword);
        }
    });
    try {
        LOGGER.info("Starting SFTP server on port {}", port);
        sshd.start();
    } catch (IOException e) {
        LOGGER.error("Error starting SFTP server", e);
    }
}
 
Example 14
public boolean authenticate(String username, PublicKey publicKey, ServerSession session) {
    // first we need to see if they have an entry.
    Map<PublicKey, AuthorizedKey> map = userToPkToAuthKeyMap.get(username);

    if (null == map) {
        LOGGER.error("Failed to authenticate unknown user {} from {}.", username, session.getIoSession()
                        .getRemoteAddress());
        return false;
    }

    AuthorizedKey ak = map.get(publicKey);
    if (null == ak) {
        LOGGER.error("Failed authentication of user {} from {} with unknown public key.", username, session
                        .getIoSession().getRemoteAddress());
        return false;
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Successful authentication of user {} from {} with public key {}.", new Object[] {username,
                        session.getIoSession().getRemoteAddress(), ak.getAlias()});
    }

    return true;
}
 
Example 15
Source Project: micro-integrator   Source File: ESBJAVA3470.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Starts a SFTP server on port 22
 * @param carbonHome
 */
private void setupSftpServer(String carbonHome) {
    SshServer sshd = SshServer.setUpDefaultServer();
    sshd.setPort(FTP_PORT);
    //sshd.setKeyPairProvider(new FileKeyPairProvider(new
    // String[]{"/home/ravi/WORK/SUPPORT/JIRA/SKYTVNZDEV-26/SftpTest/dist/hostkey.ser"}));
    ClassLoader classLoader = getClass().getClassLoader();
    log.info("Using identity file: " + classLoader.getResource("sftp/id_rsa.pub").getFile());
    File file = new File(classLoader.getResource("sftp/id_rsa.pub").getFile());
    sshd.setKeyPairProvider(createTestHostKeyProvider(Paths.get(file.getAbsolutePath())));
    sshd.setUserAuthFactories(Arrays.asList(new UserAuthPublicKeyFactory()));
    sshd.setFileSystemFactory(new VirtualFileSystemFactory(Paths.get(carbonHome)));
    sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() {
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            return "sftpuser".equals(username);
        }
    });
    sshd.setCommandFactory(new ScpCommandFactory());
    sshd.setSubsystemFactories(Arrays.asList(new SftpSubsystemFactory()));
    SftpServerRunner sftpServerRunner = new SftpServerRunner(sshd);

    try {
        sftpServerRunner.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 16
Source Project: termd   Source File: BogusPasswordAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean authenticate(String username, String password, ServerSession session) {
    boolean result = (username != null) && username.equals(password);
    if (log.isDebugEnabled()) {
        log.debug("authenticate({}) {} / {} - sucess = {}", session, username, password, Boolean.valueOf(result));
    }

    return result;
}
 
Example 17
Source Project: sftpserver   Source File: Server.java    License: Apache License 2.0 5 votes vote down vote up
public boolean checkUserPassword(final ServerSession session, final String user, final String pwd) {
	final StringBuilder sb = new StringBuilder(40);
	boolean traceInfo = false;
	boolean authOk = false;
	try {
		if (!isEnabledUser(user)) {
			sb.append("[user disabled]");
			return authOk;
		}
		final String value = getValue(user, PROP_PWD);
		if (value == null) {
			sb.append("[no password]");
			return authOk;
		}
		final boolean isCrypted = PasswordEncrypt.isCrypted(value);
		authOk = isCrypted ? PasswordEncrypt.checkPassword(value, pwd) : value.equals(pwd);
		if (!isCrypted) {
			sb.append("[config-unencrypted]");
		}
		traceInfo = isCrypted;
	} finally {
		sb.append("[").append(authOk ? "OK" : "FAIL").append("]");
		if (authOk) {
			logger.authPasswordPostLogin(session, user, (traceInfo ? Level.INFO : Level.WARN), sb.toString());
		} else {
			logger.authPasswordPostLogin(session, user, Level.ERROR, sb.toString());
		}
	}
	return authOk;
}
 
Example 18
Source Project: termd   Source File: SinglePublicKeyAuthTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPublicKeyAuthWithCache() throws Exception {
    final ConcurrentHashMap<String, AtomicInteger> count = new ConcurrentHashMap<String, AtomicInteger>();
    TestCachingPublicKeyAuthenticator auth = new TestCachingPublicKeyAuthenticator(new PublickeyAuthenticator() {
        @SuppressWarnings("synthetic-access")
        @Override
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            String fp = KeyUtils.getFingerPrint(key);
            count.putIfAbsent(fp, new AtomicInteger());
            count.get(fp).incrementAndGet();
            return key.equals(pairRsa.getPublic());
        }
    });
    delegate = auth;

    try (SshClient client = setupTestClient()) {
        client.start();

        try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            session.addPublicKeyIdentity(pairRsaBad);
            session.addPublicKeyIdentity(pairRsa);
            session.auth().verify(5L, TimeUnit.SECONDS);

            assertEquals("Mismatched authentication invocations count", 2, count.size());

            String fpBad = KeyUtils.getFingerPrint(pairRsaBad.getPublic());
            String fpGood = KeyUtils.getFingerPrint(pairRsa.getPublic());
            assertTrue("Missing bad public key", count.containsKey(fpBad));
            assertTrue("Missing good public key", count.containsKey(fpGood));
            assertEquals("Mismatched bad key authentication attempts", 1, count.get(fpBad).get());
            assertEquals("Mismatched good key authentication attempts", 1, count.get(fpGood).get());
        } finally {
            client.stop();
        }
    }

    Thread.sleep(100L);
    assertTrue("Cache not empty", auth.getCache().isEmpty());
}
 
Example 19
Source Project: sftpserver   Source File: ServiceLogger.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void opening(final ServerSession session, final String remoteHandle, final Handle localHandle)
		throws IOException {
	if (!logRequest)
		return;
	if (log.isInfoEnabled()) {
		final Path path = localHandle.getFile();
		log.info("request opening(" + toHuman(session) + ")[" + remoteHandle + "][" //
				+ (Files.isDirectory(path) ? "directory" : "file") + "] " + path);
	}
}
 
Example 20
Source Project: termd   Source File: AsyncAuthTestBase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSyncAuthFailed() throws Exception {
  startServer();
  authenticator = new PasswordAuthenticator() {
    @Override
    public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
      return false;
    }
  };
  assertFalse(authenticate());
}
 
Example 21
Source Project: termd   Source File: AsyncAuthTestBase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSyncAuthSucceeded() throws Exception {
  startServer();
  authenticator = new PasswordAuthenticator() {
    @Override
    public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
      return true;
    }
  };
  assertTrue(authenticate());
}
 
Example 22
Source Project: termd   Source File: AsyncAuthTestBase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncAuthTimeout() throws Exception {
  startServer(500);
  authenticator = new PasswordAuthenticator() {
    @Override
    public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
      throw new AsyncAuth();
    }
  };
  try {
    authenticate();
  } catch (JSchException e) {
    assertTrue("Unexpected failure " + e.getMessage(), e.getMessage().startsWith("SSH_MSG_DISCONNECT"));
  }
}
 
Example 23
Source Project: termd   Source File: AsyncAuthTestBase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncAuthSucceededAfterTimeout() throws Exception {
  startServer(500);
  authenticator = new PasswordAuthenticator() {
    @Override
    public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
      final AsyncAuth auth = new AsyncAuth();
      new Thread() {
        @Override
        public void run() {
          try {
            Thread.sleep(1000);
          } catch (InterruptedException ignore) {
          } finally {
            auth.setAuthed(true);
          }
        }
      }.start();
      throw auth;
    }
  };
  try {
    authenticate();
  } catch (JSchException e) {
    assertTrue("Unexpected failure " + e.getMessage(), e.getMessage().startsWith("SSH_MSG_DISCONNECT"));
  }
}
 
Example 24
private String sessionTable(ServerSession session) {
    return helper.renderTable(SimpleTable.builder()
            .column("Property").column("Value")
            .line(Arrays.asList("Session id", session.getIoSession().getId()))
            .line(Arrays.asList("Local address", session.getIoSession().getLocalAddress()))
            .line(Arrays.asList("Remote address", session.getIoSession().getRemoteAddress()))
            .line(Arrays.asList("Server version", session.getServerVersion()))
            .line(Arrays.asList("Client version", session.getClientVersion()))
            .build());
}
 
Example 25
@Override
public boolean authenticate(String username, String pass,
                            ServerSession serverSession) throws PasswordChangeRequiredException {

    serverSession.getIoSession().setAttribute(AUTHENTICATION_ATTRIBUTE, new SshAuthentication(username, username));

    return username.equals(this.user) && pass.equals(this.password);
}
 
Example 26
Source Project: ssh-shell-spring-boot   Source File: SshShellUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
public static ChannelSession mockChannelSession(Long id) {
    ChannelSession session = mock(ChannelSession.class);
    ServerSession serverSession = mock(ServerSession.class);
    when(session.getSession()).thenReturn(serverSession);
    IoSession ioSession = mock(IoSession.class);
    when(serverSession.getIoSession()).thenReturn(ioSession);
    when(ioSession.getId()).thenReturn(id);
    return session;
}
 
Example 27
Source Project: sftpserver   Source File: ServiceLogger.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void closing(final ServerSession session, final String remoteHandle, final Handle localHandle) {
	if (!logRequest)
		return;
	if (log.isInfoEnabled()) {
		final Path path = localHandle.getFile();
		log.info("request close(" + toHuman(session) + ")[" + remoteHandle + "][" //
				+ (Files.isDirectory(path) ? "dir" : "file") + "] " + path);
	}
}
 
Example 28
@Override
public boolean authenticate(String username, String password, ServerSession session) throws
        PasswordChangeRequiredException {
    try {
        Authentication auth = authProvider.authenticate(
                new UsernamePasswordAuthenticationToken(username, password));
        session.getIoSession().setAttribute(Constants.USER, username);
        session.getIoSession().setAttribute(Constants.USER_ROLES, auth.getAuthorities().stream()
                .map(ga -> ga.getAuthority()).collect(Collectors.toSet()));
        return true;
    } catch (AuthenticationException ex) {
        log.warn(ex.getMessage());
        return false;
    }
}
 
Example 29
@Override
public boolean authenticate(String username, String password, ServerSession session) throws
        PasswordChangeRequiredException {
    if (username.equals(props.getUsername()) && password.equals(props.getPassword())) {
        session.getIoSession().setAttribute(Constants.USER_ROLES, systemCommandRoles);
        session.getIoSession().setAttribute(Constants.USER, username);
        return true;
    }
    return false;
}
 
Example 30
Source Project: sftpserver   Source File: Server.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean authenticate(final String username, final String password, final ServerSession session) {
	logger.authPasswordPreLogin(session, username);
	if ((username != null) && (password != null)) {
		return db.checkUserPassword(session, username, password);
	}
	logger.authPasswordPostLogin(session, username, Level.ERROR, "[null data][FAIL]");
	return false;
}