Swagger 문서 접근 권한
안녕하세요 Swagger UI의 경우 실제 서비스를 배포했을 때, 일반 유저는 /documentation에 접근하지 못 하도록 설정할 수 있나요? 내부 개발자들만 볼 수 있도록 접근 권한을 막는 방법이 있는지 궁금합니다.
감사합니다.
답변 1
0
swagger에 비밀번호를 적용하는 방법으로 basic-auth라는 것을 이용하는 방법이 있습니다.
설정에 관하여 간단하게 설명을 드리도록 하겠습니다.
우선 fastify/basic-auth를 다음과 같이 설치해 주시기 바랍니다.
참고로 강좌의 fastify버전의 경우 v4버전이기 때문에 basic-auth는 5버전을 사용하셔야 합니다.
npm i @fastify/basic-auth@5
다음으로 main.ts를 열고 필요한 설정을 해야 합니다 .
fastify에서 필요한 FastifyRequest, FastifyReply, HookHandlerDoneFunction을 불러오고
여기에 설치한 BasicAuth를 가져와 줍니다.
여기에 validate함수를 만들고 여기에서 아이디, 패스워드를 확인하도록 설정합니다
다음으로 register로 basicAuth를 등록하고 validate 함수를 연동해 줍니다.
이제 addHook에 onRequest를 설정하고
접근하는 url이 documentation일 경우 이 basic-auth가 작동하게 만들면 되겠습니다.
여기서 주의할 점으로 기존 예제와 달리 main.ts에서 register로 각종 플러그인을 등록할 경우 await을 사용해야 한다는 것입니다.
이부분을 유의해서 사용해 보시기 바랍니다.
main.ts
import Fastify from 'fastify'
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox'
import type { FastifyCookieOptions } from '@fastify/cookie'
import fasstifyCookie from '@fastify/cookie'
import routes from './routes'
import { SECRET_KEY } from './lib/constants'
import { currentlyAuthPlugin } from './plugin/authPlugin'
import { checkStartupUser, checkStartupArticle } from './startup'
import cors from '@fastify/cors'
import fastifySwagger from '@fastify/swagger'
import fastifySwaggerUi from '@fastify/swagger-ui'
import { swaggerConfig, swaggerUiConfig } from './config/swagger'
//추가코드
import { FastifyRequest, FastifyReply, HookHandlerDoneFunction } from 'fastify'
import BasicAuth from '@fastify/basic-auth';
const fastify = Fastify({
logger: true,
// https: {
// key: fs.readFileSync('./server.key'),
// cert: fs.readFileSync('./server.crt'),
// }
}).withTypeProvider<TypeBoxTypeProvider>()
// fastify.get('/ping', async (request, reply) => {
// return 'pong\n'
// })
// 각 register등록시 await 사용
await fastify.register(cors, {
origin: true, // Access-Control-Allow-Origin
credentials: true, //Access-Control-Allow-Credentials
})
await fastify.register(fastifySwagger, swaggerConfig)
await fastify.register(fastifySwaggerUi, swaggerUiConfig)
await fastify.register(fasstifyCookie, {
secret: SECRET_KEY,
} as FastifyCookieOptions )
await fastify.register(currentlyAuthPlugin)
await fastify.register(routes)
// basic-auth with swagger 추가 코드
const authenticate = {realm: 'Westeros'}
await fastify.register(BasicAuth, {validate, authenticate})
function validate (username:string, password:string, req:FastifyRequest, reply:FastifyReply, done:HookHandlerDoneFunction) {
if (username === 'admin' && password === '1111') {
done()
} else {
done(new Error('Winter is coming'))
}
}
fastify.addHook("onRequest", (req:FastifyRequest, res:FastifyReply, done:HookHandlerDoneFunction) => {
if (req.url.startsWith(`/documentation`)) {
fastify.basicAuth(req, res, done);
} else {
done();
}
})
const start = async () => {
try {
await checkStartupUser()
await checkStartupArticle()
await fastify.listen({port: 8083})
console.log(`Server Start!!`)
}
catch(error) {
fastify.log.error(error)
process.exit(1)
}
}
start()
코드 공유
0
80
1
prisma 버전 변경
0
125
2
추가 강의 요청?
0
65
1
@Controller 요청하는 방식에 대해 궁금합니다.
1
61
2
저는 맥북인데 이건 그냥 윈도우용으로만 수업하시네요
0
53
1
prisma migrate 오류
0
179
3
Swagger 강의, Unable to infer base url 이거 뜨시는 분들 도움되시라고
0
118
1
H2 접속 에러
0
142
3
401 not expired token 에러 메세지는 언제 쓰이나요?
0
266
2
item을 id로 get하는데 1을 넣었을 때 500에러가 나와요.
0
102
1
swagger spring boot 3 적용 run 실행 에러
0
257
2
앱에 refreshToken을 전송할때 궁금한점이 있습니다.
0
329
2
배포-ubuntu에서 문제
0
243
1
openssl 설치후 적용 안되요
0
357
1
comment 기능
0
193
1
섹션 5 login 인증 기능
0
332
2
Prisma 환경 설정 질문있어요!
0
247
2
Invalid bound statement (not found): com.helloword.fitstStart.mapper.QuickMapper.findById 에 대한 질의 입니다.
0
559
1
QuickMapper를 찾을 수 없다는 오류가 뜹니다. @Autowired 사용에 문제가 있는 걸까요?
2
382
3
TypeError 관련하여 문의드립니다.
0
293
1
똑같이 따라하고 오류나서 다시해보고 다시해보고 올려주신 코드 확인해봐도 계속 에러가 뜨는대요 ㅠ.ㅠ
0
800
1
mybatis의 hashmap 데이터 호출시 대문자로 불러와야 되나요?
0
526
1
강좌의 샘플 프로젝트 파일을 올려주시면 좋을 것 같아요.
0
557
2
@Autowired 관련
0
265
1





