/// <summary>
        /// Initializes a new instance of the <see cref="AuthenticatedClient"/> class.
        /// </summary>
        /// <param name="apiToken">The API token.</param>
        /// <param name="subdomain">The production subdomain.</param>
        public AuthenticatedClient(string apiToken, string subdomain)
        {
            var oktaSettings = new OktaSettings();
            oktaSettings.ApiToken = apiToken;
            oktaSettings.Subdomain = subdomain;

            BaseClient = new OktaHttpClient(oktaSettings);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthenticatedClient"/> class.
        /// </summary>
        /// <param name="apiToken">The API token.</param>
        /// <param name="baseUri">The base URI.</param>
        public AuthenticatedClient(string apiToken, Uri baseUri)
        {
            var oktaSettings = new OktaSettings()
            {
                ApiToken = apiToken,
                BaseUri = baseUri
            };

            BaseClient = new OktaHttpClient(oktaSettings);
        }
Beispiel #3
0
        protected override void BeginProcessing()
        {
            if (Client == null)
            {
                var oktaSettings = new OktaSettings()
                {
                    ApiToken = Token,
                    BaseUri = String.IsNullOrEmpty(FullDomain) ? null : new Uri(FullDomain),
                    Subdomain = Subdomain
                };

                Client = new OktaClient(oktaSettings);
            }
        }
        public void DeleteSessionToken()
        {
            OktaSettings oktaSettings = new OktaSettings();
            oktaSettings.BaseUri = new Uri(Environment.GetEnvironmentVariable("OKTA_TEST_URL"));
            oktaSettings.ApiToken = Environment.GetEnvironmentVariable("OKTA_TEST_KEY");

            String username = Environment.GetEnvironmentVariable("OKTA_TEST_ADMIN_NAME");
            String password = Environment.GetEnvironmentVariable("OKTA_TEST_ADMIN_PASSWORD");

            SessionsClient sessionsClient = new SessionsClient(oktaSettings);

            var session = sessionsClient.Create(username, password);
            sessionsClient.Close(session.Id);
        }
Beispiel #5
0
        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);
        }
        public void CreateSessionRedirectUrl()
        {
            String fakeEndpoint = "http://validurl.com:9999";
            String fakeSessionToken = "FakeSessionToken";
            String fakeRedirect = "https://this.is.fake:42/really?really=true&also=very+true";

            // Create a SessionsClient
            OktaSettings oktaSettings = new OktaSettings();
            oktaSettings.BaseUri = new Uri(fakeEndpoint);
            oktaSettings.ApiToken = "fakeApiToken";
            SessionsClient sessionsClient = new SessionsClient(oktaSettings);

            // Crate the session url string
            String sessionUrlString = sessionsClient.CreateSessionUrlString(fakeSessionToken, new Uri(fakeRedirect));

            // Check the format
            Assert.AreEqual("http://validurl.com:9999/login/sessionCookieRedirect?token=FakeSessionToken&redirectUrl=https%3A%2F%2Fthis.is.fake%3A42%2Freally%3Freally%3Dtrue%26also%3Dvery%2Btrue", sessionUrlString);
        }
 public GroupUsersClient(Group group, OktaSettings oktaSettings) : base(oktaSettings, Constants.EndpointV1 + Constants.GroupsEndpoint + "/" + group.Id + Constants.UsersEndpoint)
 {
 }
 public AccountController(IOptions <OktaSettings> oktaSettings)
 {
     _oktaSettings = oktaSettings.Value;
 }
Beispiel #9
0
 public OrgFactorsClient(OktaSettings oktaSettings) : base(oktaSettings, Constants.EndpointV1 + Constants.OrgEndpoint + Constants.FactorsEndpoint)
 {
 }
