tVoss42
tVoss42

Reputation: 582

How to authenticate Facebook JWT in .Net Core API

I am in the process of creating a mobile app that allows users to log in via Facebook. Once logged in, the app holds on to a Bearer token used to make further requests. I am attempting to pass this token along to a C# .Net Core API. I'm attempting to write as little auth code as possible as doing it myself is prone to huge security issues.

Currently my code in Startup.cs looks like this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {

    app.UseJwtBearerAuthentication(new JwtBearerOptions {
        AuthenticationScheme = "Bearer",        
    });

    app.UseFacebookAuthentication(new FacebookOptions {
        AppId = "****",
        AppSecret = "****",
        SignInScheme = "Bearer"
    });

    app.UseMvc();
}

With this, all requests return 401, even with a valid Bearer token. Now I'm not 100% sure UseJwtBearerAuthentication is even compatible with UseFacebookAuthentication, and if it is I'm sure I'm missing some code here. What steps should I take to get this working?

Upvotes: 7

Views: 1384

Answers (1)

Krusty
Krusty

Reputation: 1173

I've posted some day ago the same question but I didn't received any answer. Anyway, googling, I've found the only (?) possible solution. When your client logged into Facebook, you have to send your Facebook token to a custom endpoint of your server. This endpoint shall:

  • Verify if the token received is valid using Facebook API (very easy)
  • Try to log the user using ExternalLoginSignInAsync method of SignInManager<User> class: var result = await _signInManager.ExternalLoginSignInAsync(provider, userId, isPersistent: false); where userId is the Facebook id user
  • if result.Succeeded is false:
    • Get the Facebook user info using https://graph.facebook.com/{userId} endpoint
    • Create a User entity with that information
    • Create the user in the database using await _userManager.AddLoginAsync(user, userLoginInfo);, where userLoginInfo should contains the provider (Facebook), userId (Facebook user Id) and application(your app name)
    • Call await _signInManager.SignInAsync(user, false); to sign the user

You can get the user from the database using _userManager.FindByIdAsync(userId);

Now your API can returns a token that will be accepted as Authorization header

Upvotes: 1

Related Questions