Facebook login Oauth Fix 2017 GetExternalLoginInfoAsync null access_denied

Recently I noticed  that my facebook login  MVC app  suddenly stopped working  after login button clicked  I was redirected back with “access_denied” error

After  Hours of wasted time, I found a solution.     The problem was that facebook recently had updated their API,   and  they forced  developers to update their app’s as well.

Anyway, after update now  we receive JSON-encoded response instead body encoded.    So  Here is Quick Fix

 

1  Create Class


public class FacebookOauthResponse
{
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
}

 

 

2 Extend   : HttpClientHandler And Create Class For Example FacebookBackChannelHandler

</pre>
public class FacebookBackChannelHandler
: HttpClientHandler
{
protected override async System.Threading.Tasks.Task<HttpResponseMessage>
SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
var result = await base.SendAsync(request, cancellationToken);
if (!request.RequestUri.AbsolutePath.Contains("access_token"))
return result;

// For the access token we need to now deal with the fact that the response is now in JSON format, not form values. Owin looks for form values.
var content = await result.Content.ReadAsStringAsync();
var facebookOauthResponse = JsonConvert.DeserializeObject<FacebookOauthResponse>(content);

var outgoingQueryString = HttpUtility.ParseQueryString(string.Empty);
outgoingQueryString.Add(nameof(facebookOauthResponse.access_token),
facebookOauthResponse.access_token);
outgoingQueryString.Add(nameof(facebookOauthResponse.expires_in),
facebookOauthResponse.expires_in + string.Empty);
outgoingQueryString.Add(nameof(facebookOauthResponse.token_type),
facebookOauthResponse.token_type);
var postdata = outgoingQueryString.ToString();

var modifiedResult = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(postdata)
};

return modifiedResult;
}
}
<pre>

 

 

 

3  Open Startup.Auth

And Find your Facebook   Auth options

 

</pre>
var options = new FacebookAuthenticationOptions()
{
AppId = ConfigurationManager.AppSettings["appid"],
AppSecret = ConfigurationManager.AppSettings["appsecret"],
BackchannelHttpHandler = new FacebookBackChannelHandler()    // Pass    Our New Handled   As Option

};
<pre>

 

 

 

And that’s it.   Once again Thank’s Facebook For Hours of wasted  Time.

 

Leave a Reply

Your email address will not be published. Required fields are marked *