Beispiel #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            ConfigureMongoDatabase(services);

            services.AddSingleton <HomebrewingDbService>();
            services.AddSingleton <IRecipeValidator, RecipeValidator>();

            var mapperConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new DefaultProfile());
            });

            services.AddSingleton(mapperConfig.CreateMapper());

            services.AddAutoMapper(typeof(Startup));

            var oktaSettings = new OktaSettings
            {
                Domain           = Configuration["Okta:OktaDomain"],
                AdminAppClientId = Configuration["Okta:OktaAdminAppClientId"]
            };

            services.AddSingleton(oktaSettings);

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = OktaDefaults.ApiAuthenticationScheme;
                options.DefaultChallengeScheme    = OktaDefaults.ApiAuthenticationScheme;
                options.DefaultSignInScheme       = OktaDefaults.ApiAuthenticationScheme;
            })
            .AddOktaWebApi(new OktaWebApiOptions
            {
                OktaDomain = oktaSettings.Domain
            });

            services.AddAuthorization();

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "HomebrewApi", Version = "v1"
                });
                c.EnableAnnotations();
                c.AddSecurityDefinition("Bearer",
                                        new OpenApiSecurityScheme
                {
                    Name         = "Bearer",
                    BearerFormat = "JWT",
                    Scheme       = "bearer",
                    Description  = "Specify the authorization token.",
                    In           = ParameterLocation.Header,
                    Type         = SecuritySchemeType.Http
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        Array.Empty <string>()
                    }
                });
            });
        }
Beispiel #11
0
 public UsersClient(OktaSettings oktaSettings) : base(oktaSettings, Constants.EndpointV1 + Constants.UsersEndpoint)
 {
 }
Beispiel #12
0
 public OktaClient(OktaSettings oktaSettings)
     : base(oktaSettings)
 {
 }
Beispiel #13
0
 public AuthClient(OktaSettings oktaSettings) : base(oktaSettings) { resourcePath = Constants.EndpointV1 + Constants.AuthnEndpoint; }
Beispiel #14
0
 public AuthClient(OktaSettings oktaSettings) : base(oktaSettings)
 {
     resourcePath = Constants.EndpointV1 + Constants.AuthnEndpoint;
 }
Beispiel #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ApiClient{T}"/> class.
 /// </summary>
 /// <param name="oktaSettings">The Okta settings to configure the <see cref="AuthenticatedClient.BaseClient"/></param>
 /// <param name="resourcePath">The resource path relative to the <see cref="AuthenticatedClient.BaseUri"/></param>
 public ApiClient(OktaSettings oktaSettings, string resourcePath) : base(oktaSettings)
 {
     this.resourcePath = resourcePath;
 }
