LoginSignup
4
9

More than 5 years have passed since last update.

ASP.NET Core 2.0でのTwitter認証とAccessTokenとAccessTokenSecretの取得

Posted at

調べてもネット上に情報がなかったのでメモ...((φ( ̄ー ̄〃)ノ□、 メモメモ♪

ASP.NET Core 2.0でのTwitter認証は基本的にASP.NET Identityを使うのが楽で

この通りで、MSのサンプルプログラムもあるので悩ま無いのだけど

例えば認証時に認証ユーザのAccessToken/AccessTokenSecretを取得したいような場合には

ツイッター認証の設定時にTwitterOption.EventsOnCreatingTicketにFuncを設定して


 services.AddAuthentication().AddTwitter(twitterOptions =>
            {
                twitterOptions.ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"];
                twitterOptions.ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"];
                twitterOptions.Events.OnCreatingTicket = async context =>
                {
                    var identity = (ClaimsIdentity)context.Principal.Identity;
                    identity.AddClaim(new Claim(nameof(context.AccessToken), context.AccessToken));
                    identity.AddClaim(new Claim(nameof(context.AccessTokenSecret), context.AccessTokenSecret));
                };
            });

このようにしてIdentityのClaimを追加して

OAuthのコールバックを受け取るActionで


ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync();
var accessToken = info.Principal.Claims.FirstOrDefault(x=> x.Type == "AccessToken")?.Value;
var accessSecret = info.Principal.Claims.FirstOrDefault(x => x.Type == "AccessTokenSecret")?.Value;

こんな感じで取得できます。

4
9
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
4
9