CustomRequestCultureProvider:context.User.Identity.IsAuthenticated始终为false

时间:2018-02-14 11:48:18

标签: asp.net-core asp.net-core-identity asp.net-core-localization

我正在尝试在我的本地化管道中实现CustomRequestCultureProvider,以从数据库中检索用户文化。要识别用户,我需要ClaimsPrincipal,但出于某种原因,即使用户已通过身份验证,context.User.Identity.IsAuthenticated也始终为false。

以下是相关代码(截断以突出显示我的问题:身份验证已在运行;本地化代码基于localization tutorial)。

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<RequestLocalizationOptions>(options =>
        {
            var supportedCultures = new[]
            {
                new CultureInfo("fr"),
                new CultureInfo("en"),
            };

            options.DefaultRequestCulture = new RequestCulture("fr");
            options.SupportedCultures = supportedCultures;
            options.SupportedUICultures = supportedCultures;

            // we insert at 2, because we want to first check the query, then the cookie, then the DB, then the headers
            options.RequestCultureProviders.Insert(2, new CustomRequestCultureProvider(async context =>
            {
                // ----->> ISSUE IS HERE: this is always false!
                if (context.User.Identity.IsAuthenticated)
                    return new ProviderCultureResult("en");

                return null;
            }));
        });

        services
            .AddLocalization(options => options.ResourcesPath = "Resources")
            .AddMvc()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            ;

        return services;
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseRequestLocalization();
        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseMvcWithDefaultRoute();
        return app;
    }
}

我应该如何检索ClaimsPrincipal中的CustomRequestCultureProvider

注意:更改注册顺序(在app.UseAuthentification之前调用app.UseRequestLocalization无法解决问题)。

2 个答案:

答案 0 :(得分:3)

以防万一以后有人遇到这个问题,我在ASP.NET Core 2.1中也遇到了类似的问题,结果发现我在插入CustomRequestCultureProvider之后正在注册身份验证中间件。为了解决该问题,我将app.UseAuthentication()上方的options.RequestCultureProviders.Insert(...

答案 1 :(得分:0)

我设法通过手动调用身份验证管道来使其工作。我怀疑我需要这样做,因为稍后在中间件管道中触发Authorize属性,因此检索ClaimsPrincipal为时过早(我可能错了)。

无论如何,这是我修改CustomRequestCultureProvider

的方式
// we insert at 2, because we want to first check the query, then the cookie, then the DB, then the headers
options.RequestCultureProviders.Insert(2, new CustomRequestCultureProvider(async context =>
{
    // retrieve the ClaimsPrincipal from the cookies
    // note: this is dependent on how your authentication is set up
    var authResult = await context.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    if (!authResult.Succeeded)
        return null;

    var user = authResult.Principal;
    if (user != null)
        return new ProviderCultureResult("en");

    return null;
}));