Статьи

Настройка Spring Social Connect Framework для MongoDB

В моем предыдущем посте я говорил о первой задаче, которую мне пришлось изменить, — изменить модель данных и добавить структуру соединений. Здесь я хочу дать более подробную информацию о том, как я это сделал. Проект Spring Social уже предоставляет реализацию репозитория соединений на основе jdbc для сохранения данных пользовательских соединений в реляционной базе данных. Однако я использую MongoDB, поэтому мне нужно настроить код, и я обнаружил, что это сделать относительно легко. Данные о подключении пользователя будут сохранены как объект UserSocialConnection , это документ MongoDB:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@SuppressWarnings('serial')
@Document(collection = 'UserSocialConnection')
public class UserSocialConnection extends BaseEntity {
    private String userId;
    private String providerId;
    private String providerUserId;
    private String displayName;
    private String profileUrl;
    private String imageUrl;
    private String accessToken;
    private String secret;
    private String refreshToken;
    private Long expireTime;
 
    //Getter/Setter omitted.
 
    public UserSocialConnection() {
        super();
    }
 
    public UserSocialConnection(String userId, String providerId, String providerUserId, int rank,
            String displayName, String profileUrl, String imageUrl, String accessToken, String secret,
            String refreshToken, Long expireTime) {
        super();
        this.userId = userId;
        this.providerId = providerId;
        this.providerUserId = providerUserId;
        this.displayName = displayName;
        this.profileUrl = profileUrl;
        this.imageUrl = imageUrl;
        this.accessToken = accessToken;
        this.secret = secret;
        this.refreshToken = refreshToken;
        this.expireTime = expireTime;
    }
}

BaseEntity просто имеет идентификатор. С помощью проекта Spring Data мне не нужно писать код операций CRUD для UserSocialConnection , просто расширьте MongoRepository :

01
02
03
04
05
06
07
08
09
10
11
public interface UserSocialConnectionRepository extends MongoRepository<UserSocialConnection, String>{
    List<UserSocialConnection> findByUserId(String userId);
 
    List<UserSocialConnection> findByUserIdAndProviderId(String userId, String providerId);
 
    List<UserSocialConnection> findByProviderIdAndProviderUserId(String providerId, String providerUserId);
 
    UserSocialConnection findByUserIdAndProviderIdAndProviderUserId(String userId, String providerId, String providerUserId);
 
    List<UserSocialConnection> findByProviderIdAndProviderUserIdIn(String providerId, Collection<String> providerUserIds);
}

После того, как у нас будет наша база данных UserSocialConnectionRepository , мы реализуем необходимые для Social Social ConnectionRepository и UsersConnectionRepository . Я просто скопировал код из JdbcConnectionRepository и JdbcUsersConnectionRepository и создал свой собственный MongoConnectionRepository и MongoUsersConnectionRepository .

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
public class MongoUsersConnectionRepository implements UsersConnectionRepository{
 
    private final UserSocialConnectionRepository userSocialConnectionRepository;
 
    private final SocialAuthenticationServiceLocator socialAuthenticationServiceLocator;
 
    private final TextEncryptor textEncryptor;
 
    private ConnectionSignUp connectionSignUp;
 
    public MongoUsersConnectionRepository(UserSocialConnectionRepository userSocialConnectionRepository,
            SocialAuthenticationServiceLocator socialAuthenticationServiceLocator, TextEncryptor textEncryptor){
        this.userSocialConnectionRepository = userSocialConnectionRepository;
        this.socialAuthenticationServiceLocator = socialAuthenticationServiceLocator;
        this.textEncryptor = textEncryptor;
    }
 
    /**
     * The command to execute to create a new local user profile in the event no user id could be mapped to a connection.
     * Allows for implicitly creating a user profile from connection data during a provider sign-in attempt.
     * Defaults to null, indicating explicit sign-up will be required to complete the provider sign-in attempt.
     * @see #findUserIdsWithConnection(Connection)
     */
    public void setConnectionSignUp(ConnectionSignUp connectionSignUp) {
        this.connectionSignUp = connectionSignUp;
    }
 
