반응형
250x250
Notice
Recent Posts
Recent Comments
Link
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Archives
Today
Total
관리 메뉴

가끔 보자, 하늘.

Sign in my_serivce 구축하기 1/2 본문

개발 이야기/개발 및 서비스

Sign in my_serivce 구축하기 1/2

가온아 2023. 2. 27. 18:13

OAuth 서비스 만들기에 앞서..  Before creating an OAuth service... 

OAuth는 타사 애플리케이션이 자격 증명을 노출하지 않고 다른 서비스에서 사용자의 데이터에 액세스할 수 있도록 하는 인증을 위한 공개 표준입니다. 간단히 말해서 사용자는 로그인 자격 증명을 공유하지 않고도 한 웹사이트나 앱에 저장된 정보에 대한 액세스 권한을 다른 웹사이트나 앱에 부여할 수 있습니다. OAuth is an open standard for authentication that allows third-party applications to access your data from other services without exposing your credentials. Simply put, it allows users to grant access to information stored on one website or app to another without sharing their login credentials.

이 글에서는 고유한 OAuth 서비스를 만드는 데 필요한 단계를 살펴보겠습니다. 인증 엔드포인트, 액세스 토큰 및 범위와 같은 OAuth 프로토콜 및 해당 구성 요소를 설명하는 것으로 시작하겠습니다. 그런 다음 서버 설정, API 개발 및 데이터베이스 스키마 디자인과 같은 주제를 다루는 기술 구현 세부 사항에 대해 자세히 살펴보겠습니다. In this article, we'll walk through the steps required to create your own OAuth service. We'll start by describing the OAuth protocol and its components, such as authentication endpoints, access tokens, and scopes. Then we'll dive into the technical implementation details, covering topics like server setup, API development, and database schema design. 

자신만의 OAuth 서비스를 만드는 것은 쉬운 일이 아니지만 많은 이점이 있습니다. 사용자의 데이터와 인증을 완벽하게 제어할 수 있으며 정확한 필요에 맞게 서비스를 사용자 정의할 수 있습니다. 또한 OAuth 프로토콜과 이를 구현하는 데 관련된 보안 고려 사항에 대해 더 깊이 이해할 수 있습니다. Creating your own OAuth service isn't easy, but it has many benefits. You have complete control over your users' data and authentication, and you can customize the service to meet your exact needs. You also gain a deeper understanding of the OAuth protocol and the security considerations involved in implementing it. 

 

오픈소스로 구축해보기  Build with open source

이제 우리만의 OAuth 서비스를 만들어 봅시다! 물론 이 글은 개발 절차를 이해하고 샘플 서비스를 구축하는 것이 목적이기 때문에 오픈 소스로 공개된 클래식한 샘플 프로젝트를 활용해 보겠습니다. Now let's create our own OAuth service! Of course, the goal of this article is to understand the development process and build a sample service, so we'll use a classic, open-sourced sample project.

oauth-example 프로젝트는 node-oauth2-server를 포함하고 있으므로 따로 설치할 필요는 없습니다. 적절한 위치에 프로젝트를 복제하세요. The oauth-example project includes node-oauth2-server, so you don't need to install it separately. Clone the project to an appropriate location.

git clone https://github.com/14gasher/oauth-example.git

이제 기본적인 준비는 되었습니다. 샘플을 실행해 보기 전에 잠시 OAuth에 대한 기본 내용을 간단히 알아보고 다음으로 넘어가겠습니다.

OAuth 의 흐름 알아보기  Learn about OAuth flow

더 진행하기 전에 OAuth 의 흐름을 간단히 정리하고 이 샘플에서 어떻게 구현되어 있는지 살펴보겠습니다. 우선 OAuth의 흐름을 간단히 정리하면 아래와 같습니다.Before we go any further, let's briefly summarize the flow of OAuth and see how it's implemented in this sample. First, let's briefly summarize the flow of OAuth.

(RFC 6749 - 4.1 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)

RFC 6749에는 승인 절차의 종류를 Authorization Code Grant, Implicit Grant, Resource Owner Password Credentials Grant, Client Credentials Grant로 구분하여 정리했습니다. 이에 대한 상세한 내용은 여기서 언급하지는 않겠습니다. 이 글에서는 웹과 앱 인증에 주로 사용하는 Authorization Code Grant에 대해서만 알아보겠습니다. RFC 6749 categorizes the types of authorization processes into Authorization Code Grant, Implicit Grant, Resource Owner Password Credentials Grant, and Client Credentials Grant. We won't go into the details of each of these here; for this article, we'll focus on Authorization Code Grant, which is commonly used for web and app authentication.

위 표에서 언급된 주요 참여자에 대한 설명은 간단히 아래 표로 정리합니다. The table below briefly summarizes the key players mentioned in the table above. 

  • Resource Owner : 자원의 소유자로 실질적인 사용자를 말합니다. The owner of the resource is the actual user.
  • Authorization Server : Resource Owner의 자원을 보유하고 있으며 Client가 Resource Owner의 계정 정보에 접근하기 위해 권한을 요청할 때, 인증 과정을 수행하고 Access Token을 발급합니다. When you own a Resource Owner's resource and a Client requests permission to access the Resource Owner's account information, you perform an authentication process and issue an Access Token.
  • Client : Resource Server에 접속해 정보를 가져와 이를 소비하는 객체입니다. 여러분이 사용하는 웹 서버 혹은 앱을 예로 들 수 있습니다. An object that connects to a Resource Server to get information and consume it. An example is a web server or app you use.
  • User Agent : 로그인 페이지를 열고, 사용자가 로그인 정보를 입력하고 인증을 완료하면 Authorization Server에서 AuthorizationCode를 발급받아 Client에게 전달합니다. Opens a login page, and when the user enters their login information and completes authentication, the Authorization Server obtains an authorization code and passes it to the client. 

