Facebook Login with Spring Social using Existing User Access Token

回眸只為那壹抹淺笑 提交于 2019-12-02 18:22:01

I had the exact same issue and here's how I made it work. You probably have a SocialConfigurer somewhere with the following:

@Configuration
@EnableSocial
public class SocialConfig implements SocialConfigurer {

    @Autowired
    private DataSource dataSource;

    @Bean
    public FacebookConnectionFactory facebookConnectionFactory() {
        FacebookConnectionFactory facebookConnectionFactory = new FacebookConnectionFactory("AppID", "AppSecret");
        facebookConnectionFactory.setScope("email");
        return facebookConnectionFactory;
    }

    @Override
    public void addConnectionFactories(ConnectionFactoryConfigurer cfConfig, Environment env) {
        cfConfig.addConnectionFactory(facebookConnectionFactory());
    }

    @Override
    public UserIdSource getUserIdSource() {
        return new AuthenticationNameUserIdSource();
    }

    @Override
    public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
        return new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText());
    }

    // Other @Bean maybe ...
}

From here, what you can do is, in a Controller/RestController, add a mapping with a RequestParam for your token that you will send to your server:

@Autowired
private FacebookConnectionFactory facebookConnectionFactory;

@Autowired
private UsersConnectionRepository usersConnectionRepository;

@RequestMapping(value = "/my-facebook-url", method = RequestMethod.POST)
public String fb(@RequestParam String token) {
    AccessGrant accessGrant = new AccessGrant(token);
    Connection<Facebook> connection = facebookConnectionFactory.createConnection(accessGrant);

    UserProfile userProfile = connection.fetchUserProfile();
    usersConnectionRepository.createConnectionRepository(userProfile.getEmail()).addConnection(connection);

    // ...

    return "Done";
}

Useful references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!