This blog can help you work with Sitecore JSS and extend the layout service context. The following steps will guide you to create the pipeline processor and patch it in the right place in order to work appropriately.
Layout service is an open REST API and by default, it does not expect username as part of query string params. This approach/solution will help you to create a virtual user/assign the appropriate roles in order to leverage the Sitecore OOTB authorization capabilities.
Use Case: If there are multiple user groups and you want to manage the access at the item or folder level, Sitecore can make the decision either to redirect the 401-Unauthorised Access page or allow that user to access the requested page.
1. Create a pipeline/processor(C# class)
C# class code:
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Web; using Sitecore.Data.Managers; using Sitecore.Kernel; using Sitecore.JavaScriptServices.Configuration; using Sitecore.JavaScriptServices.ViewEngine.LayoutService.Pipelines.GetLayoutServiceContext; using Sitecore.LayoutService.ItemRendering.Pipelines.GetLayoutServiceContext; using Sitecore.Data; using Sitecore.Security.Accounts; using Newtonsoft.Json; using Sitecore.Security; using Sitecore.Eventing.Remote; using System.Diagnostics.Eventing.Reader; namespace ABC.Pipelines {
public class VirtualUserAuth : JssGetLayoutServiceContextProcessor { protected override void DoProcess(GetLayoutServiceContextArgs args, AppConfiguration application) {
bool isSecureAccessEnabled = false;
//Add condition and call the method-CreateVirtualUser()
// Pass userObject as argument
//Parsing the query string parameters from layout service api call
var userId = Convert.ToString(HttpContext.Current.Request.Params["userid"]);var user = CreateVirtualUser(userObject);
//Read a custom property from the user object and assign it to the layout service context object
isSecureAccessEnabled = user.Profile.GetCustomProperty("eligibility");args.ContextData.Add("userAccess", new { enabled = isSecureAccessEnabled });
//Modifying the response payload}
public User CreateVirtualUser(string userObject) { //Deserializing the received userObject LoggedUser loggedUser = JsonConvert.DeserializeObject<LoggedUser>(userObject); //Parsing the data for creation of virtual user string userId = loggedUser.EmailId; string domain = loggedUser.Domain; string domainUser = string.Format(@"{0}\{1}", domain, userId); //Check if such a user already exists if (Sitecore.Security.Accounts.User.Exists(domainUser)) { return Sitecore.Security.Accounts.User.FromName(domainUser, true); } //Create virtual user based on the emailid User user = Sitecore.Security.Authentication.AuthenticationManager.BuildVirtualUser(string.Format(@"{0}\{1}", domain, userId), true); user.RuntimeSettings.Load(); user.RuntimeSettings.AddedRoles.Clear(); user.Roles.RemoveAll(); if (loggedUser.IsEligible) { //Assign User Roles AssignUserRoles(user, userRole); } //Set the user profile and return return SetupVirtualUserProfile(user, loggedUser); } //Method to set the user role public void AssignUserRoles(User user, string userRole) { Role role = Role.FromName(userRole); if (role != null) { //Assign the role user.Roles.Add(Role.FromName(userRole)); } } //Method to setup the Virtual User Profile public User SetupVirtualUserProfile(User user, LoggedUser loggedUser) { //Set default values for custom properties user.Profile.FullName = loggedUser.EmailId; user.Profile.Email = loggedUser.EmailId; //Set custom properties for the user profile user.Profile.SetCustomProperty("isMaxUser", loggedUser.Eligibility.isISOnetUser.ToString()); user.Profile.SetCustomProperty("hasAddOnPermissions", loggedUser.Eligibility.hasAddOnPermissions()); //Save the profile user.Profile.Save(); user.RuntimeSettings.IsVirtual = true; user.RuntimeSettings.Save(); user.Profile.Reload(); return user; } }
}
2. Create a patch Config file
<?xml version="1.0" encoding="utf-8" ?>
<!--
Purpose: This include file configures the Layout service extension getLayoutServiceContext to verify user's access on Sitecore Item
-->
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:role="http://www.sitecore.net/xmlconfig/role/" >
<sitecore role:require="Standalone or ContentDelivery or ContentManagement">
<pipelines>
<group groupName="layoutService">
<pipelines>
<getLayoutServiceContext>
<processor type="ABC.Pipelines.UserItemAuthorization, ABC.Pipelines"
resolve="true">
</processor>
</getLayoutServiceContext>
</pipelines>
</group>
</pipelines>
</sitecore>
</configuration>
3. Layout service API call with userId
/sitecore/api/layout/render/default?item={Page Item ID}&sc_apikey=67HJK9-2EB0-DFG67-AAA5-DFG789KJL&userid=abc@xyz.com
Happy Learning!
No comments:
Post a Comment