Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 7개 있습니다.)

C# - Azure AD 인증을 지원하는 ASP.NET Core/5+ 웹 애플리케이션 예제 구성

미리 말씀드리면, 이번엔 다음 글의 실습을 정리한 것입니다. ^^

How to implement Azure AD Authentication in ASP.NET Core 5.0 Web Application
; https://www.faciletechnolab.com/blog/2021/4/13/how-to-implement-azure-ad-authentication-in-aspnet-core-50-web-application

Azure AD는, 달리 말해서 기존의 Windows 서버에 있던 Active Directory의 Azure 버전이라고 보면 됩니다. 즉, Active Directory의 SaaS 버전이라고 볼 수 있는데 이에 대한 OAuth 인증 방식도 포함하고 있기 때문에 다른 응용 프로그램에서도 기존의 OAuth 방식대로 Azure AD의 인증 시스템을 연동할 수 있는 것입니다.

단지, 우리가 일반적으로 알고 있는 OAuth 인증을 제공하는 서비스(예를 들어, Facebook, Twitter, Kakao)들의 경우 대부분 해당 서비스에 가입하고 있는 사용자를 모두 인증해 주는 것인 반면, Azure AD의 경우에는 해당 Active Directory에 등록된 사용자들만 인증해준다는 차이점이 있습니다. 그런 관점에서 보면, 언제든 아주 쉽게 구성할 수 있는 OAuth 인증 서버라고 봐도 무방합니다.

Azure AD 프리 버전의 가격정책을 보면,

Azure Active Directory 가격
; https://azure.microsoft.com/ko-kr/pricing/details/active-directory/

가장 중요한 "디렉터리 개체"의 제한이 500,000개라고 하니 이는 웬만한 규모의 중소기업은 모두 소화할 수 있을 정도의 수치입니다. (50만 개까지 가능하지만, 그래도 기본 사용량은 5만 개로 제한되어 있으며 그 이상 필요하면 직접 문의를 해야 한다고 합니다.)

자, 그럼 우리도 무료 OAuth 인증 서버와 간단한 테스트 웹 앱을 하나 가져볼까요? ^^




우선, 제목에서처럼 ASP.NET Core Web App을 .NET 5.0, "Configure for HTTPS" 옵션을 켜서 생성합니다.

asp_net_core_and_ad_auth_1.png

이후 곧바로 F5 키를 눌러 실행하면 웹 브라우저가 뜨고 그때의 주소창에 있는 URL을 기억해 둡니다. (이 글에서의 예제는 "https://localhost:44356"이었습니다.)

그다음, Azure Portal에 방문해,

Microsoft Azure portal
; https://azure.microsoft.com/en-us/features/azure-portal/
; https://portal.azure.com/

로그인하고 "Azure Active Directory"로 이동 후 좌측의 패널에서 (예전에는 "Microsoft - My applications"로 제공하던) "App registrations" 메뉴를 선택해,

asp_net_core_and_ad_auth_2.png

나오는 화면에서 "New registration" 링크를 클릭 후 "Name" 필드만 입력하고 "Register" 버튼을 누릅니다. (이때의 Name 필드에 입력한 값은, 이후 여러분이 만든 웹 사이트에서 로그인할 때 방문하는 Azure AD 측의 페이지에 출력됩니다.)

asp_net_core_and_ad_auth_3.png

그럼 아래와 같은 화면으로 전환이 되고, 여기서 "Application (client) ID"와 "Directory (tenant) ID"를 복사합니다. (경험 많은 분은 아시겠지만, 바로 이 값들이 여타 OAuth 인증에서 필요로 하는 토큰 값들입니다.)

asp_net_core_and_ad_auth_4.png

이제 좌측 패널의 "API permissions" 링크를 눌러 나오는 화면에서 "Microsoft Graph" 링크를 누르면,

asp_net_core_and_ad_auth_5.png

권한 편집을 할 수 있는데, 여기서 "OpenId permissions" 범주의 "openid"와 "profile" 옵션을 체크해 업데이트를 합니다.

asp_net_core_and_ad_auth_6.png

자, 이제 마지막 단계입니다. 좌측 패널에서 "Authentication"을 선택, "Platform configurations"에서 "Add a platform" 링크를 누르면 펼쳐지는 선택 항목에서 "Web"을 선택하고,

asp_net_core_and_ad_auth_7.png

하단의 "ID tokens" 옵션과 함께 여러분이 개발하고 있는 웹 사이트의 URL에 "signin-oidc"를 더해 "Redirect URIs" 란에 입력합니다. (이 글의 테스트 앱은 "https://localhost:44356"으로 실행되므로 "https://localhost:44356/signin-oidc")

asp_net_core_and_ad_auth_8.png




