Skip to content

Authenticated Server

Nick 닉 edited this page Jan 15, 2016 · 3 revisions

Creating an authenticated server is a bit more complicated than making a basic server because you need to specify an AuthenticationPacket and an Authenticator.

The AuthenticationPacket contains the necessary credentials in order for a client to successfully authenticated and the Authenticator takes the credentials given by an AuthenticationPacket and determines whether or not to authorize the connection.

The first thing we need to do is create an extension of AuthenticationPacket. In this example, I will be authenticating a user by a username and password:

public class UserAuthenticationPacket extends AuthenticationPacket {

    //If you choose not to use the encrypted socket I recommend that
    //you use some method of encryption in this packet
    private String username, password;

    public UserAuthenticationPacket() {} //necessary for all packets

    public UserAuthenticationPacket(String username, String password){
        this.username = username;
        this.password = password;
    }

    public String getUsername(){ return username; }

    public String getPassword(){ return password; }

}

Next we have to build an Authenticator that takes in an AuthenticationPacket and determines whether or not it is valid:

public class UserAuthenticator implements Authenticator {
    
    public boolean authenticate(AuthenticationPacket authenticationPacket) {
         //Code that could ping a website, check a database, etc.
    }

}

Before we create the AuthenticatedTcpServerManager, we have to create a ServerSocket. To create a encrypted SSLServerSocket with default settings, use

TcpSocketFactory.generateServerSocket(port);

otherwise, you can create your own.

Now we can create our AuthenticatedTcpServerManager. The AuthenticatedTcpServerManager contructor takes a ServerSocket, instance of your Authenticator, the class of your AuthenticationPacket and a boolean (true = start listening, false = wait for startConnManager() call)

AuthenticatedTcpServerManager serverManager = new AuthenticatedTcpServerManager(serverSocket, new UserAuthenticator(), UserAuthenticationPacket.class, true);

Clone this wiki locally