Facebook Social Login Fails with "Invalid State" Error

Problem statement

When attempting to login with Facebook, the LoginResult generates the following error.

Invalid State

When trying again after the error (Facebook login form is not presented as Facebook session is still valid) and the Auth0 login is successful.

Cause

The state parameter may be getting changed by Facebook. Facebook adds a #_=_ suffix to the state value and causes the state validation to fail. The SDK library used likely follows the OIDC standard and doesn’t expect this additional suffix.

Solution

Others have this problem as well, and the suggested workaround is to remove the suffix before the validation. Here is a fix example from this issue being reported with a .NET Maui application and the IdentityModel.OidcClient library that removes the suffix from the state value:

public async Task<BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken = default)
{
    try
    {
        WebAuthenticatorResult result = await WebAuthenticator.Default.AuthenticateAsync(
            new Uri(options.StartUrl),
            new Uri(options.EndUrl));

        var url = new RequestUrl(options.EndUrl)
            .Create(new Parameters(result.Properties));

        // FB adding #_=_ to the end of the url, so we need to remove it
        if (url.EndsWith("%23_%3D_"))
        {
            url = url.Substring(0, url.LastIndexOf("%23_%3D_"));
        }

        return new BrowserResult
        {
            Response = url,
            ResultType = BrowserResultType.Success
        };
    }
    catch (TaskCanceledException)
    {
        return new BrowserResult
        {
            ResultType = BrowserResultType.UserCancel,
            ErrorDescription = "Login canceled by the user."
        };
    }
}

Related References