1.2.2 • Published 6 months ago
@com.ctu.iotlab/authenticator v1.2.2
How to use
The library provides a factory (AuthenticatorFactory
) that supports authentication with Keycloak and automatically sets the token in the Axios header.
Steps
1. Install Required Dependencies
To install Axios
, run:
npm i axios
Install oda-authenticator
library, run:
npm i "@com.ctu.iotlab/oda-authenticator"
2. Configure Keycloak
Begin by configuring Keycloak with the necessary settings. You can do this by creating a KeycloakConfig
object as follows:
import { KeycloakConfig } from '@com.ctu.iotlab/oda-authenticator'
const keycloakConfig: KeycloakConfig = {
url: '<your_keycloak_server>',
realm: 'realm',
clientId: 'client_id'
}
3. Get the Authenticator:
Use the AuthenticatorFactory
to get an authenticator instance:
import axios from 'axios'
import { AuthenticatorFactory, KeycloakConfig } from '@com.ctu.iotlab/oda-authenticator'
const authenticator = await AuthenticatorFactory.getAuthenticator(axios, keycloakConfig)
4. Authenticate
authenticator.authenticate(30) // 30 is the minTokenValidity
Example Usage
import axios from 'axios'
import { AuthenticatorFactory, KeycloakConfig } from '@com.ctu.iotlab/oda-authenticator'
const keycloakConfig: KeycloakConfig = {
url: 'http://localhost:8880', // Your keycloak server
realm: 'kc',
clientId: 'kc'
}
export const authMiddleware = () => {
AuthenticatorFactory.getAuthenticator(axios, keycloakConfig).then((authenticator) => {
authenticator.authenticate(30).then(() => {
// Example API call to test if the token is set in the header
axios.get('https://jsonplaceholder.typicode.com/todos/1').then((response) => {
console.log(response.data)
})
})
})
}