Handling Encrypted SSN in LWC: Show Full or Masked SSNs Based on User Permission

Learn how to safely display Social Security Numbers in a Lightning Web Component by checking the View Encrypted Data permission in Apex, formatting SSNs securely, and returning only masked values to unauthorized users.

Why this matters

Encrypted fields in Salesforce (like SSN) are protected: only users with the View Encrypted Data permission should see the full value. Lightning Web Components (LWC) do not automatically enforce encrypted field visibility, so you must perform permission checks and masking in Apex before sending values to the client. This ensures compliance with security policies and prevents accidental exposure of sensitive data.

Approach Overview

The recommended pattern is:

  • Check whether the current user has the View Encrypted Data permission (via PermissionSetAssignment).
  • Format or mask the SSN in Apex depending on permission.
  • Return the safe, formatted string to the LWC for display.

Key Apex utilities

Below are two utility methods: one to check the permission and another to sanitize (mask) the SSN when required.

Check View Encrypted Data permission

public static Boolean userHasEncryptedData(Id userId) {
    // Query permission set assignments that grant View Encrypted Data
    List<PermissionSetAssignment> psaEncrypt = [
        SELECT Id
        FROM PermissionSetAssignment
        WHERE PermissionSet.PermissionsViewEncryptedData = true
        AND AssigneeId = :userId
        WITH SYSTEM_MODE
    ];
    // Return true if at least one matching permission set assignment exists
    return !psaEncrypt.isEmpty();
}

Sanitize / mask SSN when user lacks permission

public static String sanitizeEncryptedData(Boolean hasEncryptedData, String stringToSanitize){
    if(!hasEncryptedData && stringToSanitize != null){
        // Mask all but last 4 digits (format: ***-***-1234)
        return '***-***-' + stringToSanitize.right(4);
    } else {
        // User is authorized or value is null — return original
        return stringToSanitize;
    }
}

Apex controller for LWC

Combine the utilities in a controller method that the LWC can call. This example assumes the SSN field API name is SSN__c on Lead.

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

        // Check permission
        Boolean hasEncryptedData = userHasEncryptedData(currentUserId);

        // Fetch Lead's SSN (encrypted field)
        Lead leadRecord = [SELECT SSN__c FROM Lead WHERE Id = :leadId LIMIT 1];

        // Return formatted (masked or full) string
        return sanitizeEncryptedData(hasEncryptedData, leadRecord.SSN__c);
    }
}

Lightning Web Component (LWC)

The LWC simply calls the Apex method and displays the returned, already-formatted SSN.

leadSSN.js

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

export default class LeadSSN extends LightningElement {
    @api recordId;
    @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>

Best practices & testing

  • Ensure your encrypted field (SSN__c) is set up correctly in Salesforce and that only necessary profiles/permission sets have View Encrypted Data.
  • Unit test Apex methods to validate both branches (authorized and unauthorized users).
  • Use with sharing on controllers when appropriate and avoid returning raw sensitive values to the client.
  • Log access carefully (avoid logging full SSNs) and follow your org’s data retention and audit policies.

Conclusion

By validating the View Encrypted Data permission in Apex and masking SSNs before returning them to the LWC, you can safely display sensitive information only to authorized users. This pattern keeps the client-side simple and centralizes the security logic in Apex, making it easier to test and audit.

Why this matters for Salesforce admins, developers, and business users: Admins control who can see full encrypted data via permission sets; developers get a safe pattern to follow when building LWCs; business users receive a consistent UI showing either a masked or full SSN depending on their access — protecting sensitive customer data while enabling legitimate business use.