Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Vishal 3 posts 73 karma points
    1 week ago
    Vishal
    0

    Custom AUthentication on Umbraco 13.5.1 using HttpContext.SignInAsync -> User object not set

    0

    I'm experiencing an issue with implementing user authentication on the frontend of a web application using Umbraco version 13.5.1.

    Here's what I've done so far:

    Configured Authentication in Program.cs: // Program.cs WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

    builder.Services.AddHttpContextAccessor(); builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie();

    builder.CreateUmbracoBuilder() .AddBackOffice() .AddWebsite() .AddDeliveryApi() .AddComposers() .AddNotificationHandler

    CoreModule.Load(builder.Services); BusinessModule.Load(builder.Services);

    WebApplication app = builder.Build();

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

    await app.BootUmbracoAsync();

    app.UseUmbraco() .WithMiddleware(u => { u.UseBackOffice(); u.UseWebsite(); }) .WithEndpoints(u => { u.UseInstallerEndpoints(); u.UseBackOfficeEndpoints(); u.UseWebsiteEndpoints(); });

    await app.RunAsync();

    Created a SurfaceController for Authentication:

    //AccountController.cs

    public class AccountController : SurfaceController { private readonly Business.Services.Interfaces.IUserService _userService;

    public AccountController(Business.Services.Interfaces.IUserService userService,
                                IUmbracoContextAccessor umbracoContextAccessor,
                                IUmbracoDatabaseFactory databaseFactory,
                                ServiceContext services,
                                AppCaches appCaches,
                                IProfilingLogger profilingLogger,
                                IPublishedUrlProvider publishedUrlProvider)
    : base(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider)
    {
        _userService = userService;
    }
    
    [HttpPost]
    public async Task<IActionResult> Login(string email, string password)
    {
        if (_userService.ValidateUser(email, password))
        {
            //Dummy DATA
            var userData = new
            {
                Value = new {
                    Email = email,
                    Name = "Diogo Lopes",
                    CustomerId = 1234,
                    CustomerContactId = 1234
                }
            };
    
            var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, userData.Value.Name),
                    new Claim(ClaimTypes.Email, userData.Value.Email),
                    new Claim("CustomerId", userData.Value.CustomerId.ToString()),
                    new Claim("CustomerContactId", userData.Value.CustomerContactId.ToString()),
                };
    
            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
    
            var authProperties = new AuthenticationProperties
            {
                IsPersistent = true
            };
    
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, authProperties);
    
            var rootNode = CurrentPage.AncestorOrSelf("webStore");
            return RedirectToUmbracoPage(rootNode);
        }
        else
        {
            TempData["LoginError"] = "Invalid username or password.";
            return RedirectToCurrentUmbracoPage();
        }
    }
    
    [HttpPost]
    public async Task<IActionResult> Logout()
    {
        await HttpContext.SignOutAsync("CookieAuth");
        return RedirectToAction("Login");
    }
    

    }

    I'm experiencing an issue with implementing user authentication on the frontend of a web application using Umbraco version 13.3.2.

    Here's what I've done so far:

    Configured Authentication in Program.cs:

    // Program.cs WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

    builder.Services.AddHttpContextAccessor(); builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie();

    builder.CreateUmbracoBuilder() .AddBackOffice() .AddWebsite() .AddDeliveryApi() .AddComposers() .AddNotificationHandler

    CoreModule.Load(builder.Services); BusinessModule.Load(builder.Services);

    WebApplication app = builder.Build();

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

    await app.BootUmbracoAsync();

    app.UseUmbraco() .WithMiddleware(u => { u.UseBackOffice(); u.UseWebsite(); }) .WithEndpoints(u => { u.UseInstallerEndpoints(); u.UseBackOfficeEndpoints(); u.UseWebsiteEndpoints(); });

    await app.RunAsync();

    Created a SurfaceController for Authentication:

    //AccountController.cs

    public class AccountController : SurfaceController { private readonly Business.Services.Interfaces.IUserService _userService;

    public AccountController(Business.Services.Interfaces.IUserService userService,
                                IUmbracoContextAccessor umbracoContextAccessor,
                                IUmbracoDatabaseFactory databaseFactory,
                                ServiceContext services,
                                AppCaches appCaches,
                                IProfilingLogger profilingLogger,
                                IPublishedUrlProvider publishedUrlProvider)
    : base(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider)
    {
        _userService = userService;
    }
    
    [HttpPost]
    public async Task<IActionResult> Login(string email, string password)
    {
        if (_userService.ValidateUser(email, password))
        {
            //Dummy DATA
            var userData = new
            {
                Value = new {
                    Email = email,
                    Name = "Diogo Lopes",
                    CustomerId = 1234,
                    CustomerContactId = 1234
                }
            };
    
            var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, userData.Value.Name),
                    new Claim(ClaimTypes.Email, userData.Value.Email),
                    new Claim("CustomerId", userData.Value.CustomerId.ToString()),
                    new Claim("CustomerContactId", userData.Value.CustomerContactId.ToString()),
                };
    
            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
    
            var authProperties = new AuthenticationProperties
            {
                IsPersistent = true
            };
    
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, authProperties);
    
            var rootNode = CurrentPage.AncestorOrSelf("webStore");
            return RedirectToUmbracoPage(rootNode);
        }
        else
        {
            TempData["LoginError"] = "Invalid username or password.";
            return RedirectToCurrentUmbracoPage();
        }
    }
    
    [HttpPost]
    public async Task<IActionResult> Logout()
    {
        await HttpContext.SignOutAsync("CookieAuth");
        return RedirectToAction("Login");
    }
    

    } In the SurfaceController, I set the claims and use HttpContext.SignInAsync to sign in the user. I can see the authentication cookie being created successfully. However, the User object is not being updated correctly after the sign-in process.

    Here are the steps I followed in more detail:

    Configured the authentication settings in Program.cs during the application startup. Implemented a SurfaceController to handle the authentication logic. Set the user claims and called HttpContext.SignInAsync. Despite the authentication cookie being created, the User object remains unaffected.

    What could be causing this issue? Any insights or suggestions would be greatly appreciated.

    I tested the current configurationon an empty MVC project and it works correctly.

    Thank you!

Please Sign in or register to post replies

Write your reply to:

Draft