1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4 
5 using System.Net.Http.Headers;
6 using System.Text;
7 
8 namespace System.Net.Http
9 {
10     internal partial class AuthenticationHelper
11     {
12         public const string Basic = "Basic";
13 
TrySetBasicAuthToken(HttpRequestMessage request, ICredentials credentials)14         public static bool TrySetBasicAuthToken(HttpRequestMessage request, ICredentials credentials)
15         {
16             NetworkCredential credential = credentials.GetCredential(request.RequestUri, Basic);
17             if (credential == null)
18             {
19                 return false;
20             }
21 
22             request.Headers.Authorization = new AuthenticationHeaderValue(Basic, GetBasicTokenForCredential(credential));
23             return true;
24         }
25 
GetBasicTokenForCredential(NetworkCredential credential)26         public static string GetBasicTokenForCredential(NetworkCredential credential)
27         {
28             if (credential.UserName.IndexOf(':') != -1)
29             {
30                 // TODO #23135: What's the right way to handle this?
31                 throw new NotImplementedException($"Basic auth: can't handle ':' in username \"{credential.UserName}\"");
32             }
33 
34             string userPass = credential.UserName + ":" + credential.Password;
35             if (!string.IsNullOrEmpty(credential.Domain))
36             {
37                 if (credential.Domain.IndexOf(':') != -1)
38                 {
39                     // TODO #23135: What's the right way to handle this?
40                     throw new NotImplementedException($"Basic auth: can't handle ':' in domain \"{credential.Domain}\"");
41                 }
42 
43                 userPass = credential.Domain + "\\" + userPass;
44             }
45 
46             return Convert.ToBase64String(Encoding.UTF8.GetBytes(userPass));
47         }
48     }
49 }
50