This is a loopback-next extension for adding authentication layer to a REST application in loopback 4.
This extension is based on the implementation guidelines provided on official @loopback/authentication page.
It provides support for seven passport based strategies.
passport-oauth2-client-password - OAuth 2.0 client password authentication strategy for Passport. This module lets you authenticate requests containing client credentials in the request body, as defined by the OAuth 2.0 specification.
passport-http-bearer - HTTP Bearer authentication strategy for Passport. This module lets you authenticate HTTP requests using bearer tokens, as specified by RFC 6750, in your Node.js applications.
passport-local - Passport strategy for authenticating with a username and password. This module lets you authenticate using a username and password in your Node.js applications.
passport-oauth2-resource-owner-password - OAuth 2.0 resource owner password authentication strategy for Passport. This module lets you authenticate requests containing resource owner credentials in the request body, as defined by the OAuth 2.0 specification.
passport-google-oauth2 - Passport strategy for authenticating with Google using the Google OAuth 2.0 API. This module lets you authenticate using Google in your Node.js applications.
keycloak-passport - Passport strategy for authenticating with Keycloak. This library offers a production-ready and maintained Keycloak Passport connector.
passport-instagram - Passport strategy for authenticating with Instagram using the Instagram OAuth 2.0 API. This module lets you authenticate using Instagram in your Node.js applications.
passport-apple - Passport strategy for authenticating with Apple using the Apple OAuth 2.0 API. This module lets you authenticate using Apple in your Node.js applications.
passport-facebook - Passport strategy for authenticating with Facebook using the Facebook OAuth 2.0 API. This module lets you authenticate using Facebook in your Node.js applications.
passport-cognito-oauth2 - Passport strategy for authenticating with Cognito using the Cognito OAuth 2.0 API. This module lets you authenticate using Cognito in your Node.js applications.
passport-SAML - Passport strategy for authenticating with SAML using the SAML 2.0 API. This module lets you authenticate using SAML in your Node.js applications
custom-passport-otp - Created a Custom Passport strategy for 2-Factor-Authentication using OTP (One Time Password).
passport-auth0 - Passport strategy for authenticating with auth0. This module lets you authenticate using Auth0 in your Node.js applications.
You can use one or more strategies of the above in your application. For each of the strategy (only which you use), you just need to provide your own verifier function, making it easily configurable. Rest of the strategy implementation intricacies is handled by extension.
For a quick starter guide, you can refer to our loopback 4 starter application which utilizes all of the above auth strategies from the extension in a simple multi-tenant application. Refer to the auth module there for specific details on authentication.
// application.tsexportclassToDoApplicationextendsBootMixin(ServiceMixin(RepositoryMixin(RestApplication)),){constructor(options:ApplicationConfig={}){super(options);// Set up the custom sequencethis.sequence(MySequence);// Set up default home pagethis.static('/',path.join(__dirname,'../public'));// Add authentication componentthis.component(AuthenticationComponent);// .... Rest of the code below}}
Once this is done, you are ready to configure any of the available strategy in the application.
First, create an AuthClient model implementing the IAuthClient interface. The purpose of this model is to store oauth registered clients for the app in the DB. See sample below.
Add the verifier function for the strategy. You need to create a provider for the same strategy. You can add your application specific business logic for client auth here. Here is simple example.
For accessing the authenticated AuthClient model reference, you can inject the CURRENT_CLIENT provider, provided by the extension, which is populated by the auth action sequence above.
Add the verifier function for the strategy. You need to create a provider for the same. You can add your application specific business logic for client auth here. Here is simple example for JWT tokens.
The above example has an import and injection of a RevokedTokenRepository, which could be used to keep track of revoked tokens in a datasource like Redis. You can find an implementation of this repository here and the Redis datasource here.
Please note the Verify function type VerifyFunction.BearerFn
Now bind this provider to the application in application.ts.
@authenticate(STRATEGY.BEARER)@get('/users',{responses:{'200':{description:'Array of User model instances',content:{'application/json':{schema:{type:'array',items:{'x-ts-type':User}},},},},},})asyncfind(@param.query.object('filter',getFilterSchemaFor(User))filter?:Filter,):Promise<User[]>{returnawaitthis.userRepository.find(filter);}
For accessing the authenticated AuthUser model reference, you can inject the CURRENT_USER provider, provided by the extension, which is populated by the auth action sequence above.
In order to use it, run npm install passport-local.
First, create a AuthUser model implementing the IAuthUser interface. You can implement the interface in the user model itself. See sample below.
Add the verifier function for the strategy. You need to create a provider for the same. You can add your application specific business logic for client auth here. Here is a simple example.
For accessing the authenticated AuthUser model reference, you can inject the CURRENT_USER provider, provided by the extension, which is populated by the auth action sequence above.
In order to use it, run npm install passport-oauth2-resource-owner-password.
First, create an AuthClient model implementing the IAuthClient interface. The purpose of this model is to store oauth registered clients for the app in the DB. See sample below.
Add the verifier function for the strategy. You need to create a provider for the same. You can add your application specific business logic for client auth here. Here is a simple example.
For accessing the authenticated AuthUser and AuthClient model reference, you can inject the CURRENT_USER and CURRENT_CLIENT provider, provided by the extension, which is populated by the auth action sequence above.
First, create a OtpCache model. This model should have OTP and few details of user and client (which will be used to retrieve them from database), it will be used to verify otp and get user, client. See sample below.
Add the verifier function for the strategy. You need to create a provider for the same. You can add your application specific business logic for auth here. Here is a simple example.
//You can use your other strategies also@authenticate(STRATEGY.LOCAL)@post('/auth/send-otp',{responses:{[STATUS_CODE.OK]:{description:'Send Otp',content:{[CONTENT_TYPE.JSON]:Object,},},},})asynclogin(@requestBody()req:LoginRequest,):Promise<{key:string;}>{// User is authenticated before this step.// Now follow these steps:// 1. Create a unique key.// 2. Generate and send OTP to user's email/phone.// 3. Store the details in redis-cache using key created in step-1. (Refer OtpCache model mentioned above)// 4. Response will be the key created in step-1}
After this, create an API with @@authenticate(STRATEGY.OTP) decorator. See below.
For accessing the authenticated AuthUser model reference, you can inject the CURRENT_USER provider, provided by the extension, which is populated by the auth action sequence above.
In order to use it, run npm install passport-google-oauth20 and npm install @types/passport-google-oauth20.
First, create a AuthUser model implementing the IAuthUser interface. You can implement the interface in the user model itself. See sample below.
@model({name:'users',})exportclassUserextendsEntityimplementsIAuthUser{@property({type:'number',id:true,})id?:number;@property({type:'string',required:true,name:'first_name',})firstName:string;@property({type:'string',name:'last_name',})lastName:string;@property({type:'string',name:'middle_name',})middleName?:string;@property({type:'string',required:true,})username:string;@property({type:'string',})email?:string;// Auth provider - 'google'@property({type:'string',required:true,name:'auth_provider',})authProvider:string;// Id from external provider@property({type:'string',name:'auth_id',})authId?:string;@property({type:'string',name:'auth_token',})authToken?:string;@property({type:'string',})password?:string;constructor(data?:Partial<User>){super(data);}}
Now bind this model to USER_MODEL key in application.ts
Add the verifier function for the strategy. You need to create a provider for the same. You can add your application specific business logic for client auth here. Here is a simple example.
Please note above that we are creating two new APIs for google auth. The first one is for UI clients to hit. We are authenticating client as well, then passing the details to the google auth. Then, the actual authentication is done by google authorization url, which redirects to the second API we created after success. The first API method body is empty as we do not need to handle its response. The google auth provider in this package will do the redirection for you automatically.
For accessing the authenticated AuthUser model reference, you can inject the CURRENT_USER provider, provided by the extension, which is populated by the auth action sequence above.
In order to use it, run npm install passport-instagram.
First, create a AuthUser model implementing the IAuthUser interface. You can implement the interface in the user model itself. See sample below.
@model({name:'users',})exportclassUserextendsEntityimplementsIAuthUser{@property({type:'number',id:true,})id?:number;@property({type:'string',required:true,name:'first_name',})firstName:string;@property({type:'string',name:'last_name',})lastName:string;@property({type:'string',name:'middle_name',})middleName?:string;@property({type:'string',required:true,})username:string;@property({type:'string',})email?:string;// Auth provider - 'instagram'@property({type:'string',required:true,name:'auth_provider',})authProvider:string;// Id from external provider@property({type:'string',name:'auth_id',})authId?:string;@property({type:'string',name:'auth_token',})authToken?:string;@property({type:'string',})password?:string;constructor(data?:Partial<User>){super(data);}}
Now bind this model to USER_MODEL key in application.ts
Add the verifier function for the strategy. You need to create a provider for the same. You can add your application specific business logic for client auth here. Here is a simple example.
Please note above that we are creating two new APIs for instagram auth. The first one is for UI clients to hit. We are authenticating client as well, then passing the details to the instagram auth. Then, the actual authentication is done by instagram authorization url, which redirects to the second API we created after success. The first API method body is empty as we do not need to handle its response. The instagram auth provider in this package will do the redirection for you automatically.
For accessing the authenticated AuthUser model reference, you can inject the CURRENT_USER provider, provided by the extension, which is populated by the auth action sequence above.
In order to use it, run npm install --save passport-apple.
First, create a AuthUser model implementing the IAuthUser interface. You can implement the interface in the user model itself. See sample below.
@model({name:'users',})exportclassUserextendsEntityimplementsIAuthUser{@property({type:'number',id:true,})id?:number;@property({type:'string',required:true,name:'first_name',})firstName:string;@property({type:'string',name:'last_name',})lastName:string;@property({type:'string',name:'middle_name',})middleName?:string;@property({type:'string',required:true,})username:string;@property({type:'string',})email?:string;// Auth provider - 'apple'@property({type:'string',required:true,name:'auth_provider',})authProvider:string;// Id from external provider@property({type:'string',name:'auth_id',})authId?:string;@property({type:'string',name:'auth_token',})authToken?:string;@property({type:'string',})password?:string;constructor(data?:Partial<User>){super(data);}}
Now bind this model to USER_MODEL key in application.ts
Add the verifier function for the strategy. You need to create a provider for the same. You can add your application specific business logic for client auth here. Here is a simple example.
Please note above that we are creating two new APIs for apple auth. The first one is for UI clients to hit. We are authenticating client as well, then passing the details to the apple auth. Then, the actual authentication is done by apple authorization url, which redirects to the second API we created after success. The first API method body is empty as we do not need to handle its response. The apple auth provider in this package will do the redirection for you automatically.
For accessing the authenticated AuthUser model reference, you can inject the CURRENT_USER provider, provided by the extension, which is populated by the auth action sequence above.
In order to use it, run npm install passport-facebook.
First, create a AuthUser model implementing the IAuthUser interface. You can implement the interface in the user model itself. See sample below.
@model({name:'users',})exportclassUserextendsEntityimplementsIAuthUser{@property({type:'number',id:true,})id?:number;@property({type:'string',required:true,name:'first_name',})firstName:string;@property({type:'string',name:'last_name',})lastName:string;@property({type:'string',name:'middle_name',})middleName?:string;@property({type:'string',required:true,})username:string;@property({type:'string',})email?:string;// Auth provider - 'facebook'@property({type:'string',required:true,name:'auth_provider',})authProvider:string;// Id from external provider@property({type:'string',name:'auth_id',})authId?:string;@property({type:'string',name:'auth_token',})authToken?:string;@property({type:'string',})password?:string;constructor(data?:Partial<User>){super(data);}}
Now bind this model to USER_MODEL key in application.ts
Add the verifier function for the strategy. You need to create a provider for the same. You can add your application specific business logic for client auth here. Here is a simple example.
Please note above that we are creating two new APIs for facebook auth. The first one is for UI clients to hit. We are authenticating client as well, then passing the details to the facebook auth. Then, the actual authentication is done by facebook authorization url, which redirects to the second API we created after success. The first API method body is empty as we do not need to handle its response. The facebook auth provider in this package will do the redirection for you automatically.
For accessing the authenticated AuthUser model reference, you can inject the CURRENT_USER provider, provided by the extension, which is populated by the auth action sequence above.
In order to use it, run npm install @exlinc/keycloak-passport.
First, create a AuthUser model implementing the IAuthUser interface. You can implement the interface in the user model itself. See sample below.
@model({name:'users',})exportclassUserextendsEntityimplementsIAuthUser{@property({type:'number',id:true,})id?:number;@property({type:'string',required:true,name:'first_name',})firstName:string;@property({type:'string',name:'last_name',})lastName:string;@property({type:'string',name:'middle_name',})middleName?:string;@property({type:'string',required:true,})username:string;@property({type:'string',})email?:string;// Auth provider - 'keycloak'@property({type:'string',required:true,name:'auth_provider',})authProvider:string;// Id from external provider@property({type:'string',name:'auth_id',})authId?:string;@property({type:'string',name:'auth_token',})authToken?:string;@property({type:'string',})password?:string;constructor(data?:Partial<User>){super(data);}}
Now bind this model to USER_MODEL key in application.ts
Add the verifier function for the strategy. You need to create a provider for the same. You can add your application specific business logic for client auth here. Here is a simple example.
exportclassMySequenceimplementsSequenceHandler{/** * Optional invoker for registered middleware in a chain. * To be injected via SequenceActions.INVOKE_MIDDLEWARE. */@inject(SequenceActions.INVOKE_MIDDLEWARE,{optional:true})protectedinvokeMiddleware:InvokeMiddleware=()=>false;constructor(@inject(SequenceActions.FIND_ROUTE)protectedfindRoute:FindRoute,@inject(SequenceActions.PARSE_PARAMS)protectedparseParams:ParseParams,@inject(SequenceActions.INVOKE_METHOD)protectedinvoke:InvokeMethod,@inject(SequenceActions.SEND)publicsend:Send,@inject(SequenceActions.REJECT)publicreject:Reject,@inject(AuthenticationBindings.USER_AUTH_ACTION)protectedauthenticateRequest:AuthenticateFn<AuthUser>,){}asynchandle(context:RequestContext){try{const{request,response}=context;constroute=this.findRoute(request);constargs=awaitthis.parseParams(request,route);request.body=args[args.length-1];constauthUser:AuthUser=awaitthis.authenticateRequest(request,response,);constresult=awaitthis.invoke(route,args);this.send(response,result);}catch(err){this.reject(context,err);}}}
After this, you can use decorator to apply auth to controller functions wherever needed. See below.
Please note above that we are creating two new APIs for keycloak auth. The first one is for UI clients to hit. We are authenticating client as well, then passing the details to the keycloak auth. Then, the actual authentication is done by keycloak authorization url, which redirects to the second API we created after success. The first API method body is empty as we do not need to handle its response. The keycloak auth provider in this package will do the redirection for you automatically.
For accessing the authenticated AuthUser model reference, you can inject the CURRENT_USER provider, provided by the extension, which is populated by the auth action sequence above.
For providing a custom verifier for a particular route, you can pass a binding key for a verifier provider as the fourth parameter of the authenticate decorator.
Note - The key VerifyBindings.BEARER_SIGNUP_VERIFY_PROVIDER can be any custom key, it just be bound to a verify function provider.
In order to use it, run npm install @node-saml/passport-saml.
SAML (Security Assertion Markup Language) is an XML-based standard for exchanging authentication and authorization data between parties, in particular, between an identity provider (IdP) and a service provider (SP).
First, create a AuthUser model implementing the IAuthUser interface. You can implement the interface in the user model itself. See sample below.
@model({name:'users',})exportclassUserextendsEntityimplementsIAuthUser{@property({type:'number',id:true,})id?:number;@property({type:'string',required:true,name:'first_name',})firstName:string;@property({type:'string',name:'last_name',})lastName:string;@property({type:'string',name:'middle_name',})middleName?:string;@property({type:'string',required:true,})username:string;@property({type:'string',})email?:string;// Auth provider - 'SAML'@property({type:'string',required:true,name:'auth_provider',})authProvider:string;// Id from external provider@property({type:'string',name:'auth_id',})authId?:string;@property({type:'string',name:'auth_token',})authToken?:string;@property({type:'string',})password?:string;constructor(data?:Partial<User>){super(data);}}
Now bind this model to USER_MODEL key in application.ts
Add the verifier function for the strategy. You need to create a provider for the same. You can add your application specific business logic for client auth here. Here is a simple example.
@authenticateClient(STRATEGY.CLIENT_PASSWORD)@authenticate(STRATEGY.SAML,{accessType:'offline',scope:['profile','email'],callbackURL:process.env.SAML_CALLBACK_URL,issuer:process.env.SAML_ISSUER,cert:process.env.SAML_CERT,entryPoint:process.env.SAML_ENTRY_POINT,audience:process.env.SAML_AUDIENCE,logoutUrl:process.env.SAML_LOGOUT_URL,passReqToCallback:!!+(process.env.SAML_AUTH_PASS_REQ_CALLBACK??0),validateInResponseTo:!!+(process.env.VALIDATE_RESPONSE??1),idpIssuer:process.env.IDP_ISSUER,logoutCallbackUrl:process.env.SAML_LOGOUT_CALLBACK_URL,})@authorize({permissions:['*']})@post('/auth/saml',{description:'POST Call for saml based login',responses:{[STATUS_CODE.OK]:{description:'Saml Token Response',content:{[CONTENT_TYPE.JSON]:{schema:{[X_TS_TYPE]:TokenResponse},},},},},})asyncpostLoginViaSaml(@requestBody({content:{[CONTENT_TYPE.FORM_URLENCODED]:{schema:getModelSchemaRef(ClientAuthRequest),},},})clientCreds?:ClientAuthRequest,//NOSONAR):Promise<void>{//do nothing}@authenticate(STRATEGY.SAML,{accessType:'offline',scope:['profile','email'],callbackURL:process.env.SAML_CALLBACK_URL,issuer:process.env.SAML_ISSUER,cert:process.env.SAML_CERT,entryPoint:process.env.SAML_ENTRY_POINT,audience:process.env.SAML_AUDIENCE,logoutUrl:process.env.SAML_LOGOUT_URL,passReqToCallback:!!+(process.env.SAML_AUTH_PASS_REQ_CALLBACK??0),validateInResponseTo:!!+(process.env.VALIDATE_RESPONSE??1),idpIssuer:process.env.IDP_ISSUER,logoutCallbackUrl:process.env.SAML_LOGOUT_CALLBACK_URL,})@authorize({permissions:['*']})@post(`/auth/saml-redirect`,{responses:{[STATUS_CODE.OK]:{description:'Okta SAML callback',content:{[CONTENT_TYPE.JSON]:{schema:{[X_TS_TYPE]:TokenResponse},},},},},})asyncoktaSamlCallback(@inject(AuthenticationBindings.CURRENT_USER)user:AuthUser|undefined,@inject(RestBindings.Http.REQUEST)request:Request,@param.query.string('client')clientId:string,@inject(RestBindings.Http.RESPONSE)response:Response,@requestBody({content:{[CONTENT_TYPE.FORM_URLENCODED]:{},},})oktaData:AnyObject,):Promise<void>{if(!clientId||!user){thrownewHttpErrors.Unauthorized(AuthErrorKeys.ClientInvalid);}constclient=awaitthis.authClientRepository.findOne({where:{clientId,},});if(!client?.redirectUrl){thrownewHttpErrors.Unauthorized(AuthErrorKeys.ClientInvalid);}try{consttoken=awaitthis.getAuthCode(client,user);response.redirect(`${client.redirectUrl}?code=${token}`);}catch(error){this.logger.error(error);thrownewHttpErrors.Unauthorized(AuthErrorKeys.InvalidCredentials);}}
Please note above that we are creating two new APIs for SAML. The first one is for UI clients to hit. We are authenticating client as well, then passing the details to the SAML. Then, the actual authentication is done by SAML authorization url, which redirects to the second API we created after success. The first API method body is empty as we do not need to handle its response. The SAML provider in this package will do the redirection for you automatically.
Note: For auth/saml-redirect one needs to configure the SSO path by incorporating the client ID as a query parameter in existing application set up within your Okta environment for which you intend to enable SSO as follows:
For accessing the authenticated AuthUser model reference, you can inject the CURRENT_USER provider, provided by the extension, which is populated by the auth action sequence above.
The logoutVerify function is used in the node-saml library as a part of the Passport SAML authentication process. This function is used to verify the authenticity of a SAML logout request.
The logout process in SAML is used to end the user's session on the service provider, and the logoutVerify function is used to verify that the logout request is coming from a trusted IdP.
The implementation of the logoutVerify function may vary depending on the specific requirements and the security constraints of the application. It is typically used to verify the signature on the logout request, to ensure that the request has not been tampered with, and to extract the user's identity information from the request.
functionlogoutVerify(req:Request<AnyObject,AnyObject,AnyObject>,profile:Profile|null,done:VerifiedCallback,):void{// Check if a user is currently authenticatedif(req.isAuthenticated()){// Log the user out by removing their session datareq.logout(done);// Call the "done" callback to indicate successdone(null,{message:'User successfully logged out'});}else{// Call the "done" callback with an error to indicate that the user is not logged indone(newError('User is not currently logged in'));}}
This function is called when a user logs out of the application.Once this function is implemented,it will be called when the user logs out of the application,allowing the application to perform any necessary tasks before ending the user's session.
@param req - The request object.
@param {Profile | null} profile - The user's profile, as returned by the provider.
@param {VerifiedCallback} done - A callback to be called when the verificationis complete.
If a https proxy agent is needed for keycloak and google auth, just add an environment variable named HTTPS_PROXY or https_proxy with proxy url as value. It will add that proxy agent to the request.
As action based sequence will be deprecated soon, we have provided support for middleware based sequences. If you are using middleware sequence you can add authentication to your application by enabling client or user authentication middleware. This can be done by binding the AuthenticationBindings.CONFIG :
This binding needs to be done before adding the Authentication component to your application.
Apart from this all other steps for authentication for all strategies remain the same.
In order to use it, run npm install passport-auth0 and npm install @types/passport-auth0.
First, create a AuthUser model implementing the IAuthUser interface. You can implement the interface in the user model itself. See sample below.
@model({name:'users',})exportclassUserextendsEntityimplementsIAuthUser{@property({type:'number',id:true,})id?:number;@property({type:'string',required:true,name:'first_name',})firstName:string;@property({type:'string',name:'last_name',})lastName:string;@property({type:'string',name:'middle_name',})middleName?:string;@property({type:'string',required:true,})username:string;@property({type:'string',})email?:string;// Auth provider - 'auth0'@property({type:'string',required:true,name:'auth_provider',})authProvider:string;// Id from external provider@property({type:'string',name:'auth_id',})authId?:string;@property({type:'string',name:'auth_token',})authToken?:string;@property({type:'string',})password?:string;constructor(data?:Partial<User>){super(data);}}
Now bind this model to USER_MODEL key in application.ts
Add the verifier function for the strategy. You need to create a provider for the same. You can add your application specific business logic for client auth here. Here is a simple example.
Please note above that we are creating two new APIs for auth0 authentication. The first one is for UI clients to hit. We are authenticating client as well, then passing the details to the auth0. Then, the actual authentication is done by auth0 authorization url, which redirects to the second API we created after success. The first API method body is empty as we do not need to handle its response. The provider in this package will do the redirection for you automatically.
For accessing the authenticated AuthUser model reference, you can inject the CURRENT_USER provider, provided by the extension, which is populated by the auth action sequence above.
If you've noticed a bug or have a question or have a feature request, search the issue tracker to see if someone else in the community has already created a ticket.
If not, go ahead and make one!
All feature requests are welcome. Implementation time may vary. Feel free to contribute the same, if you can.
If you think this extension is useful, please star it. Appreciation really helps in keeping this project alive.