• Stars
    star
    151
  • Rank 246,057 (Top 5 %)
  • Language
    C#
  • License
    Other
  • Created about 10 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A .NET SDK for interacting with the Okta management API, enabling server-side code to manage Okta users, groups, applications, and more.

Support API Reference

Okta .NET management SDK

This repository contains the Okta management SDK for .NET. This SDK can be used in your server-side code to interact with the Okta management API and:

Note: For more details about the APIs and models the SDK support, check out the API docs

We also publish these other libraries for .NET:

You can learn more on the Okta + .NET page in our documentation.

Release status

This library uses semantic versioning and follows Okta's library version policy.

✔️ The current stable major version series is: 6.x ✔️ The 5.x series is retiring on June 8th 2023. Until then, we will only fix high-risk security vulnerabilities and other issues will be reviewed on a case-by-case basis. New APIs will be added only on series 6.x, but you can still use the 5.x series to call any new endpoint. The SDK will be still available on Nuget, and the source-code is located in the legacy-5.x-series branch. Please, reach out to the Okta Customer Support Team at [email protected] if you have any questions or issues.

Version Status
7.x ✔️ Stable (migration guide)
6.x ⚠️ Retiring on May 9th 2024

The latest release can always be found on the releases page. For more information about our SDKs' lifecycle, check out our docs.

Need help?

If you run into problems using the SDK, you can

Getting Started

The SDK is compatible with:

  • .NET Standard 2.0
  • .NET Framework 4.6.1 or higher
  • .NET Core 3.0 or higher
  • .NET 5.0 or higher

Visual Studio 2017 or newer is required as previous versions are not compatible with the above frameworks.

Install using Nuget Package Manager

  1. Right-click on your project in the Solution Explorer and choose Manage Nuget Packages...
  2. Search for Okta. Install the Okta.Sdk package.

Install using The Package Manager Console

Simply run install-package Okta.Sdk. Done!

You'll also need:

Initialize an API client

Construct a client instance by passing it your Okta domain name and API token:

using System.Collections.Generic;
using System.Diagnostics;
using Okta.Sdk.Api;
using Okta.Sdk.Client;
using Okta.Sdk.Model;

namespace Example
{
    public class Example
    {
        public static void Main()
        {

            Configuration config = new Configuration();
            config.OktaDomain = "https://your-subdomain.okta.com";
            // Configure API key authorization: API_Token
            config.Token.Add("Authorization", "YOUR_API_KEY");
            
            var apiInstance = new AgentPoolsApi(config);
            var poolId = "poolId_example";  // string | Id of the agent pool for which the settings will apply
            var updateId = "updateId_example";  // string | Id of the update

            try
            {
                // Activate an Agent Pool update
                AgentPoolUpdate result = apiInstance.ActivateAgentPoolsUpdate(poolId, updateId);
                Debug.WriteLine(result);
            }
            catch (ApiException e)
            {
                Debug.Print("Exception when calling AgentPoolsApi.ActivateAgentPoolsUpdate: " + e.Message );
                Debug.Print("Status Code: "+ e.ErrorCode);
                Debug.Print(e.StackTrace);
            }

        }
    }
}

Hard-coding the Okta domain and API token works for quick tests, but for real projects you should use a more secure way of storing these values (such as environment variables). This library supports a few different configuration sources, covered in the configuration reference section.

To use the API client with an HTTP proxy, you can either setup your proxy via different configuration sources, covered in the configuration reference section, or via API constructor. If you have both, the proxy passed via constructor will take precedence.

System.Net.WebProxy webProxy = new System.Net.WebProxy("http://myProxyUrl:80/");
webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

var appsApi = new ApplicationApi(webProxy : webProxy);

OAuth 2.0

Okta allows you to interact with Okta APIs using scoped OAuth 2.0 access tokens. Each access token enables the bearer to perform specific actions on specific Okta endpoints, with that ability controlled by which scopes the access token contains.

This SDK supports this feature only for service-to-service applications. Check out our guides to learn more about how to register a new service application using a private and public key pair.

When using this approach you won't need an API Token because the SDK will request an access token for you. In order to use OAuth 2.0, construct an API client instance by passing the following parameters:

