Skip to content
戻る

ASP.NET Core IdentityでTwitter認証をするとAn unhandled exception occurred while processing the requestが発生する

Published:  at  12:31

概要

ASP.NET Core Identiyを使ったTwitter認証の実装で認証を実施する際にエラーが発生して詰まったのでメモ

本記事ではエラーの回避策のみ言及し、Twitter Developersでのアプリ申請には言及しない。

目次

環境

参考サイト様

成果物

https://github.com/Lycheejam/blog-sample/tree/master/twitter-callback 🔗

前提(使用したプロジェクト)

プロジェクト生成

下記コマンドで生成

dotnet new mvc -n twitter-callback -au Individual

必要パッケージの追加

プロジェクトフォルダにて下記コマンドを実行しMicrosoft.AspNetCore.Authentication.Twitterを追加

dotnet add package Microsoft.AspNetCore.Authentication.Twitter

コードの編集

下記公式チュートリアルのままコードを追加する。
https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/twitter-logins?view=aspnetcore-2.2#configure-twitter-authentication 🔗

Startup.csappsettings.jsonを編集する。
Gitも編集に合わせてコミットしているので差分を確認いただければわかりやすいと思います。
→差分:https://github.com/Lycheejam/blog-sample/commit/9e63053d04f1ee5f238e76abd4462073e8b59a1b 🔗

public void ConfigureServices(IServiceCollection services) {
	//省略
    services.AddAuthentication().AddTwitter(twitterOptions => {
        twitterOptions.ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"];
        twitterOptions.ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"];
    });
    //省略
}

下記を追記、ConsumerKeyConsumerSecretについては適宜置き換えのこと

"Authentication": {
    "Twitter:ConsumerKey": "ConsumerKey",
    "Twitter:ConsumerSecret": "ConsumerSecret"
  }

事象

該当プロジェクトをビルドし起動。その後、Loginリンクより画面遷移を実施しTwitterボタンを押下し認証する。
その際に下記のエラーが発生する。(操作手順は下記画像左から赤丸を参照)

An unhandled exception occurred while processing the request.
HttpRequestException: Response status code does not indicate success: 403 (Forbidden).
System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
//以下略

原因

Twitter APIの仕様変更に伴いTwitter Developerサイトのアプリ詳細にて登録可能なcallback先が正しくなかった場合、上記エラーを返す仕様となったため。(コールバック先をチェックしている。)

対策

Twitter Developerサイトのアプリ詳細にてcallback先を編集する。(下記画像を参照のこと)

以下自分の詰まりポイント

ローカル環境だからIPがない

127.0.0.1は登録可能なので127.0.0.1で登録する。
Macの場合もWindowsの場合もhostsを要確認のこと
Macはデフォルトでlocalhost127.0.0.1だったがWindows 10の端末ではhosts127.0.0.1がコメントアウトとなっていた。
(自分でコメントアウトしたのかどうかは覚えてない…)

Callback先がわからない

ASP.NET Core Identityでは仕様で/signin-twitterにコールバックされます。
公式ドキュメントにも記載がありますが見逃して時間がかかりました。

The URI segment /signin-twitter is set as the default callback of the Twitter authentication provider. You can change the default callback URI while configuring the Twitter authentication middleware via the inherited RemoteAuthenticationOptions.CallbackPath property of the TwitterOptions class.
https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/twitter-logins?view=aspnetcore-2.2#create-the-app-in-twitter 🔗

Callbackを正しく設定したがエラーとなる

デバッグにてlocalhostにブラウザでアクセスしているから

Tips

デバッグの際にデフォルトの起動IPを変更する。
該当プロジェクトを選択オプション実行構成DefaultASP.NET CoreタブからアプリのURLを変更する。
下記画像を参照のこと。

雑感

これ本当に詰まっちゃって時間取られて公式ドキュメントちゃんと読んでればこんなことにはならなかったのに案件でした。



前の記事
Mac環境のASP.NET Core MVCでdocker上のMySQLを使用する
次の記事
dotnet cliのMVCテンプレートの認証オプション