function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
iRiteshiRitesh 

Authorization Required Error

i am getting an error Authorization Required.i am using google data api toolkit for apex(http://wiki.developerforce.com/page/Google_Data_API_Toolkit).i am getting an error.i modified code a little .my AuthSubController class code is

 

public class AuthSubController {

public AuthSubController(){

 if ( ApexPages.currentPage().getParameters().get('token') != null) { 
          //  string sessToken = 
            // AuthSubUtil.exchangeForSessionToken( 
              //  ApexPages.currentPage().getParameters().get('token'));
 GoogSession__c session = new googSession__c(id=
                ApexPages.currentPage().getParameters().get('url').substring(5),
                 AuthSubSessionToken__c = null );
            
       //     update session;
}
}
        public pagereference exchangeRequestToken() {
    
        return null;
    }
    

    public boolean getRequestToken() {
        return (ApexPages.currentPage().getParameters().get('token') == null
        && ApexPages.currentPage().getParameters().get('id') != null);
    }
    
    public static testMethod void t1() {   
   
        PageReference pageRef = Page.authsub;
        Test.setCurrentPage(pageRef);
  
        AuthSubController stc = new AuthSubController( );
        ApexPages.currentPage().getParameters().put('token', 'yyyy');
        ApexPages.currentPage().getParameters().put('id', 'yyyy');
        stc.exchangeRequestToken();
        stc.getRequestToken();
    }
     public static testMethod void t2() {   
   
        PageReference pageRef = Page.authsub;
        Test.setCurrentPage(pageRef);
  
        AuthSubController stc = new AuthSubController( );
        stc.getRequestToken();
        stc.exchangeRequestToken();
        
    }
    
    public string getHello(){
    return ApexPages.currentPage().getParameters().get('url').substring(5);
    
    }
    
}

 

and my  Auth Sub Util class is

 

public class AuthSubUtil {
    static string tokenInfo = 'https://www.google.com/accounts/AuthSubTokenInfo';
    static string authRequest = 'https://www.google.com/accounts/AuthSubRequest';
    static string subSession = 'https://www.google.com/accounts/AuthSubSessionToken';
    static string revokeUrl = 'https://www.google.com/accounts/AuthSubRevokeToken';
    
    public static Map<String, String> getTokenInfo(string token) {
        Map<String, String> ret = new Map<String, String> ();

        GoogleService service = new GoogleService('auth'); 
        service.AuthSubToken = token; 
        service.getFeedMethod('GET',tokenInfo, null, null );
        
        string[] lines =  service.response.getBody().split('\n');
        
        try { 
            for (string s: lines) {
                string[] nv = s.split('='); 
                ret.put(nv[0],nv[1]);
            } 
        } catch (exception e) {
            // an error or invalid token...
            system.debug( service.response.getBody() );
        } 
        return ret;
    }
    
    //  Creates the request URL to be used to retrieve an AuthSub token.
    public static String    getRequestUrl(string proto, string host, 
                                            String nextUrl, String scope) {
        // first we need to go thru the Salesforce GoogleAuthSub callback servlet
        // and that (next destination) needs to be encoded
        string encodedNext = proto + '://' + host +     
            '/_ui/core/google/GoogleAuthSubCallback?url=' + 
            EncodingUtil.urlEncode( nextUrl, 'UTF-8' ); 
        
        // then we need to encode again to allow it to pass thru to the google authsub sevlet
        string twiceEncodedNext =  EncodingUtil.urlEncode( encodedNext, 'UTF-8' ) ; 
        
        // finaly construct the first step in the redirect process, send your users to this url
        // must be done by the end user, in a browser...
        return authRequest + '?next='+ twiceEncodedNext + '&scope='+ scope + '&session=1&secure=0'; 
    }
    
    //  Creates the pagereference to be used to retrieve an AuthSub token.
    public static pagereference    getRequestPageReference(string proto, string host, 
                                            String nextUrl, String scope) {
        // first we need to go thru the Salesforce GoogleAuthSub callback servlet
        // and that (next destination) needs to be encoded
        string encodedNext = proto + '://' + host +     
            '/_ui/core/google/GoogleAuthSubCallback?url=' + 
            EncodingUtil.urlEncode( nextUrl, 'UTF-8' ); 
        
        // then we need to encode again to allow it to pass thru to the google authsub sevlet
        //string twiceEncodedNext =  EncodingUtil.urlEncode( encodedNext, 'UTF-8' ) ; 
        
        // finaly construct the first step in the redirect process, send your users to this url
        // must be done by the end user, in a browser...
        return  new PageReference( authRequest + '?next='+ encodedNext + '&scope='+ scope + '&session=1&secure=0'); 
    }

         
    //    Exchanges the one time use token returned in the URL for a session token.
    public static String    exchangeForSessionToken(String onetimeUseToken ) { 
        GoogleService service = new GoogleService('auth'); 
        service.AuthSubToken = onetimeUseToken;
        service.getFeedMethod('GET', subSession, null, GoogleService.CONTENT_TYPE_URL);
        return getTokenFromReply( service.response.getbody());
    }     
    
    // Parses and returns the AuthSub token returned by Google on a successful AuthSub login request.
    public static String    getTokenFromReply(String bodyOrUrl) {
        string[] atoken = bodyOrUrl.split('=');
        if ( atoken.size() != 2) { 
            system.debug( 'invalid token, or response from AuthSubSessionToken, no token');
            return null;
        }
        system.debug('session token is: '+atoken[1].trim());
        return atoken[1].trim();
    }

    public  static void     revokeToken(String token) {
         // Revokes the specified token.
        GoogleService service = new GoogleService('auth'); 
        service.AuthSubToken = token; 
        service.getFeed( revokeUrl ); 
    }
    
    /*  
    static String   getPrivateKeyFromKeystore(String keystore, String keystorePass, String keyAlias, String keyPass)
              Retrieves the private key from the specified keystore.          
    */
    
    /* 
     * test methods below here 
     */
    static final string sessionAuthToken = 'CJ3pqczuBBCpgI2pBw';
    
    public static testMethod void testGetTokenInfo() { 
        system.debug ( AuthSubUtil.getTokenInfo( sessionAuthToken) );
        system.debug ( AuthSubUtil.getTokenInfo( 'badtoken' ) );
    }
    
    public static testMethod void testexchangeForSessionToken() { 
        CalendarService service = new CalendarService();  
        AuthSubUtil.exchangeForSessionToken( 'teststtoken' );
        
    }
    
    public static testMethod void testgetTokenFromReply() { 
        CalendarService service = new CalendarService();  
        AuthSubUtil.getTokenFromReply( 'url=teststtoken' );
        AuthSubUtil.getTokenFromReply( 'urlbadteststtoken' );
    }
    
    public static testMethod void testrevokeToken() { 
        CalendarService service = new CalendarService();  
        AuthSubUtil.revokeToken( 'teststtoken' );
     
    }
    
    public static testMethod void testgetRequestUrl() { 
        string expected = 'https://www.google.com/accounts/AuthSubRequest?next=https%3A%2F%2Ftapp0.salesforce.com%2F_ui%2Fcore%2Fgoogle%2FGoogleAuthSubCallback%3Furl%3D%252Fapex%252Fgsession%253Fid%253Da0AT0000000FO1QMAW&scope=http://www.google.com/calendar/feeds/&session=1&secure=0';
        CalendarService service = new CalendarService();  
        
        string checkUrl =  AuthSubUtil.getRequestUrl( 'https', 'tapp0.salesforce.com', 
            '/apex/gsession?id=a0AT0000000FO1QMAW',  // next  
            'https://www.google.com/calendar/feeds/' );   // scope 
            
        system.debug ( expected ) ; 
        system.debug ( checkUrl );   
        system.assert(  expected == checkUrl , ' mis match request url '); 
    }
    

  public static testMethod void  testgetRequestPageReference(){
    
        String strProto = 'https';
        String strHost = 'na2.salesforce.com';
        String strNextUrl = '/apex/authsub';
        String strScopeUrl = 'https://spreadsheets.google.com/feeds/';
              
         PageReference p = AuthSubUtil.getRequestPageReference( strProto, strHost, strNextUrl, strScopeUrl);
        system.debug (p); 
      
      STRING expected = 'https://www.google.com/accounts/AuthSubRequest?next=https%3A%2F%2Fna2.salesforce.com%2F_ui%2Fcore%2Fgoogle%2FGoogleAuthSubCallback%3Furl%3D%252Fapex%252Fauthsub&scope=http%3A%2F%2Fspreadsheets.google.com%2Ffeeds%2F&secure=0&session=1';
      system.assert( expected == p.getUrl() , 'page reference genreated is bad'); 
    }
        
}

 

 

my authsub page is

 

<apex:page controller="AuthSubController" showHeader="false">
<head><title>Hello World</title>
<meta name="google-site-verification" content="XCzApP9fdbR3auxPHd3-X0g7uCNbrXZDQU_jm5GHXLI" />
</head>
          <apex:outputPanel rendered="{!$CurrentPage.parameters.token != null}"> 
The one time use token is :<b>{!$CurrentPage.parameters.token}</b>
            <br />
Record to update is {!$CurrentPage.parameters.id}
<br />
URL to update is {!hello}
<apex:form >
<apex:commandbutton action="{!exchangeRequestToken}"
                oncomplete="window.close();" value="Request Session token" />
        </apex:form>
        </apex:outputPanel>
</apex:page>
in my authsub page controller class is AuthSubController
if you AuthSubController class there is a constructor and for highlighting i am pasting constructor here

public AuthSubController(){

 if ( ApexPages.currentPage().getParameters().get('token') != null) { 
          //  string sessToken = 
            // AuthSubUtil.exchangeForSessionToken( 
              //  ApexPages.currentPage().getParameters().get('token'));
 GoogSession__c session = new googSession__c(id=
                ApexPages.currentPage().getParameters().get('url').substring(5),
                 AuthSubSessionToken__c = null );
            
       //     update session;
}
}

if i make these lines commented(as shown in constructor ) then there is no (Authorization Required).if uncommented code of constructor is given below:
public AuthSubController(){

 if ( ApexPages.currentPage().getParameters().get('token') != null) { 
            string sessToken = 
             AuthSubUtil.exchangeForSessionToken( 
                ApexPages.currentPage().getParameters().get('token'));
 GoogSession__c session = new googSession__c(id=
                ApexPages.currentPage().getParameters().get('url').substring(5),
                 AuthSubSessionToken__c = null );
            
            update session;
}
}
in this case there is Authorization required error.i gave all permission to GoogSeession__c in public access settings of site for sure.probably main problem is with this line.
error come when i redirected to authsub home page
  string sessToken = 
             AuthSubUtil.exchangeForSessionToken( 
                ApexPages.currentPage().getParameters().get('token'));
can any one please help me how to remove this Authorization Required error.please dont look at above two big code segments these are only for completeness of question main is thes constructor code where i am getting error.


cvuyyurucvuyyuru

Did you try providuing remote access for site user profile?