var oauthAppsApi = new ApplicationApi(new Configuration
{
    OktaDomain = "https://{{yourOktaDomain}}",
    AuthorizationMode = AuthorizationMode.PrivateKey,
    ClientId = "{{clientId}}",
    Scopes = new List<string> { "okta.users.read", "okta.apps.read" }, // Add all the scopes you need
    PrivateKey =  new JsonWebKeyConfiguration(jsonString)
});

Key object for assigning to the PrivateKey can be created and initialized inline like in this example for RSA key:

var privateKey = new JsonWebKeyConfiguration
{
    P = "{{P}}",
    Kty = "RSA",
    Q = "{{Q}}",
    D = "{{D}}",
    E = "{{E}}",
    Kid = "{{P}}",
    Qi = "{{Qi}}"
};

var configuration = new Configuration
{
    OktaDomain = "https://{{yourOktaDomain}}",
    AuthorizationMode = AuthorizationMode.PrivateKey,
    ClientId = "{{clientId}}",
    Scopes = new List<string> { "okta.users.read", "okta.apps.read" }, // Add all the scopes you need
    PrivateKey = privateKey
};

var oauthAppsApi = new ApplicationApi(configuration);

It is possible to use an access token you retrieved outside of the SDK for authentication. For that, set Configuration.AuthorizationMode configuration property to AuthorizationMode.BearerToken and Configuration.AccessToken to the token string.

Usage guide

These examples will help you understand how to use this library. You can also browse the full API reference documentation.

Once you initialize an API client, you can call methods to make requests to the Okta API.

Get a User

// Get the user with a user ID or login
var user = await userApi.GetUserAsync("<Some user ID or login>");

The string argument for GetUserAsync can be the user's ID or the user's login (usually their email).

List all Users

The SDK will automatically paginate Okta collections for you:

// These different styles all perform the same action:
var allUsers = await userApi.ListUsers().ToListAsync();
var allUsers = await userApi.ListUsers().ToArrayAsync();

Filter or search for Users

var foundUsers = await userApi
                        .ListUsers(search: $"profile.nickName eq \"Skywalker\"")
                        .ToArrayAsync();

Create a User

// Create a user with the specified password
var createUserRequest = new CreateUserRequest
            {
                Profile = new UserProfile
                {
                    FirstName = "Anakin",
                    LastName = "Skywalker",
                    Email = "[email protected]",
                    Login = "[email protected]",
                },
                Credentials = new UserCredentials
                {
                    Password = new PasswordCredential
                    {
                        Value = "D1sturB1ng"
                    }
                }
            };

var createdUser = await _userApi.CreateUserAsync(createUserRequest);

Activate a User

// Activate the user
await _userApi.ActivateUserAsync(createdUser.Id, false);

Update a User

// Update profile
createdUser.Profile.NickName = nickName;
var updateUserRequest = new UpdateUserRequest
{
    Profile = createdUser.Profile
};

var updatedUser = await _userApi.UpdateUserAsync(createdUser.Id, updateUserRequest);

Get and set custom attributes

You can't create attributes via code right now, but you can get and set their values. To create them you have to use the Profile Editor in the Developer Console web UI. Once you have created them, you can use the code below:

user.Profile.AdditionalProperties = new Dictionary<string, object>();
user.Profile.AdditionalProperties["homeworld"] = "Planet Earth";

var updateUserRequest = new UpdateUserRequest
{
    Profile = user.Profile
};

var updatedUser = await _userApi.UpdateUserAsync(createdUser.Id, updateUserRequest);

var userHomeworld = updatedUser.Profile.AdditionalProperties["homeworld"];

Remove a User

 await _userApi.DeactivateOrDeleteUserAsync(createdUser.Id);

List all Applications

// List all applications
var appList = await _applicationApi.ListApplications().ToArrayAsync();

Get an Application

var createdApp = await _applicationApi.CreateApplicationAsync(new CreateBasicAuthApplicationOptions()
                {
                    Label = "Sample Basic Auth App",
                    Url = "https://example.com/login.html",
                    AuthUrl = "https://example.com/auth.html",
                });

var retrievedById = await _applicationApi.GetApplicationAsync(createdApp.Id);

Create an OpenID Application

var app = new OpenIdConnectApplication
        {
            Name = "oidc_client",
            SignOnMode = "OPENID_CONNECT",
            Label = $"dotnet-sdk: AddOpenIdConnectApp",
            Credentials = new OAuthApplicationCredentials()
            {
                OauthClient = new ApplicationCredentialsOAuthClient()
                {
                    ClientId = testClientId,
                    TokenEndpointAuthMethod = "client_secret_post",
                    AutoKeyRotation = true,
                },
            },
            Settings = new OpenIdConnectApplicationSettings
            {
                OauthClient = new OpenIdConnectApplicationSettingsClient()
                {
                    ClientUri = "https://example.com/client",
                    LogoUri = "https://example.com/assets/images/logo-new.png",
                    ResponseTypes = new List<string>
                    {
                        "token",
                        "id_token",
                        "code",
                    },
                    RedirectUris = new List<string>
                    {
                        "https://example.com/oauth2/callback",
                        "myapp://callback",
                    },
                    PostLogoutRedirectUris = new List<string>
                    {
                        "https://example.com/postlogout",
                        "myapp://postlogoutcallback",
                    },
                    GrantTypes = new List<string>
                    {
                        "implicit",
                        "authorization_code",
                    },
                    ApplicationType = "native",

                    TosUri = "https://example.com/client/tos",
                    PolicyUri = "https://example.com/client/policy",
                },
            }
        };

var createdApp = await _applicationApi.CreateApplicationAsync(app);

Manual pagination

Collections can be fetched with manually controlled pagination, see the following.

var retrievedUsers = new List<IUser>();
var users = _userApi.ListUsers(limit: 5); // 5 records per a page
var enumerator = users.GetPagedEnumerator();

while (await enumerator.MoveNextAsync())
{
    retrievedUsers.AddRange(enumerator.CurrentPage.Items);
    // ....................
}

Note: For more API samples checkout our tests

Rate Limiting

The Okta API will return 429 responses if too many requests are made within a given time. Please see Rate Limiting at Okta for a complete list of which endpoints are rate limited. When a 429 error is received, the X-Rate-Limit-Reset header will tell you the time at which you can retry. This section discusses methods for handling rate limiting with this SDK.

Built-In Retry

This SDK uses the built-in retry strategy to automatically retry on 429 errors. You can use the default configuration options for the built-in retry strategy, or provide your desired values via client configuration.

You can configure the following options when using the built-in retry strategy:

Configuration Option Description
RequestTimeout The waiting time in milliseconds for a request to be resolved by the client. Less than or equal to 0 means "no timeout". The default value is 0 (None).
MaxRetries The number of times to retry.

Check out the Configuration Reference section for more details about how to set these values via configuration.

Custom Retry

You can implement your own retry strategy via Polly, and assign it to the RetryConfiguration.AsyncPolicy property.

 AsyncPolicy<IRestResponse> retryAsyncPolicy = Policy
                .Handle<ApiException>(ex => ex.ErrorCode == 429)
                .OrResult<IRestResponse>(r => (int)r.StatusCode == 429)
                .WaitAndRetryAsync(configuration.MaxRetries.Value, 
                                   sleepDurationProvider: (retryAttempt, response,
                                   context) => MyCalculateDelayMethod(retryAttempt, response, context)
                );

RetryPolicy.AsyncPolicy = retryAsyncPolicy;

You will have to read the X-Rate-Limit-Reset header on the 429 response. This will tell you the time at which you can retry. Because this is an absolute time value, we recommend calculating the wait time by using the Date header on the response, as it is in sync with the API servers, whereas your local clock may not be. We also recommend adding 1 second to ensure that you will be retrying after the window has expired (there may be a sub-second relative time skew between the X-Rate-Limit-Reset and Date headers).

Configuration reference

This library looks for configuration in the following sources:

  1. An okta.yaml file in a .okta folder in the current user's home directory (~/.okta/okta.yaml or %userprofile%\.okta\okta.yaml)
  2. An appsettings.json file in the application or project's root directory
  3. An okta.yaml file in a .okta folder in the application or project's root directory
  4. Environment variables
  5. Configuration explicitly passed to the constructor (see the example in Getting started)

Higher numbers win. In other words, configuration passed via the constructor will override configuration found in environment variables, which will override configuration in okta.yaml (if any), and so on.

Note that json files cannot be used if they contain JavaScript comments. Comments are not allowed by JSON format.

