图像认证

问题描述 投票:0回答:1

我有一个 NestJS 应用程序,用于服务器需要身份验证的图像。对于我的身份验证,我使用 JWT,但是当我想在 img 标签中显示图像时,我无法将 Authorization 标头附加到 GET 请求。我读过一些关于如何验证文件的文章,其中一些推荐了 Signed Url,但没有真正展示它应该如何实现。

我使用 NestJS 作为后端 API,使用 MINIO 作为我的数据存储。

javascript typescript nestjs minio
1个回答
0
投票

要在 NestJS 应用程序中提供经过身份验证的图像,您可以通过 Minio 使用签名 URL。签名 URL 允许临时访问资源,无需授权标头,使它们适合在标签中提供图像等场景。

// Image controller to generate signed URLs
@Controller('images')
export class ImageController {
  constructor(private imageService: ImageService) {}

  @Get(':filename')
  @UseGuards(AuthGuard()) // Protect route with authentication
  async getImage(@Param('filename') filename: string, @Req() req: Request) {
    try {
      const signedUrl = await this.imageService.generateSignedUrl(filename, req.user);
      return { signedUrl };
    } catch (error) {
      // Handle error
    }
  }
}

// Image service to generate signed URLs
@Injectable()
export class ImageService {
  constructor(private minioClient: MinioClient) {}

  async generateSignedUrl(filename: string, user: any): Promise<string> {
    // Logic to generate signed URL for the image based on filename and user
    // Use Minio SDK to generate signed URL
    // Example:
    // const signedUrl = await this.minioClient.presignedGetObject('bucketName', filename);
    return signedUrl;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.