Tuesday, 4 February 2025

Handling Encrypted Fields in Salesforce LWC: Displaying SSN Based on User Permissions

Use Case

In Salesforce, encrypted fields provide an extra layer of security by allowing access only to users with the View Encrypted Data permission. In standard layouts and Lightning pages, Salesforce automatically manages the visibility of encrypted data based on a user's profile and permissions.

However, if you're building a Lightning Web Component (LWC) that displays Social Security Numbers (SSN), you must manually handle data masking. The goal is:

  • ✅ If a user has View Encrypted Data permission, they should see the full SSN (e.g., 113-212-4444).
  • ❌ If a user does not have View Encrypted Data permission, they should see only the last 4 digits, with the rest masked (e.g., ***-***-4444).

Since LWC does not inherently handle encrypted field visibility, we need to manage this logic in Apex before sending the formatted SSN to the component.

Solution: Handling Encrypted SSN in Apex

The best way to handle this is to:

  1. Check if the user has View Encrypted Data permission.
  2. Format the SSN based on the user's permission.
  3. Send the formatted SSN to LWC for display.

1️⃣ Utility Method to Check "View Encrypted Data" Permission

The following Apex method verifies if a user has the View Encrypted Data permission. If they do, they can see the full SSN; otherwise, we restrict it.

/***********************************************************
 * Description: Checks if the user has View Encrypted Data permission.
 * @param: userId - The User ID whose permissions need to be checked.
 * @return: Boolean - True if the user has permission, false otherwise.
 ***********************************************************/
public static boolean userHasEncryptedData(Id userId) {
    List<PermissionSetAssignment> psaEncrypt =
[SELECT Id
            FROM PermissionSetAssignment
            WHERE PermissionSet.PermissionsViewEncryptedData = true
            AND AssigneeId = :userId WITH SYSTEM_MODE];
    return psaEncrypt.isEmpty(); // Returns true if permission exists
}

🔹 How it Works:
  • The method queries the PermissionSetAssignment object to check if the View Encrypted Data permission is assigned to the user.
  • If the permission exists, it returns true; otherwise, it returns false.

2️⃣ Utility Method to Format SSN Based on User Permission

Once we determine if the user has permission, we format the SSN accordingly before sending it to the LWC component.

/***********************************************************
* Description: Sanitize the string if the user does not have view encrypted data permission.
*
* @param: hasEncryptedData - if the user has encrypted data permission
* @param: stringToSanitize - the string to santitize before returning to client
* @param: fieldType - this is the type of field to sanitize, only perform if encrypted string
*
* @return: boolean
* ********************************************************/
public static String sanitizeEncryptedData(Boolean hasEncryptedData,
                                    String stringToSanitize){
    if(!hasEncryptedData && stringToSanitize != null){
        return '***-***-'+stringToSanitize.right(4);
    } else{
        return stringToSanitize;
    }

}
🔹 How it Works:
  • If the user does not have View Encrypted Data the function masks the first 5 digits (***-***-) and only shows the last 4 digits.
  • If the user has permission, it returns the full SSN.

3️⃣ Apex Controller to Fetch Formatted SSN for LWC

Now, let’s combine both utility methods into an Apex controller that retrieves 
the SSN based on the user's permission.

public with sharing class LeadSSNController {
    @AuraEnabled(cacheable=true)
    public static String getFormattedSSN(Id leadId) {
        // Get current user Id
        Id currentUserId = UserInfo.getUserId();

        // Check if the user has View Encrypted Data permission
        Boolean hasEncryptedData = userHasEncryptedData(currentUserId);

        // Fetch Lead's SSN field (Assuming the field API name is SSN__c)
        Lead leadRecord = [SELECT SSN__c FROM Lead WHERE Id = :leadId LIMIT 1];

        // Format SSN before sending to LWC
        return sanitizeEncryptedData(hasEncryptedData, leadRecord.SSN__c);
    }
}
🔹 How it Works:
  • Retrieves the Lead's SSN field from Salesforce Checks whether the current user has the View Encrypted Data permission
  • Formats the SSN accordingly before returning it to the LWC component.

4️⃣ LWC Component To Display SSN

Now, the Lightning Web Component (LWC) simply receives the formatted SSN from Apex and 
displays it.


🔹 leadSSN.js

import { LightningElement, api, wire, track } from 'lwc';
import getFormattedSSN from '@salesforce/apex/LeadSSNController.getFormattedSSN';

export default class LeadSSN extends LightningElement {
    @api recordId; // Lead Id passed when placed on Lead Record Page
    @track formattedSSN;

    @wire(getFormattedSSN, { leadId: '$recordId' })
    wiredSSN({ error, data }) {
        if (data) {
            this.formattedSSN = data;
        } else if (error) {
            console.error('Error fetching SSN:', error);
            this.formattedSSN = 'Error loading SSN';
        }
    }
}
🔹 leadSSN.html
<template>
    <lightning-card title="Lead SSN">
        <div class="slds-p-around_medium">
            <p><b>SSN:</b> {formattedSSN}</p>
        </div>
    </lightning-card>
</template>

📌 Final Steps: Deploy & Test

1️⃣ Deploy the LWC Component

  • Add the LeadSSN component to the Lead Record Page.

2️⃣ Assign the Lightning Page to Users

  • Ensure Lightning Pages are enabled for all profiles.

3️⃣ Test in Different User Profiles

  • Login as a user with View Encrypted Data → See full SSN.
  • Login as a user without View Encrypted Data → See masked SSN.

🎯 Conclusion

In standard Salesforce layouts, encrypted fields are automatically handled.

However, when displaying sensitive data in an LWC component, you must:

  1. Check if the user has View Encrypted Data permission.
  2. Format the data accordingly in Apex before passing it to LWC.
  3. Ensure secure handling by displaying only the last 4 digits when necessary.

This approach ensures compliance with data security policies while allowing

authorized users to view full SSNs.

No comments: