ASP.NET Core에서 WS-Federation으로 사용자 인증

이 자습서에서는 사용자가 ADFS(Active Directory Federation Services) 또는 Microsoft Entra ID와 같은 WS-Federation 인증 공급자로 로그인할 수 있도록 하는 방법을 보여 줍니다. Facebook, Google 및 외부 공급자 인증에 설명된 ASP.NET Core 샘플 앱을 사용합니다.

ASP.NET Core 앱의 경우 Microsoft.AspNetCore.Authentication.WsFederation에서 WS-Federation 지원을 제공합니다. 이 구성 요소는 Microsoft.Owin.Security.WsFederation에서 이동되며 해당 구성 요소의 많은 메커니즘을 공유합니다. 그러나 구성 요소는 몇 가지 중요한 방법이 다릅니다.

기본적으로 새 미들웨어는 다음과 같습니다.

  • 원치 않는 로그인을 허용하지 않습니다. WS-Federation 프로토콜의 이 기능은 XSRF 공격에 취약합니다. 그러나 AllowUnsolicitedLogins 옵션을 사용하여 활성화할 수 있습니다.
  • 모든 양식 게시물에서 로그인 메시지를 확인하지는 않습니다. 로그인에 CallbackPath 대한 요청만 검사. CallbackPath 기본값 /signin-wsfed 은 클래스의 WsFederationOptions 상속된 RemoteAuthenticationOptions.CallbackPath 속성을 통해 변경될 수 있습니다. 이 경로는 옵션을 사용하도록 설정하여 다른 인증 공급자와 공유할 수 있습니다 SkipUnrecognizedRequests .

Active Directory로 앱 등록

ADFS(Active Directory Federation Services)

  • ADFS 관리 콘솔에서 서버의 신뢰 당사자 트러스트 추가 마법사를 엽니다.

Add Relying Party Trust Wizard: Welcome

  • 수동으로 데이터를 입력하도록 선택합니다.

Add Relying Party Trust Wizard: Select Data Source

  • 신뢰 당사자의 표시 이름을 입력합니다. 이름은 ASP.NET Core 앱에 중요하지 않습니다.

  • Microsoft.AspNetCore.Authentication.WsFederation은 토큰 암호화를 지원하지 않으므로 토큰 암호화 인증서를 구성하지 마세요.

Add Relying Party Trust Wizard: Configure Certificate

  • 앱의 URL을 사용하여 WS-Federation Passive 프로토콜에 대한 지원을 활성화합니다. 앱에 대한 포트가 올바른지 확인합니다.

Add Relying Party Trust Wizard: Configure URL

참고 항목

HTTPS URL이어야 합니다. IIS Express는 개발 중에 앱을 호스팅할 때 자체 서명된 인증서를 제공할 수 있습니다. Kestrel에는 수동 인증서 구성이 필요합니다. 자세한 내용은 Kestrel 설명서를 참조하세요.

  • 마법사의 나머지 부분을 통해 다음을 클릭하고 마지막에 닫기를 클릭합니다.

  • ASP.NET Core Identity에서는 이름 ID 클레임이 필요합니다. 클레임 규칙 편집 대화 상자에서 추가합니다.

Edit Claim Rules

  • 변환 클레임 규칙 추가 마법사에서 기본 클레임으로 LDAP 특성 보내기 템플릿을 선택한 상태로 두고 다음을 클릭합니다. SAM-Account-Name LDAP 특성을 이름 ID 나가는 클레임에 매핑하는 규칙을 추가합니다.

Add Transform Claim Rule Wizard: Configure Claim Rule

  • 클레임 규칙 편집 창에서 마침>확인을 클릭합니다.

Microsoft Entra ID

  • Microsoft Entra ID 테넌트의 앱 등록 블레이드로 이동합니다. 새 애플리케이션 등록을 클릭합니다.

Microsoft Entra ID: App registrations

  • 앱 등록의 이름을 입력합니다. ASP.NET Core 앱에 중요하지 않습니다.
  • 앱이 수신 대기하는 URL을 로그온 URL로 입력합니다.

Microsoft Entra ID: Create app registration

  • 엔드포인트를 클릭하고 페더레이션 메타데이터 문서 URL을 확인합니다. WS-Federation 미들웨어의 MetadataAddress입니다.

