Authorization Code Grant - 권한 부여 코드 승인

+----------+
| Resource |
|   Owner  |
|          |
+----------+
     ^
     |
    (B)
+----|-----+          Client Identifier      +---------------+
|         -+----(A)-- & Redirection URI ---->|               |
|  User-   |                                 | Authorization |
|  Agent  -+----(B)-- User authenticates --->|     Server    |
|          |                                 |               |
|         -+----(C)-- Authorization Code ---<|               |
+-|----|---+                                 +---------------+
  |    |                                         ^      v
 (A)  (C)                                        |      |
  |    |                                         |      |
  ^    v                                         |      |
+---------+                                      |      |
|         |>---(D)-- Authorization Code ---------'      |
|  Client |          & Redirection URI                  |
|         |                                             |
|         |<---(E)----- Access Token -------------------'
+---------+       (w/ Optional Refresh Token)

Note: The lines illustrating steps (A), (B), and (C) are broken into
two parts as they pass through the user-agent.

                 Figure 3: Authorization Code Flow

https://tools.ietf.org/html/rfc6749#section-4.1

용어 정의

OAuth defines four roles:

resource owner
  An entity capable of granting access to a protected resource.
  When the resource owner is a person, it is referred to as an
  end-user.

resource server
  The server hosting the protected resources, capable of accepting
  and responding to protected resource requests using access tokens.

client
  An application making protected resource requests on behalf of the
  resource owner and with its authorization.  The term "client" does
  not imply any particular implementation characteristics (e.g.,
  whether the application executes on a server, a desktop, or other
  devices).

authorization server
  The server issuing access tokens to the client after successfully
  authenticating the resource owner and obtaining authorization.

The interaction between the authorization server and resource server
is beyond the scope of this specification.  The authorization server
may be the same server as the resource server or a separate entity.
A single authorization server may issue access tokens accepted by
multiple resource servers.

https://tools.ietf.org/html/rfc6749#section-1.1

  • Authentication : 인증
  • Authorization : 허가

  • protected resource : resource server에 저장된 보호된 resource owner의 자원
  • resource owner : 사용자
  • resource server : access_token을 검사하여 resource owner의 자원을 제공
  • client : 3rd party application
  • authorization server : 인증 서버, client를 인증하여 access_token을 발급 한다.

(A) 인증 코드 요청

GET /auth
    ?response_type=code
    &client_id=clientcodendkendlwe
    &state={Some State Code}
    &redirect_uri=https://client.redirect.uri
    &scope=create+delete
Host: server.example.com

rfc6749에는 다음이 필수임을 명시하고 있습니다.

 The client constructs the request URI by adding the following
   parameters to the query component of the authorization endpoint URI
   using the "application/x-www-form-urlencoded" format, per Appendix B:

   response_type
         REQUIRED.  Value MUST be set to "code".

   client_id
         REQUIRED.  The client identifier as described in Section 2.2.

   redirect_uri
         OPTIONAL.  As described in Section 3.1.2.
   scope
         OPTIONAL.  The scope of the access request as described by
   state
         RECOMMENDED.  An opaque value used by the client to maintain
         state between the request and callback.  The authorization
         server includes this value when redirecting the user-agent back
         to the client.  The parameter SHOULD be used for preventing
         cross-site request forgery as described in Section 10.12.

https://tools.ietf.org/html/rfc6749#section-4.1.1

필수

  • response_type : app이 Authorization Code 인증을 시작하고 있음을 OAuth 서버에 알립니다. Authorization Code Grantcode로 설정해야 합니다.
  • client_id : OAuth서버에 등록된 클라이언트들의 식별자 입니다. OAuth 서버에 사전에 등록한 client_id를 입력합니다.

옵션

아래 옵션은 OAuth서버에 따라 필수로 요구할 수 있습니다.

  • redirect_uri : 요청을 승인 한 후 code를 보낼 client 주소를 입력합니다.
  • state : 서버에 보내는 임의의 값입니다. 서버는 이를 응답시 state값에 넣어줍니다. CSRF를 막는데 사용합니다.
  • scope : client의 허용할 권한 범위입니다.

(B) 유저 인증

resource owner를 인증합니다. 예를 들면, 카카오톡으로 로그인 하기가 있습니다.

(C) - 1 정상적인 코드 응답

code
     REQUIRED.  The authorization code generated by the
     authorization server.  The authorization code MUST expire
     shortly after it is issued to mitigate the risk of leaks.  A
     maximum authorization code lifetime of 10 minutes is
     RECOMMENDED.  The client MUST NOT use the authorization code
     more than once.  If an authorization code is used more than
     once, the authorization server MUST deny the request and SHOULD
     revoke (when possible) all tokens previously issued based on
     that authorization code.  The authorization code is bound to
     the client identifier and redirection URI.

