@irv/auth-middleware-public
v1.2.1
Published
Middleware to add authentication endpoints to any Node client web project to make authentication easier.
Downloads
51
Maintainers
Keywords
Readme
Node Version 7.6.0
koa Version 2.0.0
koa-router Version 7.1.0
koa-passport Version 3.0.0
express Version 4.15.4
passport-saml Version 0.15.0
passport 0.4.0
Things to know before you use this in your app:
- This module is quite stable - you can pull this module and it's one internally developed public dependancy, @irv/kong-client-public.
Auth Proxy Middleware
Koa
Options
{
targetURL: 'auth api target url',
// Where you want the auth endpoints to be mounted
prefix: '/auth',
// Your Client Key
clientKey: 'EXAMPLEKEY',
// Optional session timeout (in hours)
sessionTimeoutHrs: 2,
// The function below is executed after a successful SSO login.
// Required for Service Provider Only.
ssoLoginCallback: async (ctx, next) => Promise,
kongClient: {
username: 'username from Kong',
secret: 'secret from Kong',
isSigningEnabled: false, // Default is false
timeout: 300000 // Default is 300000
}
}
How to use the Service Provider Koa middleware
Require the auth-middleware-public
const authMiddleware = require('@irv/auth-middleware-public').authMiddleware;
OR
const authMiddleware = require('@irv/auth-middleware-public').authMiddlewareKoa;
You must pass the app and the options in.
const app = new Koa();
authMiddleware(app, config.api.auth);
Service Provider ssoLoginCallback
Details
This function is called during the SSO POST
request. You should first await next()
to call the proxy controller, which authenticates with the Auth API. If it does not throw an exception, then the user object and new session token retrieved from the Mimic Auth API will be in the request body (ctx.body.user
and ctx.body.sessionToken
). See structure below:
ctx: {
body: {
user: {
identityHash: 'somehashedvalue',
clientId: #,
identityProviderSlug: 'some-slug',
firstName: 'First',
lastName: 'Last',
email: '[email protected]',
authInfo: {
authprovideruserid: '..',
otherfield: '..'
}
},
sessionToken: 'SOME_SESSION_TOKEN'
}
}
You can use this data to find the existing user, or create a new one, and then log them in.
If you want to handle any errors that occur during the proxy request you can wrap the await next()
call in a try...catch
block.
async (ctx, next) => {
try {
// Proxy the request to the Auth API
await next();
// If we get here, the proxy request was successful.
// `ctx.body` contains the response data from the proxy request.
} catch (err) {
// If we get here, the proxy request failed
}
}
How to use the Identity Provider lib (New in v5.0.0)
idpKoa
below is a function that takes the same options
outlined above. Note: The ssoLoginCallback
field is only required for the SP functionality
const idpKoa = require('@irv/auth-middleware-public').idpKoa
const idp = idpKoa(config.api.auth);
Once initialized with options
, the object contains a router
and samlResponseMiddleware
.
The router
has the metadata route to provide metadata to service providers. Below is how to initialize it. Note: Using both the SP authMiddleware
(shown above) and this idp.router
on the same server is A-OK.
const app = new Koa();
const router = idp.router;
router(app);
The samlResponseMiddleware
is a middleware with the signature async (ctxt, next) => {}
. Use this middleware after the desired route to trigger a form POST to the Service Provider. You will need to attach an idpMiddleware
object to the context with the serviceProviderSlug
, identityHash
and additionalAttributes
. The identityHash
is that of the user logging into the Service Provider. The additionalAttributes
are any additional fields you want sent with that user to the Service Provider.
const samlResponseMiddleware = idp.samlResponseMiddleware;
// In your routes:
router.get('/sso/idp/:slug', async (ctx, next) => {
ctx.idpMiddleware = {
serviceProviderSlug: 'slug',
identityHash: 'XYZ1234...',
additionalAttributes: {
billingId: '',
customerId: '',
...
},
};
await next();
}, samlResponseMiddleware);
Express
Options
{
targetURL: 'auth api target url',
// Where you want the auth endpoints to be mounted
prefix: '/auth',
// Your Client Key
clientKey: 'EXAMPLEKEY',
// Optional session timeout (in hours)
sessionTimeoutHrs: 2,
// A function that's executed after SSO login
ssoLoginCallback: (req, res) => Promise,
kongClient: {
username: 'username from Kong',
secret: 'secret from Kong',
isSigningEnabled: false, // Default is false
timeout: 300000 // Default is false
}
}
To use as express middleware
Require the auth-middleware-public
const authMiddleware = require('@irv/auth-middleware-public').authMiddlewareExpress;
You must pass the app and the options in.
const app = express();
// Use 1 of the 2 parser examples:
// 1. For Express 4.16 and greater use the built-in express parsing middlewares
app.use(express.urlencoded());
app.use(express.json());
// 2. For Express 4.15 and below use the body-parser package
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
authMiddleware(app, config.api.auth);
SSO Login Callback Details
This function is called after the SSO POST
request. On success, the request body should contain the user object (req.body.user
and req.body.sessionToken
). On failure, the request body will not have a user object and will have an error message instead. See structure below:
req: {
body: {
user: {
identityHash: 'somehashedvalue',
clientId: #,
identityProviderSlug: 'some-slug',
firstName: 'First',
lastName: 'Last',
email: '[email protected]',
authInfo: {
authprovideruserid: '..',
otherfield: '..'
}
},
sessionToken: 'SOME_SESSION_TOKEN'
}
}
You can use the user data to find the existing user, or create a new one, and then log them in.
Use the res
object to send, render, redirect etc.
(req, res) => {
// Success Case: If the req.body contains a user object, everything was successful
// Error Case: If the req.body does not contain a user object, it will have an error message
console.log(req.body); // Should contain the user object on success
// Finish up the response with a send, render, redirect etc.
res.send('Whatever you want to send');
}
Run Tests and Linter
To run just the tests, use npm run test
.
To run just the linter, use npm run lint
.
To run the tests and eslint, npm run test-lint
.
Proxy routes
GET [prefix]/sso/:idprovider
- Proxy's to the Auth API path that routes to the SP Initiated SSO ProcessGET [prefix]/sso/saml/:idprovider
- Starts the SP Initiated SAML SSO ProcessGET [prefix]/sso/saml/:idprovider/metadata
- Get's the Identity Provider's metadata (from the Auth API) for SAML AuthPOST [prefix]/sso/saml/:idprovider
- Proxy's the post body (the SAML Response) to the Auth API to parse and interpretPOST [prefix]/sso/signed/:idprovider
- Proxy's the post body, that includes a time based signature of the post body, to the Auth APIPOST [prefix]/sso/hash/:idprovider
- Proxy's the post body, that includes a time based md5 hash, to the Auth APIPOST [prefix]/sso/corelogic/:idprovider/auth-key
- Proxy's the post body, that includes a UserID, to the Auth API. This returns a GUID for the identity provider to use in account creation.POST [prefix]/sso/corelogic/:idprovider
- Proxy's the post body, that includes a hashed Password according to CoreLogic/Matrix specs, to the Auth API