Home > Blockchain >  Blazor: Authentication remains false
Blazor: Authentication remains false

Time:12-02

I have a middleware in my Startup.cs file which checks the users current authentication state. However, when debugging, it appears that even after a successful login the authentication remains false. I have searched for a solution, many of which provide solutions that not do work or do not apply to my project. I was wondering if anyone has come across this issue or could provide any insight into how I might resolve this issue. Thanks in advance

Startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
        app.UseHttpsRedirection();
        app.UseBlazorFrameworkFiles();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseIdentityServer();
        app.UseAuthentication();
 app.Use(async (context, next) =>
    {
        await next.Invoke();

        if (context.User.Identity.IsAuthenticated)
        {
            var username = context.User.Identity.Name;

            using (var dbContext = context.RequestServices.GetRequiredService<ApplicationDbContext>())
            {
                var user = dbContext.Users.Where(u => u.UserName == username).FirstOrDefault();
                user.LastAccessed = DateTime.Now;
                dbContext.Update(user);
                dbContext.SaveChanges();

            }
        }
    });
  app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapControllers();
            endpoints.MapFallbackToFile("index.html");
        });
}

CodePudding user response:

You could try to put the app.UseAuthentication(); before app.UseRouting(); like this :

app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseIdentityServer();
app.UseAuthentication();
app.UseRouting();

CodePudding user response:

This is the order:

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

 app.Use(async (context, next) =>
    {
        await next.Invoke();

        if (context.User.Identity.IsAuthenticated)
        {
            var username = context.User.Identity.Name;

            using (var dbContext = context.RequestServices.GetRequiredService<ApplicationDbContext>())
            {
                var user = dbContext.Users.Where(u => u.UserName == username).FirstOrDefault();
                user.LastAccessed = DateTime.Now;
                dbContext.Update(user);
                dbContext.SaveChanges();

            }
        }
    });
  
  • Related