npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@telefonica/baikal-sdk

v1.13.5

Published

Telefónica Kernel SDK

Downloads

1,320

Readme

Node.js SDK for Baikal

Provides an authentication SDK for the 4th Platform.

Installation

npm i @telefonica/baikal-sdk

Usage

Create a client

const OpenIDClient = require('@telefonica/baikal-sdk').OpenIDClient;

const client = new OpenIDClient({
  authserverEndpoint: 'http://auth.xxx.baikalplatform.com',
  clientId: 'your_oauth_client_id',
  clientSecret: 'your_oauth_client_secret',
  // For using grantUser method (jwt-bearer grant type)
  clientKeys: [{ key: 'stringWithTheKey', format: 'pem' }], // optional
  issuer: 'http://yourserver.com/', // your jwt issuer id
  privateCertsPath: '/path/to/certs/directory', // directory to read certificates/private keys.
});

Get an access_token for a user using authorization_code This flow involves 2 steps. Refer to the ./examples/authcode.js for a complete usage example.

// 1st step, triggered by a user login attempt: get a redirect url and a web session ready to be saved and serialized
// It's recommened that you save the session in a `secure` `httpOnly` cookie
const { url, session } = await client.authorize({
  redirect_uri: 'http://your-public-host.com/callback',
  scopes: ['list', 'of', 'scopes'], // optional
  purposes: ['list', 'of', 'purposes'], // optional
  state: 'random-string-for-each-request-with-some-context-for-you', // optional
});

// 2nd step: callback tiggered by a browser redirect launched by the authorization server.
// pass the session you saved in the earlier step an
const { access_token } = await client.grantCode(req.query, session);

Get an access_token for a user using jwt-bearer

const { access_token } = await client.grantUser({
  sub: 'userSUB',
  scopes: ['list', 'of', 'scopes'],
  purposes: ['list', 'of', 'purposes'],
  authorization_id: '46921050-e97c-418b-928c-4158256be92c', //optional
});

Get a client_credentials access_token

const { access_token } = await client.grantClient({
  scopes: ['list', 'of', 'scopes'], // optional
  purposes: ['list', 'of', 'purposes'], //optional
});

Introspect an access_token

const introspection = await client.introspect({
  token: 'the_access_token_you_want_to_introspect',
  token_type_hint: 'Bearer', // optional
});

Expose your public keys in a server route to use with a jwt-bearer

If you have configured your issuer in the authserver to read from an endpoint, you should expose your public keys in an accessible route.

// Using express as server
const OpenIDClient = require('@telefonica/baikal-sdk').OpenIDClient;
const express = require('express');

const app = express();
const client = new OpenIDClient();

app.use('/jwk', async (req, res, next) => res.json(await client.getKeyStore()));

app.listen(3000);

Configuration

The OpenIDClient configuration will be read from environment if ommited

export BAIKAL_AUTHSERVER_ENDPOINT='http://auth.xxx.baikalplatform.com'
export BAIKAL_CLIENT_ID='your_oauth_client_id'
export BAIKAL_CLIENT_SECRET='your_oauth_client_secret'
export BAIKAL_ISSUER='http://yourserver.com/'
export BAIKAL_PRIVATE_CERTS_PATH='/path/to/certs/directory'

Supported certs format are (should match the file extension):

  • json: JSON stringified JWK
  • private: DER encoded 'raw' private key
  • pkcs8: DER encoded (unencrypted!) PKCS8 private key
  • public: DER encoded SPKI public key (alternate to 'spki')
  • spki: DER encoded SPKI public key
  • pkix: DER encoded PKIX X.509 certificate
  • x509: DER encoded PKIX X.509 certificate
  • pem: PEM encoded of PKCS8 / SPKI / PKIX

Grant public methods accept a request config as the last argument, to allow specifying headers and timeout per-request

const { access_token } = await client.grantClient(
  { scopes: [], purposes: [] },
  {
    headers: {
      'X-Correlator': '1234-5678-9012-3456-7890',
    },
    timeout: 3000,
  }
);

Use a keep-alive agent

const { OpenIDClient, httpClient } = require('@telefonica/baikal-sdk');
const https = require('https');

const httpsAgent = new https.Agent({ keepAlive: true });
httpClient.defaults.httpsAgent = httpsAgent;

Debug sdk requests We use debug package to debug our requests under the key baikal-sdk

DEBUG=baikal-sdk node your_service.js

Examples description

Describe the examples/authcode.js implementation.

General init code

Initializes an OpenID Connect client with the URL of an authentication server and sets up an Express application to manage sessions using cookies with a secret key. The OpenID client can be used for handling authentication and authorization in the application.

const client = new OpenIDClient({
  authserverEndpoint: 'https://auth.global-int-current.baikalplatform.com',
});

app.use(
  cookieSession({
    secret: 'secret',
  })
);

Route [ / ]

The root route (/) initiates the OIDC authorization process. It redirects users to the OpenIDClient provider for authentication.

app.get('/', async (req, res, next) => {
  try {
    const { url, session } = await client.authorize({
      redirect_uri: 'http://localhost:3000/callback',
      scopes: ['openid', 'offline_access'],
      purposes: ['4p-test'],
    });
    req.session.login = session;
    console.log(`Redirecting browser to ${url}`);
    res.redirect(url);
  } catch (err) {
    next(err);
  }
});

Route [ /callback ]

The callback route (/callback) handles the callback from the OpenIDClient provider and obtains the access token.

app.get('/callback', async (req, res, next) => {
  try {
    console.log('Redirection callback called');

    const tokenSet = await client.grantCode(req.body, req.session.login);

    const token = await client.introspect({ token: tokenSet.access_token });
    res.json({ tokenSet, token });
  } catch (err) {
    next(err);
  }
});

Optional Parameters in the Request Body (req.body):

{
   error:"",
   error_description:"",
   state:"",
   code:""
}

LICENSE

Copyright 2019 Telefónica

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.