AAD(Azure Active Directory)의 설정을 마쳤으면, 다시 프로젝트로 돌아와 "appsettings.json" 파일에 AAD 인증에서 복사해 두었던 "Application (client) ID"와 "Directory (tenant) ID"를 다음과 같이 설정해 줍니다.

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "AllowedHosts": "*",
    "AzureAd": {
        "Instance": "https://login.microsoftonline.com/",
        "ClientId": "...your-client-id...",
        "TenantId": "...your-tenant-id..."
    }
}

그리고 AAD 인증에 대한 코드를 이미 구현하고 있는 패키지 2개를 추가하고,

// Microsoft identity platform and OpenID Connect protocol
// https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-protocols-oidc

Install-Package Microsoft.AspNetCore.Authentication.OpenIdConnect
Install-Package Microsoft.Identity.Web

Startup.cs 파일에 ConfigureServices 메서드 내의 services.AddRazorPages 호출 이전 단계에 AddAuthentication, AddControllersWithViews 메서드 호출 코드를 추가합니다.

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;

...[생략]...

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                    .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));

            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });

            services.AddRazorPages();
        }
...[생략]...

그다음 Configure 내에서는 app.UseAuthorization 호출 이전에 app.UseAuthentication 호출을 추가합니다.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}

이게 끝입니다. 인증이 정상적으로 되었는지 테스트하기 위해 Index.cshtml에 로그인 계정의 이름을 출력하는 코드를 추가하고,

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

@if(User.Identity.IsAuthenticated)
{
    <p>
        @User.Identity.Name
    </p>
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core?WT.mc_id=DT-MVP-4038148">building Web apps with ASP.NET Core</a>.</p>
</div>

빌드 후 실행하면 app.UseAuthentication 호출로 인해 곧바로 인증 페이지로 넘어가는데, AAD에 등록된 계정으로 로그인이 되면 최초에는 이러한 승인을 허가하는 다음의 화면이 보이게 됩니다.

asp_net_core_and_ad_auth_9.png

"Accept"를 눌러 진행하면 화면은 다시 웹 애플리케이션으로 넘어가 index.cshtml에 추가해 두었던 User.Identity.Name 항목에 값이 들어가게 됩니다.

asp_net_core_and_ad_auth_10.png




이후에는 보관된 auth cookie로 인해 해당 페이지를 재방문하면 곧바로 로그인이 완료된 페이지로 진입이 됩니다. 만약 로그아웃을 명시적으로 하고 싶다면 다음과 같이 "HttpContext.SignOutAsync" 메서드를 호출하면 됩니다.

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;

namespace WebApplication1.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger _logger;

        public IndexModel(ILogger logger)
        {
            _logger = logger;
        }

        public async Task OnGet()
        {
            if (this.Request.Query.ContainsKey("o") == true)
            {
                // CookieAuthenticationDefaults.AuthenticationScheme == "Cookies"
                await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                await HttpContext.SignOutAsync("OpenIdConnect");
                return;
            }

            foreach (System.Security.Claims.Claim claim in User.Claims)
            {
                string text = claim.Value;
                System.Diagnostics.Trace.WriteLine($"{claim.Type}: {claim.Value}");
            }
            /* 출력 결과
            aio: AW...[136 글자 생략]..../u
            http://schemas.microsoft.com/identity/claims/identityprovider: https://sts.windows.net/91...[guid_중간_생략]...ad/
            name: TestUsr
            http://schemas.microsoft.com/identity/claims/objectidentifier: 2a...[guid_중간_생략]...58
            preferred_username: testusr@test.net
            prov_data: {"at":true,"prov":"...","altsecid":"HUE...[36 글자 생략]...R4nw"}
            rh: 0...[50 글자 생략]...IA.
            http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: FN....[39 글자 생략]...i8
            http://schemas.microsoft.com/identity/claims/tenantid: 3...[tenant_id 생략]...0
            uti: _A...[19 글자 생략]...A
            */
        }
    }
}

위와 같이 구현했으니, "https://localhost:44356/?o"로 호출을 하면 SignOutAsync가 호출되고 아래와 같은 화면으로 넘어가 어떤 계정을 로그아웃 시킬지 선택하게 됩니다. (하나밖에 없는데, 굳이 선택을... ^^;)

asp_net_core_and_ad_auth_11.png

이것은, 해당 웹 사이트에서만 로그아웃 되는 정도가 아니라 그 계정 자체가 로그아웃되므로 Single-Sign-On이 되는 다른 사이트를 방문하려는 경우에도 이젠 다시 로그인을 진행해야 합니다.

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




로그인 화면에서 다음과 같은 오류가 발생한다면?

AADSTS700054: response_type 'id_token' is not enabled for the application.

Azure AD의 Authentication 설정에서 "Platform configurations"의 "Add a platform"으로 "Web" 설정이 등록되지 않았기 때문입니다.

