const { createSecurityContext, XsuaaService, SECURITY_CONTEXT, errors: { ValidationError }} = require("@sap/xssec");
const credentials = { clientid, ... } // access service credentials, e.g. via @sap/xsenv
const authService = new XsuaaService(credentials) // or: IdentityService, XsaService, UaaService ...
async function authMiddleware(req, res, next) {
try {
const secContext = await createSecurityContext(authService, { req });
// or: const secContext = await createSecurityContext([xsuaaService, identityService]], { req }); for hybrid authentication
// user is authenticated -> tie the SecurityContext to this req object via the dedicated Symbol
req[SECURITY_CONTEXT] = secContext;
return next();
} catch (e) {
// user could not be authenticated
if(e instanceof ValidationError) {
// request has invalid authentication (e.g. JWT expired, wrong audience, ...)
LOG.debug("Unauthenticated request: ", e);
return res.sendStatus(401);
} else {
// authentication could not be validated due to Error
LOG.error("Error while authenticating user: ", e);
return res.sendStatus(500);
}
}
}
app.use(authMiddleware);
const { createSecurityContext, XsuaaService, SECURITY_CONTEXT, errors: { ValidationError }} = require("@sap/xssec");
const credentials = { clientid, ... } // access service credentials, e.g. via @sap/xsenv
const authService = new XsuaaService(credentials) // or: IdentityService, XsaService, UaaService ...
async function authMiddleware(req, res, next) {
try {
const secContext = await createSecurityContext(authService, { req });
// or: const secContext = await createSecurityContext([xsuaaService, identityService]], { req }); for hybrid authentication
// user is authenticated -> tie the SecurityContext to this req object via the dedicated Symbol
req[SECURITY_CONTEXT] = secContext;
return next();
} catch (e) {
// user could not be authenticated
if(e instanceof ValidationError) {
// request has invalid authentication (e.g. JWT expired, wrong audience, ...)
LOG.debug("Unauthenticated request: ", e);
return res.sendStatus(401);
} else {
// authentication could not be validated due to Error
LOG.error("Error while authenticating user: ", e);
return res.sendStatus(500);
}
}
}
app.use(authMiddleware);