샘플 프로젝트를 실행하며 RFC 6749의 표를 비교하기 Running the sample project and comparing the tables in RFC 6749 

아래 내용은 https://www.rfc-editor.org/rfc/rfc6749#section-4.1 의 내용을 참고하여 생략된 부분을 추가하여 작성했으니 원본링큰의 내용도 꼭 한 번 읽어보시기 바랍니다. The following is adapted from https://www.rfc-editor.org/rfc/rfc6749#section-4.1 with some omissions, so be sure to read the original link as well.
위 RFC 6749의 diagram의 순서는 모든 흐름을 기록하기 힘들기 때문에 간략하게 정리되어 있습니다. The order of the diagram in RFC 6749 above is simplified because it would be difficult to record all the flows. 

샘플 실행을 위해 위에서 복제했던 프로젝트의 패키지를 설치 후 실행을 해봅니다. For a sample run, install and run the package from the project we cloned above. 

> npm install
> npm run devAuth

이제 접속해 봅니다. 이 프로젝트는 로그인 화면 샘플도 같이 제공하고 있습니다. And now let's connect. The project also comes with a login page sample.

 

이 화면은 Resource Owner[사용자]가 Client[서비스]에 접속한 상태라고 할 수 있으며 아직 User Agent[로그인 창]을 호출하지 않은 상태입니다. In this screen, the Resource Owner [user] is connected to the Client [service] and has not yet invoked the User Agent [login window]. 

"Login with Oauth Server" 버튼을 누르면 위 다이어그램의 (A)가 진행됩니다. 이때 Client는 User Agent에게 client identifier, requested scope, redirection URI 등을 전달합니다.  When the "Login with Oauth Server" button is pressed, part (A) of the above diagram proceeds. At this time, the Client passes the client identifier, requested scope and redirection URI, etc. to the User Agent. 

Resource Owner[사용자]가 Client[서비스]에 접속하여 로그인을 시도합니다. User Agent는 유저에게 인증 정보를 입력받아 Authorization Server로 전달합니다. 위 다어이그램의 (B)가 진행되죠. 인증 정보를 확인 후 Authorization Server는 Authorization Code를 발급(C)합니다. 결과는 아래 화면과 같습니다. A Resource Owner [user] connects to the Client [service] and tries to sign in. The User Agent receives authentication information from the user and passes it to the Authorization Server. After verifying the credentials, the Authorization Server issues an Authorization Code(C). The result is shown in the screen below. 

Authorization Code는 임시 발급된 값으로 유효시간이 상당히 짧습니다. Resource Owner가 개입하지 않고 Authorization Code를 받은 Client 는 즉시 Authorization Server에게 최종 목적인 Access Token을 요청(D)하게 됩니다. The Authorization Code is a temporary value and has a fairly short validity. Without intervention from the Resource Owner, the Client that receives the Authorization Code will immediately request an Access Token from the Authorization Server(D), which is the final objective.

이 예제에서는 이 과정을 확인할 수 있게 분리했으며 그 결과로 위와 같은 화면을 볼 수 있습니다. redirect uri는 backend에서 받아서 처리할 수도 있고, frontend에서 받아서 처리할 수도 있습니다. frontend에서 받아서 처리하는 경우에는 PKCE와 CORS를 지원하는 redirect uri를 추가해야 합니다. 하지만, 가능하면 backend에서 redirect uri를 처리하는 것이 좋습니다. In this example, we've isolated this process so that we can see it, and as a result, you should see a screen like the one above. Redirect URIs can be received and processed in the backend, or they can be received and processed in the frontend. If the frontend receives and processes redirects, you'll need to add support for PKCE and CORS. However, it's best to handle redirects in the backend if possible. 

"Get Token From Code" 버튼을 눌러 (D)의 과정을 수동으로 진행시킬 수 있으며 정상적이라면 아래 "Token :" 과 "Refresh Token :" 텍스트 옆에 발급된 최종 Access Token 과 Refresh Token 값을 확인할 수 있습니다.  You can manually go through the process in (D) by pressing the "Get Token From Code" button and if all goes well, you should see the final Access Token and Refresh Token values issued next to the "Token :" and "Refresh Token :" text below. 

사용된 node-oauth2-server와 oauth-example 코드가 깔끔하게 잘 정리되어 있어 이 예제를 분석하는 것만으로도 직접 서비스를 구현하는데 큰 어려움은 없을 겁니다. The node-oauth2-server and oauth-example code used is neatly organized, so you shouldn't have much trouble implementing the service yourself just by analyzing this example. 

하지만 실질적인 서비스를 구축하기 위해서는 많은 과정들이 남아 있습니다. But there's still a lot of work to be done to build a real service. 

Resource Owner의 정보를 관리할 DB를 구축/연동해야 하며 여러 서비스에서 사용할 수 있도록 Client Id/ Secret을 등록, 관리해야 합니다. 또한 유저들이 자신의 정보를 어떻게 제공해야 할지도 결정할 수 있도록 해야 하죠. You need to build/connect a DB to manage resource owner's information, register and manage client id/secret for use in multiple services, and let users decide how to provide their information. 

만약 여러분이 자신의 서비스를 구축할 예정이라면 다음 글도 도움이 될 것이라 생각되네요. 도움이 되셨기를... ^^   If you're looking to build your own service , you might also find the following article helpful. I hope you enjoyed this article!  :)

반응형