@meniga/identity
v6.1.36-alpha.0
Published
A library that makes it easy to use identity server authentication in a react app
Downloads
581
Readme
@meniga/identity
This package helps you with communication to an oidc provider like IdentityServer
This package is based on the redux-oidc and oidc-client npm packages with few helpers.
Getting started
App
You have to add the OidcProvider to the root of the app
import { createBrowserRouter, RouterProvider } from '@meniga/router'
import { globalConfig, getBooleanConfigValue } from '@meniga/config'
import { OidcProvider} from '@meniga/identity'
import { store } from '@meniga/redux'
...
const _configBasename = globalConfig('routing.prefix', '')
const _configIdentity = globalConfig('identity', {
post_logout_redirect_uri: '',
redirect_uri: '',
silent_redirect_uri: '',
forgot_password_uri: '',
})
const App = () => {
...
return <Fragment>
<OidcProvider store={ store } basename={ _configBasename } config={ _configIdentity }>
<RouterProvider router={ browserRouter } />
</OidcProvider>
</Fragment>
}
The OidcProvider accepts three properties:
- store - your redux store
- basename - your react router basename
- config - your identity server/authority config
Config
For more information about the configuration and required and optional properties go to: https://github.com/IdentityModel/oidc-client-js/wiki
Easiest way to provide this config - if you are using @meniga/config in your app - is to create an identity.js config file with the following config, using the values set in your oidc provider.
module.exports = {
authority: 'URL TO THE IDENTITY SERVER',
client_id: 'THE CLIENT ID AS CONFIGURED IN THE IDENTITY SERVER',
redirect_uri: '/callback',
post_logout_redirect_uri: '',
forgot_password_uri: '/login/forgot',
silent_redirect_uri: '/silent_renew.html',
/**
* Depends on what token you want to get from the identity server.
* For example use 'token' to get access_token
* The .well-known configuration of the server has a list of supported response types.
*/
response_type: 'token',
/**
* For Microsoft B2C Identity Server this should be the value of the client_id
*/
scope: 'openid profile email',
loadUserInfo: true,
/**
* Whether or not there should be an automatic attempt to renew the access token prior to its expiration
*/
automaticSilentRenew: true,
/**
* Whether or not the token should be saved in browser storage
*/
storeToken: true,
/**
* The names used to store the access_token and token_type in browser storage.
* Shouldn't be changed if your app is using @meniga/core for api requests.
*/
tokenName: 'accessToken',
tokenTypeName: 'accessTokenType'
}
Note: client_id, scope, callback_uri and silent_redirect_uri should match the configuration made on the identity server.
Router
This setup is based on using @meniga/router but works for anyone using react-router or similar library.
In your apps router you will have to add the following components to authenticate
- UserIsAuthenticated is to restrict access to only authenticated users (you will have to do your onw authorization).
- Config options for UserIsAuthenticated are the same as connectedReduxRedirect in redux-auth-wrapper
- AuthenticationCallback is a component that handles the callback from the oidc provider and saves it to storage.
- It will redirect to the previous url the user was looking after it have done all its work.
- LoginPage is a component that handles redirect to the login page of the oidc provider.
- LogoutPage is similar to the LoginPage that it handles the redirect to the oidc provider but this one redirects to a logout page
None of these components are required but they save a lot of time.
import { Route, Router } from 'cosmic-core'
import { AuthenticationCallback, UserIsAuthenticated, LoginPage, LogoutPage } from '@meniga/identity'
const routes = [
{
key: 'callbackRoute',
element: <AuthenticationCallback callbackUrl={ '/' } errorComponent={ AppError } onError={ () => { }} />,
path: '/callback'
},
{
key: 'loginRoute',
path: '/login',
element: <LoginPage />
},
{
key: 'logoutRoute',
path: '/logout',
element: <LogoutPage />
}
]
const browserRouter = createBrowserRouter(routes, { basename: _configBasename })
Get user info
You can access basic user info using userManager.getUser(). That gives you a promise that resolves to all the info inside state.oidc.user object.
import { getSavedUserManager } from '@meniga/identity'
const handleGetUserSuccess = ( user ) => {
console.log('USER', user)
}
const handleGetUserError = ( e ) => {
console.log('GET USER ERROR', e);
}
const userManager = getSavedUserManager()
userManager.getUser()
.then(handleGetUserSuccess)
.catch(handleGetUserError)
Silent renew token
@meniga/identity supports renewing the bearer token periodically. To set this up you need to provide silent_redirect_uri config options pointing to a html file that has all the code nessasary to renew the token. This html file is injected to the app in an iFrame. The iFrame then is redirected to the IdentityServer for a new token that is proccessed by the iFrame and sent back to the main window.
Normally this can be done with the following code in webpack.config.js or webpack.custom.config.js if you are using @meniga/cli
{
entry: {
Silent_renew: '@meniga/identity/lib/components/SilentRenew.js'
},
...
plugins: [
new plugins.HtmlWebpackPlugin({
...
excludeChunks: ['Silent_renew'],
...
}),
new plugins.HtmlWebpackPlugin({
chunks: ['Silent_renew'],
title: 'Identity server silent renew',
filename: 'silent_renew.html',
})
]
}
or if you are using vite:
(as silentRenew.js)
import { processSilentRenew } from '@meniga/identity'
processSilentRenew()
(as part of vite.config.js)
createHtmlPlugin({
pages: [
...,
{
entry: './app/silentRenew.js',
filename: 'silent_renew.html',
template: 'silent_renew.html',
injectOptions: {
data: {
title: 'Identity server silent renew',
},
}
}
]
})