Microsoft Entra ID: Endpoints

  • 새 앱 등록으로 이동합니다. API 표시를 클릭합니다. 애플리케이션 ID URI 설정>저장을 클릭합니다. 애플리케이션 ID URI를 기록해 둡니다. WS-Federation 미들웨어의 Wtrealm입니다.

Microsoft Entra ID: App registration properties

ASP.NET Core Identity 없이 WS-Federation 사용

WS-Federation 미들웨어는 Identity 없이 사용할 수 있습니다. 예시:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(sharedOptions =>
    {
        sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        sharedOptions.DefaultChallengeScheme = WsFederationDefaults.AuthenticationScheme;
    })
     .AddWsFederation(options =>
     {
         options.Wtrealm = Configuration["wsfed:realm"];
         options.MetadataAddress = Configuration["wsfed:metadata"];
     })
     .AddCookie();

    services.AddControllersWithViews();
    services.AddRazorPages();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

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

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
    });
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(sharedOptions =>
    {
        sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        sharedOptions.DefaultChallengeScheme = WsFederationDefaults.AuthenticationScheme;
    })
    .AddWsFederation(options =>
    {
        options.Wtrealm = Configuration["wsfed:realm"];
        options.MetadataAddress = Configuration["wsfed:metadata"];
    })
    .AddCookie();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

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

    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

ASP.NET Core Identity에 대한 외부 로그인 제공자로서 WS-Federation 추가

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();


    services.AddAuthentication()
        .AddWsFederation(options =>
        {
            // MetadataAddress represents the Active Directory instance used to authenticate users.
            options.MetadataAddress = "https://<ADFS FQDN or AAD tenant>/FederationMetadata/2007-06/FederationMetadata.xml";

            // Wtrealm is the app's identifier in the Active Directory instance.
            // For ADFS, use the relying party's identifier, its WS-Federation Passive protocol URL:
            options.Wtrealm = "https://localhost:44307/";

            // For AAD, use the Application ID URI from the app registration's Overview blade:
            options.Wtrealm = "api://bbd35166-7c13-49f3-8041-9551f2847b69";
        });

    services.AddControllersWithViews();
    services.AddRazorPages();
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDefaultIdentity<IdentityUser>()
        .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddAuthentication()
        .AddWsFederation(options =>
        {
            // MetadataAddress represents the Active Directory instance used to authenticate users.
            options.MetadataAddress = "https://<ADFS FQDN or AAD tenant>/FederationMetadata/2007-06/FederationMetadata.xml";

            // Wtrealm is the app's identifier in the Active Directory instance.
            // For ADFS, use the relying party's identifier, its WS-Federation Passive protocol URL:
            options.Wtrealm = "https://localhost:44307/";

            // For AAD, use the Application ID URI from the app registration's Overview blade:
            options.Wtrealm = "api://bbd35166-7c13-49f3-8041-9551f2847b69";
        });

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

오버로드는 AddAuthentication(IServiceCollection, String) 속성을 설정합니다 DefaultScheme . AddAuthentication(IServiceCollection, Action<AuthenticationOptions>) 오버로드를 통해 인증 옵션을 설정할 수 있으며, 이로서 다양한 용도를 위해 기본 인증 체계를 설정할 수 있습니다. 이전에 구성된 AuthenticationOptions 속성을 재정의하기 위한 AddAuthentication 후속 호출입니다.

AuthenticationBuilder 인증 처리기를 등록하는 확장 메서드는 인증 체계당 한 번만 호출할 수 있습니다. 구성표 속성, 구성표 이름 및 표시 이름을 구성할 수 있는 오버로드가 있습니다.

WS-Federation으로 로그인

앱으로 이동하고 탐색 헤더에서 로그인 링크를 클릭합니다. WsFederation을 사용하여 로그인하는 옵션이 있습니다. Log in page

ADFS를 공급자로 사용하면 단추가 ADFS 로그인 페이지로 리디렉션됩니다. ADFS sign-in page

Microsoft Entra ID를 공급자로 사용하면 단추가 Microsoft Entra ID 로그인 페이지로 리디렉션됩니다. Microsoft Entra ID sign-in page

새 사용자에 대한 성공적인 로그인은 앱의 사용자 등록 페이지로 리디렉션됩니다. Register page