Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

s3 private bucket 파일 가져오기 Invalid character in header content ["authorization"] 이슈 #11

Open
develjsw opened this issue Nov 28, 2023 · 0 comments

Comments

@develjsw
Copy link
Owner

develjsw commented Nov 28, 2023

  1. 이슈 :
    회사에서 s3 private bucket의 pdf file binary코드로 가져와 base64로 암호화 하고 반환하는 작업을 진행
    local에서는 정상 동작했고 설정 값도 정상 이였지만 개발 서버에 배포 후 테스트 하면 Invalid character in header content ["authorization"] 에러 발생

  2. 원인 :
    개발 서버의 경우 configService를 통해 가져온 accessKeyId와 secretAccessKey값에 자동 줄바꿈 처리가 되는 점 확인

  3. 해결 방안 :
    trim()을 사용하여 해결

  4. 사용한 패키지 및 소스 코드

[ 패키지 설치 명령어 ]
- (구 버전) $ npm install aws-sdk
- (신 버전) $ npm install @aws-sdk/client-s3
[ 소스 코드 (구 버전) ]
import * as AWS from 'aws-sdk'

async binaryEncoding(filePath: string): Promise<string> {
	try {
		const s3: AWS.S3 = new AWS.S3({
			accessKeyId: this.configService.get('s3.private.accessKeyId'),
			secretAccessKey: this.configService.get(
				's3.private.secretAccessKey',
			),
		})

		AWS.config.update({ region: 'ap-northeast-2' })

		const params = {
			Bucket: this.configService.get('s3.private.bucket'),
			Key: filePath,
		}

		const file = await s3.getObject(params).promise()
		file.ContentEncoding = 'utf-8'
		file.ContentType = 'application/pdf'

		return file.Body.toString('base64')
	} catch (error: any) {
		console.log(`F : binaryEncoding Error - `, error)
		throw new Error(error)
	}
}
[ 소스 코드 (신 버전) ]
import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3'

async binaryEncoding(filePath: string): Promise<any> {
	try {
		const client = new S3Client({
			region: 'ap-northeast-2',
			credentials: {
				accessKeyId: this.configService.get(
					's3.private.accessKeyId',
				),
				secretAccessKey: this.configService.get(
					's3.private.secretAccessKey',
				),
			},
		})

		const params = {
			Bucket: this.configService.get('s3.private.bucket'),
			Key: filePath,
			ContentType: 'application/pdf',
			ResponseContentEncoding: 'utf-8',
		}

		const data = await client.send(new GetObjectCommand(params))
		return Buffer.from(await data.Body.transformToByteArray()).toString(
			'base64',
		)
	} catch (error: any) {
		console.log(`F : binaryEncoding Error - `, error)
		throw new Error(error)
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant