ASP.NET Identity - プロキシ環境下で外部サービスによるユーザ認証を行う

ローカルの開発環境などプロキシを使っている環境下で、ASP.NET Identity を使って外部サービスによるユーザ認証を行うには、サーバ間通信の際にプロキシの設定を行う必要があるのですが、それはどこでするの?ってお話です。

たとえば Google の OAuth 2.0 の場合、GoogleOAuth2AuthenticationOptions の BackchannelHttpHandler プロパティに、プロキシの情報を設定した WebRequestHandler を設定します。

// Startup.Auth.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;

namespace WebApp {
    public partial class Startup {
        public void ConfigureAuth(IAppBuilder app) {
            // クッキーを使った認証を有効にする
            app.UseCookieAuthentication(new CookieAuthenticationOptions {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = CookieAuthenticationDefaults.LoginPath,
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // プロキシ
            var proxy = new WebProxy {
                // 認証情報を設定
                Credentials = new NetworkCredential("USER_NAME","PASSWORD"),
            };

            // GoogleのOAuth 2.0を有効にする
            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions {
                // サーバ間通信で使用するWebRequestHandlerを指定
                BackchannelHttpHandler = new WebRequestHandler {
                    // プロキシ情報を設定して、使用するように
                    Proxy = proxy,
                    UseProxy = true,
                },
                ClientId = "CLIENT_ID",
                ClientSecret = "CLIENT_SECRET",
            });
        }
    }
}

他のサービスの場合も、オプションクラスに BackchannelHttpHandler というプロパティがあるので同じように設定すればよさそうです。 たとえば Facebook は FacebookAuthenticationOptions に、Microsoft の場合は MicrosoftAccountAuthenticationOptions に BackchannelHttpHandler というプロパティがあります。