Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

An Authorization Extension for LoopBack 4 Applications

License

NotificationsYou must be signed in to change notification settings

sourcefuse/loopback4-authorization

ARC By SourceFuse logo

npm versionSonar Quality GateSynk StatusGitHub contributorsdownloadsLicensePowered By LoopBack 4

Overview

A LoopBack 4 extension for Authorization Capabilities. It's very simple to integration yet powerful and effective.

Install

npm install loopback4-authorization

Quick Starter

For a quick starter guide, you can refer to ourloopback 4 starter application which utilizes method #3 from the above in a simple multi-tenant application.

Usage

Ways of Integration:

On a higher level, it provides three ways of integration:

1. User Level Permissions Only

Where permissions are associated directly to user. In this case, each user entry in DB contains specific array of permission keys.

2. Role Based Permissions

Where permissions are associated to roles and users have a specific role attached. This actually reduces redundancy in DB a lot, as most of the time, users will have many common permissions. If that is not the case for you, then, use the first method.

3. Role Based Permissions with User Level Flexibility

This is the most flexible architecture. In this case, method #2 is implemented as is.

On top of it, we also add user-level permissions override, allow/deny permissions over role permissions. So, say there is user who can perform all admin role actions except he cannot remove users from the system. So, DeleteUser permission can be denied at user level and role can be set as Admin for the user.

Extension enhancement using CASBIN authorisation

Refer to the usage section below for details on integration.

In order to use this component into your LoopBack application, please follow below steps.

Steps

Bind Component

AddAuthorizationComponent to your application, Like below:

this.bind(AuthorizationBindings.CONFIG).to({allowAlwaysPaths:['/explorer'],});this.component(AuthorizationComponent);

Implement Permission Interface

If using method #1 from above, implement Permissions interface in User model and add permissions array.

