ASP.NET Core 5 MVC : httpContext.User not authenticated in custom CultureProvider

Viewed 138

I have to add localization in my web application.

A request is that a grpc service will give the default language for all users, so in the startup I'm trying to read that value but don't know how to use a registered service inside new CustomRequestCultureProvider

public static CultureInfo[] supportedCultures = new[] { new CultureInfo("it-IT"), new CultureInfo("en-US")};

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<ISpaClient, GrpcSpaClient>();

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

    services.Configure<RequestLocalizationOptions>(options =>
        {
            options.DefaultRequestCulture = new RequestCulture(culture: supportedCultures[0].ToString(), uiCulture: supportedCultures[0].ToString());
            options.SupportedCultures = supportedCultures;
            options.SupportedUICultures = supportedCultures;

            options.RequestCultureProviders.Clear();
            options.RequestCultureProviders.Add(new MyCustomRequestCultureProvider());
        });
}

My custom class

public class MyCustomRequestCultureProvider : RequestCultureProvider
{
    public override async Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
    {
        await Task.Yield();

        if (httpContext == null)
        {
            throw new ArgumentNullException(nameof(httpContext));
        }

        if (!httpContext.User.Identity.IsAuthenticated)
        {
            return null;
        }
        
        var culture = httpContext.User
                                 .Claims
                                 .FirstOrDefault(c => c.Type == TipoClaim.linguaPredefinita.ToString())?
                                 .Value;

        if (culture == null)
        {
            return null;
        }

        return new ProviderCultureResult(culture);
    }
}

But here httpContext.User is never Authenticated, even if the page is

1 Answers

My best guess is that you called UseRequestLocalization before UseAuthentication.

Related