_signInManager.GetExternalLoginInfoAsync() 总是返回 null 和打开 id 到 azure 广告

Bil*_*ill 6 asp.net-core-mvc asp.net-core

为什么 signinmanager getexternallogininfoasync 方法总是返回 null?

我将 VS2015 与默认的 asp.net 核心(不是框架)项目一起用于具有个人用户帐户的 MVC (这是一项要求)。使用第三方登录的目的是让用户自行注册。基于角色的授权将由 asp.net 标识使用通过 Azure AD 注册时提供的标识进行处理。

如果以下对登录经理的解释不正确,请纠正我。此方法应提供有关外部登录的详细信息,并返回一个 claimprincipal 对象,其中包含用户提供的身份提供者提供的声明。

我使用以下指南在我的 Startup.cs(下面的类部分)中设置 OpenIdConnectAuthentication

https://azure.microsoft.com/en-us/documentation/samples/active-directory-dotnet-webapp-openidconnect/

当我启动外部登录提供程序时,它会将我定向到组织登录页面并成功。

但是,应由 signinmanager 方法填充的变量信息为 null

如果我在回调类中放置一个断点,则会填充 User 并且 IsAuthenticated 变量为 true。

我可以驱动允许用户自己在应用程序中注册的功能,但是,这是我第一次尝试实现第三方登录,我想了解在这一点上我做错了什么。

启动文件

  public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
        // Add Authentication services.
        services.AddAuthentication(sharedOptions => {
            sharedOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

        });
        //services.AddDistributedMemoryCache();
        //services.AddSession();
        services.AddMvc();

        // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseApplicationInsightsRequestTelemetry();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseApplicationInsightsExceptionTelemetry();

        app.UseStaticFiles();

        app.UseIdentity();

        // Configure the OWIN pipeline to use cookie auth.
        app.UseCookieAuthentication( new CookieAuthenticationOptions());



        //Add external authentication middleware below.To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
        app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
        {

            SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme,
            CallbackPath = "/signin-oidc",
            ClientId = Configuration["AzureAD:ClientId"],
            Authority = String.Format(Configuration["AzureAd:AadInstance"], Configuration["AzureAd:Tenant"]),
            ResponseType = OpenIdConnectResponseType.IdToken,
            PostLogoutRedirectUri = Configuration["AzureAd:PostLogoutRedirectUri"],
            Events = new OpenIdConnectEvents
            {
                //OnRemoteFailure = OnAuthenticationFailed,
            }
        });

        //app.UseSession();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

外部登录

        public IActionResult ExternalLogin(string provider, string returnUrl = null)
    {

        // Request a redirect to the external login provider.
        var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
        var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
        return Challenge(properties, provider);
    }
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Bil*_*ill 5

过去曾多次报告此方法产生空值的问题。对于任何开箱即用的受支持的身份验证方法都不会发生这种情况。至少在将 OAuth 与 azure AD 一起使用并遵循帖子中提供的方法时,这是一个问题。但是,有一种解决方法仍然允许使用默认项目类型。只需将生成ExternalLoginInfo 变量(info) 的方法替换为使用用户原则构建的您自己的ExternalLoginInfo 类即可。

 ExternalLoginInfo info = new ExternalLoginInfo(User,
            "Microsoft",
            User.Claims.Where(x=>x.Type== "http://schemas.microsoft.com/identity/claims/objectidentifier").FirstOrDefault().Value.ToString(),
           "Microsoft" );
Run Code Online (Sandbox Code Playgroud)

ASP.NET MVC 5(VS2013 最终版):使用 OWIN 登录 Facebook 失败(loginInfo 为 null)

MVC 5 Owin Facebook Auth 导致空引用异常

http://blogs.msdn.com/b/webdev/archive/2013/10/16/get-more-information-from-social-providers-used-in-the-vs-2013-project-templates.aspx


Joh*_*Fun 5

就我而言,我需要在启动时添加它时显式传递,如本 github 问题中所述:nullhttps : //github.com/AzureAD/microsoft-identity-web/issues/133cookieScheme

services.AddAuthentication(idp.LoginProvider).AddMicrosoftIdentityWebApp(
  o => {
    o.Instance = config.Instance;
    o.Domain = config.Domain;
    o.ClientId = config.ClientId;
    o.TenantId = config.TenantId;
    o.CallbackPath = config.CallbackPath;
    o.SignInScheme = IdentityConstants.ExternalScheme;
    o.SignOutScheme = IdentityConstants.ExternalScheme;
  },
  openIdConnectScheme: idp.LoginProvider,
  cookieScheme: null // YAR
);
Run Code Online (Sandbox Code Playgroud)