@model({name:'users',})exportclassUserextendsEntityimplementsPermissions<string>{// .....// other attributes here// .....  @property({type:'array',itemType:'string',})permissions:string[];constructor(data?:Partial<User>){super(data);}}

If using method #2 or #3 from above, implement Permissions interface in Role model and add permissions array.

@model({name:'roles',})exportclassRoleextendsEntityimplementsPermissions<string>{// .....// other attributes here// .....  @property({type:'array',itemType:'string',})permissions:string[];constructor(data?:Partial<Role>){super(data);}}

ImplementUserPermissionsOverride Interface

If using method #3 from above, implement UserPermissionsOverride interface in User model and add user level permissions array as below.Do this if there is a use-case of explicit allow/deny of permissions at user-level in the application.You can skip otherwise.

@model({name:'users',})exportclassUserextendsEntityimplementsUserPermissionsOverride<string>{// .....// other attributes here// .....  @property({type:'array',itemType:'object',})permissions:UserPermission<string>[];constructor(data?:Partial<User>){super(data);}}

User Permissions Provider

For method #3, This extension exposes a provider functionAuthorizationBindings.USER_PERMISSIONS to evaluate the user permissions based on its role permissions and user-level overrides.

Just inject it like below:

@inject(AuthorizationBindings.USER_PERMISSIONS)privatereadonlygetUserPermissions:UserPermissionsFn<string>,

and invoke it

constpermissions=this.getUserPermissions(user.permissions,role.permissions);

Add a step in custom sequence to check for authorization whenever any endpoint is hit.

import{inject}from'@loopback/context';import{FindRoute,HttpErrors,InvokeMethod,ParseParams,Reject,RequestContext,RestBindings,Send,SequenceHandler,}from'@loopback/rest';import{AuthenticateFn,AuthenticationBindings}from'loopback4-authentication';import{AuthorizationBindings,AuthorizeErrorKeys,AuthorizeFn,UserPermissionsFn,}from'loopback4-authorization';import{AuthClient}from'./models/auth-client.model';import{User}from'./models/user.model';constSequenceActions=RestBindings.SequenceActions;exportclassMySequenceimplementsSequenceHandler{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>,    @inject(AuthenticationBindings.CLIENT_AUTH_ACTION)protectedauthenticateRequestClient:AuthenticateFn<AuthClient>,    @inject(AuthorizationBindings.AUTHORIZE_ACTION)protectedcheckAuthorisation:AuthorizeFn,    @inject(AuthorizationBindings.USER_PERMISSIONS)privatereadonlygetUserPermissions:UserPermissionsFn<string>,){}asynchandle(context:RequestContext){constrequestTime=Date.now();try{const{request, response}=context;constroute=this.findRoute(request);constargs=awaitthis.parseParams(request,route);request.body=args[args.length-1];awaitthis.authenticateRequestClient(request);constauthUser:User=awaitthis.authenticateRequest(request);// Do ths if you are using method #3constpermissions=this.getUserPermissions(authUser.permissions,authUser.role.permissions,);// This is the important line added for authorization. Needed for all 3 methodsconstisAccessAllowed:boolean=awaitthis.checkAuthorisation(permissions,// do authUser.permissions if using method #1request,);// Checking access to route hereif(!isAccessAllowed){thrownewHttpErrors.Forbidden(AuthorizeErrorKeys.NotAllowedAccess);}constresult=awaitthis.invoke(route,args);this.send(response,result);}catch(err){this.reject(context,err);}}}

The above sequence also contains user authentication usingloopback4-authentication package. You can refer to the documentation for the same for more details.

Now we can add access permission keys to the controller methods using authorize decorator as below:

@authorize(['CreateRole'])@post(rolesPath,{responses:{[STATUS_CODE.OK]:{description:'Role model instance',content:{[CONTENT_TYPE.JSON]:{schema:{'x-ts-type':Role}},},},},})asynccreate(@requestBody()role:Role):Promise<Role>{returnawaitthis.roleRepository.create(role);}

This endpoint will only be accessible if logged in user has permissionCreateRole.

A good practice is to keep all permission strings in a separate enum file like this.

exportconstenumPermissionKey{ViewOwnUser='ViewOwnUser',ViewAnyUser='ViewAnyUser',ViewTenantUser='ViewTenantUser',CreateAnyUser='CreateAnyUser',CreateTenantUser='CreateTenantUser',UpdateOwnUser='UpdateOwnUser',UpdateTenantUser='UpdateTenantUser',UpdateAnyUser='UpdateAnyUser',DeleteTenantUser='DeleteTenantUser',DeleteAnyUser='DeleteAnyUser',ViewTenant='ViewTenant',CreateTenant='CreateTenant',UpdateTenant='UpdateTenant',DeleteTenant='DeleteTenant',ViewRole='ViewRole',CreateRole='CreateRole',UpdateRole='UpdateRole',DeleteRole='DeleteRole',ViewAudit='ViewAudit',CreateAudit='CreateAudit',UpdateAudit='UpdateAudit',DeleteAudit='DeleteAudit',}

Overriding Permissions

API endpoints provided by ARC API (aka Sourceloop) services have their permissions pre-defined in them bundled.

In order to override them you can bind your custom permissions in theAuthorizationBindings.PERMISSION binding key.This accepts an object that should have Controller class name as the root level key and the value of which is another object of method to permissions array mapping.

Like below:

this.bind(AuthorizationBindings.PERMISSION).to({MessageController:{create:['CreateMessage','ViewMessage'],updateAll:['UpdateMessage','ViewMessage','ViewMessageNum']}AttachmentFileController:{create:['CreateAttachmentFile','ViewAttachmentFile'],updateAll:['UpdateAttachmentFile','ViewAttachmentFileNum']}});

You can easily check the name of the controller and it's method name from the source code of the services or from the Swagger UI (clicking the endpoint in swagger append the controller and method name in the URL likeLoginController.login wherelogin is the method name).

Serving the static files:

Authorization configuration binding sets up paths that can be accessed without any authorization checks, allowing static files to be served directly from the root URL of the application.The allowAlwaysPaths property is used to define these paths for the files in public directory i.e for a test.html file in public directory ,one can provide its path as follows:

this.bind(AuthorizationBindings.CONFIG).to({  allowAlwaysPaths: ['/explorer','/test.html'],});

To set up the public directory as a static,one can add the following in application.ts file.

this.static('/', path.join(__dirname, '../public'));

If, in case the file is in some other folder thenapp.static() can be called multiple times to configure the app to serve static assets from different directories.

this.static('/', path.join(__dirname, '../public'));this.static('/downloads', path.join(__dirname, '../downloads'));

For more details,referhere

Extension enhancement using CASBIN authorisation

As a further enhancement to these methods, we are usingcasbin library to define permissions at level of entity or resource associated with an API call. Casbin authorisation implementation can be performed in two ways:

  1. Using default casbin policy document - Define policy document in default casbin format in the app, and configure authorise decorator to use those policies.
  2. Defining custom logic to form dynamic policies - Implement dynamic permissions based on app logic in casbin-enforcer-config provider. Authorisation extension will dynamically create casbin policy using this business logic to give the authorisation decisions.

Casbin Usage

In order to use this enhacement into your LoopBack application, please follow below steps.

  • Add providers to implement casbin authorisation along with authorisation component.
this.bind(AuthorizationBindings.CONFIG).to({allowAlwaysPaths:['/explorer'],});this.component(AuthorizationComponent);this.bind(AuthorizationBindings.CASBIN_ENFORCER_CONFIG_GETTER).toProvider(CasbinEnforcerConfigProvider,);this.bind(AuthorizationBindings.CASBIN_RESOURCE_MODIFIER_FN).toProvider(CasbinResValModifierProvider,);
  • Implement theCasbin Resource value modifier provider. Customise the resource value based on business logic using route arguments parameter in the provider.
import{Getter,inject,Provider}from'@loopback/context';import{HttpErrors}from'@loopback/rest';import{AuthorizationBindings,AuthorizationMetadata,CasbinResourceModifierFn,}from'loopback4-authorization';exportclassCasbinResValModifierProviderimplementsProvider<CasbinResourceModifierFn>{constructor(    @inject.getter(AuthorizationBindings.METADATA)privatereadonlygetCasbinMetadata:Getter<AuthorizationMetadata>,    @inject(AuthorizationBindings.PATHS_TO_ALLOW_ALWAYS)privatereadonlyallowAlwaysPath:string[],){}value():CasbinResourceModifierFn{return(pathParams:string[],req:Request)=>this.action(pathParams,req);}asyncaction(pathParams:string[],req:Request):Promise<string>{constmetadata:AuthorizationMetadata=awaitthis.getCasbinMetadata();if(!metadata&&!!this.allowAlwaysPath.find(path=>req.path.indexOf(path)===0)){return'';}if(!metadata){thrownewHttpErrors.InternalServerError(`Metadata object not found`);}constres=metadata.resource;// Now modify the resource parameter using on path params, as per business logic.// Returning resource value as such for default case.return`${res}`;}}
  • Implement thecasbin enforcer config provider . Provide the casbin model path. Model definition can be initialized from.CONF file, from code, or from a string.In the case of policy creation being handled by extension (isCasbinPolicy parameter is false), provide the array of Resource-Permission objects for a given user, based on business logic.In other case, provide the policy from file or as CSV string or fromcasbin Adapters.NOTE: In the second case, if model is initialized from .CONF file, then any of the above formats can be used for policy. But if model is being initialised from code or string, then policy should be provided ascasbin adapter only.
import{Provider}from'@loopback/context';import{CasbinConfig,CasbinEnforcerConfigGetterFn,IAuthUserWithPermissions,}from'loopback4-authorization';import*aspathfrom'path';exportclassCasbinEnforcerConfigProviderimplementsProvider<CasbinEnforcerConfigGetterFn>{constructor(){}value():CasbinEnforcerConfigGetterFn{return(authUser:IAuthUserWithPermissions,resource:string,isCasbinPolicy?:boolean,)=>this.action(authUser,resource,isCasbinPolicy);}asyncaction(authUser:IAuthUserWithPermissions,resource:string,isCasbinPolicy?:boolean,):Promise<CasbinConfig>{constmodel=path.resolve(__dirname,'./../../fixtures/casbin/model.conf');// Model initialization from file path/**     * import * as casbin from 'casbin';     *     * To initialize model from code, use     *      let m = new casbin.Model();     *      m.addDef('r', 'r', 'sub, obj, act'); and so on...     *     * To initialize model from string, use     *      const text = `     *      [request_definition]     *     r = sub, obj, act     *     *      [policy_definition]     *      p = sub, obj, act     *     *      [policy_effect]     *      e = some(where (p.eft == allow))     *     *      [matchers]     *      m = r.sub == p.sub && r.obj == p.obj && r.act == p.act     *       `;     *      const model = casbin.newModelFromString(text);     */// Write business logic to find out the allowed resource-permission sets for this user. Below is a dummy value.//const allowedRes = [{resource: 'session', permission: "CreateMeetingSession"}];constpolicy=path.resolve(__dirname,'./../../fixtures/casbin/policy.csv',);constresult:CasbinConfig={      model,//allowedRes,      policy,};returnresult;}}
  • Add the dependency injections for resource value modifer provider, and casbin authorisation function in the sequence.ts
    @inject(AuthorizationBindings.CASBIN_AUTHORIZE_ACTION)protectedcheckAuthorisation:CasbinAuthorizeFn,    @inject(AuthorizationBindings.CASBIN_RESOURCE_MODIFIER_FN)protectedcasbinResModifierFn:CasbinResourceModifierFn,
  • Add a step in custom sequence to check for authorization whenever any endpoint is hit.
import{inject}from'@loopback/context';import{FindRoute,HttpErrors,InvokeMethod,ParseParams,Reject,RequestContext,RestBindings,Send,SequenceHandler,}from'@loopback/rest';import{AuthenticateFn,AuthenticationBindings}from'loopback4-authentication';import{AuthorizationBindings,AuthorizeErrorKeys,AuthorizeFn,UserPermissionsFn,}from'loopback4-authorization';import{AuthClient}from'./models/auth-client.model';import{User}from'./models/user.model';constSequenceActions=RestBindings.SequenceActions;exportclassMySequenceimplementsSequenceHandler{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>,    @inject(AuthenticationBindings.CLIENT_AUTH_ACTION)protectedauthenticateRequestClient:AuthenticateFn<AuthClient>,    @inject(AuthorizationBindings.CASBIN_AUTHORIZE_ACTION)protectedcheckAuthorisation:CasbinAuthorizeFn,    @inject(AuthorizationBindings.CASBIN_RESOURCE_MODIFIER_FN)protectedcasbinResModifierFn:CasbinResourceModifierFn,){}asynchandle(context:RequestContext){constrequestTime=Date.now();try{const{request, response}=context;constroute=this.findRoute(request);constargs=awaitthis.parseParams(request,route);request.body=args[args.length-1];awaitthis.authenticateRequestClient(request);constauthUser:User=awaitthis.authenticateRequest(request);// Invoke Resource value modifierconstresVal=awaitthis.casbinResModifierFn(args);// Check authorisationconstisAccessAllowed:boolean=awaitthis.checkAuthorisation(authUser,resVal,request,);// Checking access to route hereif(!isAccessAllowed){thrownewHttpErrors.Forbidden(AuthorizeErrorKeys.NotAllowedAccess);}constresult=awaitthis.invoke(route,args);this.send(response,result);}catch(err){this.reject(context,err);}}}
  • Now we can add access permission keys to the controller methods using authorizedecorator as below. Set isCasbinPolicy parameter to use casbin default policy format. Default is false.
@authorize({permissions:['CreateRole'],resource:'role',isCasbinPolicy:true})@post(rolesPath,{responses:{[STATUS_CODE.OK]:{description:'Role model instance',content:{[CONTENT_TYPE.JSON]:{schema:{'x-ts-type':Role}},},},},})asynccreate(@requestBody()role:Role):Promise<Role>{returnawaitthis.roleRepository.create(role);}

Feedback

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 andmake 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, pleasestar it. Appreciation really helps in keeping this project alive.

Contributing

Please readCONTRIBUTING.md for details on the process for submitting pull requests to us.

Code of conduct

Code of conduct guidelineshere.

License

MIT


[8]ページ先頭

©2009-2025 Movatter.jp