1

We have an Experience site with a custom Apex login controller.

When a user logs in, the controller captures the URL from the PageReference returned by Site.login() and sends the login URL to the user via email.

In a sandbox, the user browses to the link and gets logged in.

In production, the user browses to the link and gets redirected back to the login page.

Is there a security setting that prevents this from working in production orgs, or are they more restricted than sandboxes?

Here is an example of the Apex controller:

public with sharing class CustomLoginController {
    @AuraEnabled
    public static void login(String email, String password, String startUrl) {
        // Get the login page reference URL
        PageReference pageRef = Site.login(email, password, startUrl);
        String loginUrl = pageRef.getUrl();

        // Get the email template
        EmailTemplate emailTemplate = [SELECT Id, Subject FROM EmailTemplate WHERE DeveloperName = 'Login_Template'];

        // Get the HTML from the email template and inject the login URL
        Messaging.SingleEmailMessage message = Messaging.renderStoredEmailTemplate(emailTemplate.Id, null, null);
        String html = message.getHTMLBody().replace('##loginUrl##', loginUrl);

        // Send the email
        sendEmail(email, emailTemplate.Subject, html);
    }

    private static void sendEmail(String toAddress, String subject, String html) {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new List<String>{ toAddress });
        mail.setSubject(subject);
        mail.setHtmlBody(html);
        mail.setOrgWideEmailAddressId('XXX');
        Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{ mail });
    }
}
2
  • Welcome to SFSE! Please take a moment to read How to Ask and take the tour. Including a Minimal, Reproducible Example would be helpful.
    – identigral
    Mar 28, 2023 at 15:21
  • @identigral I've included an example of the Apex controller. We've verified the email works, and includes the correct URL, so I haven't included an example of the email template.
    – Will
    Mar 29, 2023 at 16:17

1 Answer 1

1

The answer was simple in the end.

It turns out we were being logged in, but also redirected back to the login page.

The startUrl URL was an incorrect path. Once that was fixed, we were redirected to the correct page after logging in.

(I'm still not sure why the sandbox org redirected us to the Home page, but the production org redirected us to the Login page.)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .