вторник, 13 октября 2015 г.

Solution to display Salesforce user profile photos on external Force.com sites without authentication

Displaying Salesforce user profile images on external sites is a wide known problem. Access to User.SmallPhotoURL or User.LargePhotoURL needs authentication and that's the trouble. There are various solutions provided by different Salesforce developers, for example:
  • authorizing via OAuth by attaching "?oauth=[your-token]" to photo url - seriously?.. send valid access token to unauthorized client?
  • saving user photos as custom objects attachments - pretty tricky to implement and really ugly solution.
But there is a simple and 100%-working solution (thanks to Denis from Synebo)!

public String getUserPhotoURL(String UserId) {
    ConnectApi.Photo ph =  ConnectApi.ChatterUsers.getPhoto(null, UserId);
    return ph.fullEmailPhotoUrl;
}
 Notice, that resulting URL expires 30 days after it was obtained. It doesn't matter if you are using it on dynamic pages (since you are requesting a new URL every time when page is reloaded), but keep it in mind when using URL in some static stuff (emails, static pages, etc).

2 комментария:

  1. Hello!

    I applied the solution that you suggested but I receive the following error: [{System.NoAccessException: Insufficient Privileges: You do not have the level of access necessary to perform the operation you requested. Please contact the owner of the record or your administrator if access is necessary.\n\nClass.ConnectApi.ChatterUsers.getUser: line 480, column 1\nClass.CrossOrgUsersPhotos.doGet: line 10, column 1;}]

    I have a force.com site which exposes a web service to be consumed by an external application to show the users profile picture. The web service definition is:
    @RestResource(urlMapping='/UsersPhotos/*')
    global class UsersPhotos {
    @HttpGet
    global static String doGet() {
    String userId = RestContext.request.params.get('userId');
    ConnectApi.Photo ph = ConnectApi.UserProfiles.getPhoto(null, userId);
    return ph.fullEmailPhotoUrl;
    }
    }

    Any idea what could be wrong here? Do I need to add additional permissions to my force.com site?

    Thanks.

    ОтветитьУдалить
    Ответы
    1. I'm sorry, the error that I got is the following (I am using the api version 46.0):

      photo: [{System.NoAccessException: Insufficient Privileges: You do not have the level of access necessary to perform the operation you requested. Please contact the owner of the record or your administrator if access is necessary.\n\nClass.ConnectApi.UserProfiles.getPhoto: line 266, column 1\nClass.UsersPhotos.doGet: line 7, column 1;}]

      Удалить