Skip to main content

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.

Comments

Popular posts from this blog

Style in LWC

 Following are the ways we can apply in CSS in LWC. 1. Inline CCS Inline CSS is not recommended approaches, it is take highest priority among all CSS. style="color:green;font-size:10px;" is inline CSS added to div < template >     < lightning-card title = "Inline CSS" >         < div >             < div style = "color:green;font-size:10px;" > This is inline Style div </ div >         </ div >     </ lightning-card > </ template >  2. External CSS style can be applied to an elements such as h1, p,div span etc. It can applied to class using "." notation. for example .user{} It can also be applied to pseudo class.  for example .user:hover{} Id locator is not being used in LWC to apply style To apply external css, need to create separate CSS file, file name should be exactly matched with component name. for example - If component name is ...

How to Create/Delete file attachments(Content Document) through Apex ?

 There are 3 standard salesforce objects to store file attachments. Content Document, ContentDocumentVersion, ContentDocumentLink.  Here is the article to talk about these objects and relationship.  https://www.forcetalks.com/blog/contentdocument-and-contentversion-in-salesforce-an-overview/ ContentDocumentVersion ContentDocumentLink This post is all about how to create/delete content document though Apex. Here is code snippet // Insert Content Version record ContentVersion contentVersionRec = new ContentVersion(Title='filename',PathOnClient ='FileName.pdf',VersionData = bodyBlob,origin = 'H'); INSERT contentVersionRec; // this will insert one record in ContentDocument and ContentVersion , ContentDocument  is parent and  ContentVersion is child record // get contentdocument id contentVersionRec = [SELECT Id, Title, ContentDocumentId FROM ContentVersion WHERE Id = :contentVersionRec .Id LIMIT 1]; // Create Content Document Link record- This will attach ...

Lifecycle hooks in LWC

There are 3 phase of LWC component  1. Mounting  A. constructor, B. connnectedCallback C. render D. renderedCallback 2. UnMounting  A. disconnectedcallback 3. Error  A.errorcallback Note - render is not lifecycle hook, it is protected method of Lightning element class. Mounting Phase LWC Creation and Render Life cycle Constructor Method ·        This method called when component is instantiated and It flows from parent to child component. ·        Need to call Super() inside constructor method ·        Can’t access any component properties or child component because it’s not ready yet. ·        Host element can be accessed through “this. template” inside constructor method. ·        Don’t add any attributes to host inside constructor C   constructor (){          super (); //...