This repository has been archived by the owner on Jun 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathAzureAuthentication.cs
74 lines (62 loc) · 2.36 KB
/
AzureAuthentication.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Inedo.Serialization;
namespace Inedo.BuildMasterExtensions.Azure
{
[SlimSerializable]
[Serializable]
public class AzureAuthentication
{
[Persistent]
public string SubscriptionID { get; set; }
[Persistent]
public string PEMENcoded { get; set; }
[Persistent]
public string CertificateName { get; set; }
[Persistent]
public string ConfigFileName { get; set; }
public bool HasCertificate => !string.IsNullOrEmpty(this.PEMENcoded) || !string.IsNullOrEmpty(this.CertificateName) || !string.IsNullOrEmpty(this.ConfigFileName);
public X509Certificate2 Certificate
{
get
{
if (!string.IsNullOrEmpty(this.PEMENcoded))
return this.GetCertificateFromString(this.PEMENcoded);
if (!string.IsNullOrEmpty(this.CertificateName))
return this.GetCertificateFromStore(this.CertificateName);
return null;
}
}
internal X509Certificate2 GetCertificateFromStore(string name)
{
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
try
{
store.Open(OpenFlags.ReadOnly);
var certs = store.Certificates.Find(X509FindType.FindBySubjectName, name, false);
if (certs.Count == 0)
throw new InvalidOperationException($"Cannot find a certificate named \"{name}\" in the machine store.");
return certs[0];
}
finally
{
store.Close();
}
}
internal X509Certificate2 GetCertificateFromString(string pemEncodedCertificate)
{
try
{
var file = Path.GetTempFileName();
File.WriteAllText(file, pemEncodedCertificate, Encoding.ASCII);
return new X509Certificate2(file);
}
catch (Exception ex)
{
throw new InvalidOperationException("An error occurred decoding the certificate from its PEM-encoded value, error was: " + ex.Message, ex);
}
}
}
}