Restrict Access to Lightning Applications with Step-Up Authentication

If your Lightning app contains sensitive data or information, you can very easily implement an extra layer of data security by requiring users to verify their identity before they access the app. Users with a standard session who try to access the app are prompted to verify their identity using two-factor authentication. When users authenticate successfully, their session security level “steps up” from standard to high assurance.

Users can authenticate with a time-based one-time password (TOTP) generated by an authenticator app like Salesforce Authenticator. You can also extend this example to integrate with other two-factor authentication methods, such as a one-time password sent via email or SMS.

This post shows how to build step-up authentication for a simple Lightning app that displays the org’s top 10 opportunities.

 

Step 1: Create an Apex class

First, create an AuraEnabled Apex helper that implements the following methods:

  • getSessionLevel – Get the current user session level. The returned value can be either STANDARD or HIGH_ASSURANCE.
  • getOppts – Get a list of 10 opportunities based on amount ONLY if the current user session is HIGH_ASSURANCE.
  • verify – Verify the one-time-password code provided by the user. If the code is valid, the method raises the user session level to HIGH_ASSURANCE and returns true.
  1. From Setup, enter “apex” in the Quick Find box, then select Apex Classes.
  2. Click New and implement the StepUpLightningHelper class as follows:
public class StepUpLightningHelper {

  @AuraEnabled
  public static String getSessionLevel() {
    Map<String,String> session = Auth.SessionManagement.getCurrentSession();
    String sessionLevel = session.get('SessionSecurityLevel');

    return sessionLevel;
  }

  @AuraEnabled
  public static List getOppts() {
    String level = getSessionLevel();

    if(level == 'HIGH_ASSURANCE') 
      return [Select Name, Id From Opportunity Order By Amount desc Limit 10];

    return null;
  }

  @AuraEnabled
  public static boolean verify(string code) {

    Boolean status=false;

    try {
      status = Auth.SessionManagement.validateTotpTokenForUser(code);
    }
    catch(Exception e)
    {
      system.debug('The key is invalid or the current user has attempted too many validations');
      return status;
    }

    if(status == true)
      Auth.SessionManagement.setSessionLevel(Auth.SessionLevel.HIGH_ASSURANCE);

    return status;
  }
}

3. Click Save.

 

Step 2: Create a Lightning component

Create a Lightning component with a reference to the Apex class that you created in the previous step.

This component displays the list of opportunities retrieved from the Apex object. Remember: if the users session is STANDARD, the list will be empty.

This component also uses the <aura:renderIf> tag to conditionally render the code that is responsible for getting the one-time password from the user and sending it to the server for verification.

  1. In the Developer Console, click File > New > Lightning Component. Specify StepUp as the bundle name and click Submit.
  2. Implement the component as follow:
<aura:component controller="StepUpLightningHelper" implements="force:appHostable">
  <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
  <aura:attribute name="tenOppts" type="Object" />
  <aura:attribute name="errorText" type="String" />

  <h1>My Top 10 Opportunities</h1><br/><br/>
  <ui:outputText value="Your Session Level is: "/>
  <ui:outputText value="{!v.sessionLevel}"/>
  <br/><br/>

  <aura:renderIf isTrue="{!v.sessionLevel == 'STANDARD'}">
    <ui:inputText aura:id="code" label="Enter Verification Code: " placeholder="code" />
    <ui:outputText value="{!v.errorText}"/>
    <br/><br/>
    <ui:button aura:id="button" label="Verify" press="{!c.doVerify}"/><br/>
  </aura:renderIf>

  <aura:iteration items="{!v.tenOppts}" var="item">
    <ui:outputText value="{!item.Name}"/><br/>
  </aura:iteration>
</aura:component>

3. Click File > Save.

 

Step 3: Create a Lightning controller

In the controller element, create the following methods:

  • doInit – Call the getSessionLevel and getOppts methods of the Apex helper and retrieve the current user session level and the list of opportunities.
  • doVerify – Call the verifyAndGetOppts method of the Apex helper.
  1. In the right menu click Controller.
  2. Implement the Controller as follows:
({
  doInit : function(component, event, helper) {
    var action = component.get("c.getSessionLevel");
    action.setCallback(this, function(a) {
      component.set("v.sessionLevel", a.getReturnValue());
    });

    $A.enqueueAction(action);

    var action = component.get("c.getOppts");
    action.setCallback(this, function(a) {
      component.set("v.tenOppts", a.getReturnValue());
    });

    $A.enqueueAction(action);
  },

  doVerify : function(component) {
    var action = component.get("c.verify");

    action.setParams({
      code : component.find("code").get("v.value")
    });

    action.setCallback(this, function(a) {
      component.set("v.tenOppts", a.getReturnValue());
      if(a.getReturnValue() == false)
        component.set("v.errorText", "Invalid code. Try again.");
      else
        $A.get("e.force:refreshView").fire();
    });

    $A.enqueueAction(action);
  }
})

3. Click File > Save.

 

Step 4: Create a custom tab for the Step Up component

Now you just need a tab for the Step Up component.

  1. From Setup, enter “Tabs” in the Quick Find box, then select Tabs.
  2. Click New in the Lightning Component Tabs related list.
  3. Select c:StepUp from the Lightning Component drop-down menu.
  4. In Tab Label, enter “My Top 10 Opportunities”.
  5. Choose a tab style.
  6. Click Next.
  7. When prompted to add the tab to profiles, accept the default and click Save.

 

Add the component to the Salesforce1 menu

  1. From Setup, enter “Salesforce1 Navigation” in the Quick Find box, then select Salesforce1 Navigation.
  2. Move Step Up from the Available list to the Selected list.
  3. Click Save.

 

Step 5: Connect Salesforce Authenticator to your account

  1. Download Salesforce Authenticator for iOS or Android and install it on your mobile device.
  2. Log in to your Salesforce org.
  3. From your personal settings, enter “Advanced User Details” in the Quick Find box, then select Advanced User Details. No results? Enter “Personal Information” in the Quick Find box, then select Personal Information.
  4. Find App Registration: One-Time Password Generator and click Connect.
  5. Use the Salesforce Authenticator app (or another authenticator app that supports the TOTP algorithm) to scan the QR code displayed by your account. During the registration Salesforce shares a secret key with the Authenticator client app. This secret will be used later to generate a random one-time-password code.

 

Step 6: Test the component in Salesforce1

  1. Log in to the Salesforce1 mobile app.
  2. Tap the menu button in the upper left corner and select Step Up
  3. Get a verification code from Salesforce Authenticator.
  4. Enter the code in Salesforce1 and tap Verify. During verification both the client and the server compute a one-time-password code based on the current time and the shared secret key. If the one-time-password code provided by the client matches the code generated by Salesforce the verification succeeds and the Lightning app will raise the session level to HIGA_ASSURANCE and get the list of 10 top opportunities.
Bookmark the permalink. Trackbacks are closed, but you can post a comment.