    public List<String> findUserIdsWithConnection(Connection<?> connection) {
        ConnectionKey key = connection.getKey();
        List<UserSocialConnection> userSocialConnectionList =
                this.userSocialConnectionRepository.findByProviderIdAndProviderUserId(key.getProviderId(), key.getProviderUserId());
        List<String> localUserIds = new ArrayList<String>();
        for (UserSocialConnection userSocialConnection : userSocialConnectionList){
            localUserIds.add(userSocialConnection.getUserId());
        }
 
        if (localUserIds.size() == 0 && connectionSignUp != null) {
            String newUserId = connectionSignUp.execute(connection);
            if (newUserId != null)
            {
                createConnectionRepository(newUserId).addConnection(connection);
                return Arrays.asList(newUserId);
            }
        }
        return localUserIds;
    }
 
    public Set<String> findUserIdsConnectedTo(String providerId, Set<String> providerUserIds) {
        final Set<String> localUserIds = new HashSet<String>();
 
        List<UserSocialConnection> userSocialConnectionList =
                this.userSocialConnectionRepository.findByProviderIdAndProviderUserIdIn(providerId, providerUserIds);
        for (UserSocialConnection userSocialConnection : userSocialConnectionList){
            localUserIds.add(userSocialConnection.getUserId());
        }
        return localUserIds;
    }
 
    public ConnectionRepository createConnectionRepository(String userId) {
        if (userId == null) {
            throw new IllegalArgumentException('userId cannot be null');
        }
        return new MongoConnectionRepository(userId, userSocialConnectionRepository, socialAuthenticationServiceLocator, textEncryptor);
    }
 
}

MongoUsersConnectionRepository очень похож на JdbcUsersConnectionRepository . Но для MongoConnectionRepository мне нужно было внести некоторые изменения:

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
public class MongoConnectionRepository implements ConnectionRepository {
 
    private final String userId;
 
    private final UserSocialConnectionRepository userSocialConnectionRepository;
 
    private final SocialAuthenticationServiceLocator socialAuthenticationServiceLocator;
 
    private final TextEncryptor textEncryptor;
 
    public MongoConnectionRepository(String userId, UserSocialConnectionRepository userSocialConnectionRepository,
            SocialAuthenticationServiceLocator socialAuthenticationServiceLocator, TextEncryptor textEncryptor) {
        this.userId = userId;
        this.userSocialConnectionRepository = userSocialConnectionRepository;
        this.socialAuthenticationServiceLocator = socialAuthenticationServiceLocator;
        this.textEncryptor = textEncryptor;
    }
 
    public MultiValueMap<String, Connection<?>> findAllConnections() {
        List<UserSocialConnection> userSocialConnectionList = this.userSocialConnectionRepository
                .findByUserId(userId);
 
        MultiValueMap<String, Connection<?>> connections = new LinkedMultiValueMap<String, Connection<?>>();
        Set<String> registeredProviderIds = socialAuthenticationServiceLocator.registeredProviderIds();
        for (String registeredProviderId : registeredProviderIds) {
            connections.put(registeredProviderId, Collections.<Connection<?>> emptyList());
        }
        for (UserSocialConnection userSocialConnection : userSocialConnectionList) {
            String providerId = userSocialConnection.getProviderId();
            if (connections.get(providerId).size() == 0) {
                connections.put(providerId, new LinkedList<Connection<?>>());
            }
            connections.add(providerId, buildConnection(userSocialConnection));
        }
        return connections;
    }
 
    public List<Connection<?>> findConnections(String providerId) {
        List<Connection<?>> resultList = new LinkedList<Connection<?>>();
        List<UserSocialConnection> userSocialConnectionList = this.userSocialConnectionRepository
                .findByUserIdAndProviderId(userId, providerId);
        for (UserSocialConnection userSocialConnection : userSocialConnectionList) {
            resultList.add(buildConnection(userSocialConnection));
        }
        return resultList;
    }
 
    @SuppressWarnings('unchecked')
    public <A> List<Connection<A>> findConnections(Class<A> apiType) {
        List<?> connections = findConnections(getProviderId(apiType));
        return (List<Connection<A>>) connections;
    }
 
