LoginSignup
5
8

More than 5 years have passed since last update.

ASP.NET Core - OAuth認証を行う (Google)

Posted at

開発環境

  • .NETCoreApp 1.1
  • Windows 10
  • Visual Studio Community 2017

準備

SSLを有効化しておいてください.
http://qiita.com/musubi05/items/b627effde1e10c43f2e6

Google API Consoleで必要な認証情報を取得

https://console.developers.google.com/projectselector/apis/library にアクセスし,Googleアカウントでログインします.
0.png

プロジェクトを作成します.
1.png
2.png

作成後,Google+ APIの登録を行います.
ライブラリから,Google+ APIを選択します.
3.png

登録後,認証情報を作製します.
4.png

認証情報の種類: Google+ API
APIを呼び出す場所: Webサーバー (nodejs, Tomcatなど)
アクセスするデータの種類: ユーザデータ
を選択します.
5.png

承認済みのリダイレクトURIに,自身のURLを入力します (SSLポートを指定する).
必ず,signin-google を付加します.
例:https://localhost:44385/signin-google
6.png

登録します.
7.png

認証情報をダウンロードし,登録を完了します.
8.png
9.png

ダウンロードしたJSONファイルを開き,client_idとclient_secretを確認します.
10.png

ユーザシークレット情報の登録

先程入手したclient_idとclient_secretを,ユーザシークレット情報としてアプリケーションに登録します.

コンソールから

dotnet user-secrets set Authentication:Google:ClientID <client_id>
dotnet user-secrets set Authentication:Google:ClientSecret <client_secret>

Visual Studioから

ソリューションを右クリック->ユーザシークレットの管理(G)をクリック
開かれたsecrets.jsonファイルを以下のように記述します.

secrets.json
{
  "Authentication:Google:ClientId": "<client_id>",
  "Authentication:Google:ClientSecret": "<client_secret>"
}

NuGetでMicrosoft.AspNetCore.Authentication.Googleを入れる

認証に必要なパッケージをインストールします.

dotnet add package Microsoft.AspNetCore.Authentication.Google

Google Middlewareを有効にする

以下に示す,app.UseGoogleAuthenticationの処理を,Startup.csのConfigureメソッド内に記述します.
必ず,app.UseIdentity();の後に記述します.

startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // 中略
    app.UseIdentity();

    app.UseGoogleAuthentication(new GoogleOptions()
    {    
        ClientId = Configuration["Authentication:Google:ClientId"],
        ClientSecret = Configuration["Authentication:Google:ClientSecret"]
    });
    // 中略
}

ビルドが通れば,完了です.

参考

5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8