/
WebRequestPSCmdlet.Common.cs
784 lines (675 loc) · 28.4 KB
/
WebRequestPSCmdlet.Common.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Net;
using System.IO;
using System.Text;
using System.Collections;
using System.Globalization;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
#if !CORECLR
using mshtml;
#endif
using Microsoft.Win32;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The valid values for the -Authentication parameter for Invoke-RestMethod and Invoke-WebRequest
/// </summary>
public enum WebAuthenticationType
{
/// <summary>
/// No authentication. Default.
/// </summary>
None,
/// <summary>
/// RFC-7617 Basic Authentication. Requires -Credential
/// </summary>
Basic,
/// <summary>
/// RFC-6750 OAuth 2.0 Bearer Authentication. Requires -Token
/// </summary>
Bearer,
/// <summary>
/// RFC-6750 OAuth 2.0 Bearer Authentication. Requires -Token
/// </summary>
OAuth,
}
/// <summary>
/// Base class for Invoke-RestMethod and Invoke-WebRequest commands.
/// </summary>
public abstract partial class WebRequestPSCmdlet : PSCmdlet
{
#region Virtual Properties
#region URI
/// <summary>
/// gets or sets the parameter UseBasicParsing
/// </summary>
[Parameter]
public virtual SwitchParameter UseBasicParsing { get; set; }
/// <summary>
/// gets or sets the Uri property
/// </summary>
[Parameter(Position = 0, Mandatory = true)]
[ValidateNotNullOrEmpty]
public virtual Uri Uri { get; set; }
#endregion
#region Session
/// <summary>
/// gets or sets the Session property
/// </summary>
[Parameter]
public virtual WebRequestSession WebSession { get; set; }
/// <summary>
/// gets or sets the SessionVariable property
/// </summary>
[Parameter]
[Alias("SV")]
public virtual string SessionVariable { get; set; }
#endregion
#region Authorization and Credentials
/// <summary>
/// Gets or sets the AllowUnencryptedAuthentication property
/// </summary>
[Parameter]
public virtual SwitchParameter AllowUnencryptedAuthentication { get; set; }
/// <summary>
/// Gets or sets the Authentication property used to determin the Authentication method for the web session.
/// Authentication does not work with UseDefaultCredentials.
/// Authentication over unencrypted sessions requires AllowUnencryptedAuthentication.
/// Basic: Requires Credential
/// OAuth/Bearer: Requires Token
/// </summary>
[Parameter]
public virtual WebAuthenticationType Authentication { get; set; } = WebAuthenticationType.None;
/// <summary>
/// gets or sets the Credential property
/// </summary>
[Parameter]
[Credential]
public virtual PSCredential Credential { get; set; }
/// <summary>
/// gets or sets the UseDefaultCredentials property
/// </summary>
[Parameter]
public virtual SwitchParameter UseDefaultCredentials { get; set; }
/// <summary>
/// gets or sets the CertificateThumbprint property
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public virtual string CertificateThumbprint { get; set; }
/// <summary>
/// gets or sets the Certificate property
/// </summary>
[Parameter]
[ValidateNotNull]
public virtual X509Certificate Certificate { get; set; }
/// <summary>
/// gets or sets the SkipCertificateCheck property
/// </summary>
[Parameter]
public virtual SwitchParameter SkipCertificateCheck { get; set; }
/// <summary>
/// Gets or sets the Token property. Token is required by Authentication OAuth and Bearer.
/// </summary>
[Parameter]
public virtual SecureString Token { get; set; }
#endregion
#region Headers
/// <summary>
/// gets or sets the UserAgent property
/// </summary>
[Parameter]
public virtual string UserAgent { get; set; }
/// <summary>
/// gets or sets the DisableKeepAlive property
/// </summary>
[Parameter]
public virtual SwitchParameter DisableKeepAlive { get; set; }
/// <summary>
/// gets or sets the TimeOut property
/// </summary>
[Parameter]
[ValidateRange(0, Int32.MaxValue)]
public virtual int TimeoutSec { get; set; }
/// <summary>
/// gets or sets the Headers property
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
[Parameter]
public virtual IDictionary Headers { get; set; }
#endregion
#region Redirect
/// <summary>
/// gets or sets the RedirectMax property
/// </summary>
[Parameter]
[ValidateRange(0, Int32.MaxValue)]
public virtual int MaximumRedirection
{
get { return _maximumRedirection; }
set { _maximumRedirection = value; }
}
private int _maximumRedirection = -1;
#endregion
#region Method
/// <summary>
/// gets or sets the Method property
/// </summary>
[Parameter(ParameterSetName = "StandardMethod")]
[Parameter(ParameterSetName = "StandardMethodNoProxy")]
public virtual WebRequestMethod Method
{
get { return _method; }
set { _method = value; }
}
private WebRequestMethod _method = WebRequestMethod.Default;
/// <summary>
/// gets or sets the CustomMethod property
/// </summary>
[Parameter(Mandatory=true,ParameterSetName = "CustomMethod")]
[Parameter(Mandatory=true,ParameterSetName = "CustomMethodNoProxy")]
[Alias("CM")]
[ValidateNotNullOrEmpty]
public virtual string CustomMethod
{
get { return _customMethod; }
set { _customMethod = value; }
}
private string _customMethod;
#endregion
#region NoProxy
/// <summary>
/// gets or sets the NoProxy property
/// </summary>
[Parameter(Mandatory=true,ParameterSetName = "CustomMethodNoProxy")]
[Parameter(Mandatory=true,ParameterSetName = "StandardMethodNoProxy")]
public virtual SwitchParameter NoProxy { get; set; }
#endregion
#region Proxy
/// <summary>
/// gets or sets the Proxy property
/// </summary>
[Parameter(ParameterSetName = "StandardMethod")]
[Parameter(ParameterSetName = "CustomMethod")]
public virtual Uri Proxy { get; set; }
/// <summary>
/// gets or sets the ProxyCredential property
/// </summary>
[Parameter(ParameterSetName = "StandardMethod")]
[Parameter(ParameterSetName = "CustomMethod")]
[Credential]
public virtual PSCredential ProxyCredential { get; set; }
/// <summary>
/// gets or sets the ProxyUseDefaultCredentials property
/// </summary>
[Parameter(ParameterSetName = "StandardMethod")]
[Parameter(ParameterSetName = "CustomMethod")]
public virtual SwitchParameter ProxyUseDefaultCredentials { get; set; }
#endregion
#region Input
/// <summary>
/// gets or sets the Body property
/// </summary>
[Parameter(ValueFromPipeline = true)]
public virtual object Body { get; set; }
/// <summary>
/// gets or sets the ContentType property
/// </summary>
[Parameter]
public virtual string ContentType { get; set; }
/// <summary>
/// gets or sets the TransferEncoding property
/// </summary>
[Parameter]
[ValidateSet("chunked", "compress", "deflate", "gzip", "identity", IgnoreCase = true)]
public virtual string TransferEncoding { get; set; }
/// <summary>
/// gets or sets the InFile property
/// </summary>
[Parameter]
public virtual string InFile { get; set; }
/// <summary>
/// keep the original file path after the resolved provider path is
/// assigned to InFile
/// </summary>
private string _originalFilePath;
#endregion
#region Output
/// <summary>
/// gets or sets the OutFile property
/// </summary>
[Parameter]
public virtual string OutFile { get; set; }
/// <summary>
/// gets or sets the PassThrough property
/// </summary>
[Parameter]
public virtual SwitchParameter PassThru { get; set; }
#endregion
#endregion Virtual Properties
#region Virtual Methods
internal virtual void ValidateParameters()
{
// sessions
if ((null != WebSession) && (null != SessionVariable))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.SessionConflict,
"WebCmdletSessionConflictException");
ThrowTerminatingError(error);
}
// Authentication
if (UseDefaultCredentials && (Authentication != WebAuthenticationType.None))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationConflict,
"WebCmdletAuthenticationConflictException");
ThrowTerminatingError(error);
}
if ((Authentication != WebAuthenticationType.None) && (null != Token) && (null != Credential))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenConflict,
"WebCmdletAuthenticationTokenConflictException");
ThrowTerminatingError(error);
}
if ((Authentication == WebAuthenticationType.Basic) && (null == Credential))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationCredentialNotSupplied,
"WebCmdletAuthenticationCredentialNotSuppliedException");
ThrowTerminatingError(error);
}
if ((Authentication == WebAuthenticationType.OAuth || Authentication == WebAuthenticationType.Bearer) && (null == Token))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenNotSupplied,
"WebCmdletAuthenticationTokenNotSuppliedException");
ThrowTerminatingError(error);
}
if (!AllowUnencryptedAuthentication && (Authentication != WebAuthenticationType.None) && (Uri.Scheme != "https"))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired,
"WebCmdletAllowUnencryptedAuthenticationRequiredException");
ThrowTerminatingError(error);
}
// credentials
if (UseDefaultCredentials && (null != Credential))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.CredentialConflict,
"WebCmdletCredentialConflictException");
ThrowTerminatingError(error);
}
// Proxy server
if (ProxyUseDefaultCredentials && (null != ProxyCredential))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyCredentialConflict,
"WebCmdletProxyCredentialConflictException");
ThrowTerminatingError(error);
}
else if ((null == Proxy) && ((null != ProxyCredential) || ProxyUseDefaultCredentials))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyUriNotSupplied,
"WebCmdletProxyUriNotSuppliedException");
ThrowTerminatingError(error);
}
// request body content
if ((null != Body) && (null != InFile))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.BodyConflict,
"WebCmdletBodyConflictException");
ThrowTerminatingError(error);
}
// validate InFile path
if (InFile != null)
{
ProviderInfo provider = null;
ErrorRecord errorRecord = null;
try
{
Collection<string> providerPaths = GetResolvedProviderPathFromPSPath(InFile, out provider);
if (!provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
{
errorRecord = GetValidationError(WebCmdletStrings.NotFilesystemPath,
"WebCmdletInFileNotFilesystemPathException", InFile);
}
else
{
if (providerPaths.Count > 1)
{
errorRecord = GetValidationError(WebCmdletStrings.MultiplePathsResolved,
"WebCmdletInFileMultiplePathsResolvedException", InFile);
}
else if (providerPaths.Count == 0)
{
errorRecord = GetValidationError(WebCmdletStrings.NoPathResolved,
"WebCmdletInFileNoPathResolvedException", InFile);
}
else
{
if (Directory.Exists(providerPaths[0]))
{
errorRecord = GetValidationError(WebCmdletStrings.DirecotryPathSpecified,
"WebCmdletInFileNotFilePathException", InFile);
}
_originalFilePath = InFile;
InFile = providerPaths[0];
}
}
}
catch (ItemNotFoundException pathNotFound)
{
errorRecord = new ErrorRecord(pathNotFound.ErrorRecord, pathNotFound);
}
catch (ProviderNotFoundException providerNotFound)
{
errorRecord = new ErrorRecord(providerNotFound.ErrorRecord, providerNotFound);
}
catch (System.Management.Automation.DriveNotFoundException driveNotFound)
{
errorRecord = new ErrorRecord(driveNotFound.ErrorRecord, driveNotFound);
}
if (errorRecord != null)
{
ThrowTerminatingError(errorRecord);
}
}
// output ??
if (PassThru && (OutFile == null))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing,
"WebCmdletOutFileMissingException");
ThrowTerminatingError(error);
}
}
internal virtual void PrepareSession()
{
// make sure we have a valid WebRequestSession object to work with
if (null == WebSession)
{
WebSession = new WebRequestSession();
}
if (null != SessionVariable)
{
// save the session back to the PS environment if requested
PSVariableIntrinsics vi = SessionState.PSVariable;
vi.Set(SessionVariable, WebSession);
}
//
// handle credentials
//
if (null != Credential && Authentication == WebAuthenticationType.None)
{
// get the relevant NetworkCredential
NetworkCredential netCred = Credential.GetNetworkCredential();
WebSession.Credentials = netCred;
// supplying a credential overrides the UseDefaultCredentials setting
WebSession.UseDefaultCredentials = false;
}
else if ((null != Credential || null!= Token) && Authentication != WebAuthenticationType.None)
{
ProcessAuthentication();
}
else if (UseDefaultCredentials)
{
WebSession.UseDefaultCredentials = true;
}
if (null != CertificateThumbprint)
{
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
X509Certificate2Collection tbCollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, CertificateThumbprint, false);
if (tbCollection.Count == 0)
{
CryptographicException ex = new CryptographicException(WebCmdletStrings.ThumbprintNotFound);
throw ex;
}
foreach (X509Certificate2 tbCert in tbCollection)
{
X509Certificate certificate = (X509Certificate)tbCert;
WebSession.AddCertificate(certificate);
}
}
if (null != Certificate)
{
WebSession.AddCertificate(Certificate);
}
//
// handle the user agent
//
if (null != UserAgent)
{
// store the UserAgent string
WebSession.UserAgent = UserAgent;
}
if (null != Proxy)
{
WebProxy webProxy = new WebProxy(Proxy);
webProxy.BypassProxyOnLocal = false;
if (null != ProxyCredential)
{
webProxy.Credentials = ProxyCredential.GetNetworkCredential();
}
else if (ProxyUseDefaultCredentials)
{
// If both ProxyCredential and ProxyUseDefaultCredentials are passed,
// UseDefaultCredentials will overwrite the supplied credentials.
webProxy.UseDefaultCredentials = true;
}
WebSession.Proxy = webProxy;
}
if (-1 < MaximumRedirection)
{
WebSession.MaximumRedirection = MaximumRedirection;
}
// store the other supplied headers
if (null != Headers)
{
foreach (string key in Headers.Keys)
{
// add the header value (or overwrite it if already present)
WebSession.Headers[key] = Headers[key].ToString();
}
}
}
#endregion Virtual Methods
#region Helper Properties
internal string QualifiedOutFile
{
get { return (QualifyFilePath(OutFile)); }
}
internal bool ShouldSaveToOutFile
{
get { return (!string.IsNullOrEmpty(OutFile)); }
}
internal bool ShouldWriteToPipeline
{
get { return (!ShouldSaveToOutFile || PassThru); }
}
#endregion Helper Properties
#region Helper Methods
/// <summary>
/// Verifies that Internet Explorer is available, and that its first-run
/// configuration is complete.
/// </summary>
/// <param name="checkComObject">True if we should try to access IE's COM object. Not
/// needed if an HtmlDocument will be created shortly.</param>
protected bool VerifyInternetExplorerAvailable(bool checkComObject)
{
// TODO: Remove this code once the dependency on mshtml has been resolved.
#if CORECLR
return false;
#else
bool isInternetExplorerConfigurationComplete = false;
// Check for IE for both PS Full and PS Core on windows.
// The registry key DisableFirstRunCustomize can exits at one of the following path.
// IE uses the same descending order (as mentioned) to check for the presence of this key.
// If the value of DisableFirstRunCustomize key is set to greater than zero then Run first
// is disabled.
string[] disableFirstRunCustomizePaths = new string[] {
@"HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Internet Explorer\Main",
@"HKEY_CURRENT_USER\Software\Policies\Microsoft\Internet Explorer\Main",
@"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main",
@"HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer\Main" };
foreach (string currentRegPath in disableFirstRunCustomizePaths)
{
object val = Registry.GetValue(currentRegPath, "DisableFirstRunCustomize", string.Empty);
if (val != null && !string.Empty.Equals(val) && Convert.ToInt32(val, CultureInfo.InvariantCulture) > 0)
{
isInternetExplorerConfigurationComplete = true;
break;
}
}
if (!isInternetExplorerConfigurationComplete)
{
// Verify that if IE is installed, it has been through the RunOnce check.
// Otherwise, the call will hang waiting for users to go through First Run
// personalization.
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Internet Explorer\\Main"))
{
if (key != null)
{
foreach (string setting in key.GetValueNames())
{
if (setting.IndexOf("RunOnce", StringComparison.OrdinalIgnoreCase) > -1)
{
isInternetExplorerConfigurationComplete = true;
break;
}
}
}
}
}
if (isInternetExplorerConfigurationComplete && checkComObject)
{
try
{
IHTMLDocument2 ieCheck = (IHTMLDocument2)new HTMLDocument();
System.Runtime.InteropServices.Marshal.ReleaseComObject(ieCheck);
}
catch (System.Runtime.InteropServices.COMException)
{
isInternetExplorerConfigurationComplete = false;
}
}
// Throw exception in PS Full only
if (!isInternetExplorerConfigurationComplete)
throw new NotSupportedException(WebCmdletStrings.IEDomNotSupported);
return isInternetExplorerConfigurationComplete;
#endif
}
private Uri PrepareUri(Uri uri)
{
uri = CheckProtocol(uri);
// before creating the web request,
// preprocess Body if content is a dictionary and method is GET (set as query)
IDictionary bodyAsDictionary;
LanguagePrimitives.TryConvertTo<IDictionary>(Body, out bodyAsDictionary);
if ((null != bodyAsDictionary)
&& ((IsStandardMethodSet() && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get))
|| (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "GET")))
{
UriBuilder uriBuilder = new UriBuilder(uri);
if (uriBuilder.Query != null && uriBuilder.Query.Length > 1)
{
uriBuilder.Query = uriBuilder.Query.Substring(1) + "&" + FormatDictionary(bodyAsDictionary);
}
else
{
uriBuilder.Query = FormatDictionary(bodyAsDictionary);
}
uri = uriBuilder.Uri;
// set body to null to prevent later FillRequestStream
Body = null;
}
return uri;
}
private Uri CheckProtocol(Uri uri)
{
if (null == uri) { throw new ArgumentNullException("uri"); }
if (!uri.IsAbsoluteUri)
{
uri = new Uri("http://" + uri.OriginalString);
}
return (uri);
}
private string QualifyFilePath(string path)
{
string resolvedFilePath = PathUtils.ResolveFilePath(path, this, false);
return resolvedFilePath;
}
private string FormatDictionary(IDictionary content)
{
if (content == null)
throw new ArgumentNullException("content");
StringBuilder bodyBuilder = new StringBuilder();
foreach (string key in content.Keys)
{
if (0 < bodyBuilder.Length)
{
bodyBuilder.Append("&");
}
object value = content[key];
// URLEncode the key and value
string encodedKey = WebUtility.UrlEncode(key);
string encodedValue = String.Empty;
if (null != value)
{
encodedValue = WebUtility.UrlEncode(value.ToString());
}
bodyBuilder.AppendFormat("{0}={1}", encodedKey, encodedValue);
}
return bodyBuilder.ToString();
}
private ErrorRecord GetValidationError(string msg, string errorId)
{
var ex = new ValidationMetadataException(msg);
var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this);
return (error);
}
private ErrorRecord GetValidationError(string msg, string errorId, params object[] args)
{
msg = string.Format(CultureInfo.InvariantCulture, msg, args);
var ex = new ValidationMetadataException(msg);
var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this);
return (error);
}
private bool IsStandardMethodSet()
{
return (ParameterSetName == "StandardMethod");
}
private bool IsCustomMethodSet()
{
return (ParameterSetName == "CustomMethod");
}
private string GetBasicAuthorizationHeader()
{
string unencoded = String.Format("{0}:{1}", Credential.UserName, Credential.GetNetworkCredential().Password);
Byte[] bytes = Encoding.UTF8.GetBytes(unencoded);
return String.Format("Basic {0}", Convert.ToBase64String(bytes));
}
private string GetBearerAuthorizationHeader()
{
return String.Format("Bearer {0}", new NetworkCredential(String.Empty, Token).Password);
}
private void ProcessAuthentication()
{
if(Authentication == WebAuthenticationType.Basic)
{
WebSession.Headers["Authorization"] = GetBasicAuthorizationHeader();
}
else if (Authentication == WebAuthenticationType.Bearer || Authentication == WebAuthenticationType.OAuth)
{
WebSession.Headers["Authorization"] = GetBearerAuthorizationHeader();
}
else
{
Diagnostics.Assert(false, String.Format("Unrecognized Authentication value: {0}", Authentication));
}
}
#endregion Helper Methods
}
}