Social login with Spring-Social


Social login has the advantage to simplify user account creation and to provide application with more accurate user information.

Implementing a social login with each social networking sites using an OAuth protocol could be a headache for a developer.

Spring provides social API and implements it for most of famous social networking site like LinkedIn, Facebook and Twitter. This API integrates easily to a Spring security project to provide authentication using OAuth2 protocol.

This post presents how to use Spring social to authenticate users for an Angular and Spring based project.

You can get project source code on GitHub and you can run the application here.

1 – Add maven dependencies

In order to use Spring Social you must add the necessary dependencies. For the sample we will add the following Spring Social dependencies:




<!-- add more social dependencies like github, twitter, google ... -->

2 – Spring Security config

We have to setup a security filter, SocialAuthenticationFilter, to integrate it with Spring Security so that a social network provider can be activated when a user needs to be authenticated. The security filer will listen to URL’s that start with /auth and route incoming requests to the corresponding social network provider. A request sent to /auth/linkedin will be redirected to the LinkedIn provider. The security filter is configured by an SpringSocialConfigurer.

@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan(basePackages = {""})
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // Dependency injection code ...

    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**", "/index.html", "/login.html",
                "/partials/**", "/template/**", "/", "/error/**");

    protected void configure(HttpSecurity http) throws Exception {
                // Exception Handling config ...
                // Login config ...
                // Logout config ...
                // Remember me config ...
            .apply(new SpringSocialConfigurer()

    public SocialUserDetailsService socialUsersDetailService() {
        return new SimpleSocialUsersDetailService(userDetailsService());

Next, we implement a SocialUserDetailsService to provide user details for the SpringSocialConfigurer.

public class SimpleSocialUsersDetailService implements SocialUserDetailsService {

    private UserDetailsService userDetailsService;

    public SimpleSocialUsersDetailService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;

    public SocialUserDetails loadUserByUserId(String userId) 
                           throws UsernameNotFoundException, DataAccessException {
        UserDetails userDetails = userDetailsService.loadUserByUsername(userId);
        return new SocialUser(userDetails.getUsername(), 
                           userDetails.getPassword(), userDetails.getAuthorities());


2 – Spring Social config

We can configure Spring Social by following these steps:

  • Implement the SocialConfigurer interface.
  • Add @EnableSocial annotation to have the Spring MVC configuration defined in SocialConfiguration imported.
  • Configure each provider with the standard OAuth Client Id and Client Secret properties. This is done in the class SocialConfigurer where we add a connection factory implementation for each social network service.
  • Implement getUserIdSource() method. The UserIdSource object returned by this method is responsible of determining the correct account id of the user. Because our case the username of the user as an account id, we implement this method by returning a new AuthenticationNameUserIdSource object.
  • Implement the getUsersConnectionRepository() method. In this application we use the provided Jdbc Spring Implementation.
@ComponentScan(basePackages = {""})
public class SocialConfig implements SocialConfigurer {

 private AccountConnectionSignUpService accountConnectionSignUpService;

 private DataSource dataSource;

 public void addConnectionFactories(ConnectionFactoryConfigurer cfc, Environment env) {
  cfc.addConnectionFactory(new LinkedInConnectionFactory(
  cfc.addConnectionFactory(new GitHubConnectionFactory(
  cfc.addConnectionFactory(new TwitterConnectionFactory(
  GoogleConnectionFactory gcf = new GoogleConnectionFactory(

 public UserIdSource getUserIdSource() {
  return new AuthenticationNameUserIdSource();

 public UsersConnectionRepository
 getUsersConnectionRepository(ConnectionFactoryLocator cfl) {
  JdbcUsersConnectionRepository repository =
   new JdbcUsersConnectionRepository(dataSource, cfl, Encryptors.noOpText());
  return repository;

The JdbcUsersConnectionRepository implementation requires adding UserConnection table to the database schema.

We use the following SQL statement to create the table:

create table UserConnection (userId varchar(255) not null,
	providerId varchar(255) not null,
	providerUserId varchar(255),
	rank int not null,
	displayName varchar(255),
	profileUrl varchar(512),
	imageUrl varchar(512),
	accessToken varchar(512) not null,
	secret varchar(512),
	refreshToken varchar(512),
	expireTime bigint,
	primary key (userId, providerId, providerUserId));
create unique index UserConnectionRank on UserConnection(userId, providerId, rank);

Next, we implement our ConnectionSignUp implementation. After user social authentication, we store user profile information in the user repository.

public class AccountConnectionSignUpService implements ConnectionSignUp {

 private UserRepo usersRepo;

 public String execute(Connection < ? > connection) {
  Profile profile = new Profile();
  BeanUtils.copyProperties(connection.fetchUserProfile(), profile);
  String userId = UUID.randomUUID().toString();
  usersRepo.createUser(userId, profile);
  return userId;

3 – Get OAuth application Id and secret

The links bellows allow you to get an applications ids and secrets:

These screenshots show steps to follow to get OAuth application Ids and secrets for LinkedIn and Google.

This slideshow requires JavaScript.


Spring-Social is not just for Social login, it provides APIs for most of known SaaS (Software as a Service) providers; for example Spring-Social provides an API for getting user connections or friends.

In this post, we provide a sample project to implement Social login for a web application. For more details, you can checkout the source code from GitHub and test online the application here.


2 thoughts on “Social login with Spring-Social

  1. Hi,
    Great tutorial, very informative.
    I have a question – if I would like to expand this implementation so not only angular app will be able mobile apps will be able to connect – what do I need to add? (I would like to use the sdk instead of web redirection)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s