LoopBack 4 认证 Action 深度解析:从序列伪代码到中间件自动化认证
LoopBack 4 认证 Action 深度解析:从序列伪代码到中间件自动化认证
@loopback/authentication 是 LoopBack 4 的认证组件,其核心逻辑集中于一个被称为 authentication action(认证动作) 的模块:它负责解析端点上的认证元数据、按名称查找认证策略、调用策略的 authenticate() 校验请求,并把校验出的用户画像(UserProfile)绑定到请求上下文供后续处理器注入。本文以 authentication-action.md 为主体,结合仓库内 AuthenticateActionProvider、策略解析器与验收测试的源码实现,逐行拆解认证 action 的工作原理,并说明在现代中间件序列(middleware-based sequence)下如何免手动接入、直接获得自动化的请求认证能力。读完本文,你将能够:理解认证 action 的内部调用链与错误处理策略、明白序列模式与中间件模式的取舍,以及在自己的控制器中正确使用 @authenticate() 装饰器与 SecurityBindings.USER 注入。
图片来源:packages/authentication/docs/imgs/auth-framework-architecture.png,描述了认证框架中 action、strategy、service、controller 各自的职责边界。
认证 Action 在认证组件中的定位
在开始之前,需要先厘清认证 action 在整个认证组件中的位置。AuthenticationComponent 作为组件,向应用暴露了四类能力(见 authentication.component.ts):
AuthenticateActionProvider—— 提供authentication.actions.authenticate绑定,即本文的主角认证 action;AuthenticationStrategyProvider—— 提供authentication.strategy绑定,负责按名称解析认证策略;AuthMetadataProvider—— 提供authentication.operationMetadata绑定,负责读取控制器方法上的认证元数据;AuthenticationMiddlewareProvider—— 提供middleware.authentication绑定,是中间件模式的入口,内部直接委托给认证 action。
这里需要特别注意原文档开篇的加粗提示:对于基于中间件的序列(middleware-based sequence,即 LoopBack 4 默认的 MiddlewareSequence)而言,本节内容并不需要你手动接入——认证中间件会被自动发现并添加到序列中。只有当你使用旧式的自定义 SequenceHandler 时,才需要像下文演示的那样手动把认证 action 注入并调用。
认证 Action 的接口契约
认证 action 的类型定义位于 types.ts:
/**
* interface definition of a function which accepts a request
* and returns an authenticated user
*/
export interface AuthenticateFn {
(request: Request): Promise<UserProfile | undefined>;
}
它接收一个来自 REST 层的 Request(即 Express 风格的请求对象),异步返回两种结果之一:
UserProfile—— 认证成功,表示当前请求对应的已登录用户;undefined—— 当前操作不需要认证(例如控制器方法上没有@authenticate装饰器)。
返回值会被绑定到 SecurityBindings.USER,下游的控制器函数、拦截器都可以通过依赖注入(DI)直接拿到当前用户。
认证 Action 核心实现逐行解析
原文档 authentication-action.md 给出了一份精简的伪代码,完整呈现如下:
import HttpErrors from 'http-errors';
async action(request: Request): Promise<UserProfile | undefined> {
const authStrategy = await this.getAuthStrategy();
if (!authStrategy) {
// The invoked operation does not require authentication.
return undefined;
}
try {
const userProfile: UserProfile = await authStrategy.authenticate(request);
this.setCurrentUser(userProfile);
// a convenient return for the next request handlers
return userProfile;
} catch (err) {
// interpret the raw error code/msg here and throw the corresponding HTTP error
// convert it to http error
if (err.code == '401') {
throw new HttpErrors.Unauthorized(err.message);
}
}
}
这份伪代码勾勒出认证 action 的三个核心步骤:
- 解析策略:通过
getAuthStrategy()获取当前请求对应的认证策略。若解析结果为undefined,说明被调用的操作不需要认证,直接返回undefined放行; - 执行认证:调用
authStrategy.authenticate(request)校验凭据,成功后得到userProfile; - 绑定用户并返回:通过
setCurrentUser(userProfile)把用户画像绑定到请求上下文(对应SecurityBindings.USER),并作为返回值供后续处理器使用; - 异常转换:把策略抛出的底层错误码解释并转换为对应的 HTTP 错误(示例中为 401 Unauthorized)。
与真实实现 AuthenticateActionProvider 的对照
伪代码只是骨架,仓库中真正的实现位于 auth-action.provider.ts 的 AuthenticateActionProvider。其构造函数通过 @inject.getter() 注入了一个延迟解析的策略 getter——这一点很关键:
@inject.getter(AuthenticationBindings.STRATEGY)
readonly getStrategies: Getter<
AuthenticationStrategy | AuthenticationStrategy[] | undefined
>,
@inject.setter(SecurityBindings.USER)
readonly setCurrentUser: Setter<UserProfile>,
由于 provider 在序列/中间件构造阶段就被实例化,而此时当前路由(从而认证元数据)尚未确定,因此必须注入 getter 函数,把策略的解析推迟到 action() 真正执行的那一刻。value() 方法把 action 包装成标准的 AuthenticateFn:
value(): AuthenticateFn {
return request => this.action(request);
}
真实实现较伪代码还多了三处重要演进,值得展开:
其一,支持多策略。 现代实现允许 @authenticate('a', 'b') 声明多个策略,action() 会把策略统一转为数组并逐个尝试(auth-action.provider.ts):
// convert to array if required
strategies = Array.isArray(strategies) ? strategies : [strategies];
const authErrors: unknown[] = [];
for (const strategy of strategies) {
let authResponse: UserProfile | RedirectRoute | undefined = undefined;
try {
authResponse = await strategy.authenticate(request);
} catch (err) {
if (this.options.failOnError) {
throw err;
}
authErrors.push(err);
}
// ...
}
默认情况下,某个策略抛错会被收集起来继续尝试下一个;只要其中一个策略成功,错误即被丢弃。只有当全部策略都失败时,才会抛出收集到的第一个错误。若希望“一票否决”,可以开启 failOnError 选项(见 types.ts 中的 AuthenticationOptions):
export interface AuthenticationOptions {
defaultMetadata?: AuthenticationMetadata[];
failOnError?: boolean;
}
其二,支持 OAuth2 重定向。 策略的 authenticate() 除了返回 UserProfile,还可以返回 RedirectRoute。action 检测到重定向结果后,会把目标 URL 与状态码(通常为 302/303)通过 setRedirectUrl / setRedirectStatus 绑定到上下文,由控制器决定如何执行实际跳转(见 keys.ts 中的 AUTHENTICATION_REDIRECT_URL 与 AUTHENTICATION_REDIRECT_STATUS 绑定)。
其三,统一的兜底错误。 若所有策略都返回了 undefined(即没有返回用户画像),action 会抛出一个携带 USER_PROFILE_NOT_FOUND 错误码的非协议错误,由上层统一映射为 HTTP 401:
const error = new Error(
`User profile not returned from strategy's authenticate function`,
);
Object.assign(error, {code: USER_PROFILE_NOT_FOUND});
throw error;
策略解析与元数据:Action 背后的两个 Provider
认证 action 自身的逻辑并不复杂,真正的“按需分派”发生在它背后的两个 provider 上。
AuthMetadataProvider:读取 @authenticate 元数据
AuthMetadataProvider 注入当前控制器类与方法名,从反射元数据中读取认证信息:
value(): AuthenticationMetadata[] | undefined {
if (!this.controllerClass || !this.methodName) return;
const metadata = getAuthenticateMetadata(
this.controllerClass,
this.methodName,
);
// Skip authentication if `skip` is `true`
if (metadata?.[0]?.skip) return undefined;
if (metadata) return metadata;
// Fall back to default metadata
return this.options.defaultMetadata;
}
这里包含了三个语义:
- 方法上没有
@authenticate装饰器时返回undefined,请求匿名放行; - 装饰器带
skip: true时同样跳过认证,这正是@authenticate.skip()糖装饰器的实现基础(见 authenticate.decorator.ts); - 可以配置组件的
defaultMetadata,为所有未装饰的方法设置默认认证策略,形成“默认全站认证、个别放行”的策略。
getAuthenticateMetadata 的实现遵循“方法级优先、类级兜底”的查找顺序(authenticate.decorator.ts),因此你既可以把 @authenticate('jwt') 放在类上统一保护,也可以在个别方法上用 @authenticate.skip() 打开匿名入口。
AuthenticationStrategyProvider:扩展点按名查找
AuthenticationStrategyProvider 被声明为一个扩展点(@extensionPoint),所有认证策略都以扩展的方式注册进来:
@extensionPoint(
AuthenticationBindings.AUTHENTICATION_STRATEGY_EXTENSION_POINT_NAME,
{scope: BindingScope.TRANSIENT},
)
export class AuthenticationStrategyProvider
implements Provider<AuthenticationStrategy[] | undefined> {
constructor(
@extensions() protected authenticationStrategies: Getter<AuthenticationStrategy[]>,
@inject(AuthenticationBindings.METADATA) protected metadata?: AuthenticationMetadata[],
) {}
// ...
}
策略的注册入口是 types.ts 中的 registerAuthenticationStrategy(context, strategyClass),它把策略类作为扩展添加到 authentication.strategies 命名空间;asAuthStrategy 则是一个供 @injectable() 使用的绑定模板(同文件 L136-L144)。策略按 name 属性被匹配——这正是 authentication-strategy.md 中 AuthenticationStrategy 接口要求每个策略必须有唯一 name 的原因。若找不到对应名称,则抛出携带 AUTHENTICATION_STRATEGY_NOT_FOUND 错误码的错误:
const error = new Error(`The strategy '${name}' is not available.`);
Object.assign(error, {code: AUTHENTICATION_STRATEGY_NOT_FOUND});
throw error;
AuthenticationStrategy 接口速览
任何策略只需实现两个成员(见 types.ts):
export interface AuthenticationStrategy {
name: string;
authenticate(
request: Request,
): Promise<UserProfile | RedirectRoute | undefined>;
}
策略类可以通过构造函数注入全局或请求级的 options 以及任意所需服务(例如负责从请求中抽取凭据的 service)。仓库测试夹具提供了两个可直接参考的完整策略实现:basic-strategy.ts(从 Authorization: Basic xxx 头解析用户名/密码)与 jwt-strategy.ts(从 Authorization: Bearer xxx 头解析并校验 JWT),它们同时实现了 OASEnhancer,自动把 security scheme 合并进 OpenAPI 规格。
错误处理:错误码到 HTTP 状态码的映射
认证 action 内部只会抛出两类“非协议”错误,它们需要在上层被转换为 HTTP 语义:
AUTHENTICATION_STRATEGY_NOT_FOUND—— 策略名称未注册;USER_PROFILE_NOT_FOUND—— 策略返回的用户画像为空。
这两类错误码定义于 types.ts。注意:策略实现(如 basic/jwt 策略)自身抛出的错误通常已经带有 statusCode(它们直接抛 HttpErrors.Unauthorized),无需二次转换;只有上述两个“框架级”错误需要映射。
旧式序列模式的手动映射
在自定义 SequenceHandler 中,你需要在 catch 分支手动补上 statusCode: 401。仓库测试夹具 authentication.sequence.ts 展示了完整写法:
async handle(context: RequestContext) {
try {
const {request, response} = context;
const route = this.findRoute(request);
// call authentication action
await this.authenticateRequest(request);
// Authentication successful, proceed to invoke controller
const args = await this.parseParams(request, route);
const result = await this.invoke(route, args);
this.send(response, result);
} catch (error) {
if (
error.code === AUTHENTICATION_STRATEGY_NOT_FOUND ||
error.code === USER_PROFILE_NOT_FOUND
) {
Object.assign(error, {statusCode: 401 /* Unauthorized */});
}
this.reject(context, error);
return;
}
}
其中 authenticateRequest 通过 @inject(AuthenticationBindings.AUTH_ACTION) 注入(见 keys.ts 中 AUTH_ACTION 绑定的示例注释)。
中间件模式的自动映射
如果你使用的是中间件序列(默认推荐),这一切都不需要自己写。AuthenticationMiddlewareProvider 已经以中间件形式封装好了认证逻辑与错误映射:
@injectable(
asMiddleware({
group: RestMiddlewareGroups.AUTHENTICATION,
upstreamGroups: [RestMiddlewareGroups.FIND_ROUTE],
}),
)
export class AuthenticationMiddlewareProvider implements Provider<Middleware> {
value(): Middleware {
return async (ctx, next) => {
try {
await this.authenticate(ctx.request);
} catch (error) {
if (
error.code === AUTHENTICATION_STRATEGY_NOT_FOUND ||
error.code === USER_PROFILE_NOT_FOUND
) {
error.statusCode = 401;
}
throw error;
}
return next();
};
}
}
该中间件被声明在 RestMiddlewareGroups.AUTHENTICATION 分组、且上游依赖 FIND_ROUTE(必须先路由才能确定控制器方法与认证元数据),并通过 asMiddleware 自动发现机制加入默认的 MiddlewareSequence。因此,在中间件模式下,你只需要加载 AuthenticationComponent 并注册策略,认证即自动生效,这正是本文开头原文档加粗提示的含义。
端到端验证:验收测试中的行为佐证
认证 action 的各类行为都有对应的验收测试,是理解其边界的绝佳材料:
- Basic 认证成功/失败:basic-auth-extension.acceptance.ts 验证了正确凭据返回用户 ID、缺失
Authorization头返回 401(message: 'Authorization header not found.')、头格式不符(非Basic前缀、分隔符缺失、多余段)时的精确错误信息; - JWT 认证成功/失败:jwt-auth-extension.acceptance.ts 覆盖了 token 过期(
Error verifying token : jwt expired)、格式非法(invalid token/jwt malformed)等场景; - 匿名放行:两个测试文件中均包含“未加装饰器的方法允许匿名访问”的用例(返回 200
{running: true}),印证了getAuthStrategy()返回undefined即放行的逻辑; - 框架级错误映射:两个文件都测试了未注册策略(返回
code: 'AUTHENTICATION_STRATEGY_NOT_FOUND'、statusCode: 401)以及策略返回空用户画像(返回code: 'USER_PROFILE_NOT_FOUND'、statusCode: 401)的场景; - 中间件序列验证:basic-auth-extension.middleware.acceptance.ts 与 jwt-auth-extension.middleware.acceptance.ts 使用继承自
MiddlewareSequence的 authentication.middleware.sequence.ts 完成同样的断言,证明中间件模式下认证行为与序列模式完全一致且无需手工接线。
测试中还演示了控制器如何消费认证结果——通过 @inject(SecurityBindings.USER) 注入当前用户画像:
@get('/whoAmI')
@authenticate('jwt')
whoAmI(@inject(SecurityBindings.USER) userProfile: UserProfile) {
return userProfile[securityId];
}
登录与校验的完整 API 流程(以 BasicAuth + JWT 为例)
将认证 action 放到更大的图景中,它只是登录/校验两条流程中的一个环节。仓库的 authentication-system.md 用 BasicAuth + JWT 示例拆解了各部分职责:
登录流程(Login):
- 认证 action:解析元数据拿到策略 → 调用
strategy.authenticate()→ 把返回值设为当前用户; - 策略:从传输层(请求头)或本地配置文件抽取凭据 → 调用
UserService.verifyCredentials()校验并返回用户画像; - 控制器函数:调用
TokenService.generateToken()生成 JWT 并序列化到响应(sendaction 会按 OpenAPI 描述序列化)。
校验流程(Verify):
- 认证 action:同样先解析策略再调用
authenticate()并绑定当前用户; - 策略:从请求中抽取访问令牌 → 调用
TokenService.verifyToken()校验令牌并从其中解码出用户画像; - 控制器函数:直接处理注入的当前用户。
与流程对应的两个服务抽象位于 user.service.ts(verifyCredentials + convertToUserProfile,凭据形态因策略而异:本地账号为 {username, password}、OAuth 为 {clientId, clientSecret, callbackURL}、SAML 为 {path, issuer, entryPoint})与 token.service.ts(verifyToken / generateToken / 可选的 revokeToken)。测试夹具 jwt-service.ts 给出了基于 jsonwebtoken 的完整可运行实现,包括将 [securityId] 符号从 token 载荷中重建的细节。
相关文档与源码索引
要继续深挖,仓库内准备了整套配套材料:
- 认证框架总览:authentication-system.md(多策略架构、登录/校验流程、token 与 session 两种跟踪方式);
- 策略接口定义:authentication-strategy.md;
- 策略伪代码:strategies/basic-auth.md、strategies/jwt.md、strategies/oauth2.md;
- 控制器端点定义:controller-functions.md;
- 核心源码:auth-action.provider.ts、auth-strategy.provider.ts、auth-metadata.provider.ts、authenticate.decorator.ts、keys.ts、types.ts;
- 组件装配:authentication.component.ts;
- 验收测试:basic-auth-extension.acceptance.ts、jwt-auth-extension.acceptance.ts 及对应的 middleware 版本。
总而言之,认证 action 是 LoopBack 4 认证体系里“承上启下”的一环:向下通过策略扩展点按需分派校验,向上把用户画像绑定到请求上下文供 DI 注入。对绝大多数新应用而言,加载组件 + 注册策略 + 在控制器上使用 @authenticate() 即可获得完整认证能力,认证 action 本身由自动发现的中间件代为驱动,无需手工介入。
