Mauricio Sipmann
Mauricio Sipmann

Reputation: 475

.net core 2.2 facebook auth store access_token

I was following the docs here to save the access_token after a successful auth, but I have no idea where that OnPostConfirmationAsync was supposed to be in my project, I have no Account/ExternalLogin.cshtml.cs. I've also noticed that the table AspNetUserTokens at the database was empty (even after a successful login).

What I'm not understanding on how should I do that auth?

Ps::I need the access_token to do a few integrations with the Facebook API. Ps2:: I'm using dotnet 2.2

    services.AddAuthentication()
        .AddFacebook(fbOption => {
            fbOption.AppId = Configuration["Authentication:Facebook:AppId"];
            fbOption.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
            fbOption.Fields.Add("name");
            fbOption.Fields.Add("email");
            fbOption.SaveTokens = true;
        });

Upvotes: 0

Views: 405

Answers (1)

Nan Yu
Nan Yu

Reputation: 27538

It seems you are using ASP.NET Core identity with external login .

ASP.NET Core 2.1 and later provides ASP.NET Core Identity as a Razor Class Library. Applications that include Identity can apply the scaffolder to selectively add the source code contained in the Identity Razor Class Library (RCL). See document : Scaffold Identity in ASP.NET Core projects

After scaffolding identity source files to your application , you can find the ExternalLogin.cshtml.cs inside Areas/Identity/Pages/Account folder , then you can modify the OnPostConfirmationAsync to add token to cookie .

Don't forget to modify OnGetCallbackAsync function also :

if (result.Succeeded)
{

    // Store the access token and resign in so the token is included in
    // in the cookie
    var user = await _userManager.FindByLoginAsync(info.LoginProvider,
        info.ProviderKey);

    var props = new AuthenticationProperties();
    props.StoreTokens(info.AuthenticationTokens);

    await _signInManager.SignInAsync(user, props, info.LoginProvider);


    _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);
    return LocalRedirect(returnUrl);
}

After user login , you can get the access token in controller by :

var accessToken = HttpContext.GetTokenAsync("access_token").Result;

Upvotes: 3

Related Questions