Easy to use ASP.NET Core middleware that allows more control over the Facebook login compared to the built-in implementation.
Install-Package Alx.FacebookLogin
- Add the following snippet on the root level of your appsettings.json and replace the placeholders with your Facebook app settings:
"Authentication": {
"Facebook": {
"AppId": "{YOUR-APP-ID}",
"AppSecret": "{YOUR-APP-SECRET}",
"RedirectUri": "{YOUR-REDIRECT-URI}"
}
}
- In Startup.cs, include a reference to the package:
using Alx.FacebookLogin;
- In the ConfigureServices method, add the line:
services.AddFacebookLogin();
- In the Configure method, add:
app.UseFacebookLogin();
- Create a controller SessionController.cs and inject FacebookLoginService in the constructor:
using Alx.FacebookLogin;
using Microsoft.AspNetCore.Mvc;
namespace Demo.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SessionController : ControllerBase
{
private readonly FacebookLoginService fbService;
public SessionController(FacebookLoginService fbService)
{
this.fbService = fbService;
}
[HttpGet("facebook")]
public IActionResult LoginWithFacebook()
{
var userData = fbService.UserData; // contains user ID, name, email (if provided) and picture url
//Do stuff with the userData object
return Ok();
}
}
}
Once the backend is set up, all you need to do on the frontend is to call this endpoint with the code provided by Facebook. To do that:
- Replace the placeholders in the following URL with your Facebook app settings and make a request
https://www.facebook.com/v6.0/dialog/oauth?client_id=${YOUR-APP-ID}&scope=email&redirect_uri=${YOUR-REDIRECT-URI}
- If the user has granted access, you will recieve a code in the provided redirect URI. Make a GET request to the controller with a query parameter 'code', like
{BACKEND-URL}/api/session/facebook?code={FACEBOOK-CODE}
You can configure the middleware when adding it in the Startup.cs:
services.AddFacebookLogin(options =>
{
//options.Route = ...
});
Option | Default value | Description |
---|---|---|
Route | "/api/session/facebook" | The route to your controller |
Fields | ["email", "name", "picture.width(300).height(300)"] | Fields that will be requested from Facebook |
ConfigurationKeys |
{
AppId = "Authentication:Facebook:AppId",
AppSecret = "Authentication:Facebook:AppSecret",
RedirectUri = "Authentication:Facebook:RedirectUri"
} |
Configuration keys pointing to your appsettings.json |
Coming shortly...