Я хочу интегрировать Spring Social facebook в мое приложение с Spring Security (я использую конфигурации аннотаций). Все, что мне нужно, это просто подключить учетную запись facebook с моей учетной записью приложения. В простом примере я нашел следующее:
package eu.thinking4u.spring.social.simple.signinmvc.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.social.UserIdSource;
import org.springframework.social.config.annotation.ConnectionFactoryConfigurer;
import org.springframework.social.config.annotation.EnableSocial;
import org.springframework.social.config.annotation.SocialConfigurer;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository;
import org.springframework.social.connect.web.ConnectController;
import org.springframework.social.facebook.connect.FacebookConnectionFactory;
import org.springframework.social.security.AuthenticationNameUserIdSource;
@Configuration
@EnableSocial
public class SocialContext implements SocialConfigurer {
@Autowired
private DataSource dataSource;
/**
* Configures the connection factories for Facebook and Twitter.
* @param cfConfig
* @param env
*/
public void addConnectionFactories(ConnectionFactoryConfigurer cfConfig, Environment env) {
/* cfConfig.addConnectionFactory(new TwitterConnectionFactory(
env.getProperty("twitter.consumer.key"),
env.getProperty("twitter.consumer.secret")
));*/
/*cfConfig.addConnectionFactory(new FacebookConnectionFactory(
env.getProperty("facebook.app.id"),
env.getProperty("facebook.app.secret")
));*/
final FacebookConnectionFactory fbcf = new FacebookConnectionFactory(env.getProperty("facebook.app.id"),
env.getProperty("facebook.app.secret"));
fbcf.setScope("email");
cfConfig.addConnectionFactory(fbcf);
}
/**
* The UserIdSource determines the account ID of the user. The example application
* uses the username as the account ID.
*/
public UserIdSource getUserIdSource() {
return new AuthenticationNameUserIdSource();
}
public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
return new JdbcUsersConnectionRepository(
dataSource,
connectionFactoryLocator,
/**
* The TextEncryptor object encrypts the authorization details of the connection. In
* our example, the authorization details are stored as plain text.
* DO NOT USE THIS IN PRODUCTION.
*/
Encryptors.noOpText()
);
}
/**
* This bean manages the connection flow between the account provider and
* the example application.
*/
@Bean
public ConnectController connectController(ConnectionFactoryLocator connectionFactoryLocator, ConnectionRepository connectionRepository) {
return new ConnectController(connectionFactoryLocator, connectionRepository);
}
/* @Bean
public CanvasSignInController canvasSignInController(ConnectionFactoryLocator connectionFactoryLocator,
UsersConnectionRepository usersConnectionRepository, Environment env)
{
return new CanvasSignInController(connectionFactoryLocator, usersConnectionRepository,
new SimpleSignInAdapter(), env.getProperty("facebook.appKey"), env.getProperty("facebook.appSecret"),
env.getProperty("facebook.canvasPage"));
}*/
}
После входа в Facebook мы попытаемся получить профиль пользователя, например
WebRequest request
RegistrationForm dto = new RegistrationForm();
Connection<?> connection = ProviderSignInUtils.getConnection(request);
if (connection != null) {
UserProfile socialMediaProfile = connection.fetchUserProfile();
System.out.println("DTO EMAIL--->"+socialMediaProfile.getEmail());
dto.setEmail(socialMediaProfile.getEmail());
dto.setFirstName(socialMediaProfile.getFirstName());
dto.setLastName(socialMediaProfile.getLastName());
}
Я пытаюсь получить электронную почту и имя пользователя, но не работает. И имя и фамилия должным образом взяты.
Я считаю, что это ошибка в текущей версии весенней социальной. В настоящее время он отслеживается здесь: https://jira.spring.io/browse/SOCIAL-436
Тем временем вы можете обойти это, установив область с помощью скрытого поля на своей странице следующим образом:
<form action="<c:url value="/connect/facebook" />" method="POST">
<input type="hidden" name="scope" value="email" />
<p>You haven't created any connections with Facebook yet. Click the button to create
a connection between your account and your Facebook profile.</p>
<p><button type="submit"><img src="<c:url value="/resources/social/facebook/signin.png" />"/>
</button></p>
</form>