401

Unauthorized

개요

401 Unauthorized는 인증이 필요한데 자격 증명이 없거나 잘못되어 요청이 거부되었음을 뜻합니다. 이름은 "Unauthorized"지만 실제 의미는 "인증되지 않음(unauthenticated)"으로, 서버가 요청자의 신원을 확인하지 못한 상태입니다.

규격상 401 응답에는 어떤 인증 방식을 써야 하는지 알리는 WWW-Authenticate 헤더가 포함되어야 합니다. 올바른 자격 증명을 갖춰 다시 인증하면 접근할 수 있는 여지가 있다는 점에서, 재인증으로 해결되지 않는 403과 구분됩니다.

언제 발생하나

요청 / 응답 예시

요청
GET /api/me HTTP/1.1
Host: api.example.com
Authorization: Bearer expired.token.here
응답
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api", error="invalid_token"
Content-Type: application/json

{"error":"invalid_token","message":"Access token has expired"}

코드로 보기

app.use('/api', (req, res, next) => {
  const token = req.headers.authorization;
  if (!isValid(token))
    return res.status(401).set('WWW-Authenticate', 'Bearer').json({ error: 'invalid_token' });
  next();
});
curl -i https://api.example.com/api/me
# -> 401 Unauthorized  (add: -H 'Authorization: Bearer <token>')

흔한 원인

해결 방법

실무 참고

관련 상태코드

관련 헤더

스펙 근거