Beispiel #16
0
        public ActionResult PkceRoute()
        {
            string       userName       = Request["userName"];
            string       passWord       = Request["passWord"];
            string       authnlogin_but = Request["authnlogin_but"];
            string       oidclogin_but  = Request["oidclogin_but"];
            string       oidc_but       = Request["oidc_but"];
            string       location       = Request["location"];
            string       myStatus       = null;
            string       myStateToken;
            string       mySessionToken;
            string       myOktaId = null;
            AuthResponse userAuthClientRsp;

            // set relayState
            string relayState = Request["relayState"];

            TempData["relayState"] = relayState;

            Uri orgUri = new Uri(apiUrl);

            _orgSettings          = new OktaSettings();
            _orgSettings.ApiToken = apiToken;
            _orgSettings.BaseUri  = orgUri;

            _oktaClient  = new OktaClient(_orgSettings);
            _usersClient = new UsersClient(_orgSettings);
            _authClient  = new AuthClient(_orgSettings);
            try
            {
                userAuthClientRsp = _authClient.Authenticate(username: userName, password: passWord, relayState: relayState);
                logger.Debug("thisAuth status " + userAuthClientRsp.Status);
                myStatus       = userAuthClientRsp.Status;
                myStateToken   = userAuthClientRsp.StateToken;
                mySessionToken = userAuthClientRsp.SessionToken;
                if (userAuthClientRsp.Embedded.User != null)
                {
                    myOktaId = userAuthClientRsp.Embedded.User.Id;
                }
            }
            catch (OktaException ex)
            {
                if (ex.ErrorCode == "E0000004")
                {
                    logger.Debug("Invalid Credentials for User: "******"errMessage"] = "Invalid Credentials for User: "******"E0000085")
                {
                    logger.Debug("Access Denied by Polciy for User: "******"errMessage"] = "Access Denied by Polciy for User: "******"errMessage"] = "Access Denied by Polciy for User: "******" = " + ex.ErrorCode + ":" + ex.ErrorSummary);
                    // generic failure
                    TempData["errMessage"] = "Sign in process failed!";
                }
                TempData["userName"] = userName;
                return(RedirectToAction("Login"));
            }

            switch (myStatus)
            {
            case "PASSWORD_WARN":      //password about to expire
                logger.Debug("PASSWORD_WARN ");
                break;

            case "PASSWORD_EXPIRED":      //password has expired
                logger.Debug("PASSWORD_EXPIRED ");
                break;

            case "RECOVERY":      //user has requested a recovery token
                logger.Debug("RECOVERY ");
                break;

            case "RECOVERY_CHALLENGE":      //user must verify factor specific recovery challenge
                logger.Debug("RECOVERY_CHALLENGE ");
                break;

            case "PASSWORD_RESET":         //user satified recovery and must now set password
                logger.Debug("PASSWORD_RESET ");
                break;

            case "LOCKED_OUT":      //user account is locked, unlock required
                logger.Debug("LOCKED_OUT ");
                break;

            case "MFA_ENROLL":       //user must select and enroll an available factor
                logger.Debug("MFA_ENROLL ");
                break;

            case "MFA_ENROLL_ACTIVATE":       //user must activate the factor to complete enrollment
                logger.Debug("MFA_ENROLL_ACTIVATE ");
                break;

            case "MFA_REQUIRED":        //user must provide second factor with previously enrolled factor
                logger.Debug("MFA_REQUIRED ");
                break;

            case "MFA_CHALLENGE":          //use must verify factor specifc challenge
                logger.Debug("MFA_CHALLENGE ");
                break;

            case "SUCCESS":          //authentication is complete
                logger.Debug("SUCCESS");
                TempData["errMessage"] = "Authn Login Successful ";
                TempData["oktaOrg"]    = apiUrl;

                string landingPage = null;
                if (string.IsNullOrEmpty(relayState))
                {
                    landingPage = location + "/AltLanding/UnprotectedLanding";
                }
                else
                {
                    landingPage = relayState;
                }

                //optionaly get session Id locally
                Session oktaSession = new Okta.Core.Models.Session();
                oktaSession = oktaSessionMgmt.CreateSession(mySessionToken);
                string cookieToken = oktaSession.CookieToken;
                logger.Debug("session Id " + oktaSession.Id + " for User " + userName);
                mySessionToken = cookieToken;

                //exchange sessionToken for sessionCookie in OIDC Implicit workflow
                Random random       = new Random();
                string nonceValue   = random.Next(99999, 1000000).ToString();
                string stateCode    = "myStateInfo";
                string codeVerifier = oktaOidcHelper.CreateCodeVerifier();
                //store codeVerifier for token endpoint
                cacheService.SavePasscode("myKey", codeVerifier);
                string codeChallenge = oktaOidcHelper.CreateCodeChallenge(codeVerifier);
                string oauthUrl      = appSettings["oidc.authServer"] + "/v1/authorize?response_type=code&response_mode=query&code_challenge_method=S256&code_challenge=" + codeChallenge + "&client_id=" + appSettings["oidc.spintnative.clientId"] + "&scope=" + appSettings["oidc.scopes"] + "&state=" + stateCode + "&nonce=" + nonceValue + "&redirect_uri=" + appSettings["oidc.spintnative.RedirectUri_PKCE"] + "&sessionToken=" + mySessionToken + "&extra_param=myFavoriteData";
                return(Redirect(oauthUrl));



            //break;
            default:
                logger.Debug("Status: " + myStatus);
                TempData["errMessage"] = "Status: " + myStatus;
                break;
            }//end of switch
            TempData["userName"] = userName;

            return(RedirectToAction("UnprotectedLanding", "AltLanding"));
        }
