简体   繁体   中英

spring social Facebook - single Facebook Instance

I just created a project using latest spring social and spring social Facebook (and spring boot).

I'm trying to implement a Facebook signup which works fine except that it returns the same connection/profile for the first connected user every time.

My Facebook Profile Controller is:

    @RestController
@RequestMapping(path = "/api/unsecure/facebook")
public class FacebookProfileController implements Serializable {
    private static final long serialVersionUID = 1895700328147293496L;

    @Autowired
    private Facebook facebook;

    @RequestMapping(path = "/profile", method = RequestMethod.GET)
    public Result<FBUserVO> getUserFBProfile() {
        if (!facebook.isAuthorized()) {
            return ResultFactory.getFailResult("Facebook signup failed!");
        }
        FBUserVO user = FBUserToFBUserVO.INSTANCE.apply(facebook.userOperations().getUserProfile());
        PagedList<Reference> friends = facebook.friendOperations().getFriends();
        if (!friends.isEmpty()) {
            user.setFriendsMessage("You have " + friends.size() + " friends playing. Join Now!");
        }
        return ResultFactory.getSuccessResult(user);
    }
}

This works the first time... after that it will return the same profile info every time even though when I'm debugging the FacebookTemplate class, this is created using a new/valid access_token for a new user but for some reason the URLs are created maybe using the old token. I tried debugging the urls but they don't seem to send any access token.

Is there anything I'm doing wrong here? Can I get the current connection in another way?

You must use the ConnectionRepository class (which allows to remove the existing connection to Facebook provider for the first logged user which cause your problem).

Use a constructor like this and eliminate the Facebook autowiring:

private ConnectionRepository connectionRepository;
    @Inject
    public FacebookProfileController(ConnectionRepository connectionRepository) {
        this.connectionRepository = connectionRepository;
    }

through the connectionRepository instance you can get the Facebook object for the current logged user by doing:

connectionRepository.findPrimaryConnection(Facebook.class).getApi()

Note: To check if a user is not authenticated, you need to use:

connectionRepository.findPrimaryConnection(Facebook.class)==null

When you finish to extract data for the current logged user, you have to use the instruction below in order to delete the persistent connection created through constructor:

connectionRepository.removeConnections("facebook");

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM