我正在尝试按照本教程进行操作,并且正在努力将实现转换为 GraphQL。
本地策略.ts
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authenticationService: AuthenticationService) {
super();
}
async validate(email: string, password: string): Promise<any> {
const user = await this.authenticationService.getAuthenticatedUser(
email,
password,
);
if (!user) throw new UnauthorizedException();
return user;
}
}
local.guard.ts
@Injectable()
export class LogInWithCredentialsGuard extends AuthGuard('local') {
async canActivate(context: ExecutionContext): Promise<boolean> {
const ctx = GqlExecutionContext.create(context);
const { req } = ctx.getContext();
req.body = ctx.getArgs();
await super.canActivate(new ExecutionContextHost([req]));
await super.logIn(req);
return true;
}
}
身份验证.type.ts
@InputType()
export class AuthenticationInput {
@Field()
email: string;
@Field()
password: string;
}
身份验证.resolver.ts
@UseGuards(LogInWithCredentialsGuard)
@Mutation(() => User, { nullable: true })
logIn(
@Args('variables')
_authenticationInput: AuthenticationInput,
@Context() req: any,
) {
return req.user;
}
突变
mutation {
logIn(variables: {
email: "email@email.com",
password: "123123"
} ) {
id
email
}
}
即使上述凭据是正确的,我也会收到未经授权的错误。