Express JS middleware implementing sign on for Express web apps using OpenID Connect.
+ + +Node.js version >=12.0.0 is recommended, but ^10.13.0 lts/dubnium is also supported.
+npm install express-openid-connect
+
+ Follow our Secure Local Development guide to ensure that applications using this library are running over secure channels (HTTPS URLs). Applications using this library without HTTPS may experience "invalid state" errors.
+The library needs issuerBaseURL, baseURL, clientID and secret to request and accept authentication. These can be configured with environmental variables:
+ISSUER_BASE_URL=https://YOUR_DOMAIN
+CLIENT_ID=YOUR_CLIENT_ID
+BASE_URL=https://YOUR_APPLICATION_ROOT_URL
+SECRET=LONG_RANDOM_VALUE
+ ... or in the library initialization:
+// index.js
+
+const { auth } = require('express-openid-connect');
+app.use(
+ auth({
+ issuerBaseURL: 'https://YOUR_DOMAIN',
+ baseURL: 'https://YOUR_APPLICATION_ROOT_URL',
+ clientID: 'YOUR_CLIENT_ID',
+ secret: 'LONG_RANDOM_STRING',
+ })
+);
+ With this basic configuration, your application will require authentication for all routes and store the user identity in an encrypted and signed cookie.
+See the examples for route-specific authentication, custom application session handling, requesting and using access tokens for external APIs, and more.
+See the API documentation for additional configuration possibilities and provided methods.
+ +Errors raised by this library are handled by the default Express error handler which, in the interests of security, does not include the stack trace in the production environment.
+But you may want to go one step further and hide additional error details from client, like the error message. To do this see the Express documentation on writing Custom error handlers
+ +We appreciate feedback and contribution to this repo! Before you get started, please see the following:
+ +Contributions can be made to this library through PRs to fix issues, improve documentation or add features. Please fork this repo, create a well-named branch, and submit a PR with a complete template filled out.
+Code changes in PRs should be accompanied by tests covering the changed or added functionality. Tests can be run for this library with:
+npm install
+npm test
+ When you're ready to push your changes, please run the lint command first:
+npm run lint
+
+ Please use the Issues queue in this repo for questions and feedback.
+ +Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
+ +Auth0 helps you to easily:
+This project is licensed under the MIT license. See the LICENSE file for more info.
+Express JS middleware implementing sign on for Express web apps using OpenID Connect.
+The auth()
middleware requires secret, baseURL, clientID
+ and issuerBaseURL.
If you are using a response type that includes code
, you will also need: clientSecret
const express = require('express');
+const { auth } = require('express-openid-connect');
+
+const app = express();
+
+app.use(
+ auth({
+ issuerBaseURL: 'https://YOUR_DOMAIN',
+ baseURL: 'https://YOUR_APPLICATION_ROOT_URL',
+ clientID: 'YOUR_CLIENT_ID',
+ secret: 'LONG_RANDOM_STRING',
+ })
+);
+
+app.get('/', (req, res) => {
+ res.send(`hello ${req.oidc.user.name}`);
+});
+
+ app.listen(3000, () => console.log('listening at http://localhost:3000'))
+ Use this MW to protect a route, providing a custom function to check.
+const { claimCheck } = require('express-openid-connect');
+
+app.get('/admin/community', claimCheck((req, claims) => {
+ return claims.isAdmin && claims.roles.includes('community');
+}), (req, res) => {
+ res.send(...);
+});
+
+ Use this MW to protect a route based on the value of a specific claim.
+const { claimEquals } = require('express-openid-connect');
+
+app.get('/admin', claimEquals('isAdmin', true), (req, res) => {
+ res.send(...);
+});
+
+ The name of the claim
+The value of the claim, should be a primitive
+Use this MW to protect a route, checking that all values are in a claim.
+const { claimIncludes } = require('express-openid-connect');
+
+app.get('/admin/delete', claimIncludes('roles', 'admin', 'superadmin'), (req, res) => {
+ res.send(...);
+});
+
+ The name of the claim
+Claim values that must all be included
+Set authRequired to false
then require authentication
+ on specific routes.
const { auth, requiresAuth } = require('express-openid-connect');
+
+app.use(
+ auth({
+ ...
+ authRequired: false
+ })
+);
+
+app.get('/profile', requiresAuth(), (req, res) => {
+ res.send(`hello ${req.oidc.user.name}`);
+});
+
+ Express JS middleware implementing sign on for Express web apps using OpenID Connect.
+ + +Node.js version >=12.0.0 is recommended, but ^10.13.0 lts/dubnium is also supported.
+npm install express-openid-connect
+
+ Follow our Secure Local Development guide to ensure that applications using this library are running over secure channels (HTTPS URLs). Applications using this library without HTTPS may experience "invalid state" errors.
+The library needs issuerBaseURL, baseURL, clientID and secret to request and accept authentication. These can be configured with environmental variables:
+ISSUER_BASE_URL=https://YOUR_DOMAIN
+CLIENT_ID=YOUR_CLIENT_ID
+BASE_URL=https://YOUR_APPLICATION_ROOT_URL
+SECRET=LONG_RANDOM_VALUE
+ ... or in the library initialization:
+// index.js
+
+const { auth } = require('express-openid-connect');
+app.use(
+ auth({
+ issuerBaseURL: 'https://YOUR_DOMAIN',
+ baseURL: 'https://YOUR_APPLICATION_ROOT_URL',
+ clientID: 'YOUR_CLIENT_ID',
+ secret: 'LONG_RANDOM_STRING',
+ })
+);
+ With this basic configuration, your application will require authentication for all routes and store the user identity in an encrypted and signed cookie.
+See the examples for route-specific authentication, custom application session handling, requesting and using access tokens for external APIs, and more.
+See the API documentation for additional configuration possibilities and provided methods.
+ +Errors raised by this library are handled by the default Express error handler which, in the interests of security, does not include the stack trace in the production environment.
+But you may want to go one step further and hide additional error details from client, like the error message. To do this see the Express documentation on writing Custom error handlers
+ +We appreciate feedback and contribution to this repo! Before you get started, please see the following:
+ +Contributions can be made to this library through PRs to fix issues, improve documentation or add features. Please fork this repo, create a well-named branch, and submit a PR with a complete template filled out.
+Code changes in PRs should be accompanied by tests covering the changed or added functionality. Tests can be run for this library with:
+npm install
+npm test
+ When you're ready to push your changes, please run the lint command first:
+npm run lint
+
+ Please use the Issues queue in this repo for questions and feedback.
+ +Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
+ +Auth0 helps you to easily:
+This project is licensed under the MIT license. See the LICENSE file for more info.
+Use this MW to attempt silent login (prompt=none
) but not require authentication.
const { attemptSilentLogin } = require('express-openid-connect');
+
+app.get('/', attemptSilentLogin(), (req, res) => {
+ res.render('homepage', {
+ isAuthenticated: req.isAuthenticated() // show a login or logout button
+ });
+});
+
+ Express JS middleware implementing sign on for Express web apps using OpenID Connect.
+The auth()
middleware requires secret, baseURL, clientID
+ and issuerBaseURL.
If you are using a response type that includes code
, you will also need: clientSecret
const express = require('express');
+const { auth } = require('express-openid-connect');
+
+const app = express();
+
+app.use(
+ auth({
+ issuerBaseURL: 'https://YOUR_DOMAIN',
+ baseURL: 'https://YOUR_APPLICATION_ROOT_URL',
+ clientID: 'YOUR_CLIENT_ID',
+ secret: 'LONG_RANDOM_STRING',
+ })
+);
+
+app.get('/', (req, res) => {
+ res.send(`hello ${req.oidc.user.name}`);
+});
+
+ app.listen(3000, () => console.log('listening at http://localhost:3000'))
+ Use this MW to protect a route, providing a custom function to check.
+const { claimCheck } = require('express-openid-connect');
+
+app.get('/admin/community', claimCheck((req, claims) => {
+ return claims.isAdmin && claims.roles.includes('community');
+}), (req, res) => {
+ res.send(...);
+});
+
+ Use this MW to protect a route based on the value of a specific claim.
+const { claimEquals } = require('express-openid-connect');
+
+app.get('/admin', claimEquals('isAdmin', true), (req, res) => {
+ res.send(...);
+});
+
+ The name of the claim
+The value of the claim, should be a primitive
+Use this MW to protect a route, checking that all values are in a claim.
+const { claimIncludes } = require('express-openid-connect');
+
+app.get('/admin/delete', claimIncludes('roles', 'admin', 'superadmin'), (req, res) => {
+ res.send(...);
+});
+
+ The name of the claim
+Claim values that must all be included
+Set authRequired to false
then require authentication
+ on specific routes.
const { auth, requiresAuth } = require('express-openid-connect');
+
+app.use(
+ auth({
+ ...
+ authRequired: false
+ })
+);
+
+app.get('/profile', requiresAuth(), (req, res) => {
+ res.send(`hello ${req.oidc.user.name}`);
+});
+
+ The access token itself, can be an opaque string, JWT, or non-JWT token.
+Number of seconds until the access token expires.
+Returns true
if the access_token has expired.
The type of access token, Usually "Bearer".
+Performs refresh_token grant type exchange and updates the session's access token.
+let accessToken = req.oidc.accessToken;
+if (accessToken.isExpired()) {
+ accessToken = await accessToken.refresh();
+}
+ Configuration parameters passed to the auth()
middleware.
issuerBaseURL, baseURL, clientID + and secret are required but can be configured with environmental variables:
+ISSUER_BASE_URL=https://YOUR_DOMAIN
+CLIENT_ID=YOUR_CLIENT_ID
+BASE_URL=https://YOUR_APPLICATION_ROOT_URL
+SECRET=LONG_RANDOM_VALUE
+ Attempt silent login (prompt: 'none'
) on the first unauthenticated route the user visits.
+ For protected routes this can be useful if your Identity Provider does not default to
+ prompt: 'none'
and you'd like to attempt this before requiring the user to interact with a login prompt.
+ For unprotected routes this can be useful if you want to check the user's logged in state on their IDP, to
+ show them a login/logout button for example.
+ Default is false
Boolean value to enable Auth0's logout feature.
+Require authentication for all routes.
+URL parameters used when redirecting users to the authorization server to log in.
+If this property is not provided by your application, its default values will be:
+{
+ response_type: 'id_token',
+ response_mode: 'form_post,
+ scope: openid profile email'
+}
+ New values can be passed in to change what is returned from the authorization server depending on your specific scenario.
+For example, to receive an access token for an API, you could initialize like the sample below. Note that response_mode
can be omitted because the OAuth2 default mode of query
is fine:
app.use(
+ auth({
+ authorizationParams: {
+ response_type: 'code',
+ scope: 'openid profile email read:reports',
+ audience: 'https://your-api-identifier',
+ },
+ })
+);
+ Additional custom parameters can be added as well:
+app.use(auth({
+ authorizationParams: {
+ // Note: you need to provide required parameters if this object is set.
+ response_type: "id_token",
+ response_mode: "form_post",
+ scope: "openid profile email"
+ // Additional parameters
+ acr_value: "tenant:test-tenant",
+ custom_param: "custom-value"
+ }
+}));
+ REQUIRED. The root URL for the application router, eg https://localhost + Can use env key BASE_URL instead.
+REQUIRED. The Client ID for your application. + Can use env key CLIENT_ID instead.
+The Client Secret for your application. + Required when requesting access tokens. + Can use env key CLIENT_SECRET instead.
+Integer value for the system clock's tolerance (leeway) in seconds for ID token verification.` + Default is 60
+To opt-out of sending the library and node version to your authorization server
+ via the Auth0-Client
header. Default is `true
Throw a 401 error instead of triggering the login process for routes that require authentication.
+ Default is false
Function that returns an object with URL-safe state values for res.oidc.login()
.
+ Used for passing custom state parameters to your authorization server.
app.use(auth({
+ ...
+ getLoginState(req, options) {
+ return {
+ returnTo: options.returnTo || req.originalUrl,
+ customState: 'foo'
+ };
+ }
+}))
+``
+ String value for the expected ID token algorithm. Default is 'RS256'
+Array value of claims to remove from the ID token before storing the cookie session.
+ Default is ['aud', 'iss', 'iat', 'exp', 'nbf', 'nonce', 'azp', 'auth_time', 's_hash', 'at_hash', 'c_hash' ]
Boolean value to log the user out from the identity provider on application logout. Default is false
REQUIRED. The root URL for the token issuer with no trailing slash. + Can use env key ISSUER_BASE_URL instead.
+Set a fallback cookie with no SameSite attribute when response_mode is form_post. + Default is true
+Boolean value to automatically install the login and logout routes.
+Relative path to the application callback to process the response from the authorization server.
+Relative path to application login.
+Relative path to application logout.
+Either a relative path to the application or a valid URI to an external domain. + This value must be registered on the authorization server. + The user will be redirected to this after a logout has been performed.
+REQUIRED. The secret(s) used to derive an encryption key for the user identity in a session cookie and + to sign the transient cookies used by the login callback. + Use a single string key or array of keys for an encrypted session cookie. + Can use env key SECRET instead.
+Object defining application session cookie attributes.
+Custom options to pass to login.
+Override the default authorizationParams
+URL to return to after login, overrides the Default is {@link Request.originalUrl}
+Custom options to pass to logout.
+URL to returnTo after logout, overrides the Default in {@link ConfigParams.routes.postLogoutRedirect routes.postLogoutRedirect}
+The Express.js Request with oidc
context added by the auth
middleware.
app.use(auth());
+
+app.get('/profile', (req, res) => {
+ const user = req.oidc.user;
+ ...
+})
+ Return an array of Accepted media types + ordered from highest quality to lowest.
+Check if the request is fresh, aka + Last-Modified and/or the ETag + still match.
+Parse the "Host" header field hostname.
+Return the remote address, or when
+ "trust proxy" is true
return
+ the upstream addr.
When "trust proxy" is true
, parse
+ the "X-Forwarded-For" ip address list.
For example if the value were "client, proxy1, proxy2"
+ you would receive the array ["client", "proxy1", "proxy2"]
+ where "proxy2" is the furthest down-stream.
Library namespace for authentication methods and data.
+Short-hand for url.parse(req.url).pathname
.
Return the protocol string "http" or "https" + when requested with TLS. When the "trust proxy" + setting is enabled the "X-Forwarded-Proto" header + field will be trusted. If you're running behind + a reverse proxy that supplies https for you this + may be enabled.
+After middleware.init executed, Request will contain res and next properties + See: express/lib/middleware/init.js
+Short-hand for:
+req.protocol == 'https'
+Check if the request is stale, aka + "Last-Modified" and / or the "ETag" for the + resource has changed.
+Only valid for response obtained from http.ClientRequest.
+Only valid for response obtained from http.ClientRequest.
+Return subdomains as an array.
+Subdomains are the dot-separated parts of the host before the main domain of + the app. By default, the domain of the app is assumed to be the last two + parts of the host. This can be changed by setting "subdomain offset".
+For example, if the domain is "tobi.ferrets.example.com":
+ If "subdomain offset" is not set, req.subdomains is ["ferrets", "tobi"]
.
+ If "subdomain offset" is 3, req.subdomains is ["tobi"]
.
Check if the request was an XMLHttpRequest.
+Check if the given type(s)
is acceptable, returning
+ the best match when true, otherwise undefined
, in which
+ case you should respond with 406 "Not Acceptable".
The type
value may be a single mime type string
+ such as "application/json", the extension name
+ such as "json", a comma-delimted list such as "json, html, text/plain",
+ or an array ["json", "html", "text/plain"]
. When a list
+ or array is given the best match, if any is returned.
Examples:
+// Accept: text/html
+req.accepts('html');
+// => "html"
+
+// Accept: text/*, application/json
+req.accepts('html');
+// => "html"
+req.accepts('text/html');
+// => "text/html"
+req.accepts('json, text');
+// => "json"
+req.accepts('application/json');
+// => "application/json"
+
+// Accept: text/*, application/json
+req.accepts('image/png');
+req.accepts('png');
+// => undefined
+
+// Accept: text/*;q=.5, application/json
+req.accepts(['html', 'json']);
+req.accepts('html, json');
+// => "json"
+ Returns the first accepted charset of the specified character sets, + based on the request's Accept-Charset HTTP header field. + If none of the specified charsets is accepted, returns false.
+For more information, or if you have issues or concerns, see accepts.
+Returns the first accepted encoding of the specified encodings, + based on the request's Accept-Encoding HTTP header field. + If none of the specified encodings is accepted, returns false.
+For more information, or if you have issues or concerns, see accepts.
+Returns the first accepted language of the specified languages, + based on the request's Accept-Language HTTP header field. + If none of the specified languages is accepted, returns false.
+For more information, or if you have issues or concerns, see accepts.
+Event emitter + The defined events on documents including:
+Return request header.
+The Referrer
header field is special-cased,
+ both Referrer
and Referer
are interchangeable.
Examples:
+req.get('Content-Type');
+// => "text/plain"
+
+req.get('content-type');
+// => "text/plain"
+
+req.get('Something');
+// => undefined
Aliased as req.header()
.
Check if the incoming request contains the "Content-Type"
+ header field, and it contains the give mime type
.
Examples:
+ // With Content-Type: text/html; charset=utf-8
+ req.is('html');
+ req.is('text/html');
+ req.is('text/*');
+ // => true
+
+ // When Content-Type is application/json
+ req.is('json');
+ req.is('application/json');
+ req.is('application/*');
+ // => true
+
+ req.is('html');
+ // => false
+ Parse Range header field, capping to the given size
.
Unspecified ranges such as "0-" require knowledge of your resource length. In
+ the case of a byte range this is of course the total number of bytes.
+ If the Range header field is not given undefined
is returned.
+ If the Range header field is given, return value is a result of range-parser.
+ See more ./types/range-parser/index.d.ts
NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" + should respond with 4 users when available, not 3.
+A utility method for creating Readable Streams out of iterators.
+The Express.js Response with oidc
context added by the auth
middleware.
app.use(auth());
+
+app.get('/login', (req, res) => {
+ res.oidc.login();
+})
+ Send JSON response.
+Examples:
+res.json(null);
+res.json({ user: 'tj' });
+res.status(500).json('oh noes!');
+res.status(404).json('I dont have that');
+ Send JSON response with JSONP callback support.
+Examples:
+res.jsonp(null);
+res.jsonp({ user: 'tj' });
+res.status(500).jsonp('oh noes!');
+res.status(404).jsonp('I dont have that');
+ Library namespace for authentication methods and data.
+After middleware.init executed, Response will contain req property + See: express/lib/middleware/init.js
+Send a response.
+Examples:
+res.send(new Buffer('wahoo'));
+res.send({ some: 'json' });
+res.send('<p>some html</p>');
+res.status(404).send('Sorry, cant find that');
+ Event emitter + The defined events on documents including:
+Appends the specified value to the HTTP response header field. + If the header is not already set, it creates the header with the specified value. + The value parameter can be a string or an array.
+Note: calling res.set() after res.append() will reset the previously-set header value.
+ +Set Content-Disposition header to attachment with optional filename
.
Clear cookie name
.
Set Content-Type response header with type
through mime.lookup()
+ when it does not contain "/", or set the Content-Type to type
otherwise.
Examples:
+res.type('.html');
+res.type('html');
+res.type('json');
+res.type('application/json');
+res.type('png');
+ Set cookie name
to val
, with the given options
.
Options:
+maxAge
max-age in milliseconds, converted to expires
signed
sign the cookiepath
defaults to "/"Examples:
+// "Remember Me" for 15 minutes + res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
+// save as above + res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
+Transfer the file at the given path
as an attachment.
Optionally providing an alternate attachment filename
,
+ and optional callback fn(err)
. The callback is invoked
+ when the data transfer is complete, or when an error has
+ ocurred. Be sure to check res.headerSent
if you plan to respond.
The optional options argument passes through to the underlying + res.sendFile() call, and takes the exact same parameters.
+This method uses res.sendfile()
.
Respond to the Acceptable formats using an obj
+ of mime-type callbacks.
This method uses req.accepted
, an array of
+ acceptable types ordered by their quality values.
+ When "Accept" is not present the first callback
+ is invoked, otherwise the first match is used. When
+ no match is performed the server responds with
+ 406 "Not Acceptable".
Content-Type is set for you, however if you choose
+ you may alter this within the callback using res.type()
+ or res.set('Content-Type', ...)
.
res.format({ + 'text/plain': function(){ + res.send('hey'); + },
+ 'text/html': function(){
+ res.send('<p>hey</p>');
+ },
+
+ 'appliation/json': function(){
+ res.send({ message: 'hey' });
+ }
});
+In addition to canonicalized MIME types you may + also use extnames mapped to these types:
+res.format({ + text: function(){ + res.send('hey'); + },
+ html: function(){
+ res.send('<p>hey</p>');
+ },
+
+ json: function(){
+ res.send({ message: 'hey' });
+ }
});
+By default Express passes an Error
+ with a .status
of 406 to next(err)
+ if a match is not made. If you provide
+ a .default
callback it will be invoked
+ instead.
Get value for header field
.
Set Link header field with the given links
.
Examples:
+res.links({ + next: 'http://api.example.com/users?page=2', + last: 'http://api.example.com/users?page=5' + });
+Set the location header to url
.
The given url
can also be the name of a mapped url, for
+ example by default express supports "back" which redirects
+ to the Referrer or Referer headers or "/".
Examples:
+res.location('/foo/bar').; + res.location('http://example.com'); + res.location('../login'); // /blog/post/1 -> /blog/login
+Mounting:
+ When an application is mounted and res.location()
+ is given a path that does not lead with "/" it becomes
+ relative to the mount-point. For example if the application
+ is mounted at "/blog", the following would become "/blog/login".
res.location('login');
While the leading slash would result in a location of "/login":
+ res.location('/login');
+ Redirect to the given url
with optional response status
+ defaulting to 302.
The resulting url
is determined by res.location()
, so
+ it will play nicely with mounted apps, relative paths,
+ "back"
etc.
Examples:
+res.redirect('/foo/bar'); + res.redirect('http://example.com'); + res.redirect(301, 'http://example.com'); + res.redirect('http://example.com', 301); + res.redirect('../login'); // /blog/post/1 -> /blog/login
+Render view
with the given options
and optional callback fn
.
+ When a callback function is given a response will not be made
+ automatically, otherwise a response of 200 and text/html is given.
Options:
+cache
boolean hinting to the engine it should cachefilename
filename of the view being renderedTransfer the file at the given path
.
Automatically sets the Content-Type response header field.
+ The callback fn(err)
is invoked when the transfer is complete
+ or when an error occurs. Be sure to check res.sentHeader
+ if you wish to attempt responding, as the header and some data
+ may have already been transferred.
Options:
+maxAge
defaulting to 0 (can be string converted by ms
)root
root directory for relative filenamesheaders
object of headers to serve with filedotfiles
serve dotfiles, defaulting to false; can be "allow"
to send themOther options are passed along to send
.
Examples:
+ The following example illustrates how res.sendFile()
may
+ be used as an alternative for the static()
middleware for
+ dynamic situations. The code backing res.sendFile()
is actually
+ the same code, so HTTP cache support etc is identical.
app.get('/user/:uid/photos/:file', function(req, res){
+ var uid = req.params.uid
+ , file = req.params.file;
+
+ req.user.mayViewFilesFrom(uid, function(yes){
+ if (yes) {
+ res.sendFile('/uploads/' + uid + '/' + file);
+ } else {
+ res.send(403, 'Sorry! you cant see that.');
+ }
+ });
+});
+
+ Set the response HTTP status code to statusCode
and send its string representation as the response body.
Set header field
to val
, or pass
+ an object of header fields.
Examples:
+res.set('Foo', ['bar', 'baz']); + res.set('Accept', 'application/json'); + res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
+Aliased as res.header()
.
Set status code
.
Set Content-Type response header with type
through mime.lookup()
+ when it does not contain "/", or set the Content-Type to type
otherwise.
Examples:
+res.type('.html');
+res.type('html');
+res.type('json');
+res.type('application/json');
+res.type('png');
+ Adds the field to the Vary response header, if it is not there already. + Examples:
+res.vary('User-Agent').render('docs');
+ The request authentication context found on the Express request when + OpenID Connect auth middleware is added to your application.
+app.use(auth());
+
+app.get('/profile', (req, res) => {
+ const user = req.oidc.user;
+ ...
+})
+ Credentials that can be used by an application to access an API.
+The OpenID Connect ID Token.
+An object containing all the claims of the ID Token.
+Method to check the user's authenticated state, returns true
if logged in.
Credentials that can be used to refresh an access token.
+An object containing all the claims of the ID Token with the claims + specified in identityClaimFilter removed.
+Fetches the OIDC userinfo response.
+app.use(auth());
+
+app.get('/user-info', async (req, res) => {
+ const userInfo = await req.oidc.fetchUserInfo();
+ res.json(userInfo);
+})
+ The response authentication context found on the Express response when + OpenID Connect auth middleware is added to your application.
+app.use(auth());
+
+app.get('/admin-login', (req, res) => {
+ res.openid.login({ returnTo: '/admin' })
+})
+ Provided by default via the /login
route. Call this to override or have other
+ login routes with custom authorizationParams or returnTo
app.get('/admin-login', (req, res) => {
+ res.oidc.login({
+ returnTo: '/admin',
+ authorizationParams: {
+ scope: 'openid profile email admin:user',
+ }
+ });
+});
+ Provided by default via the /logout
route. Call this to override or have other
+ logout routes with custom returnTo
app.get('/admin-logout', (req, res) => {
+ res.oidc.logout({ returnTo: '/admin-welcome' })
+});
+ Configuration parameters used for the application session.
+Integer value, in seconds, for application absolute rolling duration.
+ The amount of time after the user has logged in that they will be logged out.
+ Set this to false
if you don't want an absolute duration on your session.
+ Default is 604800 seconds (7 days).
Domain name for the cookie.
+ Passed to the Response cookie as domain
Flags the cookie to be accessible only by the web server.
+ Passed to the Response cookie as httponly
.
+ Defaults to true
.
String value for the cookie name used for the internal session.
+ This value must only include letters, numbers, and underscores.
+ Default is appSession
.
Path for the cookie.
+ Passed to the Response cookie as path
If you want your session duration to be rolling, eg reset everytime the
+ user is active on your site, set this to a true
. If you want the session
+ duration to be absolute, where the user is logged out a fixed time after login,
+ regardless of activity, set this to false
+ Default is true
.
Integer value, in seconds, for application session rolling duration. + The amount of time for which the user must be idle for then to be logged out. + Default is 86400 seconds (1 day).
+Value of the SameSite Set-Cookie attribute.
+ Passed to the Response cookie as samesite
.
+ Defaults to "Lax" but will be adjusted based on {@link AuthorizationParameters.response_type}.
Marks the cookie to be used over secure channels only.
+ Passed to the Response cookie as secure
.
+ Defaults to {@link Request.secure}.
Set to true to use a transient cookie (cookie without an explicit expiration).
+ Default is false
Use this MW to attempt silent login (
+prompt=none
) but not require authentication.See attemptSilentLogin
+
+const { attemptSilentLogin } = require('express-openid-connect'); + +app.get('/', attemptSilentLogin(), (req, res) => { + res.render('homepage', { + isAuthenticated: req.isAuthenticated() // show a login or logout button + }); +}); +