I'm attempting to do a redirect from a visualforce page to a salesforce page but when it loads, I end up with the login.salesforce.com page.

The visual force controller builds the http request, and retrieves the response to send back to javascript to render the that response as HTML.

public static string HTTPRequest(string requestURL)
    HttpRequest request = new HttpRequest();
    request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());

    Http http = new Http();
    HttpResponse response = http.send(request);

    return response.getBody();

I figured that if I add the authorization header with the current user session ID (as the user is currently logged into a visual force page), that it would authenticate but I appear to be wrong.

After the login page displays, and if I manually log in, i get the expected page that I want to display.

Is this possible to do and have I just missed something?


I forgot to mention that the RemoteAction is directly affecting an IFrame... thus bypassing cross-origin issues and rendering the content within an IFrame without reloading the page. Reloading the page is not an option due to content that remains "open" within the page.

  • 3
    Can you explain why all this is necessary? A controller can return a PageReference or JavaScript can build a URL with both approaches preserving the session and with a lot less code. – Keith C Jan 11 '18 at 21:32
  • I'll update the question with the required information. – bl4kh4k Jan 12 '18 at 12:08

Visualforce like this:

<apex:commandButton value="To New Page" action="{! toNewPage }"/>

and a controller method like this:

public PageReference toNewPage() {
    String url = ...;
    PageReference pr = new PageReference(url);
    pr.getParameters().put('p1', ...);
    pr.getParameters().put('p2', ...);
    return pr;

will do the job of "redirect from a visualforce page to a salesforce page" correctly preserving the session.

| improve this answer | |
  • I forgot to mention the use of an iframe for rendering this content... I've updated my question. Would your answer be possible to do in some way from an async point of view? – bl4kh4k Jan 12 '18 at 12:10
  • @bl4kh4k More detail in your edit would help or perhaps a new question that outlines more what you are trying to accomplish as well as how you are trying to accomplish it (in detail). Consider What is the XY problem?. – Keith C Jan 12 '18 at 12:13
  • I think the original question is still valid, "logging into salesforce from a visualforce controller". As for the XY problem, I can load content into an iframe... I realize there is CORS, and Remote Site Settings however the approach is unorthodox and will succeed if I can pass the login critera into the HTTP request. – bl4kh4k Jan 12 '18 at 12:23

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.