File: System\Net\Mail\SmtpLoginAuthenticationModule.cs
Web Access
Project: src\src\libraries\System.Net.Mail\src\System.Net.Mail.csproj (System.Net.Mail)
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
 
using System.Collections.Generic;
using System.Security.Authentication.ExtendedProtection;
 
namespace System.Net.Mail
{
    internal sealed class SmtpLoginAuthenticationModule : ISmtpAuthenticationModule
    {
        private readonly Dictionary<object, NetworkCredential> _sessions = new Dictionary<object, NetworkCredential>();
 
        internal SmtpLoginAuthenticationModule()
        {
        }
 
        public Authorization? Authenticate(string? challenge, NetworkCredential? credential, object sessionCookie, string? spn, ChannelBinding? channelBindingToken)
        {
            lock (_sessions)
            {
                NetworkCredential? cachedCredential;
                if (!_sessions.TryGetValue(sessionCookie, out cachedCredential))
                {
                    if (credential == null || ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
                    {
                        return null;
                    }
 
                    _sessions[sessionCookie] = credential;
 
                    string userName = credential.UserName;
                    string domain = credential.Domain;
 
                    if (domain != null && domain.Length > 0)
                    {
                        userName = domain + "\\" + userName;
                    }
 
                    return new Authorization(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(userName)), false);
                }
                else
                {
                    _sessions.Remove(sessionCookie);
 
                    return new Authorization(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(cachedCredential.Password)), true);
                }
            }
        }
 
        public string AuthenticationType
        {
            get
            {
                return "login";
            }
        }
 
        public void CloseContext(object sessionCookie)
        {
            // This is a no-op since the context is not
            // kept open by this module beyond auth completion.
        }
    }
}