Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@telefonica/baikal-sdk

Package Overview
Dependencies
Maintainers
0
Versions
33
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@telefonica/baikal-sdk

Telefónica Kernel SDK

  • 1.13.5
  • latest
  • npm
  • Socket score

Version published
Weekly downloads
269
decreased by-28.07%
Maintainers
0
Weekly downloads
 
Created
Source

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.

FAQs

Package last updated on 09 Sep 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc