[File Server] Allow mixed Authentication Methods

0 votes
asked Apr 15 by MattiasAndries (140 points)

Hi,

I'm wondering if it is possible to authenticate a user using either Public Key Authentification OR Password Authentification. From what I've seen in the documentation it seems like I can only allow one method or allow ALL methods which I don't want.

I would like to do something like this:

        if (!string.IsNullOrWhiteSpace(authenticationEvent.Password))
        {
            user = await getAuthenticatorByMethod(AuthenticationMethods.Password).AuthenticateUser(authenticationEvent);
        }
        else if (!(authenticationEvent.Key is null))
        {
            user = await getAuthenticatorByMethod(AuthenticationMethods.PublicKey).AuthenticateUser(authenticationEvent);
        }
Applies to: File Server

1 Answer

0 votes
answered Apr 17 by Pavel Matyska (13,340 points)

Hi,

If you want to allow authentication using password OR public key, you have to allow both for the whole server using this line of code.

// allow 'password' and/or 'public key' authentication
server.Settings.AllowedAuthenticationMethods =
    AuthenticationMethods.PublicKey | AuthenticationMethods.Password

Then you can authenticate a user based on provided password OR public key

// register authentication event handler
server.Authentication += (sender, e) =>
{
    if (e.UserName == userName)
    {
        if (e.Password != null)
        {
            // when authenticating using a password, make sure it is correct
            // compare password from the authentication event with the password associated
            // with the user
            if (e.Password == password)
            {
                e.Accept(new FileServerUser(e.UserName, null, virtualRoot));
                return;
            }
        }
        else if (e.Key != null)
        {
            // when authenticating using a key, make sure it is correct
            // compare public key from the authentication event with the public key associated
            // with the user
            if (e.Key.Equals(publicKey))
            {
                e.Accept(new FileServerUser(e.UserName, null, virtualRoot));
                return;
            }
        }

    // if no correct credential was supplied, reject this authentication attempt
    e.Reject();
};

If you need to authenticate some users using password and some users using public key, please read our advanced authentication documentation page.

...