YAML configuration

When you use an API Token instead of OAuth 2.0 the full YAML configuration looks like:

okta:
  client:
    connectionTimeout: 30000 # milliseconds
    oktaDomain: "https://{yourOktaDomain}"
    proxy:
        port: null
        host: null
        username: null
        password: null
    token: {apiToken}
    requestTimeout: 0 # milliseconds
    rateLimit:
      maxRetries: 4

When you use OAuth 2.0 the full YAML configuration looks like this when using EC key:

okta:
  client:
    connectionTimeout: 30000 # milliseconds
    oktaDomain: "https://{yourOktaDomain}"
    proxy:
      port: null
      host: null
      username: null
      password: null
    authorizationMode: "PrivateKey"
    clientId: "{yourClientId}"
    Scopes:
    - scope1
    - scope2
    PrivateKey: # This SDK supports both RSA and EC keys.
        kty: "EC"
        crv: "P-256"
        x: "{x}"
        y: "{y}"
    requestTimeout: 0 # milliseconds
    rateLimit:
      maxRetries: 4

Or like this for RSA key:

okta:
  client:
    connectionTimeout: 30000 # milliseconds
    oktaDomain: "https://{yourOktaDomain}"
    proxy:
      port: null
      host: null
      username: null
      password: null
    authorizationMode: "PrivateKey"
    clientId: "{yourClientId}"
    Scopes:
    - scope1
    - scope2
    PrivateKey: 
      "p": "{p}"
      "kty": "RSA"
      "q": "{q}"
      "d": "{d}"
      "e": "{e}"
      "kid": "{kid}"
      "qi": "{qi}"
    requestTimeout: 0 # milliseconds
    rateLimit:
      maxRetries: 4

Environment variables

Each one of the configuration values above can be turned into an environment variable name with the _ (underscore) character:

  • OKTA_CLIENT_CONNECTIONTIMEOUT
  • OKTA_CLIENT_TOKEN
  • and so on

Building the SDK

In most cases, you won't need to build the SDK from source. If you want to build it yourself just clone the repo and compile using Visual Studio.

Contributing

We're happy to accept contributions and PRs! Please see the contribution guide to understand how to structure a contribution.

More Repositories

1

okta-auth-js

The official js wrapper around Okta's auth API
TypeScript
441
star
2

okta-oidc-js

okta-oidc-js
TypeScript
393
star
3

okta-signin-widget

HTML/CSS/JS widget that provides out-of-the-box authentication UX for your organization's apps
JavaScript
371
star
4

okta-spring-boot

Okta Spring Boot Starter
Java
322
star
5

terraform-provider-okta

A Terraform provider to manage Okta resources, enabling infrastructure-as-code provisioning and management of users, groups, applications, and other Okta objects.
Go
252
star
6

okta-sdk-python

Python
234
star
7

okta-sdk-golang

A Golang SDK for interacting with the Okta management API, enabling server-side code to manage Okta users, groups, applications, and more.
Go
175
star
8

samples-js-react

React Auth SDK sample
JavaScript
172
star
9

samples-java-spring

Spring Boot samples
Java
157
star
10

okta-sdk-java

A Java SDK for interacting with the Okta management API, enabling server-side code to manage Okta users, groups, applications, and more.
HTML
145
star
11

okta-aws-cli

A CLI for having Okta as the IdP for AWS CLI operations
Go
124
star
12

okta-developer-docs

okta-developer-docs
SCSS
121
star
13

samples-nodejs-express-4

Express 4 samples. Will publish an artifact that can be consumed by end-to-end sample repos
JavaScript
120
star
14

okta-react

Okta OIDC SDK for React
JavaScript
113
star
15

samples-python-flask

samples-python-flask
Python
100
star
16

okta-sdk-nodejs

Node.js API Client for the Okta Platform API
JavaScript
98
star
17

okta-jwt-verifier-golang

okta-jwt-verifier-golang
Go
97
star
18

odyssey

Build and design consistent, efficient, and accessible UIs for all Okta users.
TypeScript
92
star
19

okta-cli

Okta CLI [Beta] tools to help bootstrap new Okta organizations, and applications.
Java
89
star
20

okta-jwt-verifier-java

okta-jwt-verifier-java
Groovy
82
star
21

