Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 4개 있습니다.)
(시리즈 글이 7개 있습니다.)
개발 환경 구성: 363. Azure의 Access control 보안과 Azure Active Directory의 계정 관리 서비스
; https://www.sysnet.pe.kr/2/0/11495

개발 환경 구성: 366. Azure Active Directory(Microsoft Enfra ID)의 사용자 유형 구분 - Guest/Member
; https://www.sysnet.pe.kr/2/0/11498

개발 환경 구성: 570. C# - Azure AD 인증을 지원하는 ASP.NET Core/5+ 웹 애플리케이션 예제 구성
; https://www.sysnet.pe.kr/2/0/12614

.NET Framework: 1081. C# - Azure AD 인증을 지원하는 데스크톱 애플리케이션 예제(Windows Forms)
; https://www.sysnet.pe.kr/2/0/12735

.NET Framework: 1082. Azure Active Directory - Microsoft Graph API 호출 방법
; https://www.sysnet.pe.kr/2/0/12741

개발 환경 구성: 585. Azure AD 인증을 위한 사용자 인증 유형
; https://www.sysnet.pe.kr/2/0/12742

.NET Framework: 1083. Azure Active Directory - 외부 Token Cache 저장소를 사용하는 방법
; https://www.sysnet.pe.kr/2/0/12743




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://learn.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에 등록되지 않은 계정이기 때문입니다. 추가하고 나면 이 문제는 해결됩니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/27/2024]

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
정성태

... 121  122  123  124  125  126  127  128  129  130  [131]  132  133  134  135  ...
NoWriterDateCnt.TitleFile(s)
1780정성태10/15/201424178오류 유형: 249. The application-specific permission settings do not grant Local Activation permission for the COM Server application with CLSID
1779정성태10/15/201419710오류 유형: 248. Active Directory에서 OU가 지워지지 않는 경우
1778정성태10/10/201418156오류 유형: 247. The Netlogon service could not create server share C:\Windows\SYSVOL\sysvol\[도메인명]\SCRIPTS.
1777정성태10/10/201421265오류 유형: 246. The processing of Group Policy failed. Windows attempted to read the file \\[도메인]\sysvol\[도메인]\Policies\{...GUID...}\gpt.ini
1776정성태10/10/201418308오류 유형: 245. 이벤트 로그 - Name resolution for the name _ldap._tcp.dc._msdcs.[도메인명]. timed out after none of the configured DNS servers responded.
1775정성태10/9/201419432오류 유형: 244. Visual Studio 디버깅 (2) - Unable to break execution. This process is not currently executing the type of code that you selected to debug.
1774정성태10/9/201426626개발 환경 구성: 246. IIS 작업자 프로세스의 20분 자동 재생(Recycle)을 끄는 방법
1773정성태10/8/201429781.NET Framework: 471. 웹 브라우저로 다운로드가 되는 파일을 왜 C# 코드로 하면 안되는 걸까요? [1]
1772정성태10/3/201418570.NET Framework: 470. C# 3.0의 기본 인자(default parameter)가 .NET 1.1/2.0에서도 실행될까? [3]
1771정성태10/2/201428083개발 환경 구성: 245. 실행된 프로세스(EXE)의 명령행 인자를 확인하고 싶다면 - Sysmon [4]
1770정성태10/2/201421691개발 환경 구성: 244. 매크로 정의를 이용해 파일 하나로 C++과 C#에서 공유하는 방법 [1]파일 다운로드1
1769정성태10/1/201424113개발 환경 구성: 243. Scala 개발 환경 구성(JVM, 닷넷) [1]
1768정성태10/1/201419532개발 환경 구성: 242. 배치 파일에서 Thread.Sleep 효과를 주는 방법 [5]
1767정성태10/1/201424632VS.NET IDE: 94. Visual Studio 2012/2013에서의 매크로 구현 - Visual Commander [2]
1766정성태10/1/201422490개발 환경 구성: 241. 책 "프로그래밍 클로저: Lisp"을 읽고 나서. [1]
1765정성태9/30/201426054.NET Framework: 469. Unity3d에서 transform을 변수에 할당해 사용하는 특별한 이유가 있을까요?
1764정성태9/30/201422290오류 유형: 243. 파일 삭제가 안 되는 경우 - The action can't be comleted because the file is open in System
1763정성태9/30/201423859.NET Framework: 468. PDB 파일을 연동해 소스 코드 라인 정보를 알아내는 방법파일 다운로드1
1762정성태9/30/201424552.NET Framework: 467. 닷넷에서 EIP/RIP 레지스터 값을 구하는 방법 [1]파일 다운로드1
1761정성태9/29/201421578.NET Framework: 466. 윈도우 운영체제의 보안 그룹 이름 및 설명 문자열을 바꾸는 방법파일 다운로드1
1760정성태9/28/201419844.NET Framework: 465. ICorProfilerInfo::GetILToNativeMapping 메서드가 0x80131358을 반환하는 경우
1759정성태9/27/201430979개발 환경 구성: 240. Visual C++ / x64 환경에서 inline-assembly를 매크로 어셈블리로 대체하는 방법파일 다운로드1
1758정성태9/23/201437885개발 환경 구성: 239. 원격 데스크톱 접속(RDP)을 기존의 콘솔 모드처럼 사용하는 방법 [1]
1757정성태9/23/201418414오류 유형: 242. Lync로 모임 참여 시 소리만 들리지 않는 경우 - 두 번째 이야기
1756정성태9/23/201427416기타: 48. NVidia 제품의 과다한 디스크 사용 [2]
1755정성태9/22/201434203오류 유형: 241. Unity Web Player를 설치해도 여전히 설치하라는 화면이 나오는 경우 [4]
... 121  122  123  124  125  126  127  128  129  130  [131]  132  133  134  135  ...