Beispiel #17
0
        public ActionResult ImplicitRoute()
        {
            string       userName       = Request["userName"];
            string       passWord       = Request["passWord"];
            string       authnlogin_but = Request["authnlogin_but"];
            string       oidclogin_but  = Request["oidclogin_but"];
            string       oidc_but       = Request["oidc_but"];
            string       location       = Request["location"];
            string       myStatus       = null;
            string       myStateToken;
            string       mySessionToken;
            string       myOktaId = null;
            AuthResponse userAuthClientRsp;

            // set relayState
            string relayState = Request["relayState"];

            TempData["relayState"] = relayState;

            Uri orgUri = new Uri(apiUrl);

            _orgSettings          = new OktaSettings();
            _orgSettings.ApiToken = apiToken;
            _orgSettings.BaseUri  = orgUri;

            _oktaClient  = new OktaClient(_orgSettings);
            _usersClient = new UsersClient(_orgSettings);
            _authClient  = new AuthClient(_orgSettings);
            try
            {
                userAuthClientRsp = _authClient.Authenticate(username: userName, password: passWord, relayState: relayState);
                logger.Debug("thisAuth status " + userAuthClientRsp.Status);
                myStatus       = userAuthClientRsp.Status;
                myStateToken   = userAuthClientRsp.StateToken;
                mySessionToken = userAuthClientRsp.SessionToken;
                if (userAuthClientRsp.Embedded.User != null)
                {
                    myOktaId = userAuthClientRsp.Embedded.User.Id;
                }
            }
            catch (OktaException ex)
            {
                if (ex.ErrorCode == "E0000004")
                {
                    logger.Debug("Invalid Credentials for User: "******"errMessage"] = "Invalid Credentials for User: "******"E0000085")
                {
                    logger.Debug("Access Denied by Polciy for User: "******"errMessage"] = "Access Denied by Polciy for User: "******"errMessage"] = "Access Denied by Polciy for User: "******" = " + ex.ErrorCode + ":" + ex.ErrorSummary);
                    // generic failure
                    TempData["errMessage"] = "Sign in process failed!";
                }
                TempData["userName"] = userName;
                return(RedirectToAction("Login"));
            }

            switch (myStatus)
            {
            case "PASSWORD_WARN":      //password about to expire
                logger.Debug("PASSWORD_WARN ");
                break;

            case "PASSWORD_EXPIRED":      //password has expired
                logger.Debug("PASSWORD_EXPIRED ");
                break;

            case "RECOVERY":      //user has requested a recovery token
                logger.Debug("RECOVERY ");
                break;

            case "RECOVERY_CHALLENGE":      //user must verify factor specific recovery challenge
                logger.Debug("RECOVERY_CHALLENGE ");
                break;

            case "PASSWORD_RESET":         //user satified recovery and must now set password
                logger.Debug("PASSWORD_RESET ");
                break;

            case "LOCKED_OUT":      //user account is locked, unlock required
                logger.Debug("LOCKED_OUT ");
                break;

            case "MFA_ENROLL":       //user must select and enroll an available factor
                logger.Debug("MFA_ENROLL ");
                break;

            case "MFA_ENROLL_ACTIVATE":       //user must activate the factor to complete enrollment
                logger.Debug("MFA_ENROLL_ACTIVATE ");
                break;

            case "MFA_REQUIRED":        //user must provide second factor with previously enrolled factor
                logger.Debug("MFA_REQUIRED ");
                break;

            case "MFA_CHALLENGE":          //use must verify factor specifc challenge
                logger.Debug("MFA_CHALLENGE ");
                break;

            case "SUCCESS":          //authentication is complete
                logger.Debug("SUCCESS");
                TempData["errMessage"] = "Authn Login Successful ";
                TempData["oktaOrg"]    = apiUrl;

                string landingPage = null;
                if (string.IsNullOrEmpty(relayState))
                {
                    landingPage = location + "/AltLanding/UnprotectedLanding";
                }
                else
                {
                    landingPage = relayState;
                }

                ////optionaly get session Id locally
                //Session oktaSession = new Okta.Core.Models.Session();
                //oktaSession = oktaSessionMgmt.CreateSession(mySessionToken);
                //string cookieToken = oktaSession.CookieToken;
                //logger.Debug("session Id " + oktaSession.Id + " for User " + userName);
                //mySessionToken = cookieToken;

                //exchange sessionToken for sessionCookie in OIDC Implicit workflow
                Random random     = new Random();
                string nonceValue = random.Next(99999, 1000000).ToString();
                string stateCode  = "myStateInfo";
                string oauthUrl   = appSettings["oidc.authServer"] + "/v1/authorize?response_type=token id_token&response_mode=form_post&client_id=" + appSettings["oidc.spintweb.clientId"] + "&scope=" + appSettings["oidc.scopes"] + "&state=" + stateCode + " &nonce=" + nonceValue + "&redirect_uri=" + appSettings["oidc.spintweb.RedirectUri"] + "&sessionToken=" + mySessionToken;
                //string oauthUrl = appSettings["oidc.authServer"] + "/v1/authorize?idp=0oak4qcg796eVYakY0h7&response_type=id_token token&response_mode=form_post&client_id=" + appSettings["oidc.spintweb.clientId"] + "&scope=" + appSettings["oidc.scopes"] + "&state=" + stateCode + " &nonce=" + nonceValue + "&redirect_uri=" + appSettings["oidc.spintweb.RedirectUri"] + "&sessionToken=" + mySessionToken;
                return(Redirect(oauthUrl));


            //NOT Typical
            //have idToken returned in response
            //IRestResponse response = null;
            //var client = new RestClient(MvcApplication.apiUrl + "/oauth2/v1/authorize");
            //var request = new RestRequest(Method.GET);
            //request.AddHeader("Accept", "application/json");
            //request.AddHeader("Content-Type", "application/json");
            ////request.AddHeader("Authorization", " SSWS " + MvcApplication.apiToken);
            //request.AddQueryParameter("client_id", appSettings["oidc.spintweb.clientId"]);
            //request.AddQueryParameter("response_type", "id_token");
            ////request.AddQueryParameter("response_type", "token");
            //request.AddQueryParameter("response_mode", "okta_post_message");
            //request.AddQueryParameter("scope", "openid");
            //request.AddQueryParameter("prompt", "none");
            //request.AddQueryParameter("redirect_uri", appSettings["oidc.spintweb.RedirectUri"]);
            //request.AddQueryParameter("state", "myStateInfo");
            //request.AddQueryParameter("nonce", "myNonce");
            //request.AddQueryParameter("sessionToken", mySessionToken);
            //response = client.Execute(request);
            //int myIndex_01 = response.Content.IndexOf("data.id_token =");
            //string firstBreak = response.Content.Substring(myIndex_01 + 17);
            //int myIndex_02 = firstBreak.IndexOf(";");
            //int subLength = myIndex_02 - 1;
            //string myIdToken = firstBreak.Substring(0, subLength);
            //logger.Debug(myIdToken);
            //ViewBag.HtmlStr = response.Content;
            //return View("../AltLanding/MyContent");



            // break;
            default:
                logger.Debug("Status: " + myStatus);
                TempData["errMessage"] = "Status: " + myStatus;
                break;
            }//end of switch
            TempData["userName"] = userName;

            return(RedirectToAction("UnprotectedLanding", "AltLanding"));
        }
