Microsoft MVP성태의 닷넷 이야기
.NET Framework: 800. C# - Azure REST API 사용을 위한 인증 획득 [링크 복사], [링크+제목 복사]
조회: 12884
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

C# - Azure REST API 사용을 위한 인증 획득

지난 글에서,

C# - API를 사용해 Azure에 접근하는 방법
; https://www.sysnet.pe.kr/2/0/11480

이미 잘 만들어진 Azure 라이브러리를 이용한 Azure 서비스 제어를 해봤는데요. 마지막에 REST API를 위한 인증 및 사용법을 설명했지만, 아예 그걸 떼어내서 별도의 글로 정리를 합니다. ^^ 물론, 관련해서는 이미 마이크로소프트의 공식 문서에 다음과 같이 잘 설명하고 있습니다.

Authorize access to Azure Active Directory web applications using the OAuth 2.0 code grant flow
; https://docs.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code#request-an-authorization-code

OAuth 2.0 코드 권한 부여 흐름을 사용하여 Azure Active Directory 웹 응용 프로그램에 대한 액세스 권한 부여
; https://docs.microsoft.com/ko-kr/azure/active-directory/develop/v1-protocols-oauth-code#request-an-authorization-code

그래도 ^^ 좀 더 간단하게 정리를 해봤으니 참고가 되실 것입니다.




"Authorize access to Azure Active Directory web applications using the OAuth 2.0 code grant flow" 문서를 보면, 우리가 구해야 할 값은 결국 Azure REST API를 호출할 때마다 함께 전달될 "Authorization: Bearer ...access_token..." 값입니다. 이를 위해 필요한 것은 우선 지난 글에서 설명한,

C# - API를 사용해 Azure에 접근하는 방법
; https://www.sysnet.pe.kr/2/0/11480

IAM 계정입니다. 따라서, Azure CLI를 이용해 다음과 같이,

C:\WINDOWS\system32>az login
Note, we have launched a browser for you to login. For old experience with device code, use "az login --use-device-code"
You have logged in. Now let us find all the subscriptions to which you have access...
[
  {
    "cloudName": "AzureCloud",
    "id": "9757c718-3140-4b9b-b9f9-84ff080353b3",
    "isDefault": true,
    "name": "TestSubs",
    "state": "Enabled",
    "tenantId": "8fcc7edc-6fc9-4b63-ba94-93f2d8584b96",
    "user": {
      "name": "tester@tester.com",
      "type": "user"
    }
  }
]

C:\WINDOWS\system32>az ad sp create-for-rbac --sdk-auth
Retrying role assignment creation: 1/36
Retrying role assignment creation: 2/36
{
  "clientId": "20304878-9518-4506-aea3-a06caae4d55f",
  "clientSecret": "5590caf5-125e-4950-9fe3-9dea908a1059",
  "subscriptionId": "9757c718-3140-4b9b-b9f9-84ff080353b3",
  "tenantId": "8fcc7edc-6fc9-4b63-ba94-93f2d8584b96",
  "activeDirectoryEndpointUrl": "https://login.microsoftonline.com",
  "resourceManagerEndpointUrl": "https://management.azure.com/",
  "activeDirectoryGraphResourceId": "https://graph.windows.net/",
  "sqlManagementEndpointUrl": "https://management.core.windows.net:8443/",
  "galleryEndpointUrl": "https://gallery.azure.com/",
  "managementEndpointUrl": "https://management.core.windows.net/"
}
(위의 'az ad sp ...' 명령어로 생성된 계정은 https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps 경로에서 확인할 수 있습니다.)

"az ad ..." 명령어의 결과로 출력된 인증 정보를 C# 소스 코드에 붙여 넣습니다.

using System.IO;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static async Task Main(string[] args)
        {
            AzureRestClient client = new AzureRestClient();

            string authData = "...[json text]...";
            await client.Login(authData);

            return 0;
        }
    }
}

using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class AzureRestClient
    {
        HttpClient _client;
        string _subscriptionId;
        string _apiVersion = "2017-12-01";

        public AzureRestClient()
        {
            _client = new HttpClient();
        }

        public async Task<bool> Login(string authData)
        {
            AuthInfo authInfo = JsonConvert.DeserializeObject<AuthInfo>(authData);
            if (authInfo == null)
            {
                return false;
            }
        }
    }
}

