Sitecore终端用户登录页开发及个性化页面展示需求咨询
Alright, let's break this down into actionable, project-tested steps based on your requirements. This is a common integration between custom authentication systems and Sitecore, so I’ll walk you through each piece with code examples and best practices.
Since you don’t want to store user data in Sitecore, we’ll build a standalone ASP.NET (MVC/Razor Pages) auth flow that interacts directly with your SQL database. Here’s how to approach it:
Registration Flow
- Create a SQL table for users (use Entity Framework Core for easy data access):
CREATE TABLE AppUsers ( Id INT PRIMARY KEY IDENTITY(1,1), Email NVARCHAR(255) UNIQUE NOT NULL, Username NVARCHAR(50) UNIQUE NOT NULL, PasswordHash NVARCHAR(255) NOT NULL, IsFirstLogin BIT DEFAULT 1, CreatedAt DATETIME DEFAULT GETDATE() ) - Build a registration form that accepts email, username, and password. Always hash passwords (use BCrypt or ASP.NET Identity’s password hasher—never store plain text!):
public async Task<IActionResult> Register(RegisterViewModel model) { if (!ModelState.IsValid) return View(model); // Hash password securely var passwordHasher = new PasswordHasher<AppUser>(); var hashedPassword = passwordHasher.HashPassword(null, model.Password); // Create user entity var user = new AppUser { Email = model.Email, Username = model.Username, PasswordHash = hashedPassword }; // Save to SQL via EF Core _dbContext.AppUsers.Add(user); await _dbContext.SaveChangesAsync(); // Redirect to login page post-registration return RedirectToAction("Login"); }
Login Flow
- Validate user credentials against your SQL database, then retrieve the user ID for the next step:
public async Task<IActionResult> Login(LoginViewModel model) { if (!ModelState.IsValid) return View(model); // Fetch user from SQL var user = await _dbContext.AppUsers.FirstOrDefaultAsync(u => u.Email == model.Email); if (user == null) { ModelState.AddModelError("", "Invalid credentials"); return View(model); } // Verify password hash var passwordHasher = new PasswordHasher<AppUser>(); var result = passwordHasher.VerifyHashedPassword(user, user.PasswordHash, model.Password); if (result == PasswordVerificationResult.Failed) { ModelState.AddModelError("", "Invalid credentials"); return View(model); } // Pass validated user ID to Sitecore (see next section) SignInToSitecore(user.Id); return RedirectToAction("UserDashboard"); }
Once the user is authenticated via your SQL system, you need to sync their ID with Sitecore. The best approach here is to use Sitecore’s virtual user system (no need to create a permanent Sitecore user record) or add a custom claim to the authenticated identity:
Option 1: Virtual User (Recommended for Simple Integrations)
Virtual users let you create temporary Sitecore user profiles without storing them in Sitecore’s database:
private void SignInToSitecore(int userId) { // Log out any existing Sitecore user first to avoid conflicts if (Sitecore.Context.User.IsAuthenticated) { Sitecore.Security.Authentication.AuthenticationManager.Logout(); } // Create a unique virtual user (use user ID in the username for uniqueness) var virtualUser = Sitecore.Security.Authentication.AuthenticationManager.BuildVirtualUser($"extranet\\external-user-{userId}", true); // Store the external SQL user ID in the virtual user's profile virtualUser.Profile.SetCustomProperty("ExternalUserId", userId.ToString()); virtualUser.Profile.Save(); // Log the virtual user into Sitecore Sitecore.Security.Authentication.AuthenticationManager.LoginVirtualUser(virtualUser); }
Option 2: Custom Claims (For Advanced Identity Scenarios)
If you’re using ASP.NET Core Identity alongside Sitecore, add the user ID as a claim to the identity:
private async Task SignInToSitecore(int userId) { var claims = new List<Claim> { new Claim(ClaimTypes.NameIdentifier, userId.ToString()), new Claim(Sitecore.Security.Authentication.Claims.DefaultClaimTypes.NameIdentifier, userId.ToString()) }; var claimsIdentity = new ClaimsIdentity(claims, Sitecore.Security.Authentication.DefaultAuthenticationType); await Sitecore.Security.Authentication.AuthenticationManager.LoginAsync(claimsIdentity); }
You can retrieve the user ID in Sitecore later using Sitecore.Context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value.
Now that Sitecore has the user ID, you can fetch their widget preferences from SQL and render a personalized page. Here’s how to handle both first-time login and subsequent visits:
First-Time Login Handling
- Check the
IsFirstLoginflag in your SQL user table. If true, redirect to an onboarding page where the user selects their widgets:public async Task<IActionResult> UserDashboard() { var externalUserId = int.Parse(Sitecore.Context.User.Profile.GetCustomProperty("ExternalUserId")); var user = await _dbContext.AppUsers.FirstOrDefaultAsync(u => u.Id == externalUserId); if (user.IsFirstLogin) { return RedirectToAction("WidgetOnboarding"); } // Fetch saved widgets and render dashboard (see below) var widgets = await _dbContext.UserWidgets.Where(w => w.UserId == externalUserId).ToListAsync(); return View(new DashboardViewModel { Widgets = widgets }); } - After the user selects widgets, update the
IsFirstLoginflag to false and save their selections to SQL.
Personalized Page Rendering
- Use a Sitecore Controller Rendering to fetch the user’s widgets and dynamically load the corresponding components. For example, in your controller:
public ActionResult WidgetDashboard() { var externalUserId = int.Parse(Sitecore.Context.User.Profile.GetCustomProperty("ExternalUserId")); var widgets = _widgetService.GetUserWidgets(externalUserId); // Map widget types to Sitecore rendering IDs (define these in your config or constants) var renderings = widgets.Select(w => new RenderingViewModel { RenderingId = GetRenderingIdForWidgetType(w.Type), Parameters = new { WidgetId = w.Id } }); return View(renderings); } - In your view, loop through the renderings and render each one using Sitecore’s built-in helper:
@foreach (var rendering in Model) { @Html.Sitecore().Rendering(rendering.RenderingId, rendering.Parameters) }
内容的提问来源于stack exchange,提问作者ImSobesBoosted