Beispiel #18
0
 public ContentAuthControllerBase(OktaSettings oktaSettings)
 {
     _oktaSettings = oktaSettings;
 }
Beispiel #19
0
 public OktaClient(OktaSettings oktaSettings) : base(oktaSettings)
 {
 }
Beispiel #20
0
 public AppGroupsClient(App app, OktaSettings oktaSettings) : base(oktaSettings, Constants.EndpointV1 + Constants.AppsEndpoint + "/" + app.Id + Constants.GroupsEndpoint)
 {
 }
Beispiel #21
0
 public GroupsClient(OktaSettings oktaSettings) : base(oktaSettings, Constants.EndpointV1 + Constants.GroupsEndpoint)
 {
 }
Beispiel #22
0
 public EventsClient(OktaSettings oktaSettings) : base(oktaSettings, Constants.EndpointV1 + Constants.EventsEndpoint)
 {
 }
Beispiel #23
0
 public SessionsClient(OktaSettings oktaSettings) : base(oktaSettings, Constants.EndpointV1 + Constants.SessionsEndpoint)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AuthenticatedClient"/> class.
 /// </summary>
 /// <param name="oktaSettings">Settings to configure a <see cref="AuthenticatedClient.BaseClient"/>.</param>
 public AuthenticatedClient(OktaSettings oktaSettings)
 {
     BaseClient = new OktaHttpClient(oktaSettings);
 }
 public UserFactorsClient(User user, OktaSettings oktaSettings) : base(oktaSettings, Constants.EndpointV1 + Constants.UsersEndpoint + "/" + user.Id + Constants.FactorsEndpoint)
 {
 }
Beispiel #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AuthenticatedClient"/> class.
 /// </summary>
 /// <param name="oktaSettings">Settings to configure a <see cref="AuthenticatedClient.BaseClient"/>.</param>
 public AuthenticatedClient(OktaSettings oktaSettings)
 {
     BaseClient = new OktaHttpClient(oktaSettings);
 }