public class AuthInfo
{
    public string clientId { get; set; }
    public string clientSecret { get; set; }
    public string subscriptionId { get; set; }
    public string tenantId { get; set; }
    public string activeDirectoryEndpointUrl { get; set; }
    public string resourceManagerEndpointUrl { get; set; }
    public string activeDirectoryGraphResourceId { get; set; }
    public string sqlManagementEndpointUrl { get; set; }
    public string galleryEndpointUrl { get; set; }
    public string managementEndpointUrl { get; set; }
}

그다음, AuthInfo 구조체의 정보를 기반으로 OAuth 인증을 받으면 됩니다. (사실, AuthInfo에서 필요한 필드는 3개에 불과합니다.)

public async Task<bool> Login(string authData)
{
    AuthInfo authInfo = JsonConvert.DeserializeObject<AuthInfo>(authData);
    if (authInfo == null)
    {
        return false;
    }

    string oauth2AzureAD = string.Format("https://login.microsoftonline.com/{0}/oauth2/token", authInfo.tenantId);

    var dict = new Dictionary<string, string>();
    dict.Add("grant_type", "client_credentials");
    dict.Add("client_id", authInfo.clientId);
    dict.Add("client_secret", authInfo.clientSecret);
    dict.Add("resource", authInfo.resourceManagerEndpointUrl);
    var client = new HttpClient();
    var req = new HttpRequestMessage(HttpMethod.Post, oauth2AzureAD) { Content = new FormUrlEncodedContent(dict) };
    HttpResponseMessage hrm = await client.SendAsync(req);

    //...

    return true;
}

정상적으로 인증이 되었다면 다음과 같이 결과를 처리할 수 있습니다.

public async Task<bool> Login(string authData)
{
    //...[생략]...
    HttpResponseMessage hrm = await client.SendAsync(req);

    string result = await hrm.Content.ReadAsStringAsync();

    TokenInfo tokenInfo = JsonConvert.DeserializeObject<TokenInfo>(result);
    string tokenType = tokenInfo.token_type;
    string accessToken = tokenInfo.access_token;

    // ...
}

public class TokenInfo
{
    public string token_type { get; set; }
    public string expires_in { get; set; }
    public string ext_expires_in { get; set; }
    public string expires_on { get; set; }
    public string not_before { get; set; }
    public string resource { get; set; }
    public string access_token { get; set; }
}

바로 저렇게 받아온 tokenType과 accessToken을 기반으로 이후의 모든 호출에서 재사용하도록 HTTP 헤더에 설정해 주면 됩니다.

TokenInfo tokenInfo = JsonConvert.DeserializeObject<TokenInfo>(result);
string tokenType = tokenInfo.token_type;
string accessToken = tokenInfo.access_token;

string authHeader = string.Format("{0} {1}", tokenType, accessToken);
_client.DefaultRequestHeaders.Add("Authorization", authHeader);
_subscriptionId = authInfo.subscriptionId;

예를 들어, 다음의 Azure REST API를 호출해 보겠습니다.

Virtual Machines - List All
; https://docs.microsoft.com/en-us/rest/api/compute/virtualmachines/listall

위의 도움말에서 "Try It" 버튼을 누르면,

azure_rest_api_auth_1.png

(인증 후) "REST API Try It" 패널로 진입합니다.

azure_rest_api_auth_2.png

게임 끝이군요. 위의 화면에서 (스크롤하면) 하단 "Run" 버튼을 누르면 Request/Response에 대한 모든 내용을 확인할 수 있습니다. 따라서 위의 정보에 맞게 우리도 호출해 주고 반환된 json 정보를 잘 이용하면 되는 것입니다.

public async Task<VirtualMachineList> GetVMList()
{
    string url = string.Format(
        "https://management.azure.com/subscriptions/{0}/providers/Microsoft.Compute/virtualMachines?api-version={1}", _subscriptionId, _apiVersion);

    HttpResponseMessage hrm = await _client.GetAsync(url);
    string result = await hrm.Content.ReadAsStringAsync();

    VirtualMachineList list = JsonConvert.DeserializeObject<VirtualMachineList>(result);
    return list;
}

