# OIDC

beta Contributors are welcome

oidc-provider (opens new window) is an OAuth 2.0 Authorization Server with OpenID Connect and many additional features and standards implemented.

Certification

Filip Skokan has certified (opens new window) that oidc-provider (opens new window) conforms to the following profiles of the OpenID Connectâ„¢ protocol

  • OP Basic, Implicit, Hybrid, Config, Dynamic, Form Post, and 3rd Party-Init
  • OP Front-Channel Logout, Back-Channel Logout, RP-Initiated Logout, and Session Management
  • OP FAPI R/W MTLS and Private Key

# Features

Ts.ED provides decorators and services to create an OIDC provider with your Ts.ED application.

  • Create interactions policies,
  • Create views,
  • Use adapters to connect oidc-provider with redis/mongo/etc...
  • Automatically create jwks keys on startup

# Installation

Before using the @tsed/oidc-provider package, we need to install the oidc-provider (opens new window) module.

npm install --save oidc-provider
npm install --save @tsed/oidc-provider @tsed/jwks @tsed/adapters
1
2

Then we need to follow these steps:

  • Configure the oidc server,
  • Create the Accounts provider
  • Create the Interactions controller,
  • Create our first Login interaction and views,

TIP

Select "OpenID Connect provider" upon initialization with the Ts.ED CLI and the following will be automatically generated.

# Configuration

To use oidc-provider with Ts.ED it requires some other Ts.ED features to work properly.

  • Adapters to manage database connection,
  • Views to display pages.

Use tsed init yourApp to create a TSed application and adjust Server.ts:

import {Configuration} from "@tsed/di";
import {Accounts} from "./services/Accounts";
import {InteractionsCtrl} from "./controllers/oidc/InteractionsCtrl";

@Configuration({
  httpPort: 8083,
  mount: {
    "/": [InteractionsCtrl]
  },
  adapters: {
    lowdbDir: join(process.cwd(), "..", ".db"),
    Adapter: FileSyncAdapter
  },
  oidc: {
    // path: "/oidc",
    Accounts: Accounts,
    jwksPath: join(process.cwd(), "..", "..", "keys", "jwks.json"),
    // allowHttpLocalhost: false, // by default. true in dev mode and false in production
    clients: [
      {
        client_id: "client_id",
        client_secret: "client_secret",
        redirect_uris: ["http://localhost:3000"],
        response_types: ["id_token"],
        grant_types: ["implicit"],
        token_endpoint_auth_method: "none"
      }
    ],
    claims: {
      openid: ["sub"],
      email: ["email", "email_verified"]
    },
    features: {
      // disable the packaged interactions
      devInteractions: {enabled: false},
      encryption: {enabled: true},
      introspection: {enabled: true},
      revocation: {enabled: true}
    }
  },
  views: {
    root: `./views`,
    extensions: {
      ejs: "ejs"
    }
  }
})
class Server {}
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

# Options

import type {Type} from "@tsed/core";
import type {JwksKeyParameters} from "@tsed/jwks";
import type {Configuration} from "oidc-provider";
import type {Adapter} from "@tsed/adapters";
import type {OidcAccountsMethods} from "./OidcAccountsMethods";

export interface OidcSettings extends Configuration {
  /**
   * force the secure cookie. By default, in dev mode it's disabled and in production it's enabled.
   */
  secureCookies?: boolean;
  /**
   * Path on which the oidc-provider instance is mounted.
   */
  path?: string;
  /**
   * Issuer URI. By default, Ts.ED create issuer with http://localhost:${httpPort}
   */
  issuer?: string;
  /**
   * Path to store jwks keys.
   */
  jwksPath?: string;
  /**
   * Generate jwks from given certificates
   */
  certificates?: JwksKeyParameters[];
  /**
   * Secure keys.
   */
  secureKey?: string[];
  /**
   * Enable proxy.
   */
  proxy?: boolean;
  /**
   * Allow redirect_uri on HTTP protocol and localhost domain.
   */
  allowHttpLocalhost?: boolean;
  /**
   * Injectable service to manage accounts.
   */
  Accounts?: Type<OidcAccountsMethods>;
  /**
   * Injectable adapter to manage database connexion.
   */
  Adapter?: Type<Adapter>;
  /**
   * Use the connection name for the OIDCRedisAdapter.
   */
  connectionName?: string;
}