state
     REQUIRED if the "state" parameter was present in the client
     authorization request.  The exact value received from the
     client.

https://tools.ietf.org/html/rfc6749#section-4.1.2

HTTP/1.1 302 Found
Location: https://client.redirect.uri
          ?code={Some Auth Code}
          &state={Some State Code}

필수

  • code : codetoken으로 교환합니다. code는 짧은시간 내 만료되고 1회만 사용됩니다.

옵션

  • state : 요청시 전달한 state

서버에 따라 다르지만 보통 302Redirect로 코드와 state를 전달합니다.

(C) - 2 코드 응답 오류

4.1.2.1.  Error Response

If the request fails due to a missing, invalid, or mismatching
redirection URI, or if the client identifier is missing or invalid,
the authorization server SHOULD inform the resource owner of the
error and MUST NOT automatically redirect the user-agent to the
invalid redirection URI.

If the resource owner denies the access request or if the request
fails for reasons other than a missing or invalid redirection URI,
the authorization server informs the client by adding the following
parameters to the query component of the redirection URI using the
"application/x-www-form-urlencoded" format, per Appendix B:

error
REQUIRED.  A single ASCII [USASCII] error code from the
following:
    invalid_request
        The request is missing a required parameter, includes an
        invalid parameter value, includes a parameter more than
        once, or is otherwise malformed.
    unauthorized_client
        The client is not authorized to request an authorization
        code using this method.

    access_denied
        The resource owner or authorization server denied the
        request.

    unsupported_response_type
        The authorization server does not support obtaining an
        authorization code using this method.

    invalid_scope
        The requested scope is invalid, unknown, or malformed.

    server_error
        The authorization server encountered an unexpected
        condition that prevented it from fulfilling the request.
        (This error code is needed because a 500 Internal Server
        Error HTTP status code cannot be returned to the client
        via an HTTP redirect.)

    temporarily_unavailable
        The authorization server is currently unable to handle
        the request due to a temporary overloading or maintenance
        of the server.  (This error code is needed because a 503
        Service Unavailable HTTP status code cannot be returned
        to the client via an HTTP redirect.)

Values for the "error" parameter MUST NOT include characters
outside the set %x20-21 / %x23-5B / %x5D-7E.

error_description
        OPTIONAL.  Human-readable ASCII [USASCII] text providing
        additional information, used to assist the client developer in
        understanding the error that occurred.
        Values for the "error_description" parameter MUST NOT include
        characters outside the set %x20-21 / %x23-5B / %x5D-7E.

error_uri
        OPTIONAL.  A URI identifying a human-readable web page with
        information about the error, used to provide the client
        developer with additional information about the error.
        Values for the "error_uri" parameter MUST conform to the
        URI-reference syntax and thus MUST NOT include characters
        outside the set %x21 / %x23-5B / %x5D-7E.
state
        REQUIRED if a "state" parameter was present in the client
        authorization request.  The exact value received from the
        client.

For example, the authorization server redirects the user-agent by
sending the following HTTP response:

HTTP/1.1 302 Found
Location: https://client.example.com/cb?error=access_denied&state=xyz

https://tools.ietf.org/html/rfc6749#section-4.1.2.1

