注册外部登录Web API

时间:2015-05-14 07:58:46

标签: c# asp.net asp.net-web-api oauth-2.0 google-oauth

我不明白为什么他们不是一个明确的教程或指南,所以我希望我的问题可以在这里得到解答。

因此,尝试通过Web Api注册来自facebook或google的用户。

问题在于RegisterExternal方法,在这一行:

var info = await Authentication.GetExternalLoginInfoAsync();

返回null,从而返回BadRequest()

到目前为止我得到了什么:

Startup.Auth.cs我已经提到了身份证和秘密,请注意我也尝试使用Microsoft.Owin.Security.Facebook

var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions
            {
                AppId = "103596246642104",
                AppSecret = "1c9c8f696e47bbc661702821c5a8ae75",
                Provider = new FacebookAuthenticationProvider()
                {
                    OnAuthenticated = (context) =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("urn:facebook:access_token", context.AccessToken, ClaimValueTypes.String, "Facebook"));

                        return Task.FromResult(0);
                    }
                },
            };
            facebookOptions.Scope.Add("email");
            app.UseFacebookAuthentication(facebookOptions);



            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
            ClientId = "328779658984-t9d67rh2nr681bahfusan0m5vuqeck13.apps.googleusercontent.com",
            ClientSecret = "ZYcNHxBqH56Y0J2-tYowp9q0",
            CallbackPath = new PathString("/api/Account/ManageInfo")
        });

facebookOptions来源:this post

额外的facebookOptions没有解决问题。

我可以从Google和Facebook检索access_token。我也可以使用此access_token进行身份验证api/Account/UserInfo

GET http://localhost:4856/api/Account/UserInfo
in the header:
Authorization: Bearer R9BTVhI0...

返回: {"Email":"firstname lastname","HasRegistered":false,"LoginProvider":"Facebook"}

我注意到的一个问题是,它将我的名字作为电子邮件返回,而不是实际的电子邮件地址。

现在我想用我的数据库的新用户注册外部登录,我这样做一个POST调用:

POST http://localhost:4856/api/Account/RegisterExternal
[header]
authorization: bearer 6xcJoutY...
Content-Type: application/json
[body]
{"Email":"...@hotmail.com"}

来源:this post

现在,这会在RegisterExternal()中的代码snippit上返回BadRequest:

    public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
    {
if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            //AuthenticationManger?
            var info = await Authentication.GetExternalLoginInfoAsync();
            if (info == null)
            {
                return InternalServerError();
            }

在调试中,ExternalLoginConfirmationViewModel确实包含我的电子邮件地址。

我做错了什么?我是否必须向Startup.cs添加内容?我需要在Startup.Auth.cs中做些什么吗?我错误地拨打RegisterExternal了吗?在MVC中它是如此顺利,为什么不在Web API中呢?

Aso从this answer查看了this question,但我并不了解如何实现这一点。

1 个答案:

答案 0 :(得分:5)

这种方法并不实用,因为你正在开发一种最有可能用于应用程序的API,你最好的方法是通过API消费者处理facebook的登录,让他们发给你一个facebook认证令牌

基本上我试图这样做:

  1. 为facebook创建外部登录链接。
  2. 将用户发送到该链接,将其带到Facebook登录页面。
  3. 登录后,facebook会重定向到api。
  4. 用户将被注册,但消费API的应用/网站如何知道?
  5. 你想要做的是:

    1. API使用者创建自己的方法来登录facebook(通过SDK的应用程序)
    2. API使用者将向API发送facebook令牌以注册/登录。
    3. API将使用facebook图表端点检查令牌。
    4. 如果成功,API将返回API的持票令牌,以进一步进行身份验证请求。
    5. 因此,作为API开发人员,您可以像这样验证令牌:

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

      然后获取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"];
      }
      

      最终你会创建或找到像这样的用户:

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

      然后,如果你按照下面列出的教程,你可以拥有这个:

      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);
      

      来源,完整教程here

      我还通过SDK收到了电子邮件,并将其与POST请求一起发送,因为我管理了API和消费者。但警告:Facebook用户可能不想给你一个电子邮件地址。

      在Facebook登录AndroidIOS

      后收到电子邮件