declare global {
  namespace TsED {
    interface Configuration {
      oidc: OidcSettings;
    }
  }
}
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

Documentation on other options properties can be found on the oidc-provider (opens new window) documentation page.

WARNING

It is advised to set path to /oidc to prevent oidc-provider becoming the default exception handler on all routes. In future versions of Ts.ED this will be the default value.

# Use Redis 6.129.0+

Ts.ED provide a Redis adapter for OIDC provider. You just have to install @tsed/adapters-redis and configure a redis connection to store all OIDC provider data in Redis.

npm i --save @tsed/redis-adapters @tsed/ioredis ioredis
npm i --save-dev ioredis-mock
1
2

Then create a new RedisConnection.ts for your new redis connection:

import Redis from "ioredis";
import {registerConnectionProvider} from "@tsed/ioredis";

export const REDIS_CONNECTION = Symbol.for("REDIS_CONNECTION");
export type REDIS_CONNECTION = Redis;

registerConnectionProvider({
  provide: REDIS_CONNECTION,
  name: "default" // you can change this name at your conveniance
});
1
2
3
4
5
6
7
8
9
10

Note

You can find more details on @tsed/ioredis documentation.

Then edit the Server settings:

import {OIDCRedisAdapter, RedisAdapter} from "@tsed/adapters-redis";
import {Configuration} from "@tsed/di";
import {Accounts} from "./services/Accounts";
import {InteractionsCtrl} from "./controllers/oidc/InteractionsCtrl";

@Configuration({
  httpPort: 8083,
  mount: {
    "/": [InteractionsCtrl]
  },
  redis: [
    {
      name: "default"
      // add redis configuration
    }
  ],
  adapters: {
    Adapter: RedisAdapter,
    connectionName: "default"
  },
  oidc: {
    Adapter: OIDCRedisAdapter,
    connectionName: "default"
    /// other options
  }
})
export class Server {}
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

That all!

# Allow HTTP & localhost

By default, Ts.ED enable HTTP and localhost domain as a valid redirect uri for your OIDC project. But, sometimes you want to allow also HTTP and localhost domain in your integration or QA environment.

@Configuration({
  oidc: {
    allowHttpLocalhost: true
  }
})
1
2
3
4
5

# Secure cookies

By default, Ts.ED disable the secureCookies options in development mode and enable it in production mode. But, sometimes this options in integration environment because your server isn't under a Https protocol.

@Configuration({
  oidc: {
    secureCookies: false
  }
})
1
2
3
4
5

# TLS proxy

The OpenID Connect specification does not allow unsecured HTTP requests and oidc-provider blocks them by default. While there is a workaround (opens new window), the proper way is to use a TLS offloading proxy in front of your app. When developing, the easiest way is to use Caddy (opens new window). To use it, set proxy: true in your options and then run:

caddy reverse-proxy --from localhost:8443 --to localhost:8083
1

# Accounts