    public MultiValueMap<String, Connection<?>> findConnectionsToUsers(MultiValueMap<String, String> providerUsers) {
        if (providerUsers == null || providerUsers.isEmpty()) {
            throw new IllegalArgumentException('Unable to execute find: no providerUsers provided');
        }
 
        MultiValueMap<String, Connection<?>> connectionsForUsers = new LinkedMultiValueMap<String, Connection<?>>();
 
        for (Iterator<Entry<String, List<String>>> it = providerUsers.entrySet().iterator(); it.hasNext();) {
            Entry<String, List<String>> entry = it.next();
            String providerId = entry.getKey();
            List<String> providerUserIds = entry.getValue();
            List<UserSocialConnection> userSocialConnections =
                    this.userSocialConnectionRepository.findByProviderIdAndProviderUserIdIn(providerId, providerUserIds);
            List<Connection<?>> connections = new ArrayList<Connection<?>>(providerUserIds.size());
            for (int i = 0; i < providerUserIds.size(); i++) {
                connections.add(null);
            }
            connectionsForUsers.put(providerId, connections);
 
            for (UserSocialConnection userSocialConnection : userSocialConnections) {
                String providerUserId = userSocialConnection.getProviderUserId();
                int connectionIndex = providerUserIds.indexOf(providerUserId);
                connections.set(connectionIndex, buildConnection(userSocialConnection));
            }
 
        }
        return connectionsForUsers;
    }
 
    public Connection<?> getConnection(ConnectionKey connectionKey) {
        UserSocialConnection userSocialConnection = this.userSocialConnectionRepository
                .findByUserIdAndProviderIdAndProviderUserId(userId, connectionKey.getProviderId(),
                        connectionKey.getProviderUserId());
        if (userSocialConnection != null) {
            return buildConnection(userSocialConnection);
        }
        throw new NoSuchConnectionException(connectionKey);
    }
 
    @SuppressWarnings('unchecked')
    public <A> Connection<A> getConnection(Class<A> apiType, String providerUserId) {
        String providerId = getProviderId(apiType);
        return (Connection<A>) getConnection(new ConnectionKey(providerId, providerUserId));
    }
 
    @SuppressWarnings('unchecked')
    public <A> Connection<A> getPrimaryConnection(Class<A> apiType) {
        String providerId = getProviderId(apiType);
        Connection<A> connection = (Connection<A>) findPrimaryConnection(providerId);
        if (connection == null) {
            throw new NotConnectedException(providerId);
        }
        return connection;
    }
 
    @SuppressWarnings('unchecked')
    public <A> Connection<A> findPrimaryConnection(Class<A> apiType) {
        String providerId = getProviderId(apiType);
        return (Connection<A>) findPrimaryConnection(providerId);
    }
 
    public void addConnection(Connection<?> connection) {
        //check cardinality
        SocialAuthenticationService<?> socialAuthenticationService =
                this.socialAuthenticationServiceLocator.getAuthenticationService(connection.getKey().getProviderId());
        if (socialAuthenticationService.getConnectionCardinality() == ConnectionCardinality.ONE_TO_ONE ||
                socialAuthenticationService.getConnectionCardinality() == ConnectionCardinality.ONE_TO_MANY){
            List<UserSocialConnection> storedConnections =
                    this.userSocialConnectionRepository.findByProviderIdAndProviderUserId(
                            connection.getKey().getProviderId(), connection.getKey().getProviderUserId());
            if (storedConnections.size() > 0){
                //not allow one providerId connect to multiple userId
                throw new DuplicateConnectionException(connection.getKey());
            }
        }
 
        UserSocialConnection userSocialConnection = this.userSocialConnectionRepository
                .findByUserIdAndProviderIdAndProviderUserId(userId, connection.getKey().getProviderId(),
                        connection.getKey().getProviderUserId());
        if (userSocialConnection == null) {
            ConnectionData data = connection.createData();
            userSocialConnection = new UserSocialConnection(userId, data.getProviderId(), data.getProviderUserId(), 0,
                    data.getDisplayName(), data.getProfileUrl(), data.getImageUrl(), encrypt(data.getAccessToken()),
                    encrypt(data.getSecret()), encrypt(data.getRefreshToken()), data.getExpireTime());
            this.userSocialConnectionRepository.save(userSocialConnection);
        } else {
            throw new DuplicateConnectionException(connection.getKey());
        }
    }
 
    public void updateConnection(Connection<?> connection) {
        ConnectionData data = connection.createData();
        UserSocialConnection userSocialConnection = this.userSocialConnectionRepository
                .findByUserIdAndProviderIdAndProviderUserId(userId, connection.getKey().getProviderId(), connection
                        .getKey().getProviderUserId());
        if (userSocialConnection != null) {
            userSocialConnection.setDisplayName(data.getDisplayName());
            userSocialConnection.setProfileUrl(data.getProfileUrl());
            userSocialConnection.setImageUrl(data.getImageUrl());
            userSocialConnection.setAccessToken(encrypt(data.getAccessToken()));
            userSocialConnection.setSecret(encrypt(data.getSecret()));
            userSocialConnection.setRefreshToken(encrypt(data.getRefreshToken()));
            userSocialConnection.setExpireTime(data.getExpireTime());
            this.userSocialConnectionRepository.save(userSocialConnection);
        }
    }
 
