사용자를 식별하고 인증하기 위해 사용되는 정보
서버로 보내는 요청 헤더에 자신의 정보를 보냄
사용자 정보를 Base64로 인코딩하여 HTTP 요청 헤더에 포함시킴

| 단계 | 헤더 | 설명 | method/status |
|---|---|---|---|
| 요청 | - 첫 번째 요청에는 인증 정보가 없음 | GET | |
| 인증 요구 | https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate | - 서버는 사용자에게 사용자 이름과 비밀번호를 제공하라는 의미로 401 상태 정보와 함께 요청을 반려 - 서버는 WWW-Authenticate 헤더에 해당 영역을 설명해 놓음 | 401 Unauthorized |
| 인증 | https://developer.mozilla.org/ko/docs/Web/HTTP/Headers/Authorization | - 클라이언트는 요청을 다시 보냄 - 사용자 이름과 비밀번호를 나타낸 Authorization 헤더를 함께 보냄 | GET |
| 성공 | Authentication-Info | - 인증 정보가 정확하면 서버는 성공 응답 - Authentication-info 헤더에 추가 정보를 기술해서 응답하기도 함 | 200 OK |
Authorization: <type> <credentials>
type
인증 타입을 의미, 보통 “Basic” 사용
credentials
“Basic” 인증을 사용했다면 증명은 다음과 같이 만들어짐
if) 사용자명과 비밀번호를 사용한다면
aladdin:opensesameYWxhZGRpbjpvcGVuc2VzYW1lconst email = document.getElementById("email").value;
const password = document.getElementById("password").value;
**//btoa: 문자열을 Base64로 인코딩**
const basicAuth = `Basic ${btoa(email:password)}`;
**//첫번째 GET**
(async() => {
const firstResponse = fetch("http://localhost:8000/api/user/login");
const firstData = await firstResponse.json();
})();
**//두번째 GET -> 이때 유저 정보가 포함됨**
button.addEventListener("click", () => {
const response = await fetch("http://localhost:80880/api/user/login", {
headers: {
'Authorization': basicAuth
}
}
const data= await logIn.json();
//이후 로직
//로그인 성공이면 화면 전환, 실패면 helper text or alert
)
//user-controller.js
router.get("/login", (req, res) => {
const authHeader = req.headers['authorization']; //authHeader = "Basic asdkjasdlkas="
const auth = auth.split(' ')[1]; //auth = 'asdkjasdlkas'
//사용자가 처음 페이지를 들어와서 authHeader가 없는 경우
if(!authHeader) {
res.set('WWW-Authenticate', 'Basic realm="Please enter your username and password"');
res.status(401).send('Authentication required');
}
//로그인 버튼등을 클릭해서 사용자 정보가 authHeader에 있는 경우
if (authHeader) {
const auth = authHeader.split(' ')[1]
const [email, password] = Buffer.from(auth, 'base64).toString().split(':');
// 유저 찾기
const user = users.find(user => user.email=== email && user.password === password);
//해당 유저가 없는 경우
if(!user) {
res.set('WWW-Authenticate', 'Basic realm="Please enter your username and password"');
res.status(401).send('Authentication failed');
}
//해당 유저가 있는 경우
res.status(200).json({status: 200, message: "", data: ~});
}
})
웹 표준으로 정의된 액세스 토큰을 전송하기 위한 방식
⇒ 사용자의 세션 상태를 유지하거나 사용자 인증에 사용

const token = 'JWT 토큰';
fetch("주소", {
headers: {
'Authorization': `Bearer ${token}`
}
}).then (responese => {
//이후 로직
})//토큰 검증
jwt.verify(token.split(' ')[1], secretKey, (err, decoded) => {
if (err) {
res.sendStatus(403);
else {
req.decoded = decoded;
next();
}
});//토큰 생성
const token = jwt.sign({ username }, secretKey, { expiresIn: '1h' });
res.json({ token });참고 문헌