Search code examples
c#asp.net-core.net-coreasp.net-core-webapi

Trouble with self-hosting web API with .NET Core


i am having trouble with self-hosting my web API in .NET Core. It runs fine on IIS but i get Authentication errors when im trying to self-host. I tried using cookie authentication among other solutions but in vain. I have only 1 route for now but after putting multiple breakpoints i noticed that it doesnt even reach the constructor of my controlelr. If anyone could give me a hint of a solution i would greatly appreciate it :)

Here are snippets of my code.

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();

    app.UseApplicationInsightsExceptionTelemetry();

    app.UseMvc();
}

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

    // Add the database used
    services.AddDbContext<VaultContext>(options => options.UseSqlServer(this.Configuration.GetConnectionString("VaultDatabase")));

    // Add our repository type
    services.AddScoped<VaultRepository, VaultRepository>();
    services.AddScoped<UserResolverService, UserResolverService>();
    services.AddScoped<PersonalizationServiceClient, PersonalizationServiceClient>();
    services.AddScoped<PersistenceToDataModelConverter, PersistenceToDataModelConverter>();

    services.AddMvc(config =>
    {
        var policy = new AuthorizationPolicyBuilder()
                            .RequireAuthenticatedUser()
                            .Build();
        config.Filters.Add(new AuthorizeFilter(policy));
    });
}

The config lamda in the ''services.AddMvc'' is the only i found that worked that forced the caller to give his Windows credentials that i will later analyze and display information based on his profile. If this is not the right way to do it please tell me.

And my controller class

public VaultController(VaultRepository repository, UserResolverService currentuser, PersonalizationServiceClient personalizationService, PersistenceToDataModelConverter persistenceToDataModelConverter)
{
    this.repository = repository;
    this.currentuser = currentuser;
    this.personalizationService = personalizationService;
    this.persistenceToDataModelConverter = persistenceToDataModelConverter;
}

/// <summary>
/// The get profile.
/// </summary>
/// <returns>
/// The <see cref="IActionResult"/>.
/// </returns>
[HttpGet]
[Route("/Profile")]
[Produces(typeof(UserProfile))]
public IActionResult SearchProfile()
{
    try
    {
        if (!this.currentuser.IsAuthenticated)
        {
            throw new Exception("This service does not support anonymous calls.");
        }

        var profile = Task.Run(() => this.personalizationService.GetUserProfileAsync(this.currentuser.GetCurrentWindowsIdentityName)).Result;

        var userProfile = this.persistenceToDataModelConverter.Convert(profile);
        userProfile.UserAdLogin = this.currentuser.GetCurrentWindowsIdentityName;

        return this.Ok(userProfile);
    }
    catch (Exception ex)
    {
        return this.NotFound(ex);
    }
}

Here is the error i get

enter image description here


Solution

  • please set the value of

    options.AutomaticChallenge = true

    that should resolve the authentication handler error.

    https://social.msdn.microsoft.com/Forums/en-US/d0b65153-4313-449d-8fb8-a861c3cf8bf7/aspnet-core-1-authentication-cookie-not-being-set-in-google-chrome-works-in-ie?forum=csharpgeneral