동일한 오류 번호(AADSTS700054)이지만 위의 오류가 로그인 화면이 아닌, 로그인 처리 중에 발생할 수도 있습니다.

OpenIdConnectProtocolException: Message contains error: 'unsupported_response_type', error_description: 'AADSTS700054: response_type 'id_token' is not enabled for the application. Trace ID: 3904a6e0-e3ed-40f5-8e84-b7899b985700 Correlation ID: def94a1b-0a07-40c7-b60f-7b344c90fcc9 Timestamp: 2021-04-23 13:02:32Z', error_uri: 'https://login.microsoftonline.com/error?code=700054'.


이런 경우에는, Authentication 설정의 platform 등록 시 "ID tokens" 옵션을 선택하지 않았기 때문입니다. 따라서 해당 옵션을 활성화시키면 됩니다. (이 글에서 "Configure Web" 화면이 있는 그림의 하단에 있는 "ID tokens (used for implicit and hybrid flows)" 옵션입니다.)




로그인 시 다음과 같은 오류가 발생한다면?

AADSTS50020: User account 'testusr@testdomain.com' from identity provider 'live.com' does not exist in tenant '...' and cannot access the application '3264...[생략]...e762'(test-auth-webapp) in that tenant. The account needs to be added as an external user in the tenant first. Sign out and sign in again with a different Azure Active Directory user account.

선택한 사용자 계정이 테넌트 '...'에 없어 이 테넌트의 애플리케이션 '3264...[생략]...e762'에 액세스할 수 없습니다. 이 계정은 테넌트의 외부 사용자로 먼저 추가되어야 합니다. 다른 계정을 사용하세요.


메시지의 의미에 따라, 해당 Microsoft 계정은 여러분의 Azure AD에 등록되지 않은 계정이기 때문입니다. 추가하고 나면 이 문제는 해결됩니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/30/2021]

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

비밀번호

댓글 작성자
 



2021-05-14 09시13분
IdentityServer4 제품의 소식이 있군요.

ASP.NET Core 6 and Authentication Servers
; https://devblogs.microsoft.com/aspnet/asp-net-core-6-and-authentication-servers/

Reciprocal Public License: a license where the code is still open source but if used for commercial purposes then a paid license must be bought.

라이선스가 RPL(reciprocal public license)로 바뀌는데, 일단 비상업적으로는 무료이지만 상업적인 용도로는 유료로 전환한다고 합니다. RPL이라고 해서 뭔가 생소해서 찾아봤더니, RPL 자체에는 그런 식의 무/유료 정책은 포함되어 있지 않고 해당 오픈 소스를 사용하되 기존 소스 코드를 변경한 경우에는 파일 단위로 모두 공개해야 한다는 형식인가 봅니다. (반면, 새로 추가한 파일은 그것 자체의 라이선스를 새롭게 가져갈 수 있고.)

혹시 RPL에 대해 명확하게 아시는 분은 덧글 부탁드립니다. ^^
정성태
2021-05-14 10시39분
openiddict/openiddict-core
; https://github.com/openiddict/openiddict-core
정성태
2021-07-30 07시54분
정성태
2022-05-23 10시24분
.NET 7 WebApp with Https in Docker, secured by Azure AD
; https://dev.to/425show/net-7-webapp-with-https-in-docker-secured-by-azure-ad-2nna

.NET 6.0 - Basic Authentication Tutorial with Example API
; https://jasonwatmore.com/post/2021/12/20/net-6-basic-authentication-tutorial-with-example-api
정성태

1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13423정성태10/6/20233063스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233204닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233243닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235327스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233092스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233759닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233336닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233152오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233639닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233390디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233582닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20236853닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233364Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20234863닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233721닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20233714Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233473닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/20233426VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
13405정성태9/3/20233841닷넷: 2138. C# - async 메서드 호출 원칙
13404정성태8/29/20233364오류 유형: 876. Windows - 키보드의 등호(=, Equals sign) 키가 눌리지 않는 경우
13403정성태8/21/20233189오류 유형: 875. The following signatures couldn't be verified because the public key is not available: NO_PUBKEY EB3E94ADBE1229CF
13402정성태8/20/20233250닷넷: 2137. ILSpy의 nuget 라이브러리 버전 - ICSharpCode.Decompiler
13401정성태8/19/20233525닷넷: 2136. .NET 5+ 환경에서 P/Invoke의 성능을 높이기 위한 SuppressGCTransition 특성 [1]
13400정성태8/10/20233351오류 유형: 874. 파이썬 - pymssql을 윈도우 환경에서 설치 불가
13399정성태8/9/20233373닷넷: 2135. C# - 지역 변수로 이해하는 메서드 매개변수의 값/참조 전달
13398정성태8/3/20234135스크립트: 55. 파이썬 - pyodbc를 이용한 SQL Server 연결 사용법
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...