0

I am getting this error-

System.UnexpectedException: Salesforce System Error: 1757874930-20679 (1748552322) (1748552322) System.UnexpectedException: Salesforce System Error: 1757874930-20679 (1748552322) (1748552322) Stack Trace: Class.Auth.AuthConfiguration.getSamlSsoUrl: line 279, column 1 Class.MyDomainDiscLoginDefaultHandler.getSsoRedirect: line 55, column 1 Class.MyDomainDiscLoginDefaultHandler.login: line 24, column 1 Class.MyDomainDiscLoginDefaultHandlerTest.partnerUserValidation: line 126, column 1

Test class

        @isTest
    public class MyDomainDiscLoginDefaultHandlerTest {
        @testSetup 
        public static void setup() { 
            try {
                User sysAdminUser = new User(
                    ProfileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id,
                    LastName = 'last',
                    Email = 'testUser2FA@test.com',
                    Username = 'testUser2FA@test.com',
                    CompanyName = 'TEST',
                    Title = 'title',
                    Alias = 'tuser',
                    TimeZoneSidKey = 'America/Los_Angeles',
                    EmailEncodingKey = 'UTF-8',
                    LanguageLocaleKey = 'en_US',
                    LocaleSidKey = 'en_US'
                );
                insert sysAdminUser;

                User restrictedUser = new User(
                    ProfileId = [SELECT Id FROM Profile WHERE Name = 'Restricted'].Id,
                    LastName = 'last',
                    Email = 'testUser2FA@test.com',
                    Username = 'TelstraCustomPerm@test.com',
                    CompanyName = 'TEST',
                    Title = 'title',
                    Alias = 'Permtest',
                    TimeZoneSidKey = 'America/Los_Angeles',
                    EmailEncodingKey = 'UTF-8',
                    LanguageLocaleKey = 'en_US',
                    LocaleSidKey = 'en_US',
                    FederationIdentifier='R00100' 
                );
                insert restrictedUser;   

                // Create PermissionSet with Custom Permission and assign to test user
                PermissionSet ps = new PermissionSet();
                ps.Name = 'Test';
                ps.Label = 'Test';
                insert ps;

                SetupEntityAccess sea = new SetupEntityAccess();
                sea.ParentId = ps.Id;
                sea.SetupEntityId = [select Id from CustomPermission where DeveloperName = 'Telstra_Administrator'][0].Id;
                insert sea;

                System.debug('sea>>>>'+sea);
                PermissionSetAssignment psa = new PermissionSetAssignment();
                psa.AssigneeId = restrictedUser.id;
                psa.PermissionSetId = ps.Id;
                insert psa;

                User usr = new User(
                    ProfileId = [SELECT Id FROM Profile WHERE Name = 'CDM Admin'].Id,
                    LastName = 'last',
                    Email = 'testUser2FA@test.com',
                    Username = 'nocustompermission@test.com',
                    CompanyName = 'TEST',
                    Title = 'title',
                    Alias = 'alias',
                    TimeZoneSidKey = 'America/Los_Angeles',
                    EmailEncodingKey = 'UTF-8',
                    LanguageLocaleKey = 'en_US',
                    LocaleSidKey = 'en_US',
                    FederationIdentifier='C00100' 
                );
                insert usr; 

                User partnerUser = new User(
                    ProfileId = [SELECT Id FROM Profile WHERE Name = 'Partner Stores'].Id,
                    LastName = 'last',
                    Email = 'testUser2FA@test.com',
                    Username = 'partnerProfile@test.com',
                    CompanyName = 'TEST',
                    Title = 'title',
                    Alias = 'alias',
                    TimeZoneSidKey = 'America/Los_Angeles',
                    EmailEncodingKey = 'UTF-8',
                    LanguageLocaleKey = 'en_US',
                    LocaleSidKey = 'en_US',
                    FederationIdentifier='P00100' 
                );
                insert partnerUser; 
            }
            catch(Exception e) {
            }      
        }

        public static testmethod void CustomPermValidation(){

            try {  
                user u=[select id,FederationIdentifier,Username from user where username='TelstraCustomPerm@test.com'];
                Map<String, String> requestAttributes = new Map<String, String>();
                String startUrl = '';
                MyDomainDiscLoginDefaultHandler sa=new MyDomainDiscLoginDefaultHandler();
                PageReference  pageReference =  sa.login(u.FederationIdentifier,startUrl,requestAttributes);
                System.assertNotEquals(null, pageReference, 'Page reference was not returned');
            }
            catch(Exception e){
            }
        }   

        public static testmethod void noCustomPermValidation(){

            try {
                user u=[select id,FederationIdentifier from user where username='nocustompermission@test.com' limit 1];
                Map<String, String> requestAttributes = new Map<String, String>();
                String startUrl = '';
                MyDomainDiscLoginDefaultHandler sa=new MyDomainDiscLoginDefaultHandler();
                PageReference  pageReference =  sa.login(u.FederationIdentifier,startUrl,requestAttributes);
                System.assertNotEquals(null, pageReference, 'Page reference was not returned');
            }
            catch(Exception e){
            }
        }

        public static testmethod void partnerUserValidation(){

            try {
                user u=[select id,profile.name,FederationIdentifier from user where username='partnerProfile@test.com' limit 1];
                Map<String, String> requestAttributes = new Map<String, String>();
                system.debug('upro---->'+u.profile.name);
                String startUrl = '';
                MyDomainDiscLoginDefaultHandler sa=new MyDomainDiscLoginDefaultHandler();
                PageReference  pageReference =  sa.login(u.FederationIdentifier,startUrl,requestAttributes);
                System.assertNotEquals(null, pageReference, 'Page reference was not returned');
            }
            catch(Exception e){
            }
        }
        /*public static testmethod void testcaal(){
    user u=[select id,FederationIdentifier,Username from user where username='testUser2FA@test.com'];
    test.startTest();
    Map<String, String> requestAttributes = new Map<String, String>();
    String startUrl = '';
    MyDomainDiscLoginDefaultHandler sa=new MyDomainDiscLoginDefaultHandler();
    PageReference  pageReference = sa.login(u.username,startUrl,requestAttributes);

    }*/
        @isTest static void testLoginWithInvalidUser() {
            try {
                Map<String, String> requestAttributes = new Map<String, String>();
                String startUrl = '';
                String fedId = 'AETERYD';
                MyDomainDiscLoginDefaultHandler myDomainDiscLoginDefaultHandler = new MyDomainDiscLoginDefaultHandler();
                // Invoke login method from handler with non-existing user
                myDomainDiscLoginDefaultHandler.login(fedId, startUrl, requestAttributes);
            }catch (Auth.LoginDiscoveryException loginDiscoveryException) {
                // Assert exception message
                System.assert(loginDiscoveryException.getMessage().contains('No unique user found'), 'message=' + loginDiscoveryException.getMessage());
            }
        }
    }