필수

  • error : 에러타입
    • invalid_request : 요청 값이 없거나 잘못됨
    • unauthorized_client : 권한 없거나 등록되지 않은 `client
    • access_denied : 권한 없음 등으로 resource owner 혹은 client 접근 거부
    • unsupported_response_type : 잘못되거나 지원하지 않는 type
    • invalid_scope : 잘못된 scope
    • server_error : 서버 오류
    • temporarily_unavailable : 일시적으로 사용할 수 없음

옵션

  • error_description : 오류 설명
  • error_uri : 에러 정보 제공 사이트
  • state : 요청시 입력한 state
HTTP/1.1 302 Found
Location: https://client.redirect.uri
          ?error=access_denied
          &state={Some State Code}
          &error_description=권한이 없습니다.

(D) 토큰 요청

The client makes a request to the token endpoint by sending the
following parameters using the "application/x-www-form-urlencoded"
format per Appendix B with a character encoding of UTF-8 in the HTTP
request entity-body:

grant_type
        REQUIRED.  Value MUST be set to "authorization_code".

code
        REQUIRED.  The authorization code received from the
        authorization server.

redirect_uri
        REQUIRED, if the "redirect_uri" parameter was included in the
        authorization request as described in Section 4.1.1, and their
        values MUST be identical.

client_id
        REQUIRED, if the client is not authenticating with the
        authorization server as described in Section 3.2.1.

If the client type is confidential or the client was issued client
credentials (or assigned other authentication requirements), the
client MUST authenticate with the authorization server as described
in Section 3.2.1.
For example, the client makes the following HTTP request using TLS
(with extra line breaks for display purposes only):

    POST /token HTTP/1.1
    Host: server.example.com
    Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
    Content-Type: application/x-www-form-urlencoded

    grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
    &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb

필수

  • grant_type : authorization_code를 사용함을 명시, authorization_code로 설정
  • code : 응답 받은 code
  • redirect_uri : code를 요청할 때 사용한 redirect_uri

옵션

  • client_id : code를 요청할 때 사용한 client_id

OAuth 서버는 code를 받아 access_token으로 교환해줍니다.

POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic {Some Token Auth Code - Option}
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb

(E) - 1 정상적인 토큰 응답

OAuth 서버는 다음처럼 토큰을 응답합니다.

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache

{
    "access_token":"2YotnFZFEjr1zCsicMWpAA",
    "token_type":"bearer",
    "expires_in":3600,
    "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
    "scope":"create delete"
}

필수

  • access_token : resource_server에 사용할 토큰
  • expires_in : 토큰 만료 시간 초단위

옵션

  • token_type : 토큰 타입
  • refresh_token : access_token 재발급 시 사용할 토큰
  • scope : 권한 범위

토큰 응답 시 캐시에 토큰이 남는 것을 방지 하기 위해 해더에 다음을 추가해야 합니다.

Cache-Control: no-store
Pragma: no-cache

(E) - 2 토큰 응답 오류

error
    REQUIRED.  A single ASCII [USASCII] error code from the
    following:

    invalid_request
        The request is missing a required parameter, includes an
        unsupported parameter value (other than grant type),
        repeats a parameter, includes multiple credentials,
        utilizes more than one mechanism for authenticating the
        client, or is otherwise malformed.

    invalid_client
        Client authentication failed (e.g., unknown client, no
        client authentication included, or unsupported
        authentication method).  The authorization server MAY
        return an HTTP 401 (Unauthorized) status code to indicate
        which HTTP authentication schemes are supported.  If the
        client attempted to authenticate via the "Authorization"
        request header field, the authorization server MUST
        respond with an HTTP 401 (Unauthorized) status code and
        include the "WWW-Authenticate" response header field
        matching the authentication scheme used by the client.

    invalid_grant
        The provided authorization grant (e.g., authorization
        code, resource owner credentials) or refresh token is
        invalid, expired, revoked, does not match the redirection
        URI used in the authorization request, or was issued to
        another client.

    unauthorized_client
        The authenticated client is not authorized to use this
        authorization grant type.

    unsupported_grant_type
        The authorization grant type is not supported by the
        authorization server.
                invalid_scope
        The requested scope is invalid, unknown, malformed, or
        exceeds the scope granted by the resource owner.

    Values for the "error" parameter MUST NOT include characters
    outside the set %x20-21 / %x23-5B / %x5D-7E.

error_description
    OPTIONAL.  Human-readable ASCII [USASCII] text providing
    additional information, used to assist the client developer in
    understanding the error that occurred.
    Values for the "error_description" parameter MUST NOT include
    characters outside the set %x20-21 / %x23-5B / %x5D-7E.

error_uri
    OPTIONAL.  A URI identifying a human-readable web page with
    information about the error, used to provide the client
    developer with additional information about the error.
    Values for the "error_uri" parameter MUST conform to the
    URI-reference syntax and thus MUST NOT include characters
    outside the set %x21 / %x23-5B / %x5D-7E.

The parameters are included in the entity-body of the HTTP response
using the "application/json" media type as defined by [RFC4627].  The
parameters are serialized into a JSON structure by adding each
parameter at the highest structure level.  Parameter names and string
values are included as JSON strings.  Numerical values are included
as JSON numbers.  The order of parameters does not matter and can
vary.

https://tools.ietf.org/html/rfc6749#section-5.2

필수

  • error : 에러 타입
    • invalid_request : 요청 값이 없거나 잘못됨
    • invalid_client : 권한 없거나 등록되지 않은 client
    • invalid_grant : 잘못된, 칸료된 코드
    • unauthorized_client : 권한 없거나 등록되지 않은 client
    • unsupported_grant_type : 지원하지 않는 권한 부여 타입

옵션

  • error_description : 오류 설명
  • error_uri : 오류 설명 링크
HTTP/1.1 400 Bad Request
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache

{
    "error":"invalid_request"
}