Register External Login Web API Register External Login Web API asp.net asp.net

Register External Login Web API


This method is not really practical, since you are developing an API, that will most likely be used for apps, you best way is to handle the login with facebook by the API consumer, and let them send you an facebook auth token.

Basically I was trying to do this:

  1. Create external login link for facebook.
  2. Send user to that link that will bring them to facebook login page.
  3. After login facebook will redirect to api.
  4. User would be registered, but how does the app/website that is consuming the API know?

What you want to do is this:

  1. API consumer creates their own method to login with facebook (for apps via SDK's)
  2. API consumer will send an facebook token to the API to register/login.
  3. API will check token with facebook graph endpoint.
  4. When succeeded, API will return an bearer token for the API to make further authenticated requests.

So for you as an API developer, you would verify the token like so:

var verifyTokenEndPoint = string.Format("https://graph.facebook.com/debug_token?input_token={0}&access_token={1}", accessToken, appToken);

And then get the userId

var client = new HttpClient();var uri = new Uri(verifyTokenEndPoint);var response = await client.GetAsync(uri);if (response.IsSuccessStatusCode){    var content = await response.Content.ReadAsStringAsync();    dynamic jObj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(content);    string user_id = jObj["data"]["user_id"];    string app_id = jObj["data"]["app_id"];}

Eventually you would create or find a user like so:

IdentityUser user = await _userManager.FindAsync(new UserLoginInfo(provider, verifiedAccessToken.user_id));

And then it's all up to you how to create an bearer token, if you follow the tutorial listed below, you could have this:

var tokenExpiration = TimeSpan.FromMinutes(30);ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);identity.AddClaim(new Claim(ClaimTypes.Name, userName));identity.AddClaim(new Claim("role", "user"));var props = new AuthenticationProperties(){    IssuedUtc = DateTime.UtcNow,    ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),};var ticket = new AuthenticationTicket(identity, props);var accessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);

Source, with full tutorial here

I've also got the email via the SDK and send that along with the POST request, since I managed both the API and the consumer. Warning though: A facebook user might not want to give you an e-mail address.

Get e-mail after facebook login on Android and IOS