Apex class--

            /*******************************************************
        @name: MyDomainDiscLoginDefaultHandler
        @CreateDate: 21/05/2019
        @Description: This class is used to redirect login flow based on permissions
        @Version: 1.0
        @reference: 
        *******************************************************/
        public with sharing class MyDomainDiscLoginDefaultHandler implements Auth.MyDomainLoginDiscoveryHandler {
            public PageReference login(String identifier, String startUrl, Map<String, String> requestAttributes) {
                if (identifier != null) {
                    //Query user by Fedaration ID  
                    List<User> users = new list<user>([SELECT Id,profile.name,username,FederationIdentifier FROM User WHERE FederationIdentifier = :identifier  AND IsActive = TRUE]);

                    //Query user by Username and filter with System administrator.
                    List<User> SysAdminUsers = new list<user>([SELECT Id,profile.name,Username,FederationIdentifier FROM User WHERE Username = :identifier AND IsActive = TRUE and Profile.Name='System Administrator']);

                    //If multiple records found with same identifier
                    if(users.size()>1 || SysAdminUsers.size()>1) {
                        throw new Auth.LoginDiscoveryException('Multiple Users found with Same UserName/FederationIdentifier');
                    }
                    if(users.size() == 1) {
                        if(users[0].profile.name.equals(Label.PIMS_Partner_Profile)) {
                            System.debug('Inside telstra Retail partner permission>>>>>');
                            return getSsoRedirect(Label.PIMS_Partner_Login,users[0], startUrl, requestAttributes); //call sso flow 
                        }
                        else if(doesRunningUserHavePermission(Label.Telstra_Administrator,users)){
                            System.debug('Inside telstra administrtaor permission>>>>>');
                            return getSsoRedirect(Label.Telstra_RSA_Account_01,users[0], startUrl, requestAttributes); //call sso flow 
                        }
                        else {
                        System.debug('inside else>>>>>>');
                            return getSsoRedirect(Label.Telstra_Account_01,users[0], startUrl, requestAttributes); //call sso flow 
                        }
                    }
                    else if(SysAdminUsers.size()==1) {

                            return normalLogin(SysAdminUsers[0],startUrl, requestAttributes);

                    }
                    else {
                            throw new Auth.LoginDiscoveryException('No unique user found.'); 
                    }  
                }
                throw new Auth.DiscoveryCustomErrorException('Invalid Identifier');
            }

           /*******************************************************
            @MethodName: getSsoRedirect
            @Arguments: list,String,map
            @Description: This method is used redirecting specific SSO
            *******************************************************/
            private PageReference getSsoRedirect(String DeveloperName,User user, String startUrl, Map<String, String> requestAttributes) {
                // You can look up if the user should log in with SAML or an Auth Provider and return the URL to initialize SSO. For example:
                SamlSsoConfig SSO = [select Id from SamlSsoConfig where developerName=:developerName limit 1];
                String ssoUrl = Auth.AuthConfiguration.getSamlSsoUrl(requestAttributes.get('MyDomainURL'), startUrl, SSO.Id);
                System.debug('requestAttributes>>>>>'+requestAttributes);
                System.debug('SSO>>>>>'+SSO);
                System.debug('ssoUrl >>>>>'+ssoUrl );
                if(ssoUrl!=null || ssoUrl!='') {
                    return new PageReference(ssoUrl);
                }
                return null;
            }

            /*******************************************************
            @MethodName: normalLogin
            @Arguments: list,String,map
            @Description: This method is used redirecting to Normal login Flow
            *******************************************************/
            private PageReference normalLogin(User user, String startUrl, Map<String, String> requestAttributes) {
                return Auth.SessionManagement.finishLoginDiscovery(Auth.LoginDiscoveryMethod.password, user.Id);    
            }

            /*******************************************************
            @MethodName: doesRunningUserHavePermission
            @Arguments: CustomPermission name and User List
            @Description: This method is used for checking user is having custom permission assigned
            *******************************************************/
            public static Boolean doesRunningUserHavePermission(String CustomPermissionName,list <user>users) {
                Set<Id> accessiblePermissionIds = new Set<Id>();
                for (SetupEntityAccess access : [SELECT SetupEntityId FROM SetupEntityAccess
                                   WHERE SetupEntityType = 'CustomPermission' AND ParentId IN (
                                     SELECT PermissionSetId FROM PermissionSetAssignment
                                     WHERE Assignee.FederationIdentifier =:users[0].FederationIdentifier)])

                accessiblePermissionIds.add(access.SetupEntityId);
                return 0 < [SELECT count() FROM CustomPermission WHERE Id IN :accessiblePermissionIds AND DeveloperName =: CustomPermissionName];
            }
        }
0

From the AuthConfiguration.getSamlSsoUrl doc:

Parameters

communityUrl

Type: String

The URL for the community or My Domain subdomain. If not null and not specified as an empty string, you get the URL for a community. If null or specified as an empty string, you get the URL for a My Domain subdomain.

You should be passing null instead of requestAttributes.get('MyDomainURL') as the first argument when you call getSamlSsoUrl(...) for the baseline MyDomain-ed org.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.