    public void removeConnections(String providerId) {
        List<UserSocialConnection> userSocialConnectionList = this.userSocialConnectionRepository
                .findByUserIdAndProviderId(userId, providerId);
        for (UserSocialConnection userSocialConnection : userSocialConnectionList) {
            this.userSocialConnectionRepository.delete(userSocialConnection);
        }
    }
 
    public void removeConnection(ConnectionKey connectionKey) {
        UserSocialConnection userSocialConnection = this.userSocialConnectionRepository
                .findByUserIdAndProviderIdAndProviderUserId(userId, connectionKey.getProviderId(), connectionKey.getProviderUserId());
        this.userSocialConnectionRepository.delete(userSocialConnection);
    }
 
    // internal helpers
 
    private Connection<?> buildConnection(UserSocialConnection userSocialConnection) {
        ConnectionData connectionData = new ConnectionData(userSocialConnection.getProviderId(),
                userSocialConnection.getProviderUserId(), userSocialConnection.getDisplayName(),
                userSocialConnection.getProfileUrl(), userSocialConnection.getImageUrl(),
                decrypt(userSocialConnection.getAccessToken()), decrypt(userSocialConnection.getSecret()),
                decrypt(userSocialConnection.getRefreshToken()), userSocialConnection.getExpireTime());
        ConnectionFactory<?> connectionFactory = this.socialAuthenticationServiceLocator.getConnectionFactory(connectionData
                .getProviderId());
        return connectionFactory.createConnection(connectionData);
    }
 
    private Connection<?> findPrimaryConnection(String providerId) {
        List<UserSocialConnection> userSocialConnectionList = this.userSocialConnectionRepository
                .findByUserIdAndProviderId(userId, providerId);
 
        return buildConnection(userSocialConnectionList.get(0));
    }
 
    private <A> String getProviderId(Class<A> apiType) {
        return socialAuthenticationServiceLocator.getConnectionFactory(apiType).getProviderId();
    }
 
    private String encrypt(String text) {
        return text != null ? textEncryptor.encrypt(text) : text;
    }
 
    private String decrypt(String encryptedText) {
        return encryptedText != null ? textEncryptor.decrypt(encryptedText) : encryptedText;
    }
 
}

Сначала я заменил JdbcTemplate на UserSocialConnectionRepository для извлечения объектов UserSocialConnection из базы данных. Затем заменил ConnectionFactoryLocator на SocialAuthenticationServiceLocator из модуля SocialAuthenticationServiceLocator -Social-Security. Большое изменение в методе addConnection (выделено выше), где он сначала проверяет количество соединений. Если connectionCardinality для socialAuthenticationService имеет значение ONE_TO_ONE (что означает один userId с одной и только одной парой providerId / providerUserId) или ONE_TO_MANY (что означает, что один userId может подключаться к одному или нескольким providerId / providerUserId, но одна пара providerId / providerUserId может подключаться только одному пользователю).

После всех этих настроек последний шаг — склеить их вместе в весеннем конфиге:

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
@Configuration
public class SocialAndSecurityConfig {
    @Inject
    private Environment environment;
 
    @Inject
    AccountService accountService;
 
    @Inject
    private AuthenticationManager authenticationManager;
 
    @Inject
    private UserSocialConnectionRepository userSocialConnectionRepository;
 