static async Task<int> Main(string[] args)
{
    AzureRestClient client = new AzureRestClient();

    string authData = ..."az ad ..." 명령어의 결과...
    if (await client.Login(authData) == true)
    {
        VirtualMachineList machines = await client.GetVMList();
        foreach (var machine in machines.value)
        {
            Console.WriteLine($"{machine.name} at {machine.location}");
        }
    }            

    return 0;
}

/*
출력 결과:

vm1 at koreacentral
myvm at koreacentral
*/

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




참고로 다음의 글들도 읽어 보면 좋습니다.

Azure Active Directory-Authentication OAuth 2.0-Type Password
; https://medium.com/nearsoft-solutions/azure-active-directory-authentication-oauth-2-0-type-password-e119f9a5ad4c

Azure REST APIs with Postman in 2 Minutes
; https://blog.jongallant.com/2017/11/azure-rest-apis-postman/

SubscriptionCloudCredentials Class
; https://docs.microsoft.com/en-us/previous-versions/azure/reference/dn604052(v%3Dazure.100)

첫 번째 링크의 글이 재미있는데요. OAuth 2의 인증 방식이 "Password", "Client credentials", "Implicit", "Authorization Code" 방식이 있다고 하는데, 그에 의하면 제가 설명한 방식은 "Client credentials"에 해당합니다.

dict.Add("grant_type", "client_credentials");

그리고 저 글에서는 "Password" 방식을 이용한 인증을 한다고 설명합니다. 그런데 좀 이해가 안 되는 면이 있다면, Password 방식은 "username"과 "password" 항목을 빼면 "Client credentials"에서 전달해야 할 값과 동일합니다. 그렇다는 것은 굳이 위험하게 더 많은 정보를 구할 필요 없이 그냥 "client_credentials" 방식으로 해도 될 것 같은데, 왜??? "Password" 방식이 있느냐 하는 것입니다. 혹시 아시는 분은 덧글 부탁드립니다. ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 7/6/2020]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2018-10-25 04시16분
[QNA] 전 완전 초짜입니다. 글 잘보고 있습니다.먼저 감사합니다.
제 소견입니다. 글쓰신건 정독을 안했습니다.. 만약 질문에 맞지 않는 답변이면 언제든~ 삭제하셔도 됩니다.

아주르나, 파이어베이스나 목적(?)은 비슷한 부분이 있지 않나 싶습니다.
전 파이어베이스 문서를 읽었는데.
개요는 게임서버용도로 사용할 수 있게끔 되어있습니다.
개개인별 읽고 쓰고 해야하기에
유저, 비번이 있는게 아닌가 싶습니다.
관리자(개발자) 따로, 사용자 접근이 가능하게..
제가 설명이 많이 부족해서... 앞으로도 글 잘보겠습니다.
[guest]
2018-10-25 05시21분
그러니까, 본문의 마지막에 제가 쓴 질문에 대한 덧글을 단 거죠? 정독을 하셔야 하는데... 일단 그 부분만 다시 설명을 하면.

client_credentials 방식으로 인증을 하는 데에는 grant_type, client_id, client_secret, resource 4개의 필드만 채우면 됩니다. 그런데, grant_type을 password로 바꾸는 경우에는 앞의 4가지와 함께 username과 password를 별도로 더 넣어야 합니다. 어차피 인증은 동일한 IAM 계정으로 하게 될 텐데 password 유형에서 왜 굳이 2개의 필드를 추가로 더 넣어야 하느냐가... 의문인 것입니다.
정성태
2018-11-14 09시02분
How to Use the ADAL .NET library to Call the Microsoft Graph API in a Console Application (Using Authorization Code Flow)
; https://docs.microsoft.com/en-us/archive/blogs/aaddevsup/how-to-use-the-adal-net-library-to-call-the-microsoft-graph-api-in-a-console-application-using-authorization-code-flow
정성태

... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...
NoWriterDateCnt.TitleFile(s)
12918정성태1/13/20226406Linux: 47. WSL - shell script에서 설정한 환경 변수가 스크립트 실행 후 반영되지 않는 문제
12917정성태1/12/20225653오류 유형: 785. C# - The type or namespace name '...' could not be found (are you missing a using directive or an assembly reference?)
12916정성태1/12/20225385오류 유형: 784. TFS - One or more source control bindings for this solution are not valid and are listed below.
12915정성태1/11/20225663오류 유형: 783. Visual Studio - We didn't find any interpreters
12914정성태1/11/20227557VS.NET IDE: 172. 비주얼 스튜디오 2022의 파이선 개발 환경 지원
12913정성태1/11/20228081.NET Framework: 1133. C# - byte * (바이트 포인터)를 FileStream으로 쓰는 방법 [1]
12912정성태1/11/20228718개발 환경 구성: 623. ffmpeg.exe를 사용해 비디오 파일의 이미지를 PGM(Portable Gray Map) 파일 포맷으로 출력하는 방법 [1]
12911정성태1/11/20226044VS.NET IDE: 171. 비주얼 스튜디오 - 더 이상 만들 수 없는 "ASP.NET Core 3.1 Web Application (.NET Framework)" 프로젝트
12910정성태1/10/20226527제니퍼 .NET: 30. 제니퍼 닷넷 적용 사례 (8) - CPU high와 DB 쿼리 성능에 문제가 함께 있는 사이트
12909정성태1/10/20227921오류 유형: 782. Visual Studio 2022 설치 시 "Couldn't install Microsoft.VisualCpp.Redist.14.Latest"
12908정성태1/10/20225749.NET Framework: 1132. C# - ref/out 매개변수의 IL 코드 처리
12907정성태1/9/20226219오류 유형: 781. (youtube-dl.exe) 실행 시 "This app can't run on your PC" / "Access is denied." 오류 발생
12906정성태1/9/20226813.NET Framework: 1131. C# - 네임스페이스까지 동일한 타입을 2개의 DLL에서 제공하는 경우 충돌을 우회하는 방법 [1]파일 다운로드1
12905정성태1/8/20226470오류 유형: 780. Could not load file or assembly 'Microsoft.VisualStudio.TextTemplating.VSHost.15.0, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
12904정성태1/8/20228519개발 환경 구성: 623. Visual Studio 2022 빌드 환경을 위한 github Actions 설정 [1]
12903정성태1/7/20227120.NET Framework: 1130. C# - ELEMENT_TYPE_INTERNAL 유형의 사용 예
12902정성태1/7/20227160오류 유형: 779. SQL 서버 로그인 에러 - provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.
12901정성태1/5/20227261오류 유형: 778. C# - .NET 5+에서 warning CA1416: This call site is reachable on all platforms. '...' is only supported on: 'windows' 경고 발생
12900정성태1/5/20228906개발 환경 구성: 622. vcpkg로 ffmpeg를 빌드하는 경우 생성될 구성 요소 제어하는 방법
12899정성태1/3/20228383개발 환경 구성: 621. windbg에서 python 스크립트 실행하는 방법 - pykd (2)
12898정성태1/2/20228932.NET Framework: 1129. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 인코딩 예제(encode_video.c) [1]파일 다운로드1
12897정성태1/2/20227809.NET Framework: 1128. C# - 화면 캡처한 이미지를 ffmpeg(FFmpeg.AutoGen)로 동영상 처리 [4]파일 다운로드1
12896정성태1/1/202210673.NET Framework: 1127. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성파일 다운로드1
12895정성태12/31/20219169.NET Framework: 1126. C# - snagit처럼 화면 캡처를 연속으로 수행해 동영상 제작 [1]파일 다운로드1
12894정성태12/30/20217158.NET Framework: 1125. C# - DefaultObjectPool<T>의 IDisposable 개체에 대한 풀링 문제 [3]파일 다운로드1
12893정성태12/27/20218692.NET Framework: 1124. C# - .NET Platform Extension의 ObjectPool<T> 사용법 소개파일 다운로드1
... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...