Gathering detailed insights and metrics for @asgardeo/auth-express
Gathering detailed insights and metrics for @asgardeo/auth-express
Gathering detailed insights and metrics for @asgardeo/auth-express
Gathering detailed insights and metrics for @asgardeo/auth-express
npm install @asgardeo/auth-express
Typescript
Module System
Node Version
NPM Version
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
3
3
Asgardeo Auth Express SDK implements OIDC authentication in JavaScript/TypeScript-based server-side apps written with Express Framework. This SDK wraps around the @asgardeo/auth-node
to provide framework-specific functionalities for Express enabling the developers to use OIDC authentication in the applications with minimum effort.
Create an organization in Asgardeo if you don't already have one. The organization name you choose will be referred to as <org_name>
throughout this documentation.
If you are using Asgardeo Cloud as the identity server,
# default login url:
https://<host>:<port>/login
# default logout url:
https://<host>:<port>/logout
Install the library from the npm registry.
npm install @asgardeo/auth-express
1//Import Express 2const express = require('express'); 3 4// Import Cookie Parser to access request cookies. 5const cookieParser = require('cookie-parser'); 6 7// The SDK provides a client middleware that can be used to carry out the authentication. 8const { AsgardeoExpressClient } = require("@asgardeo/auth-express"); 9 10 11// Create a config object containing the necessary configurations. 12const config = { 13 clientID: "<YOUR_CLIENT_ID>", 14 clientSecret: "<YOUR_CLIENT_SECRET>", 15 baseUrl: "https://api.asgardeo.io/t/<org_name>", 16 appURL: "http://localhost:3000", 17 scope: ["openid", "profile"] 18}; 19 20//Initialize an Express App 21const app = express(); 22 23// Use cookie parser in the Express App. 24app.use(cookieParser()) 25 26//Initialize Asgardeo Express Client 27const authClient = AsgardeoExpressClient.getInstance(config); 28 29//Define onSignIn method to handle successful sign in 30const onSignIn = (res, response) => { 31 if (response) { 32 res.status(200).send(response); 33 } 34}; 35 36//Define onSignOut method to handle successful sign out 37const onSignOut = (res) => { 38 res.status(200).send("Sign out successful"); 39}; 40 41//Define onError method to handle errors 42const onError = (res, error) => { 43 if(error){ 44 res.status(400).send(error); 45 } 46}; 47 48//Use the Asgardeo Auth Client 49app.use( 50 AsgardeoExpressClient.asgardeoExpressAuth(onSignIn, onSignOut, onError) 51); 52 53//At this point the default /login and /logout routes should be available. 54//Users can use these two routes for authentication. 55 56//A regular route 57app.get("/", (req, res) => { 58 res.status(200).send("Hello World"); 59}); 60 61//A Protected Route 62 63//Define the callback function to handle unauthenticated requests 64const authCallback = (res, error) => { 65 if(error){ 66 res.status(400).send(error); 67 } 68 // Return true to end the flow at the middleware. 69 return true; 70}; 71 72//Create a new middleware to protect the route 73const isAuthenticated = AsgardeoExpressClient.protectRoute(authCallback); 74 75app.get("/protected", isAuthenticated, (req, res) => { 76 res.status(200).send("Hello from Protected Route"); 77}); 78 79//Start the express app on PORT 3000 80app.listen(3000, () => { console.log(`Server Started at PORT 3000`);}); 81
1asgardeoAuth(
2 onSignIn: (res: express.Response, response: TokenResponse) => void,
3 onSignOut: (res: express.Response) => void,
4 onError: (res: express.Response, exception: AsgardeoAuthException) => void
5): any;
onSignIn: (res: express.Response, response: TokenResponse) => void
This method will be called when the user successfully signs in.
res: express.Response
The res object represents the HTTP response that an Express app sends when it gets an HTTP request.
response: TokenResponse
This object will have the token response from the signIn
method. To know more about the TokenResponse
, refer to the TokenResponse section.
onSignOut: (res: express.Response) => void
This method will be called when the user signs out successfully.
express.Response
The res object represents the HTTP response that an Express app sends when it gets an HTTP request.onError: (res: express.Response, exception: AsgardeoAuthException) => void
This method will be called if an error occurs.
res: express.Response
The res object represents the HTTP response that an Express app sends when it gets an HTTP request.
exception: AsgardeoAuthException
The exception object of the error occurred.
The SDK provides a client middleware called asgardeoAuth that provides you with the necessary methods to implement authentication. You can use this middleware to initiate the AsgardeoAuth for your application. By default, the SDK implements the /login
and /logout
routes so as soon as you use asgardeoAuth middleware, the /login and /logout routes will be available out of the box for the users to authenticate.
Note: The default /login
and /logout
route names can be customized.To learn more, refer to the ExpressClientConfig
section.
1app.use(
2 AsgardeoExpressClient.asgardeoExpressAuth(onSignIn, onSignOut, onError)
3);
1protectRoute(callback: UnauthenticatedCallback): (req: express.Request, res: express.Response, next: express.nextFunction);
callback: UnauthenticatedCallback
This function handles the callback for the unauthenticated users. To know more about implementing the UnauthenticatedCallback
type, refer to the UnauthenticatedCallback section.
This middleware function can be used to protect a route. When this function is passed down to a route, it will check if the session cookie exists on the request and if not it will call the callback function and if the cookie is there, the request will proceed as usual.
1const authCallback = (res, error) => { 2 res.redirect(`/?message=${ error }`); 3 return true; 4}; 5 6const isAuthenticated = protectRoute(authCallback); 7 8app.get("/protected", isAuthenticated, (req, res) => { 9 res.status(200).send("Hello from Protected Route"); 10});
The SDK provides a singleton client class called AsgardeoExpressClient
that provides you with the necessary methods to implement authentication.
You can instantiate the class and use req.asgardeoAuth
inside a request to access this class in order to use the provided methods.
1AsgardeoExpressClient.getInstance(config: ExpressClientConfig, store?: Store);
config: ExpressClientConfig
This contains the configuration information needed to implement authentication such as the client ID, server origin etc. Additional configuration information that is needed to configure the client, can be passed down from this object (Eg: A custom login path). To learn more about what attributes can be passed into this object, refer to the ExpressClientConfig
section.
1const config = { 2 clientID: "<YOUR_CLIENT_ID>", 3 clientSecret: "<YOUR_CLIENT_SECRET>", 4 baseUrl: "<YOUR_BASE_URL>", 5 appURL: "http://localhost:3000", 6 scope: ["openid", "profile"] 7};
store: Store
(optional)
This is the object of interface Store
that is used by the SDK to store all the necessary data used ranging from the configuration data to the access token. By default, the SDK is packed with a built-in Memory Cache Store. If needed, you can implement the Store to create a class with your own implementation logic and pass an instance of the class as the second argument. This way, you will be able to get the data stored in your preferred place. To know more about implementing the Store
interface, refer to the Data Storage section.
This returns an instance of the AsgardeoExpressClient
class and if the class is not instantiated already, it will create a new instance and return it.
1app.use(AsgardeoExpressClient.getInstance(config, store););
1getIDToken(userId: string): Promise<string>
idToken: Promise<string>
A Promise that resolves with the ID Token.
This method returns the id token.
1const idToken = await authClient.getIDToken("a2a2972c-51cd-5e9d-a9ae-058fae9f7927");
1getBasicUserInfo(userId: string): Promise<BasicUserInfo>
userId: string
(optional)
If you want to use the SDK to manage multiple user sessions, you can pass a unique ID here to generate an authorization URL specific to that user. This can be useful when this SDK is used in backend applications.
basicUserInfo: Promise<BasicUserInfo> An object containing basic user information obtained from the id token.
This method returns the basic user information obtained from the payload. To learn more about what information is returned, checkout the DecodedIDTokenPayload model.
1// This should be within an async function. 2const basicUserInfo = await authClient.getBasicUserInfo("a2a2972c-51cd-5e9d-a9ae-058fae9f7927");
1getOIDCServiceEndpoints(): Promise<OIDCEndpoints>
oidcEndpoints: Promise<OIDCEndpoints>
An object containing the OIDC service endpoints returned by the .well-known
endpoint.
This method returns the OIDC service endpoints obtained from the .well-known
endpoint. To learn more about what endpoints are returned, checkout the OIDCEndpoints section.
1// This should be within an async function. 2const oidcEndpoints = await authClient.getOIDCServiceEndpoints();
1getDecodedIDToken(userId?: string): Promise<DecodedIDTokenPayload>
userId: string
(optional)
If you want to use the SDK to manage multiple user sessions, you can pass a unique ID here to generate an authorization URL specific to that user. This can be useful when this SDK is used in backend applications.
decodedIDTokenPayload: Promise<DecodedIDTokenPayload> The decoded ID token payload.
This method decodes the payload of the id token and returns the decoded values.
1// This should be within an async function. 2const decodedIDTokenPayload = await authClient.getDecodedIDToken("a2a2972c-51cd-5e9d-a9ae-058fae9f7927");
1getAccessToken(userId?: string): Promise<string>
userId: string
(optional)
If you want to use the SDK to manage multiple user sessions, you can pass a unique ID here to generate an authorization URL specific to that user. This can be useful when this SDK is used in backend applications.
accessToken: Promise<string>
The access token.
This method returns the access token.
1// This should be within an async function. 2const accessToken = await authClient.getAccessToken("a2a2972c-51cd-5e9d-a9ae-058fae9f7927");
1revokeAccessToken(userId?: string): Promise<FetchResponse>
userId: string
(optional)
If you want to use the SDK to manage multiple user sessions, you can pass a unique ID here to generate an authorization URL specific to that user. This can be useful when this SDK is used in backend applications.
A Promise that resolves with the response returned by the server.
This method clears the authentication data and sends a request to revoke the access token. You can use this method if you want to sign the user out of your application but not from the server.
1// This should be within an async function. 2const revokeToken = await auth.revokeAccessToken("a2a2972c-51cd-5e9d-a9ae-058fae9f7927");
1requestCustomGrant(config: CustomGrantConfig, userId?: string): Promise<TokenResponse | FetchResponse>
config: CustomGrantConfig
The config object contains attributes that would be used to configure the custom grant request. To learn more about the different configurations available, checkout the CustomGrantConfig model.
userId: string
(optional)
If you want to use the SDK to manage multiple user sessions, you can pass a unique ID here to generate an authorization URL specific to that user. This can be useful when this SDK is used in backend applications.
A Promise that resolves with the token information or the response returned by the server depending on the configuration passed.
This method can be used to send custom-grant requests to Asgardeo.
1const config = { 2 attachToken: false, 3 data: { 4 client_id: "{{clientID}}", 5 grant_type: "account_switch", 6 scope: "{{scope}}", 7 token: "{{token}}", 8 }, 9 id: "account-switch", 10 returnResponse: true, 11 returnsSession: true, 12 signInRequired: true 13} 14 15auth.requestCustomGrant(config).then((response) => { 16 console.log(response); 17}).catch((error) => { 18 console.error(error); 19});
1updateConfig(config: Partial<AuthClientConfig<T>>): Promise<void>
config: AuthClientConfig<T>
The config object containing the attributes that can be used to configure the SDK. To learn more about the available attributes, refer to the[ AuthClientConfig
This method can be used to update the configurations passed into the constructor of the AsgardeoAuthClient. Please note that every attribute in the config object passed as the argument here is optional. Use this method if you want to update certain attributes after instantiating the class.
1const pkce = auth.updateConfig({ 2 signOutRedirectURL: "http://localhost:3000/sign-out" 3});
1static isSignOutSuccessful(signOutRedirectURL: string): boolean
This is a static method.
signOutRedirectURL: string
The URL to which the user is redirected to after signing out from the server.
isSignedOut: boolean
A boolean value indicating if the user has been signed out or not.
This method returns if the user has been successfully signed out or not. When a user signs out from the server, the user is redirected to the URL specified by the signOutRedirectURL in the config object passed into the constructor of the AsgardeoAuthClient. The server appends path parameters indicating if the sign-out is successful. This method reads the URL and returns if the sign-out is successful or not. So, make sure you pass as the argument the URL to which the user has been redirected to after signing out from the server.
1const isSignedOut = auth.isSignOutSuccessful(<signout_redirect_url>);
1static didSignOutFail(signOutRedirectURL: string): boolean
This is a static method.
signOutRedirectURL: string
The URL to which the user is redirected to after signing out from the server.
didSignOutFail: boolean
A boolean value indicating if sign-out failed or not.
This method returns if sign-out failed or not. When a user signs out from the server, the user is redirected to the URL specified by the signOutRedirectURL in the config object passed into the constructor of the AsgardeoAuthClient. The server appends path parameters indicating if the sign-out is successful. This method reads the URL and returns if the sign-out failed or not. So, make sure you pass as the argument the URL to which the user has been redirected to after signing out from the server.
1const isSignedOutFailed = auth.isSignOutSuccessful(<signout_redirect_url>);
Since the SDK was developed with the view of being able to support various storage approaches, the SDK allows developers to use their preferred mode of storage. To that end, the SDK allows you to pass a store object when using the asgardeoAuth
middleware. This store object contains methods that can be used to store, retrieve and delete data. The SDK provides a Store interface that you can implement to create your own Store class. You can refer to the Store
section to learn mire about the Store
interface.
There are three methods that are to be implemented by the developer. They are
setData
getData
removeData
The setData
method is used to store data. The getData
method is used to retrieve data. The removeData
method is used to delete data. The SDK converts the data to be stored into a JSON string internally and then calls the setData
method to store the data. The data is represented as a key-value pairs in the SDK. The SDK uses four keys internally, and you can learn about them by referring to the Data Layer section. So, every JSON stringified data value is supposed to be stored against the passed key in the data store. A sample implementation of the Store
class using the browser session storage is given here.
1class NodeStore implements Store { 2 public setData(key: string, value: string): void { 3 sessionStorage.setItem(key, value); 4 } 5 6 public getData(key: string): string { 7 return sessionStorage.getItem(key); 8 } 9 10 public removeData(key: string): void { 11 sessionStorage.removeItem(key); 12 } 13}
This model has the following attributes.
Attribute | Required/Optional | Type | Default Value | Description |
---|---|---|---|---|
appURL | Required* | string | "" | The base URL of the application. eg: https//localhost:3000 |
clientID | Required* | string | "" | The client ID of the OIDC application hosted in the Asgardeo. |
baseUrl | Required* | string | "" | The origin of the Identity Provider. eg: https://api.asgardeo.io/t/<org_name> |
clientHost | Optional | string | The origin of the client app obtained using window.origin | The hostname of the client app. eg: https://localhost:3000 |
clientSecret | Optional | string | "" | The client secret of the OIDC application |
enablePKCE | Optional | boolean | true | Specifies if a PKCE should be sent with the request for the authorization code. |
prompt | Optional | string | "" | Specifies the prompt type of an OIDC request |
responseMode | Optional | ResponseMode | "query" | Specifies the response mode. The value can either be query or form_post |
scope | Optional | string[] | ["openid"] | Specifies the requested scopes. |
endpoints | Optional | OIDCEndpoints | OIDC Endpoints Default Values | The OIDC endpoint URLs. The SDK will try to obtain the endpoint URLS |
overrideWellEndpointConfig | Optional | boolean | false | If this option is set to true , then the endpoints object will override endpoints obtained |
wellKnownEndpoint | Optional | string | "/oauth2/token/.well-known/openid-configuration" | The URL of the .well-known endpoint. |
validateIDToken | Optional | boolean | true | Allows you to enable/disable JWT ID token validation after obtaining the ID token. |
clockTolerance | Optional | number | 60 | Allows you to configure the leeway when validating the id_token. |
sendCookiesInRequests | Optional | boolean | true | Specifies if cookies should be sent in the requests. |
cookieConfig | Optional | cookieConfig | cookieConfig Default Values | Specifies the maxAge , httpOnly and sameSite values for the cookie configuration. |
loginPath | Optional | string | /login | Specifies the default login path. |
logoutPath | Optional | string | /logout | Specifies the default logout path. |
globalAuth | Optional | boolean | false | Specifies if all the routes should be protected or not. |
Important:
When specifying a custom login and logout path using loginPath
and logoutPath
attributes, make sure you add these URLs in the Authorized redirect URLs
section in the Asgardeo Console. Also make sure you add the baseURL
in the Allowed origins
section as well.
Method | Required/Optional | Arguments | Returns | Description |
---|---|---|---|---|
setData | Required | key: string , value: string | Promise<void> | This method saves the passed value to the store. The data to be saved is JSON stringified so will be passed by the SDK as a string. |
getData | Required | key: string \ | string | This method retrieves the data from the store and returns a Promise that resolves with it. Since the SDK stores the data as a JSON string, the returned value will be a string. |
removeData | Required | key: string | Promise<void> | Removes the data with the specified key from the store. |
Method | Required/Optional | Type | Default Value | Description |
---|---|---|---|---|
maxAge | Optional | number | 90000 | The maximum age of the cookie. |
httpOnly | Optional | boolean | true | Setting this true will make sure that the cookie inaccessible to the JavaScript Document.cooki e API. |
sameSite | Optional | string | lax | Specifies the value for sameSite (Lax / Strict / None) attribute. |
secure | Optional | boolean | false | Specifies whether the cookie is secure or not. This will be needed to set to true when sameSite attribute is set to None . |
Method | Type | Description |
---|---|---|
accessToken | string | The access token. |
idToken | string | The id token. |
expiresIn | string | The expiry time in seconds. |
scope | string | The scope of the token. |
refreshToken | string | The refresh token. |
tokenType | string | The token type. |
session | string | The session ID. |
1(res: express.Response, error: string) => boolean;
This method is used to handle the callback from a protected route. You may use this function to get the request object and the error message to redirect the user to the desired error page or to redirect to the login page and authenticate the user.
1const authCallback = (res, error) => { 2 res.redirect(`/?message=${ error }`); 3 return true; 4};
Node.js
(version 10 or above).npm
package manager.The repository is a mono repository. The SDK repository is found in the lib directory. You can install the dependencies by running the following command at the root.
npm run build
Please read Contributing to the Code Base for details on our code of conduct, and the process for submitting pull requests to us.
We encourage you to report issues, improvements, and feature requests creating Github Issues.
Important: And please be advised that security issues must be reported to security@wso2com, not as GitHub issues, in order to reach the proper audience. We strongly advise following the WSO2 Security Vulnerability Reporting Guidelines when reporting the security issues.
This project is licensed under the Apache License 2.0. See the LICENSE file for details.
No vulnerabilities found.
No security vulnerabilities found.