cosullivan / SmtpServer

A SMTP Server component written in C#
MIT License
676 stars 160 forks source link

How to enforce plain authentication? #147

Closed romeosan closed 3 years ago

romeosan commented 3 years ago

Great work @cosullivan. I am just wondering how I can enforce authentication so that it does not accept anonymous connections. I already added this and it works when I enable authentication on my client but it seems that auth is optional from smtpserver side. E.g. with Thunderbird I can send when I set my client to no auth.

    public class SampleUserAuthenticator : IUserAuthenticator, IUserAuthenticatorFactory
    {
        public Task<bool> AuthenticateAsync(ISessionContext context, string user, string password, CancellationToken token)
        {
            /*
            Debug.Write(user + " | " + password);
            return Task.FromResult(user.Length > 4);
            */

            return Task.FromResult(user == "myname@mydom.com" && password == "MyPassword11");

        }
romeosan commented 3 years ago

PS: I am starting the smtp server with these options:

                X509Certificate2 cert = buildSelfSignedServerCertificate();

                var options = new SmtpServerOptionsBuilder()
                .ServerName("MyServerName") // its just a name which will be shown in the welcome string
                .Port(25, 587)
                .Port(465, isSecure: true)
                //.Certificate(CreateX509Certificate2())
                .Certificate(cert)
                .MessageStore(new SampleMessageStore())
                .MailboxFilter(new SampleMailboxFilter())
                .UserAuthenticator(new SampleUserAuthenticator())
                .Build();

                var smtpServer = new SmtpServer.SmtpServer(options);

                await smtpServer.StartAsync(CancellationToken.None);
cosullivan commented 3 years ago

Hi @romeosan ,

It sounds like you need to enable the AuthenticationRequired option which can only be set using the Endpoint builder.

.Endpoint(builder =>
    builder
        .Port(465)
        .IsSecure(true)
        .AuthenticationRequired())

So your options could look something like this (assuming you just want it enabled for port 465);

var options = new SmtpServerOptionsBuilder()
    .ServerName("MyServerName") // its just a name which will be shown in the welcome string
    .Port(25, 587)
    .Endpoint(builder =>
        builder
            .Port(465)
            .IsSecure(true)
            .AuthenticationRequired())
    .Certificate(cert)
    .MessageStore(new SampleMessageStore())
    .MailboxFilter(new SampleMailboxFilter())
    .UserAuthenticator(new SampleUserAuthenticator())
    .Build();

Thanks, Cain.

romeosan commented 3 years ago

thank you very much for the fast answer @cosullivan, that worked!