ASP.NET Advent Calendar 2016 6日目の記事です。
ASP.NET MVC 5 で新規 Web アプリケーションを作成すると、初めから以下のようなコメントアウト済みの外部サイト連携コードが埋め込まれているので、ここを少しいじれば Microsoft, Twitter, Facebook, Google 等との連携機能は割と簡単に作れる。
// Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "", // ClientSecret = "" //});
ただ、GitHub 連携のコードは組み込まれていないのでこれは手動で組み込む。
サンプルプロジェクト
本記事のサンプルプロジェクトは以下にあげてあります。
利用ライブラリ
Owin.Security.Providers という NuGet パッケージを導入する。
Package Manager Console にて以下を実行。
PM> Install-Package Owin.Security.Providers
GitHub アプリ作成
以下サイトにて GitHub アプリケーションを作成する。
これで Client ID, Client Secret が入手できる。
組み込み
App_Start/Startup.Auth.cs に以下コードを組み込む
.... // この行を追加 using Owin.Security.Providers.GitHub; .... public void ConfigureAuth(IAppBuilder app) { .... // 以下を追加 GitHubAuthenticationOptions options = new GitHubAuthenticationOptions { ClientId = "取得した Client ID", ClientSecret= "取得した Client Secret" }; options.Scope.Clear(); app.UseGitHubAuthentication(options); }