由 Hassan 出售

LoopBack 4 is an extensible Node.js framework for building modern REST and GraphQL APIs with OpenAPI support, dependency injection, and connectors for MongoDB, PostgreSQL, MySQL, Cloudant, and more.
This block provides the @loopback/authentication and @loopback/authorization packages from the LoopBack 4 monorepo, implementing a complete auth layer for REST APIs. It covers strategy-based authentication (JWT, OAuth2, SAML, OIDC, Basic), role/permission/vote-based authorization, and the decorator + provider wiring needed to secure controller methods. The typical buyer is a Node.js backend team building a LoopBack 4 or Express/REST application that needs pluggable, extensible auth.
authentication/ - @loopback/authentication: decorator, providers, services, and component for strategy-based authnauthorization/ - @loopback/authorization: component, interceptor, decorator, and types for authz (RBAC, PBAC, vote-based)boot/ - Application boot infrastructure for loading artifacts on startupbooter-lb3app/ - Booter that mounts a LoopBack 3 app inside a LoopBack 4 appcli/ - @loopback/cli scaffolding and code generation toolcontext/ - IoC/DI container (binding, injection, resolution) used across all packagescore/ - Core application lifecycle and extension point abstractionseslint-config/ - Shared ESLint configuration for LoopBack 4 packagesexpress/ - Thin wrapper integrating LoopBack 4 with Express middlewarefilter/ - Type definitions and parsers for LoopBack query filtershttp-caching-proxy/ - HTTP caching proxy used in testinghttp-server/ - HTTP/HTTPS server wrappermetadata/ - Decorator metadata reading/writing utilitiesmodel-api-builder/ - Builds REST APIs from model definitionsopenapi-spec-builder/ - Fluent builder for OpenAPI 3 specsopenapi-v3/ - OpenAPI v3 decorators and spec generationrepository/ - Data-access abstractions: repositories, models, relationsrepository-json-schema/ - Converts LoopBack models to JSON Schemarepository-tests/ - Shared acceptance tests for repository connectorsrest/ - Full REST server, sequence, routing, and validation启动隔离沙箱并在服务器端直接运行 — 无需本地配置。
此版本的 Tetrees AI Review
This TypeScript, JavaScript cli / script completed archive review with strong static results. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
管道 avcp-2026-08-04.1 · SHA-256 62d50a29a21de659…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
审查日期 2026年8月4日
将此产品直接导入你的 AI IDE、网页构建器或云端 IDE。
将 Tetrees 连接到兼容的 AI IDE,列出你拥有的产品并获取已验证 ZIP,同时不会开放卖家上传权限。
暂无评价。
Sign in to join the discussion
Loading discussion…
rest-crud/rest-explorer/ - Swagger UI explorer componentsecurity/ - Shared security type definitions (principals, permissions)service-proxy/ - Proxy service integration via datasourcestestlab/ - Testing helpers (expect, sinon wrappers, HTTP client)tsdocs/ - TypeDoc configuration and API doc generation supportnpm install @loopback/authentication @loopback/authorization
npm install @loopback/core @loopback/context @loopback/rest @loopback/security
npm install @loopback/metadata
# TypeScript peer requirements
npm install --save-dev typescript @types/node
No native modules, no pod install, no Android linking required. All packages are pure TypeScript/JavaScript.
Copy the source/ directory into your project root, e.g. vendor/loopback/.
If you are working from source (not installed npm packages), add path aliases in tsconfig.json:
{
"compilerOptions": {
"paths": {
"@loopback/authentication": ["./vendor/loopback/authentication/src"],
"@loopback/authorization": ["./vendor/loopback/authorization/src"],
"@loopback/core": ["./vendor/loopback/core/src"],
"@loopback/context": ["./vendor/loopback/context/src"],
"@loopback/rest": ["./vendor/loopback/rest/src"],
"@loopback/security": ["./vendor/loopback/security/src"]
},
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strict": true,
"target": "ES2018",
"module": "commonjs"
}
}
experimentalDecorators and emitDecoratorMetadata are mandatory; the decorator system will silently fail without them.
Register the authentication component in your application class:
import {AuthenticationComponent} from '@loopback/authentication';
import {AuthorizationComponent} from '@loopback/authorization';
this.component(AuthenticationComponent);
this.component(AuthorizationComponent);
process.env.JWT_SECRET in your own token service implementation.authenticatefunction authenticate(
strategyName: string,
options?: object,
): MethodDecorator & ClassDecorator;
Decorates a controller method (or class) to require a named authentication strategy. The REST sequence will invoke the matching strategy and reject unauthenticated requests before the method body executes. Use it on any route that must be protected.
AuthenticationComponentclass AuthenticationComponent implements Component {
providers?: ProviderMap;
bindings?: Binding[];
}
A LoopBack 4 Component that registers all authentication providers (AuthMetadataProvider, AuthenticateActionProvider, AuthenticationStrategyProvider) into the application context. Mount it once in your Application constructor via this.component(AuthenticationComponent).
TokenServiceinterface TokenService {
verifyToken(token: string): Promise<UserProfile>;
generateToken(userProfile: UserProfile): Promise<string>;
}
An interface (from authentication/src/services/token.service.ts) that your JWT or session token logic must implement. Bind your concrete class to AuthenticationBindings.TOKEN_SERVICE so the framework can inject it wherever token operations are needed.
UserServiceinterface UserService<U, C> {
verifyCredentials(credentials: C): Promise<U>;
convertToUserProfile(user: U): UserProfile;
}
Abstracts credential verification and user-to-profile conversion. Implement this interface and bind it to wire your database/user-store into the authentication pipeline.
authorizefunction authorize(spec: AuthorizationMetadata): MethodDecorator & ClassDecorator;
From @loopback/authorization. Decorates controller methods with authorization rules (allowed roles, denied roles, scopes). The AuthorizeInterceptor reads this metadata and invokes registered voters/enforcers before allowing method execution.
A REST controller method that requires callers to present a valid JWT.
import {authenticate} from '@loopback/authentication';
import {get} from '@loopback/rest';
import {SecurityBindings, UserProfile} from '@loopback/security';
import {inject} from '@loopback/core';
export class ProfileController {
@authenticate('jwt')
@get('/me')
async whoAmI(
@inject(SecurityBindings.USER) currentUser: UserProfile,
): Promise<UserProfile> {
return currentUser;
}
}
The 'jwt' string must match the name property of a registered AuthenticationStrategy implementation. If no strategy matches, the framework throws a 401.
Wire a concrete TokenService into the authentication component.
import {injectable, BindingScope} from '@loopback/core';
import {UserProfile, securityId} from '@loopback/security';
import {TokenService} from '@loopback/authentication';
import * as jwt from 'jsonwebtoken';
@injectable({scope: BindingScope.SINGLETON})
export class JWTService implements TokenService {
private secret = process.env.JWT_SECRET ?? 'change-me';
async verifyToken(token: string): Promise<UserProfile> {
const decoded = jwt.verify(token, this.secret) as {id: string; email: string};
return {[securityId]: decoded.id, email: decoded.email};
}
async generateToken(userProfile: UserProfile): Promise<string> {
return jwt.sign(
{id: userProfile[securityId], email: userProfile.email},
this.secret,
{expiresIn: '1h'},
);
}
}
// In your Application constructor:
// import {AuthenticationBindings} from '@loopback/authentication';
// this.bind(AuthenticationBindings.TOKEN_SERVICE).toClass(JWTService);
Restrict an admin endpoint to users with the admin role using @authorize.
import {authenticate} from '@loopback/authentication';
import {authorize} from '@loopback/authorization';
import {del, param} from '@loopback/rest';
export class UserAdminController {
@authenticate('jwt')
@authorize({allowedRoles: ['admin']})
@del('/users/{id}')
async deleteUser(@param.path.string('id') id: string): Promise<void> {
// Only reachable when the JWT principal has role 'admin'
await this.userRepository.deleteById(id);
}
}
The AuthorizationComponent must be registered and at least one authorizer (voter function or class) must be bound to AuthorizationBindings.AUTHORIZER for the interceptor to make a decision.
authentication/src/index.ts - Package entry; re-exports everything from component, decorators, keys, providers, services, and types.authentication/src/authentication.component.ts - Declares and registers all authentication providers as a single mountable component.authentication/src/decorators/authenticate.decorator.ts - Implements the @authenticate(strategyName) method/class decorator.authentication/src/keys.ts - Binding keys (AuthenticationBindings) for strategy, token service, user service, and metadata.authentication/src/types.ts - Core TypeScript interfaces: AuthenticationStrategy, AuthenticationMetadata.authentication/src/providers/auth-action.provider.ts - REST sequence action that triggers authentication for each request.authentication/src/providers/auth-metadata.provider.ts - Reads @authenticate metadata from the current route's controller method.authentication/src/providers/auth-strategy.provider.ts - Resolves the correct registered strategy by name for the current request.authentication/src/services/token.service.ts - TokenService interface definition.authentication/src/services/user-identity.service.ts - UserIdentityService interface for linking external identities to local users.authentication/src/services/user.service.ts - UserService interface for credential verification and profile conversion.authentication/docs/ - Detailed markdown guides for each auth strategy (JWT, OAuth2, SAML, OIDC, Basic).authorization/src/index.ts - Package entry; re-exports component, interceptor, decorator, keys, and types.authorization/src/authorization-component.ts - Mounts the authorization interceptor and default bindings.authorization/src/authorize-interceptor.ts - Global interceptor that reads @authorize metadata and calls registered voters.authorization/src/decorators/authorize.ts - Implements the @authorize(spec) decorator.authorization/src/keys.ts - AuthorizationBindings keys for authorizers, metadata, and options.authorization/src/types.ts - Interfaces: AuthorizationContext, AuthorizationMetadata, Authorizer, AuthorizationDecision.emitDecoratorMetadata: Injections silently receive undefined. Fix: set "emitDecoratorMetadata": true in tsconfig.json.@authenticate('jwt') fails with "strategy not found" if the registered strategy's name property differs. Fix: ensure strategy.name === 'jwt' exactly.this.component(AuthenticationComponent) is omitted. Fix: add both components in the Application constructor before starting the server.@authorize has no effect and requests pass through if no voter is bound to AuthorizationBindings.AUTHORIZER. Fix: bind at least one authorizer function or class.jsonwebtoken: import jwt from 'jsonwebtoken' may fail in strict ESM. Fix: use import * as jwt from 'jsonwebtoken' or set "esModuleInterop": true in tsconfig.json.SecurityBindings.USER injection returning undefined: The UserProfile is only populated after the auth action runs. Fix: ensure your sequence calls await this.authenticateRequest(request) before invoking the controller.I have a LoopBack 4 backend project and I have placed the LoopBack 4 core
packages source under `vendor/loopback/` (from the `source/` directory
described in USAGE.md). I also have USAGE.md open for reference.
Please help me integrate `@loopback/authentication` and `@loopback/authorization`
into my project step by step:
1. Read USAGE.md and `vendor/loopback/authentication/src/index.ts` to understand
all available exports.
2. Add the required tsconfig paths so TypeScript resolves `@loopback/authentication`
and `@loopback/authorization` from `vendor/loopback/`.
3. Register `AuthenticationComponent` and `AuthorizationComponent` in my
Application class (`src/application.ts`).
4. Create a `JWTService` implementing the `TokenService` interface from
`@loopback/authentication` and bind it to `AuthenticationBindings.TOKEN_SERVICE`.
5. Create a JWT `AuthenticationStrategy` class, register it, and show me how
to use `@authenticate('jwt')` on a controller method.
6. Add `@authorize({allowedRoles: ['admin']})` to an existing controller method
and create a simple role-based authorizer voter function.
7. Show me how to write a unit test using `@loopback/testlab` to verify
that an unauthenticated request returns 401.
Use only the real exported symbols from USAGE.md. Do not invent APIs.
Reference the upstream package: loopback-monorepo (loopbackio/loopback-next).
The source is licensed under the MIT License (see source/authentication/LICENSE and source/authorization/LICENSE). Original work is copyright IBM Corp. and LoopBack contributors.
Upstream repository: https://github.com/loopbackio/loopback-next Official documentation: https://loopback.io/doc/en/lb4/
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完整安装指南与集成提示词将在购买后解锁。
Automation, Utilities & Developer Tools
免费