ASP.NET Core 3.1: Web API identity sign in

Viewed 124

I am creating CookieAutentecation signin for my Web API.

I have read and followed the official article here and I have done everything correctly as far as I am concerned.

But when I put breakpoints in my controllers and inspect HttpContext.User, everything is always null, no Username, no claims, nothing.

What else do I need to make this work? Are additional steps needed for Web API vs MVC app?

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, act => {
                act.LoginPath = "/api/login";
                act.AccessDeniedPath = "/api/login";
                act.SlidingExpiration = true;
            });

    services.AddControllers();

    services.AddServices(); // <- Own app domain services 
    services.AddDataAccess(); // <- Own app domain data access
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseCors(
            options => options.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
        );

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();
    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
}

api/login

var user = new SecurityUser()
        {
            UserID = 123,
            CompleteName = "Test user",
            FirstName = "Test",
            Email = "test.user@123.com"
        };
var identity = user.ToClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, 123);
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties()
        {
            AllowRefresh = true,
           ExpiresUtc = DateTime.UtcNow.AddDays(7),
           IsPersistent = true,
        });

ToClaimsIdentity extension method:

public static ClaimsIdentity ToClaimsIdentity(this SecurityUser user, string authenticantionType, int auditUserID)
{
        var claims = new List<Claim>()
        {
            new Claim(ClaimTypes.NameIdentifier, user.UserID.ToString()),
            new Claim(ClaimTypes.Email, user.Email),
            new Claim(ClaimTypes.Name, user.FirstName),
            new Claim(SecurityUserClaimTypes.AuditUserID, auditUserID.ToString())
        };

        var identity = new ClaimsIdentity(claims, authenticantionType);
        return identity;
}

Any help would be greatly appreciated.

Edit - This is what I am taking about enter image description here

1 Answers

Thanks for your help guys!

I finally realised it was a client thing, I did three things:

  • CORS was an issue, in my .UseCors method call my my Api I allowed credentials: .AllowCredentials()
  • My client app in using Blazor, I found this article here which told me I needed to set the http request configuration to include credentials, so in my client side app startup.cs:
    WebAssemblyHttpMessageHandlerOptions.DefaultCredentials = FetchCredentialsOption.Include;
  • I am using Http not Https on my local, and Chrome was complaining about SameSite, so im my Api StartUp.cs, where I call AddAuthentication...AddCookie I added this: options.Cookie.SameSite = SameSiteMode.Unspecified;

I don't fully understand the SameSite... and I have also come across JSON Web Tokens (JWT).
But I'm not interested, as long as it's working. ;-)

Related