OktaCmdlet.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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using Okta.Core.Clients;
using System.Net;
 
namespace Okta.Core.Automation
{
    [Cmdlet(VerbsCommunications.Connect, "Okta")]
    public class OktaCmdlet : PSCmdlet
    {
        [Parameter(
            Mandatory = false,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Api token to connect to Okta"
        )]
        [Alias("ApiToken")]
        public string Token { get; set; }
 
        [Parameter(
            Mandatory = false,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Subdomain to connect to a production instance of Okta"
        )]
        public string Subdomain { get; set; }
 
        [Parameter(
            Mandatory = false,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Full Okta domain (used for alternative environments like oktapreview)"
        )]
        public string FullDomain { get; set; }
 
        internal static OktaClient Client { get; set; }
        protected override void BeginProcessing()
        {
            if (Client == null)
            {
                var oktaSettings = new OktaSettings()
                {
                    ApiToken = Token,
                    BaseUri = String.IsNullOrEmpty(FullDomain) ? null : new Uri(FullDomain),
                    Subdomain = Subdomain
                };
 
                // Support TLS 1.2
                ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072;
                Client = new OktaClient(oktaSettings);
            }
        }
 
        private void PromptForLogin()
        {
            if (String.IsNullOrEmpty(Token))
            {
                var response = this.InvokeCommand.InvokeScript("Read-Host", "Enter your API Token");
                Token = response.First().BaseObject.ToString();
                WriteVerbose("This is the token " + Token);
            }
 
            var oktaSettings = new OktaSettings()
            {
                ApiToken = Token,
                BaseUri = String.IsNullOrEmpty(FullDomain) ? null : new Uri(FullDomain),
                Subdomain = Subdomain
            };
 
            Client = new OktaClient(oktaSettings);
        }
    }
}