oidc-provider requires an Account model to find an account during an interaction. The model can be used in conjunction with the adapter to fetch an account.

    TIP

    Claims method is used by oidc-provider to expose this information in the userInfo endpoint.

    TIP

    We use the $onInit hook to create the first account automatically. You can adapt the script to your needs.

    # Interactions

    Interactions are the user flows in oidc-provider. For example, the login page is considered by oidc-provider as an interaction. We can define many interactions during the authentication flow, for example:

    • Login,
    • E-mail verification,
    • Password recovery,
    • Sharing account data consent,
    • etc.

    To have a working OIDC server with Ts.ED, we need to create at least a login and a consent interaction. To start, we have to create the Interactions controller which will be responsible to run all of our future custom interactions.

    In your controller's directory, create the oidc/InteractionsCtrl.ts file and copy the following code:

    import {Get, PathParams} from "@tsed/common";
    import {Interactions, OidcCtx} from "@tsed/oidc-provider";
    import {Name} from "@tsed/schema";
    import {AbortInteraction} from "../../interactions/AbortInteraction";
    import {ConsentInteraction} from "../../interactions/ConsentInteraction";
    import {CustomInteraction} from "../../interactions/CustomInteraction";
    import {LoginInteraction} from "../../interactions/LoginInteraction";
    
    @Name("Oidc")
    @Interactions({
      path: "/interaction/:uid",
      children: [LoginInteraction, ConsentInteraction, CustomInteraction, AbortInteraction]
    })
    export class InteractionsCtrl {
      @Get("/:interaction?")
      async prompt(@PathParams("interaction") interaction: string, @OidcCtx() oidcCtx: OidcCtx) {
        return oidcCtx.runInteraction(interaction);
      }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19

    Note

    The controller Interactions exposes the routes to display any interaction. Here we expose the route GET /interation/:uid

    The uid is the unique session id used by oidc-provider to identify the current user flow.

    Now that we have our interaction controller, we can create our first interaction.

    Create a new directory interactions. We will store all custom interactions in this directory.

      TIP

      $prompt is a special hook called by your Interactions controller.

      At this step, you can start the OIDC server and check the logs server to see if the well-known configuration has been correctly exposed:

      [2021-01-04T07:35:31.523] [INFO ] [TSED] - WellKnown is available on http://0.0.0.0:8083/.well-known/openid-configuration
      
      1

      Try also to open the link in your browser!

      Now, we need to add the Views to display our login page. Create a views directory on root level and create the following files:

        The login page is ready to be displayed. To test it, open the following link:

        http://localhost:8083/auth?client_id=client_id&response_type=id_token&scope=openid&nonce=foobar&redirect_uri=http://localhost:3000
        
        
        1
        2
        Oidc login page

        # Create custom interaction

        Here a custom interaction with extra methods to configure checks precondition and details information:

        import {View} from "@tsed/common";
        import {Env} from "@tsed/core";
        import {Constant} from "@tsed/di";
        import {Interaction, InteractionMethods, OidcCtx, OidcSession, Params, Prompt, Uid} from "@tsed/oidc-provider";
        import {Name} from "@tsed/schema";
        import {interactionPolicy, KoaContextWithOIDC} from "oidc-provider";
        import Check = interactionPolicy.Check;
        
        @Interaction({
          name: "custom",
          requestable: true
        })
        @Name("Oidc")
        export class CustomInteraction implements InteractionMethods {
          @Constant("env")
          env: Env;
        
          $onCreate() {}
        
          /**
           * return checks conditions. See: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md#interactionspolicy
           */
          checks() {
            return [
              new Check("no_session", "End-User authentication is required", (ctx) => {
                const {oidc} = ctx;
        
                if (oidc.session?.accountId) {
                  // @ts-ignore
                  return Check.NO_NEED_TO_PROMPT;
                }
        
                // @ts-ignore
                return Check.REQUEST_PROMPT;
              })
            ];
          }
        
          /**
           * return checks conditions. See: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md#interactionspolicy
           */
          details(ctx: KoaContextWithOIDC) {
            const {oidc} = ctx;
        
            return {
              ...(oidc.params?.max_age === undefined ? undefined : {max_age: oidc.params.max_age}),
              ...(oidc.params?.login_hint === undefined ? undefined : {login_hint: oidc.params.login_hint}),
              ...(oidc.params?.id_token_hint === undefined ? undefined : {id_token_hint: oidc.params.id_token_hint})
            };
          }
        
          @View("custom")
          async $prompt(
            @OidcCtx() oidcCtx: OidcCtx,
            @Prompt() prompt: Prompt,
            @OidcSession() session: OidcSession,
            @Params() params: Params,
            @Uid() uid: Uid
          ): Promise<any> {
            await oidcCtx.checkClientId();
        
            return oidcCtx.interactionPrompt({
              title: "Sign-in Custom",
              flash: false
            });
          }
        }
        
        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

        See more details on: https://github.com/panva/node-oidc-provider/blob/main/docs/README.md#interactionspolicy

        # Alter configuration

        Some part of the OIDC provider configuration needs function to work. And ideally these functions should have access to our Ts.ED Services.

        It's possible to do that by listening the $alterOidcConfiguration hook and inject the expected functions in the configuration:

        import {PlatformContext} from "@tsed/common";
        import {InjectContext, Module} from "@tsed/di";
        import {AuthorizationCode, BackchannelAuthenticationRequest, DeviceCode, RefreshToken, Client, OidcSettings} from "@tsed/oidc-provider";
        import {KoaContextWithOIDC, Provider, ResourceServer} from "oidc-provider";
        
        @Module()
        class OidcResourceIndicatorsModule {
          @InjectContext()
          protected $ctx: PlatformContext; // retrieve the Ts.ED context
        
          async $alterOidcConfiguration(config: OidcSettings): Promise<OidcSettings> {
            // example with the
            config.features!.resourceIndicators = {
              enabled: true,
              defaultResource: this.defaultResource.bind(this),
              getResourceServerInfo: this.getResourceServerInfo.bind(this),
              useGrantedResource: this.useGrantedResource.bind(this)
            };
        
            return config;
          }
        
          protected async defaultResource(ctx: KoaContextWithOIDC): Promise<string | string[]> {
            ///
            return "https://mydomain.com";
          }
        
          protected async getResourceServerInfo(ctx: KoaContextWithOIDC, resourceIndicator: string, client: Client): Promise<ResourceServer> {
            ///
            return {};
          }
        
          protected async useGrantedResource(
            ctx: KoaContextWithOIDC,
            model: AuthorizationCode | RefreshToken | DeviceCode | BackchannelAuthenticationRequest
          ): Promise<boolean> {
            return true;
          }
        }
        
        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

        # Alter OIDC policy

        Ts.ED emits a special $alterOidcPolicy event when @tsed/oidc-provider links interactions with OIDC policy. You can change the policy configuration by adding $alterOidcPolicy on InteractionsCtrl:

        import {Get, PathParams} from "@tsed/common";
        import {Interactions, OidcCtx, DefaultPolicy} from "@tsed/oidc-provider";
        import {LoginInteraction} from "../../interactions/LoginInteraction";
        
        @Interactions({
          path: "/interaction/:uid",
          children: [
            LoginInteraction // register its children interations
          ]
        })
        export class InteractionsCtrl {
          @Get("/:name?")
          async promptInteraction(@PathParams("name") name: string | undefined, @OidcCtx() oidcCtx: OidcCtx) {
            return oidcCtx.runInteraction(name);
          }
        
          $alterOidcPolicy(policy: DefaultPolicy) {
            // do something
        
            return policy;
          }
        }
        
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22

        # Implement your own adapter

        import {OidcAdapterMethods} from "@tsed/oidc-provider";
        import {Adapter} from "@tsed/adapters";
        
        export class CustomAdapter<Model extends AdapterModel> extends Adapter<Model> implements OidcAdapterMethods {
          //
          // implement all required methods
          //
          create(value: Partial<Omit<Model, "_id">>, expiresAt?: Date): Promise<Model> {}
        
          update(id: string, value: Model, expiresAt?: Date): Promise<Model | undefined> {}
        
          updateOne(predicate: Partial<Model>, value: Partial<Model>, expiresAt?: Date): Promise<Model | undefined> {}
        
          upsert(id: string, value: Model, expiresAt?: Date): Promise<Model> {}
        
          findOne(predicate: Partial<Model>): Promise<Model | undefined> {}
        
          findById(id: string): Promise<Model | undefined> {}
        
          findAll(predicate?: Partial<Model>): Promise<Model[]> {}
        
          deleteOne(predicate: Partial<Model>): Promise<Model | undefined> {}
        
          deleteMany(predicate: Partial<Model>): Promise<Model[]> {}
        
          deleteById(id: string): Promise<Model | undefined> {}
        
          //
          // if you use redis implement also the following methods
          //
          async findByUserCode(userCode: string) {}
        
          async findByUid(uid: string) {}
        
          async destroy(id: string) {}
        
          async revokeByGrantId(grantId: string) {}
        
          async consume(grantId: string) {}
        }
        
        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

        TIP

        You can find original adapters from oidc-provider project here: https://github.com/panva/node-oidc-provider/blob/main/example/adapters

        # Debug

        Use DEBUG=oidc-provider:* for debugging oidc-provider.

        # Support oidc-provider

        If you or your business uses oidc-provider (opens new window), please consider becoming a sponsor, so we can continue maintaining it and adding new features carefree.

        # Author

          # Maintainers

            Last Updated: 2/5/2023, 1:16:22 PM

            Other topics