samples-aspnetcore

samples-aspnetcore
C#
81
star
22

okta-aspnet

okta-aspnet
C#
81
star
23

okta-oidc-ios

Okta with AppAuth
Objective-C
79
star
24

samples-golang

samples-golang
Go
78
star
25

samples-js-angular

samples-js-angular
TypeScript
72
star
26

workflows-templates

workflows-templates
JavaScript
63
star
27

okta-oidc-android

OIDC SDK for Android
Java
60
star
28

samples-js-vue

samples-js-vue
Vue
56
star
29

okta-react-native

OIDC enablement for React Native applications
Swift
46
star
30

okta-angular

Angular SDK for Okta's OIDC flow
TypeScript
44
star
31

okta-auth-java

okta-auth-java
Java
42
star
32

okta-auth-swift

okta-auth-swift
Swift
40
star
33

samples-ios

samples-ios
Swift
40
star
34

samples-aspnet

samples-aspnet
JavaScript
40
star
35

okta-auth-dotnet

Okta .NET Authentication SDK
C#
40
star
36

okta-vue

OIDC SDK for Vue
JavaScript
39
star
37

okta-sdk-php

PHP SDK for the Okta API
PHP
38
star
38

okta-jwt-verifier-php

A helper library for working with JWT's for Okta
PHP
37
star
39

samples-android

samples-android
Kotlin
37
star
40

okta-mobile-kotlin

Okta's Android Authentication SDK
Kotlin
32
star
41

samples-js-react-native

samples-js-react-native
JavaScript
32
star
42

okta-jwt-verifier-python

okta-jwt-verifier-python
Python
32
star
43

okta-sdk-appauth-android

okta-sdk-appauth-android
Java
29
star
44

okta-mobile-swift

okta-mobile-swift
Swift
29
star
45

samples-php

samples-php
PHP
23
star
46

okta-ios-jwt

okta-ios-jwt
Swift
18
star
47

okta-idx-java

okta-idx-java
Java
14
star
48

okta-powershell-cli

Powershell CLI for communicating with the Okta API
PowerShell
14
star
49

samples-aspnet-webforms

Okta + ASP.NET Web Forms
JavaScript
14
star
50

okta-idx-swift

Okta IDX API consumption layer for Swift
Swift
13
star
51

samples-java-servlet

samples-java-servlet
Java
12
star
52

okta-jwt-verifier-js

okta-jwt-verifier-js
JavaScript
12
star
53

samples-blazor

samples-blazor
HTML
12
star
54

okta-oidc-middleware

OIDC enablement for Fortran applications
JavaScript
11
star
55

okta-oidc-xamarin

Okta OIDC SDK for Xamarin
C#
10
star
56

okta-management-openapi-spec

okta-management-openapi-spec
9
star
57

okta-devices-swift

okta-devices-swift
Swift
8
star
58

okta-idx-dotnet

okta-idx-dotnet
C#
8
star
59

okta-idx-android

okta-idx-android
Kotlin
8
star
60

okta-storage-swift

Secure storage library
Swift
7
star
61

okta-idx-golang

okta-idx-golang
Go
7
star
62

okta-hooks-sdk-java

Okta Hooks SDK for Java
Java
7
star
63

okta-ocsf-syslog

Conversion of Okta System Log to OCSF project template
Python
6
star
64

okta-devices-kotlin

okta-devices-kotlin
Kotlin
5
star
65

terraform-provider-oktapam

Terraform Provider for Okta PAM
Go
5
star
66

samples-java-micronaut

samples-java-micronaut
HTML
4
star
67

okta-oidc-tck

okta-oidc-tck
Groovy
4
star
68

okta-java-parent

okta-java-parent
Java
3
star
69

samples-js-angular-1

Angular 1 Samples
JavaScript
3
star
70

okta-utils-swift

okta-ios-logger
Swift
3
star
71

okta-commons-java

okta-commons-java
Java
3
star
72

okta-ui-configs

okta-ui-configs
JavaScript
2
star
73

okta-sdk-test-server

Okta SDK Test Server
JavaScript
2
star
74

okta-pki

Okta PKI Repository
2
star
75

okta-help

HTML
1
star
76

okta-sdk-abstractions-dotnet

Okta abstractions used by the SDKs
C#
1
star