    @Bean
    public SocialAuthenticationServiceLocator socialAuthenticationServiceLocator() {
        SocialAuthenticationServiceRegistry registry = new SocialAuthenticationServiceRegistry();
 
        //add google
        OAuth2ConnectionFactory<Google> googleConnectionFactory = new GoogleConnectionFactory(environment.getProperty('google.clientId'),
                environment.getProperty('google.clientSecret'));
        OAuth2AuthenticationService<Google> googleAuthenticationService = new OAuth2AuthenticationService<Google>(googleConnectionFactory);
        googleAuthenticationService.setScope('https://www.googleapis.com/auth/userinfo.profile');
        registry.addAuthenticationService(googleAuthenticationService);
 
        //add twitter
        OAuth1ConnectionFactory<Twitter> twitterConnectionFactory = new TwitterConnectionFactory(environment.getProperty('twitter.consumerKey'),
                environment.getProperty('twitter.consumerSecret'));
        OAuth1AuthenticationService<Twitter> twitterAuthenticationService = new OAuth1AuthenticationService<Twitter>(twitterConnectionFactory);
        registry.addAuthenticationService(twitterAuthenticationService);
 
        //add facebook
        OAuth2ConnectionFactory<Facebook> facebookConnectionFactory = new FacebookConnectionFactory(environment.getProperty('facebook.clientId'),
                environment.getProperty('facebook.clientSecret'));
        OAuth2AuthenticationService<Facebook> facebookAuthenticationService = new OAuth2AuthenticationService<Facebook>(facebookConnectionFactory);
        facebookAuthenticationService.setScope('');
        registry.addAuthenticationService(facebookAuthenticationService);
 
        return registry;
    }
 
    /**
     * Singleton data access object providing access to connections across all users.
     */
    @Bean
    public UsersConnectionRepository usersConnectionRepository() {
        MongoUsersConnectionRepository repository = new MongoUsersConnectionRepository(userSocialConnectionRepository,
                socialAuthenticationServiceLocator(), Encryptors.noOpText());
        repository.setConnectionSignUp(autoConnectionSignUp());
        return repository;
    }
 
    /**
     * Request-scoped data access object providing access to the current user's connections.
     */
    @Bean
    @Scope(value = 'request', proxyMode = ScopedProxyMode.INTERFACES)
    public ConnectionRepository connectionRepository() {
        UserAccount user = AccountUtils.getLoginUserAccount();
        return usersConnectionRepository().createConnectionRepository(user.getUsername());
    }
 
    /**
     * A proxy to a request-scoped object representing the current user's primary Google account.
     *
     * @throws NotConnectedException
     *             if the user is not connected to Google.
     */
    @Bean
    @Scope(value = 'request', proxyMode = ScopedProxyMode.INTERFACES)
    public Google google() {
        Connection<Google> google = connectionRepository().findPrimaryConnection(Google.class);
        return google != null ? google.getApi() : new GoogleTemplate();
    }
 
    @Bean
    @Scope(value='request', proxyMode=ScopedProxyMode.INTERFACES)  
    public Facebook facebook() {
        Connection<Facebook> facebook = connectionRepository().findPrimaryConnection(Facebook.class);
        return facebook != null ? facebook.getApi() : new FacebookTemplate();
    }
 
    @Bean
    @Scope(value='request', proxyMode=ScopedProxyMode.INTERFACES)  
    public Twitter twitter() {
        Connection<Twitter> twitter = connectionRepository().findPrimaryConnection(Twitter.class);
        return twitter != null ? twitter.getApi() : new TwitterTemplate();
    }
 
    @Bean
    public ConnectionSignUp autoConnectionSignUp() {
        return new AutoConnectionSignUp(accountService);
    }
 
    @Bean
    public SocialAuthenticationFilter socialAuthenticationFilter() {
        SocialAuthenticationFilter filter = new SocialAuthenticationFilter(authenticationManager, accountService,
                usersConnectionRepository(), socialAuthenticationServiceLocator());
        filter.setFilterProcessesUrl('/signin');
        filter.setSignupUrl(null);
        filter.setConnectionAddedRedirectUrl('/myAccount');
        filter.setPostLoginUrl('/myAccount');
        return filter;
    }
 
    @Bean
    public SocialAuthenticationProvider socialAuthenticationProvider(){
        return new SocialAuthenticationProvider(usersConnectionRepository(), accountService);
    }
 
    @Bean
    public LoginUrlAuthenticationEntryPoint socialAuthenticationEntryPoint(){
        return new LoginUrlAuthenticationEntryPoint('/signin');
    }
 
}

accountService — это моя собственная служба учетных записей пользователей, которая предоставляет функции, связанные с учетной записью, и реализует SocialUserDetailsService , UserDetailsService , UserIdExtractor

Есть еще много областей для улучшения, таких как рефакторинг MongoConnectionRepository и MongoUsersConnectionRepository чтобы иметь абстрактную реализацию репозитория социальных соединений с использованием интерфейса Spring Data Repository. И я обнаружил, что кто-то уже поднял проблему для этого: использовать Spring Data для UsersConnectionRepository .

Ссылка: Настройка Spring Social Connect Framework для MongoDB от нашего партнера по JCG Юаня Цзи в блоге Jiwhiz .