首页 > 解决方案 > 使用依赖注入时在 ASP.NET MVC 中注册 FacebookAuthentication

问题描述

目前在Startup.csIAppBuilder根据web.config信息在 Facebook 提供商中注册。

现在我想移动逻辑,以便根据数据库中的数据加载 Facebook应用程序 ID应用程序机密,或者如果不存在则从web.config.

最初:

  app.UseFacebookAuthentication(new FacebookAuthenticationOptions
  {
    AppId = ConfigurationManager.AppSettings["fb_appid"],
    AppSecret = ConfigurationManager.AppSettings["fb_appsecret"]
  });

现在,我有从数据库中检索这些 id 和 secret 的存储库。

我用默认的 fb 身份验证更改了该行:

  app.CreatePerOwinContext(() => new AppBuilderProvider(app));

public class AppBuilderProvider : IDisposable
{
    private IAppBuilder _app;

    public AppBuilderProvider(IAppBuilder app)
    {
        _app = app;
    }

    public IAppBuilder Get() { return _app; }
    public void Dispose() { }

    public void RegisterFacebook(string appId, string appSecret)
    {
        _app.UseFacebookAuthentication(new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions
        {
            AppId = appId,
            AppSecret = appSecret
        });
    }
}

在控制器中我使用:

[ChildActionOnly]
public ActionResult LoadExternalLogin()
{
      var appBuilder = HttpContext.GetOwinContext().Get<AppBuilderProvider>();

      if (_context.IsSocialNetworkLoginEnabled)
      {
        appBuilder.RegisterFacebook(_context.FacebookAppId, _context.FacebookAppSecret);
      }

      return PartialView("_ExternalLogin");
}

在部分视图中:

@{
    var loginProviders = Context.GetOwinContext().Authentication.GetExternalAuthenticationTypes();
    if (loginProviders.Any())
    {
        <div class="col-xs-5 separator"></div>
        <div class="col-xs-2"><span class="text-center" data-i18n="Login_SocialNetworkLoginLabel"></span></div>
        <div class="col-xs-5 separator"></div>
        <div class="col-xs-12">&nbsp;</div>
        using (Html.BeginFormEx(Model.Action, "Account", new { ReturnUrl = Model.ReturnUrl }, FormMethod.Post, null))
        {
            foreach (AuthenticationDescription p in loginProviders)
            {
                <button type="submit" class="btn btn-primary btn-social" id="@p.AuthenticationType" name="provider" value="@p.AuthenticationType" ><span class="socialNetworkLoginIcon icon_@p.AuthenticationType.ToLowerInvariant()"></span><span class="socialNetworkLoginText" data-i18n="Button_LoginWith_@p.AuthenticationType.ToLowerInvariant()">@p.AuthenticationType</span><span class="glyphicon glyphicon-menu-right"></span></button>
            }
        }
    }
}

问题是它loginProviders是空的,似乎无法使用我的方法注册 Facebook 身份验证。

如果我使用 withstartup.cs方法,则loginProviders集合中有一项。

为什么 ?

标签: c#asp.net-mvc

解决方案


推荐阅读